From b83dd5e42edb30a768e60728cb7355b87d4b6617 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 29 Sep 2025 23:40:39 +0200 Subject: [PATCH 001/181] First fingerprint lock offer fix, added Firebase debugging options. --- README.md | 18 ++++++++++++++++ android/app/build.gradle.kts | 7 ++++++ android/app/src/main/AndroidManifest.xml | 2 +- android/app/src/main/res/values/strings.xml | 4 ++++ lib/pages/register_page.dart | 24 +++++++++++++++------ 5 files changed, 48 insertions(+), 7 deletions(-) create mode 100644 android/app/src/main/res/values/strings.xml diff --git a/README.md b/README.md index 9e242ae..5dac23c 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,24 @@ You can download the app [here in the releases](https://github.com/jsfraz/whispe - see [Firebase setup for Flutter](https://firebase.google.com/docs/flutter/setup) and [Firebase Cloud Messaging for Flutter](https://firebase.google.com/docs/cloud-messaging/flutter/client) for more details how to implement this - app specific configuration files [are not included](.gitignore) in the repository, you need to create them yourself if you plan self host Whisper (refer to [whisper-server](https://github.com/jsfraz/whisper-server) repository for more details) +### Development + +To setup Firebase using Flutterfire you can run: + +```bash+ +flutterfire configure +``` + +Or run this for the development environment: + +```bash +flutterfire configure \ + --android-package-name cz.josefraz.whisper.debug \ + --ios-bundle-id cz.josefraz.whisper.debug +``` + +Then select your Firebase project. This will generate the necessary `firebase.json` and `lib/firebase_options.dart` files. + ## Continuous Integration a Deployment (CI/CD) The application uses GitHub Actions to automatically build and release the APK file when pushing to the `main` branch. For this process to work correctly, the following secret keys must be set in the repository settings (Settings > Secrets and variables > Actions): diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index a5ea66e..c5e8c48 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -37,10 +37,17 @@ android { } buildTypes { + debug { + // Different applicationId for debug version + applicationIdSuffix = ".debug" + // Add suffix + resValue("string", "app_name", "Whisper Debug") + } release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig = signingConfigs.getByName("debug") + resValue("string", "app_name", "Whisper") } } } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index f0cbe8b..bfe4c25 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -4,7 +4,7 @@ + + Whisper + \ No newline at end of file diff --git a/lib/pages/register_page.dart b/lib/pages/register_page.dart index dd12b52..91eb05c 100644 --- a/lib/pages/register_page.dart +++ b/lib/pages/register_page.dart @@ -164,20 +164,32 @@ class _RegisterPageState extends State { await Fluttertoast.showToast( msg: 'biometricsEnabled'.tr(), backgroundColor: Colors.grey); + + // Redirect to home page and clear navigation history + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (context) => const HomePage()), + (Route route) => false, + ); } else { await Fluttertoast.showToast( msg: 'biometricSetupFailed'.tr(), backgroundColor: Colors.red); + + // Redirect to home page and clear navigation history + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (context) => const HomePage()), + (Route route) => false, + ); } }, ); + } else { + // Redirect to home page and clear navigation history + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (context) => const HomePage()), + (Route route) => false, + ); } - - // Redirect to home page and clear navigation history - Navigator.of(context).pushAndRemoveUntil( - MaterialPageRoute(builder: (context) => const HomePage()), - (Route route) => false, - ); } } From 206416930d1eaa37ec24986730e1803e4fe81a80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 30 Sep 2025 00:15:56 +0200 Subject: [PATCH 002/181] Enhanced fingerprint settings. --- assets/translations/en.json | 2 +- lib/main.dart | 2 +- lib/pages/settings_page.dart | 71 +++++++++++++++++++---------------- lib/utils/biometric_auth.dart | 28 ++++++++++++++ lib/utils/cache_utils.dart | 2 +- 5 files changed, 69 insertions(+), 36 deletions(-) diff --git a/assets/translations/en.json b/assets/translations/en.json index f2c4902..cbfbe79 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -14,7 +14,7 @@ "biometricsDisabled": "Fingerprint login disabled", "yesText": "Yes", "noText": "No", - "okText": "OK", + "okText": "So be it", "msgPage": "Messages", "settingsButton": "Settings", "addChat": "New chat", diff --git a/lib/main.dart b/lib/main.dart index ac43a4d..986d276 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -4,7 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:hive/hive.dart'; import 'package:provider/provider.dart'; -import 'package:whisper/firebase_options.dart'; +import 'firebase_options.dart'; import '../utils/message_notifier.dart'; import '../utils/cache_utils.dart'; import 'models/app_theme.dart'; diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index f0fbc9a..70d215f 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -35,6 +35,43 @@ class _SettingsPageState extends State { setState(() {}); } + Future _toggleBiometry(bool switchValue) async { + if (switchValue) { + // Enable + final success = await BiometricAuth.storeEncryptionKey( + Singleton().boxCollectionKey, context); + if (success) { + await Fluttertoast.showToast( + msg: 'biometricsEnabled'.tr(), backgroundColor: Colors.grey); + setState(() { + _isBiometryEnabled = true; + }); + } else { + await Fluttertoast.showToast( + msg: 'biometricSetupFailed'.tr(), backgroundColor: Colors.red); + setState(() { + _isBiometryEnabled = false; + }); + } + } else { + // Disable + final success = await BiometricAuth.disableBiometricAuth(context); + if (success) { + await Fluttertoast.showToast( + msg: 'biometricsDisabled'.tr(), backgroundColor: Colors.grey); + setState(() { + _isBiometryEnabled = false; + }); + } else { + await Fluttertoast.showToast( + msg: 'biometricSetupFailed'.tr(), backgroundColor: Colors.red); + setState(() { + _isBiometryEnabled = true; + }); + } + } + } + @override Widget build(BuildContext context) { return Scaffold( @@ -123,39 +160,7 @@ class _SettingsPageState extends State { Spacer(), Switch( value: _isBiometryEnabled, - onChanged: (value) async { - if (value) { - // Enable - final success = await BiometricAuth.storeEncryptionKey( - Singleton().boxCollectionKey, context); - if (success) { - await Fluttertoast.showToast( - msg: 'biometricsEnabled'.tr(), - backgroundColor: Colors.grey); - setState(() { - _isBiometryEnabled = true; - }); - } else { - await Fluttertoast.showToast( - msg: 'biometricSetupFailed'.tr(), - backgroundColor: Colors.red); - setState(() { - _isBiometryEnabled = false; - }); - } - } else { - // Disable - await CacheUtils.setBiometryEnabled(false); - await BiometricAuth.clearEncryptionKey(); - await Fluttertoast.showToast( - msg: 'biometricsDisabled'.tr(), - backgroundColor: Colors.grey); - setState(() { - _isBiometryEnabled = false; - }); - } - await Singleton().profile.save(); - }, + onChanged: _toggleBiometry, ) ], ), diff --git a/lib/utils/biometric_auth.dart b/lib/utils/biometric_auth.dart index a39b584..9ab091a 100644 --- a/lib/utils/biometric_auth.dart +++ b/lib/utils/biometric_auth.dart @@ -70,6 +70,34 @@ class BiometricAuth { } } + /// Delete the decryption key from secure storage and disable biometric authentication + static Future disableBiometricAuth(BuildContext context) async { + try { + // Verify biometric credentials before storing the key + bool authenticated = await authenticate( + 'biometricSetupReason'.tr(), + 'biometricSetupAuth'.tr(), + context); + + if (authenticated) { + // Delete the stored key + await _secureStorage.delete(key: _biometricKeyStorageKey); + // Disable biometric authentication + await CacheUtils.setBiometryEnabled(false); + return true; + } + + return false; + } catch (e) { + debugPrint('Error disabling encryption key: $e'); + await Fluttertoast.showToast( + msg: 'biometricSetupFailed'.tr(), + backgroundColor: Colors.red + ); + return false; + } + } + /// Gets the decryption key from secure storage after biometric authentication static Future?> getEncryptionKey(BuildContext context) async { try { diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index c988989..9739e5d 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -1,6 +1,6 @@ import 'package:bcrypt/bcrypt.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/utils/biometric_auth.dart'; +import '../utils/biometric_auth.dart'; import '../models/app_theme.dart'; import '../models/private_message.dart'; import '../models/profile.dart'; From fd66052b86b36ea43a48c6132bcf5604c02c94fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 18 Jan 2026 02:23:26 +0100 Subject: [PATCH 003/181] Update README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5dac23c..9d4597d 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ You can download the app [here in the releases](https://github.com/jsfraz/whispe To setup Firebase using Flutterfire you can run: -```bash+ +```bash flutterfire configure ``` From 12a2f4582f41b362d71701b708489f622e115356 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 31 Mar 2026 02:45:04 +0200 Subject: [PATCH 004/181] Updated packages, added Linux target --- .metadata | 15 +- lib/main.dart | 19 +- lib/utils/biometric_auth.dart | 63 ++-- lib/utils/notification_service.dart | 28 +- linux/.gitignore | 1 + linux/CMakeLists.txt | 128 ++++++++ linux/flutter/CMakeLists.txt | 88 +++++ linux/flutter/generated_plugin_registrant.cc | 19 ++ linux/flutter/generated_plugin_registrant.h | 15 + linux/flutter/generated_plugins.cmake | 25 ++ linux/runner/CMakeLists.txt | 26 ++ linux/runner/main.cc | 6 + linux/runner/my_application.cc | 148 +++++++++ linux/runner/my_application.h | 21 ++ pubspec.lock | 320 ++++++++++--------- pubspec.yaml | 6 +- 16 files changed, 710 insertions(+), 218 deletions(-) create mode 100644 linux/.gitignore create mode 100644 linux/CMakeLists.txt create mode 100644 linux/flutter/CMakeLists.txt create mode 100644 linux/flutter/generated_plugin_registrant.cc create mode 100644 linux/flutter/generated_plugin_registrant.h create mode 100644 linux/flutter/generated_plugins.cmake create mode 100644 linux/runner/CMakeLists.txt create mode 100644 linux/runner/main.cc create mode 100644 linux/runner/my_application.cc create mode 100644 linux/runner/my_application.h diff --git a/.metadata b/.metadata index 4f14196..02c33e9 100644 --- a/.metadata +++ b/.metadata @@ -4,7 +4,7 @@ # This file should be version controlled and should not be manually edited. version: - revision: "be698c48a6750c8cb8e61c740ca9991bb947aba2" + revision: "db50e20168db8fee486b9abf32fc912de3bc5b6a" channel: "stable" project_type: app @@ -13,14 +13,11 @@ project_type: app migration: platforms: - platform: root - create_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 - base_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 - - platform: android - create_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 - base_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 - - platform: ios - create_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 - base_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 + create_revision: db50e20168db8fee486b9abf32fc912de3bc5b6a + base_revision: db50e20168db8fee486b9abf32fc912de3bc5b6a + - platform: linux + create_revision: db50e20168db8fee486b9abf32fc912de3bc5b6a + base_revision: db50e20168db8fee486b9abf32fc912de3bc5b6a # User provided section diff --git a/lib/main.dart b/lib/main.dart index 986d276..f5ff8fd 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,3 +1,5 @@ +import 'dart:io'; + import 'package:easy_localization/easy_localization.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; @@ -23,19 +25,22 @@ void main() async { // Initialize Flutter widgets WidgetsFlutterBinding.ensureInitialized(); - // Firebase initialization - await Firebase.initializeApp( - options: DefaultFirebaseOptions.currentPlatform, - ); + if (Platform.isAndroid || Platform.isIOS) { + await Firebase.initializeApp( + options: DefaultFirebaseOptions.currentPlatform, + ); + } // Local notifications NotificationService().init(); // Load locale await EasyLocalization.ensureInitialized(); - - // Lock orientation (https://stackoverflow.com/a/52720581/19371130) - SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); + + if (Platform.isAndroid || Platform.isIOS) { + // Lock orientation (https://stackoverflow.com/a/52720581/19371130) + SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); + } // Hive adapters Hive diff --git a/lib/utils/biometric_auth.dart b/lib/utils/biometric_auth.dart index 9ab091a..236f3bd 100644 --- a/lib/utils/biometric_auth.dart +++ b/lib/utils/biometric_auth.dart @@ -19,7 +19,8 @@ class BiometricAuth { try { canAuthenticateWithBiometrics = await _auth.canCheckBiometrics; - canAuthenticate = canAuthenticateWithBiometrics || await _auth.isDeviceSupported(); + canAuthenticate = + canAuthenticateWithBiometrics || await _auth.isDeviceSupported(); } on PlatformException catch (e) { debugPrint(e.toString()); return false; @@ -40,32 +41,30 @@ class BiometricAuth { } /// Saves the decryption key to a secure storage protected by biometrics - static Future storeEncryptionKey(List key, BuildContext context) async { + static Future storeEncryptionKey( + List key, BuildContext context) async { try { // Convert the key to a string for storage final String keyString = key.join(','); // Verify biometric credentials before storing the key bool authenticated = await authenticate( - 'biometricSetupReason'.tr(), - 'biometricSetupAuth'.tr(), - context); - + 'biometricSetupReason'.tr(), 'biometricSetupAuth'.tr(), context); + if (authenticated) { // Store the key securely - await _secureStorage.write(key: _biometricKeyStorageKey, value: keyString); + await _secureStorage.write( + key: _biometricKeyStorageKey, value: keyString); // Enable biometric authentication await CacheUtils.setBiometryEnabled(true); return true; } - + return false; } catch (e) { debugPrint('Error storing encryption key: $e'); await Fluttertoast.showToast( - msg: 'biometricSetupFailed'.tr(), - backgroundColor: Colors.red - ); + msg: 'biometricSetupFailed'.tr(), backgroundColor: Colors.red); return false; } } @@ -75,10 +74,8 @@ class BiometricAuth { try { // Verify biometric credentials before storing the key bool authenticated = await authenticate( - 'biometricSetupReason'.tr(), - 'biometricSetupAuth'.tr(), - context); - + 'biometricSetupReason'.tr(), 'biometricSetupAuth'.tr(), context); + if (authenticated) { // Delete the stored key await _secureStorage.delete(key: _biometricKeyStorageKey); @@ -86,14 +83,12 @@ class BiometricAuth { await CacheUtils.setBiometryEnabled(false); return true; } - + return false; } catch (e) { debugPrint('Error disabling encryption key: $e'); await Fluttertoast.showToast( - msg: 'biometricSetupFailed'.tr(), - backgroundColor: Colors.red - ); + msg: 'biometricSetupFailed'.tr(), backgroundColor: Colors.red); return false; } } @@ -103,19 +98,18 @@ class BiometricAuth { try { // Verify biometric credentials before retrieving the key bool authenticated = await authenticate( - 'biometricAuthReason'.tr(), - 'biometricAuthPrompt'.tr(), - context); - + 'biometricAuthReason'.tr(), 'biometricAuthPrompt'.tr(), context); + if (authenticated) { // Get the stored key - final String? keyString = await _secureStorage.read(key: _biometricKeyStorageKey); + final String? keyString = + await _secureStorage.read(key: _biometricKeyStorageKey); if (keyString != null && keyString.isNotEmpty) { // Convert the string back to a list of bytes return keyString.split(',').map((s) => int.parse(s)).toList(); } } - + return null; } catch (e) { debugPrint('Error retrieving encryption key: $e'); @@ -129,22 +123,19 @@ class BiometricAuth { } /// Performs biometric authentication - static Future authenticate(String reason, String authString, BuildContext context) async { + static Future authenticate( + String reason, String authString, BuildContext context) async { try { return await _auth.authenticate( localizedReason: reason, - options: const AuthenticationOptions( - stickyAuth: true, - biometricOnly: true, - ) + biometricOnly: true, + persistAcrossBackgrounding: true, ); - } on PlatformException catch (e) { - debugPrint('Authentication error: $e'); + } on LocalAuthException catch (e) { + debugPrint('Authentication error: ${e.code} - ${e.description}'); await Fluttertoast.showToast( - msg: 'biometricAuthFailed'.tr(), - backgroundColor: Colors.red - ); + msg: 'biometricAuthFailed'.tr(), backgroundColor: Colors.red); return false; } } -} \ No newline at end of file +} diff --git a/lib/utils/notification_service.dart b/lib/utils/notification_service.dart index 4f5556a..cbc0112 100644 --- a/lib/utils/notification_service.dart +++ b/lib/utils/notification_service.dart @@ -14,11 +14,17 @@ class NotificationService { Future init() async { const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('app_icon'); + const LinuxInitializationSettings initializationSettingsLinux = + LinuxInitializationSettings( + defaultActionName: 'whisper_message'); // TODO other options final InitializationSettings initializationSettings = - InitializationSettings(android: initializationSettingsAndroid); + InitializationSettings( + android: initializationSettingsAndroid, + linux: initializationSettingsLinux); - await _flutterLocalNotificationsPlugin.initialize(initializationSettings); + await _flutterLocalNotificationsPlugin.initialize( + settings: initializationSettings); } /// Show notifications. @@ -48,10 +54,10 @@ class NotificationService { final groupedPlatformChannelSpecifics = await groupedNotificationDetails( lines, groupedMessagesByUser.keys.length, messages.length); await _flutterLocalNotificationsPlugin.show( - messages.last.notificationId, - 'newMessagesTitle'.tr(), - 'newMessagesBody'.tr(), - groupedPlatformChannelSpecifics, + id: messages.last.notificationId, + title: 'newMessagesTitle'.tr(), + body: 'newMessagesBody'.tr(), + notificationDetails: groupedPlatformChannelSpecifics, ); } } @@ -122,10 +128,10 @@ class NotificationService { NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics); await _flutterLocalNotificationsPlugin.show( - message.notificationId, - user.username, - message.message, - platformChannelSpecifics, + id: message.notificationId, + title: user.username, + body: message.message, + notificationDetails: platformChannelSpecifics, ); } @@ -136,7 +142,7 @@ class NotificationService { for (var id in ids) { for (var notification in activeNotifications) { if (notification.id == id) { - await _flutterLocalNotificationsPlugin.cancel(id); + await _flutterLocalNotificationsPlugin.cancel(id: id); } } } diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..a886388 --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "whisper") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "cz.josefraz.whisper") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..38dd0bc --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,19 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin"); + flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..65240e9 --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,25 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_secure_storage_linux + url_launcher_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..99c7a7f --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "whisper"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "whisper"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/pubspec.lock b/pubspec.lock index 20f99ac..bff702d 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -13,18 +13,10 @@ packages: dependency: transitive description: name: _flutterfire_internals - sha256: "23d16f00a2da8ffa997c782453c73867b0609bd90435195671a54de38a3566df" + sha256: f698de6eb8a0dd7a9a931bbfe13568e8b77e702eb2deb13dd83480c5373e7746 url: "https://pub.dev" source: hosted - version: "1.3.62" - adaptive_number: - dependency: transitive - description: - name: adaptive_number - sha256: "3a567544e9b5c9c803006f51140ad544aedc79604fd4f3f2c1380003f97c1d77" - url: "https://pub.dev" - source: hosted - version: "1.0.0" + version: "1.3.68" analyzer: dependency: transitive description: @@ -37,10 +29,10 @@ packages: dependency: transitive description: name: archive - sha256: "2fde1607386ab523f7a36bb3e7edb43bd58e6edaf2ffb29d8a6d578b297fdbbd" + sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff url: "https://pub.dev" source: hosted - version: "4.0.7" + version: "4.0.9" args: dependency: transitive description: @@ -53,10 +45,10 @@ packages: dependency: transitive description: name: async - sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 url: "https://pub.dev" source: hosted - version: "2.13.0" + version: "2.13.1" basic_utils: dependency: "direct main" description: @@ -69,10 +61,10 @@ packages: dependency: "direct main" description: name: bcrypt - sha256: "9dc3f234d5935a76917a6056613e1a6d9b53f7fa56f98e24cd49b8969307764b" + sha256: "6073a700cbbc59f1d4ab27cd532755e3de5e676c4941f535f351374df849270b" url: "https://pub.dev" source: hosted - version: "1.1.3" + version: "1.2.0" boolean_selector: dependency: transitive description: @@ -101,10 +93,10 @@ packages: dependency: transitive description: name: build_daemon - sha256: "8e928697a82be082206edb0b9c99c5a4ad6bc31c9e9b8b2f291ae65cd4a25daa" + sha256: bf05f6e12cfea92d3c09308d7bcdab1906cd8a179b023269eed00c071004b957 url: "https://pub.dev" source: hosted - version: "4.0.4" + version: "4.1.1" build_resolvers: dependency: transitive description: @@ -141,18 +133,18 @@ packages: dependency: transitive description: name: built_value - sha256: a30f0a0e38671e89a492c44d005b5545b830a961575bbd8336d42869ff71066d + sha256: "0730c18c770d05636a8f945c32a4d7d81cb6e0f0148c8db4ad12e7748f7e49af" url: "https://pub.dev" source: hosted - version: "8.12.0" + version: "8.12.5" characters: dependency: transitive description: name: characters - sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b url: "https://pub.dev" source: hosted - version: "1.4.0" + version: "1.4.1" checked_yaml: dependency: transitive description: @@ -177,14 +169,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.2" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687" + url: "https://pub.dev" + source: hosted + version: "1.0.0" code_builder: dependency: transitive description: name: code_builder - sha256: "11654819532ba94c34de52ff5feb52bd81cba1de00ef2ed622fd50295f9d4243" + sha256: "6a6cab2ba4680d6423f34a9b972a4c9a94ebe1b62ecec4e1a1f2cba91fd1319d" url: "https://pub.dev" source: hosted - version: "4.11.0" + version: "4.11.1" collection: dependency: transitive description: @@ -205,26 +205,26 @@ packages: dependency: "direct main" description: name: crypto - sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855" + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf url: "https://pub.dev" source: hosted - version: "3.0.6" + version: "3.0.7" cryptography: dependency: "direct main" description: name: cryptography - sha256: d146b76d33d94548cf035233fbc2f4338c1242fa119013bead807d033fc4ae05 + sha256: "3eda3029d34ec9095a27a198ac9785630fe525c0eb6a49f3d575272f8e792ef0" url: "https://pub.dev" source: hosted - version: "2.7.0" + version: "2.9.0" dart_jsonwebtoken: dependency: "direct main" description: name: dart_jsonwebtoken - sha256: "21ce9f8a8712f741e8d6876a9c82c0f8a257fe928c4378a91d8527b92a3fd413" + sha256: cb79ed79baa02b4f59a597bf365873cbd83f9bb15273d63f7803802d21717c7d url: "https://pub.dev" source: hosted - version: "3.2.0" + version: "3.4.0" dart_style: dependency: transitive description: @@ -237,18 +237,18 @@ packages: dependency: transitive description: name: dbus - sha256: "79e0c23480ff85dc68de79e2cd6334add97e48f7f4865d17686dd6ea81a47e8c" + sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270 url: "https://pub.dev" source: hosted - version: "0.7.11" + version: "0.7.12" device_info_plus: dependency: transitive description: name: device_info_plus - sha256: "49413c8ca514dea7633e8def233b25efdf83ec8522955cc2c0e3ad802927e7c6" + sha256: b4fed1b2835da9d670d7bed7db79ae2a94b0f5ad6312268158a9b5479abbacdd url: "https://pub.dev" source: hosted - version: "12.1.0" + version: "12.4.0" device_info_plus_platform_interface: dependency: transitive description: @@ -273,14 +273,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.0.2" - ed25519_edwards: - dependency: transitive - description: - name: ed25519_edwards - sha256: "6ce0112d131327ec6d42beede1e5dfd526069b18ad45dcf654f15074ad9276cd" - url: "https://pub.dev" - source: hosted - version: "0.3.1" email_validator: dependency: "direct main" description: @@ -301,10 +293,10 @@ packages: dependency: transitive description: name: ffi - sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418" + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" url: "https://pub.dev" source: hosted - version: "2.1.4" + version: "2.2.0" file: dependency: transitive description: @@ -317,50 +309,50 @@ packages: dependency: "direct main" description: name: firebase_core - sha256: "4dd96f05015c0dcceaa47711394c32971aee70169625d5e2477e7676c01ce0ee" + sha256: "2f988dab915efde3b3105268dbd69efce0e8570d767a218ccd914afd0c10c8cc" url: "https://pub.dev" source: hosted - version: "4.1.1" + version: "4.6.0" firebase_core_platform_interface: dependency: transitive description: name: firebase_core_platform_interface - sha256: "5873a370f0d232918e23a5a6137dbe4c2c47cf017301f4ea02d9d636e52f60f0" + sha256: "0ecda14c1bfc9ed8cac303dd0f8d04a320811b479362a9a4efb14fd331a473ce" url: "https://pub.dev" source: hosted - version: "6.0.1" + version: "6.0.3" firebase_core_web: dependency: transitive description: name: firebase_core_web - sha256: "61a51037312dac781f713308903bb7a1762a7f92f7bc286a3a0947fb2a713b82" + sha256: "1399ab1f0ac3b503d8a9be64a4c997fc066bbf33f701f42866e5569f26205ebe" url: "https://pub.dev" source: hosted - version: "3.1.1" + version: "3.5.1" firebase_messaging: dependency: "direct main" description: name: firebase_messaging - sha256: ba12ad0b600e0c939fbb9391e1cd3320a5b5dad5284276b9182fc21eb1e72c2b + sha256: "8dc372085b1647f05e3ec1b8bc1dada87c0062f93b2a6976f620eb85edc44f97" url: "https://pub.dev" source: hosted - version: "16.0.2" + version: "16.1.3" firebase_messaging_platform_interface: dependency: transitive description: name: firebase_messaging_platform_interface - sha256: b4bade67bfc09fcc56eb012b3fc72b59ca9e2259a34cdfb81b368169770ff536 + sha256: "6ea10f7df747542b17679d5939213c09163aab9c301b2f9b858cb55f38efdb54" url: "https://pub.dev" source: hosted - version: "4.7.2" + version: "4.7.8" firebase_messaging_web: dependency: transitive description: name: firebase_messaging_web - sha256: "8ae4a00d178993feb79603cad324b53696375cbb78805e8eb603fe331866629d" + sha256: "1f9798c8021ccf22b7e43e7fba81becd42252cb168228379fcabb7c2ef7dd638" url: "https://pub.dev" source: hosted - version: "4.0.2" + version: "4.1.4" fixnum: dependency: transitive description: @@ -402,34 +394,34 @@ packages: dependency: "direct main" description: name: flutter_local_notifications - sha256: "7ed76be64e8a7d01dfdf250b8434618e2a028c9dfa2a3c41dc9b531d4b3fc8a5" + sha256: "0d9035862236fe38250fe1644d7ed3b8254e34a21b2c837c9f539fbb3bba5ef1" url: "https://pub.dev" source: hosted - version: "19.4.2" + version: "21.0.0" flutter_local_notifications_linux: dependency: transitive description: name: flutter_local_notifications_linux - sha256: e3c277b2daab8e36ac5a6820536668d07e83851aeeb79c446e525a70710770a5 + sha256: e0f25e243c6c44c825bbbc6b2b2e76f7d9222362adcfe9fd780bf01923c840bd url: "https://pub.dev" source: hosted - version: "6.0.0" + version: "8.0.0" flutter_local_notifications_platform_interface: dependency: transitive description: name: flutter_local_notifications_platform_interface - sha256: "277d25d960c15674ce78ca97f57d0bae2ee401c844b6ac80fcd972a9c99d09fe" + sha256: e7db3d5b49c2b7ecc68deba4aaaa67a348f92ee0fef34c8e4b4459dbef0d7307 url: "https://pub.dev" source: hosted - version: "9.1.0" + version: "11.0.0" flutter_local_notifications_windows: dependency: transitive description: name: flutter_local_notifications_windows - sha256: "8d658f0d367c48bd420e7cf2d26655e2d1130147bca1eea917e576ca76668aaf" + sha256: "3a2654ba104fbb52c618ebed9def24ef270228470718c43b3a6afcd5c81bef0c" url: "https://pub.dev" source: hosted - version: "1.0.3" + version: "3.0.0" flutter_localizations: dependency: transitive description: flutter @@ -439,58 +431,58 @@ packages: dependency: transitive description: name: flutter_plugin_android_lifecycle - sha256: b0694b7fb1689b0e6cc193b3f1fcac6423c4f93c74fb20b806c6b6f196db0c31 + sha256: "38d1c268de9097ff59cf0e844ac38759fc78f76836d37edad06fa21e182055a0" url: "https://pub.dev" source: hosted - version: "2.0.30" + version: "2.0.34" flutter_secure_storage: dependency: "direct main" description: name: flutter_secure_storage - sha256: "9cad52d75ebc511adfae3d447d5d13da15a55a92c9410e50f67335b6d21d16ea" + sha256: da922f2aab2d733db7e011a6bcc4a825b844892d4edd6df83ff156b09a9b2e40 url: "https://pub.dev" source: hosted - version: "9.2.4" - flutter_secure_storage_linux: + version: "10.0.0" + flutter_secure_storage_darwin: dependency: transitive description: - name: flutter_secure_storage_linux - sha256: be76c1d24a97d0b98f8b54bce6b481a380a6590df992d0098f868ad54dc8f688 + name: flutter_secure_storage_darwin + sha256: "8878c25136a79def1668c75985e8e193d9d7d095453ec28730da0315dc69aee3" url: "https://pub.dev" source: hosted - version: "1.2.3" - flutter_secure_storage_macos: + version: "0.2.0" + flutter_secure_storage_linux: dependency: transitive description: - name: flutter_secure_storage_macos - sha256: "6c0a2795a2d1de26ae202a0d78527d163f4acbb11cde4c75c670f3a0fc064247" + name: flutter_secure_storage_linux + sha256: "2b5c76dce569ab752d55a1cee6a2242bcc11fdba927078fb88c503f150767cda" url: "https://pub.dev" source: hosted - version: "3.1.3" + version: "3.0.0" flutter_secure_storage_platform_interface: dependency: transitive description: name: flutter_secure_storage_platform_interface - sha256: cf91ad32ce5adef6fba4d736a542baca9daf3beac4db2d04be350b87f69ac4a8 + sha256: "8ceea1223bee3c6ac1a22dabd8feefc550e4729b3675de4b5900f55afcb435d6" url: "https://pub.dev" source: hosted - version: "1.1.2" + version: "2.0.1" flutter_secure_storage_web: dependency: transitive description: name: flutter_secure_storage_web - sha256: f4ebff989b4f07b2656fb16b47852c0aab9fed9b4ec1c70103368337bc1886a9 + sha256: "6a1137df62b84b54261dca582c1c09ea72f4f9a4b2fcee21b025964132d5d0c3" url: "https://pub.dev" source: hosted - version: "1.2.1" + version: "2.1.0" flutter_secure_storage_windows: dependency: transitive description: name: flutter_secure_storage_windows - sha256: b20b07cb5ed4ed74fc567b78a72936203f587eba460af1df11281c9326cd3709 + sha256: "3b7c8e068875dfd46719ff57c90d8c459c87f2302ed6b00ff006b3c9fcad1613" url: "https://pub.dev" source: hosted - version: "3.1.2" + version: "4.1.0" flutter_test: dependency: "direct dev" description: flutter @@ -549,14 +541,22 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.1" + hooks: + dependency: transitive + description: + name: hooks + sha256: e79ed1e8e1929bc6ecb6ec85f0cb519c887aa5b423705ded0d0f2d9226def388 + url: "https://pub.dev" + source: hosted + version: "1.0.2" http: dependency: "direct main" description: name: http - sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007 + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" url: "https://pub.dev" source: hosted - version: "1.5.0" + version: "1.6.0" http_multi_server: dependency: transitive description: @@ -577,10 +577,10 @@ packages: dependency: transitive description: name: image - sha256: "4e973fcf4caae1a4be2fa0a13157aa38a8f9cb049db6529aa00b4d71abc4d928" + sha256: f9881ff4998044947ec38d098bc7c8316ae1186fa786eddffdb867b9bc94dfce url: "https://pub.dev" source: hosted - version: "4.5.4" + version: "4.8.0" intl: dependency: transitive description: @@ -601,10 +601,10 @@ packages: dependency: transitive description: name: js - sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc" url: "https://pub.dev" source: hosted - version: "0.6.7" + version: "0.7.2" json_annotation: dependency: "direct main" description: @@ -657,50 +657,50 @@ packages: dependency: transitive description: name: lints - sha256: a5e2b223cb7c9c8efdc663ef484fdd95bb243bff242ef5b13e26883547fce9a0 + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" url: "https://pub.dev" source: hosted - version: "6.0.0" + version: "6.1.0" local_auth: dependency: "direct main" description: name: local_auth - sha256: "434d854cf478f17f12ab29a76a02b3067f86a63a6d6c4eb8fbfdcfe4879c1b7b" + sha256: ae6f382f638108c6becd134318d7c3f0a93875383a54010f61d7c97ac05d5137 url: "https://pub.dev" source: hosted - version: "2.3.0" + version: "3.0.1" local_auth_android: dependency: transitive description: name: local_auth_android - sha256: "1ee0e63fb8b5c6fa286796b5fb1570d256857c2f4a262127e728b36b80a570cf" + sha256: b41970749c2d43791790724b76917eeee1e90de76e6b0eec3edca03a329bf44c url: "https://pub.dev" source: hosted - version: "1.0.53" + version: "2.0.7" local_auth_darwin: dependency: transitive description: name: local_auth_darwin - sha256: "699873970067a40ef2f2c09b4c72eb1cfef64224ef041b3df9fdc5c4c1f91f49" + sha256: a8c3d4e17454111f7fd31ff72a31222359f6059f7fe956c2dcfe0f88f49826d4 url: "https://pub.dev" source: hosted - version: "1.6.1" + version: "2.0.3" local_auth_platform_interface: dependency: transitive description: name: local_auth_platform_interface - sha256: "1b842ff177a7068442eae093b64abe3592f816afd2a533c0ebcdbe40f9d2075a" + sha256: f98b8e388588583d3f781f6806e4f4c9f9e189d898d27f0c249b93a1973dd122 url: "https://pub.dev" source: hosted - version: "1.0.10" + version: "1.1.0" local_auth_windows: dependency: transitive description: name: local_auth_windows - sha256: bc4e66a29b0fdf751aafbec923b5bed7ad6ed3614875d8151afe2578520b2ab5 + sha256: be12c5b8ba5e64896983123655c5f67d2484ecfcc95e367952ad6e3bff94cb16 url: "https://pub.dev" source: hosted - version: "1.0.11" + version: "2.0.1" logging: dependency: transitive description: @@ -713,26 +713,26 @@ packages: dependency: transitive description: name: matcher - sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 url: "https://pub.dev" source: hosted - version: "0.12.17" + version: "0.12.19" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" url: "https://pub.dev" source: hosted - version: "0.11.1" + version: "0.13.0" meta: dependency: transitive description: name: meta - sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" url: "https://pub.dev" source: hosted - version: "1.16.0" + version: "1.17.0" mime: dependency: transitive description: @@ -745,10 +745,18 @@ packages: dependency: "direct main" description: name: mobile_scanner - sha256: "5e7e09d904dc01de071b79b3f3789b302b0ed3c9c963109cd3f83ad90de62ecf" + sha256: c92c26bf2231695b6d3477c8dcf435f51e28f87b1745966b1fe4c47a286171ce + url: "https://pub.dev" + source: hosted + version: "7.2.0" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: "6ba77bb18063eebe9de401f5e6437e95e1438af0a87a3a39084fbd37c90df572" url: "https://pub.dev" source: hosted - version: "7.1.2" + version: "0.17.6" nested: dependency: transitive description: @@ -757,6 +765,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.0" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: "100a1c87616ab6ed41ec263b083c0ef3261ee6cd1dc3b0f35f8ddfa4f996fe52" + url: "https://pub.dev" + source: hosted + version: "9.3.0" package_config: dependency: transitive description: @@ -793,18 +809,18 @@ packages: dependency: transitive description: name: path_provider_android - sha256: "993381400e94d18469750e5b9dcb8206f15bc09f9da86b9e44a9b0092a0066db" + sha256: "149441ca6e4f38193b2e004c0ca6376a3d11f51fa5a77552d8bd4d2b0c0912ba" url: "https://pub.dev" source: hosted - version: "2.2.18" + version: "2.2.23" path_provider_foundation: dependency: transitive description: name: path_provider_foundation - sha256: "16eef174aacb07e09c351502740fa6254c165757638eba1e9116b0a781201bbd" + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" url: "https://pub.dev" source: hosted - version: "2.4.2" + version: "2.6.0" path_provider_linux: dependency: transitive description: @@ -833,10 +849,10 @@ packages: dependency: transitive description: name: petitparser - sha256: "1a97266a94f7350d30ae522c0af07890c70b8e62c71e8e3920d1db4d23c057d1" + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" url: "https://pub.dev" source: hosted - version: "7.0.1" + version: "7.0.2" platform: dependency: transitive description: @@ -873,10 +889,10 @@ packages: dependency: transitive description: name: posix - sha256: "6323a5b0fa688b6a010df4905a56b00181479e6d10534cecfecede2aa55add61" + sha256: "185ef7606574f789b40f289c233efa52e96dead518aed988e040a10737febb07" url: "https://pub.dev" source: hosted - version: "6.0.3" + version: "6.5.0" provider: dependency: "direct main" description: @@ -905,34 +921,34 @@ packages: dependency: "direct main" description: name: qr_code_scanner_plus - sha256: a0f1ac8e13299b3db2646635f252fe2ec67222b848b24ed34d11052faf080bfa + sha256: dae0596b2763c2fd0294f5cfddb1d3a21577ae4dc7fc1449eb5aafc957872f61 url: "https://pub.dev" source: hosted - version: "2.0.12" + version: "2.1.1" shared_preferences: dependency: transitive description: name: shared_preferences - sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5" + sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf url: "https://pub.dev" source: hosted - version: "2.5.3" + version: "2.5.5" shared_preferences_android: dependency: transitive description: name: shared_preferences_android - sha256: bd14436108211b0d4ee5038689a56d4ae3620fd72fd6036e113bf1345bc74d9e + sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53 url: "https://pub.dev" source: hosted - version: "2.4.13" + version: "2.4.23" shared_preferences_foundation: dependency: transitive description: name: shared_preferences_foundation - sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03" + sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f" url: "https://pub.dev" source: hosted - version: "2.5.4" + version: "2.5.6" shared_preferences_linux: dependency: transitive description: @@ -945,10 +961,10 @@ packages: dependency: transitive description: name: shared_preferences_platform_interface - sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9" url: "https://pub.dev" source: hosted - version: "2.4.1" + version: "2.4.2" shared_preferences_web: dependency: transitive description: @@ -1006,10 +1022,10 @@ packages: dependency: transitive description: name: source_span - sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" url: "https://pub.dev" source: hosted - version: "1.10.1" + version: "1.10.2" sprintf: dependency: "direct main" description: @@ -1062,18 +1078,18 @@ packages: dependency: transitive description: name: test_api - sha256: "522f00f556e73044315fa4585ec3270f1808a4b186c936e612cab0b565ff1e00" + sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a" url: "https://pub.dev" source: hosted - version: "0.7.6" + version: "0.7.10" timezone: dependency: transitive description: name: timezone - sha256: dd14a3b83cfd7cb19e7888f1cbc20f258b8d71b54c06f79ac585f14093a287d1 + sha256: "784a5e34d2eb62e1326f24d6f600aaaee452eb8ca8ef2f384a59244e292d158b" url: "https://pub.dev" source: hosted - version: "0.10.1" + version: "0.11.0" timing: dependency: transitive description: @@ -1102,34 +1118,34 @@ packages: dependency: transitive description: name: url_launcher_android - sha256: "199bc33e746088546a39cc5f36bac5a278c5e53b40cb3196f99e7345fdcfae6b" + sha256: "3bb000251e55d4a209aa0e2e563309dc9bb2befea2295fd0cec1f51760aac572" url: "https://pub.dev" source: hosted - version: "6.3.22" + version: "6.3.29" url_launcher_ios: dependency: transitive description: name: url_launcher_ios - sha256: d80b3f567a617cb923546034cc94bfe44eb15f989fe670b37f26abdb9d939cb7 + sha256: "580fe5dfb51671ae38191d316e027f6b76272b026370708c2d898799750a02b0" url: "https://pub.dev" source: hosted - version: "6.3.4" + version: "6.4.1" url_launcher_linux: dependency: transitive description: name: url_launcher_linux - sha256: "4e9ba368772369e3e08f231d2301b4ef72b9ff87c31192ef471b380ef29a4935" + sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a url: "https://pub.dev" source: hosted - version: "3.2.1" + version: "3.2.2" url_launcher_macos: dependency: transitive description: name: url_launcher_macos - sha256: c043a77d6600ac9c38300567f33ef12b0ef4f4783a2c1f00231d2b1941fea13f + sha256: "368adf46f71ad3c21b8f06614adb38346f193f3a59ba8fe9a2fd74133070ba18" url: "https://pub.dev" source: hosted - version: "3.2.3" + version: "3.2.5" url_launcher_platform_interface: dependency: transitive description: @@ -1142,18 +1158,18 @@ packages: dependency: transitive description: name: url_launcher_web - sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2" + sha256: d0412fcf4c6b31ecfdb7762359b7206ffba3bbffd396c6d9f9c4616ece476c1f url: "https://pub.dev" source: hosted - version: "2.4.1" + version: "2.4.2" url_launcher_windows: dependency: transitive description: name: url_launcher_windows - sha256: "3284b6d2ac454cf34f114e1d3319866fdd1e19cdc329999057e44ffe936cfa77" + sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f" url: "https://pub.dev" source: hosted - version: "3.1.4" + version: "3.1.5" vector_math: dependency: transitive description: @@ -1166,10 +1182,10 @@ packages: dependency: "direct main" description: name: vibration - sha256: "1fd51cb0f91c6d512734ca0e282dd87fbc7f389b6da5f03c77709ba2cf8fa901" + sha256: "9bb06614c69260f8bd11c80fe01ed7988905cf00e3417d656c2647e41f261d87" url: "https://pub.dev" source: hosted - version: "3.1.4" + version: "3.1.8" vibration_platform_interface: dependency: transitive description: @@ -1190,10 +1206,10 @@ packages: dependency: transitive description: name: watcher - sha256: "5bf046f41320ac97a469d506261797f35254fa61c641741ef32dacda98b7d39c" + sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" url: "https://pub.dev" source: hosted - version: "1.1.3" + version: "1.2.1" web: dependency: transitive description: @@ -1240,10 +1256,10 @@ packages: dependency: transitive description: name: win32 - sha256: "66814138c3562338d05613a6e368ed8cfb237ad6d64a9e9334be3f309acfca03" + sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e url: "https://pub.dev" source: hosted - version: "5.14.0" + version: "5.15.0" win32_registry: dependency: transitive description: @@ -1277,5 +1293,5 @@ packages: source: hosted version: "3.1.3" sdks: - dart: ">=3.9.0 <4.0.0" - flutter: ">=3.35.0" + dart: ">=3.10.3 <4.0.0" + flutter: ">=3.38.4" diff --git a/pubspec.yaml b/pubspec.yaml index ff69205..1ab7f25 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -21,14 +21,14 @@ dependencies: sdk: flutter flutter_colorpicker: ^1.1.0 flutter_launcher_icons: ^0.14.3 - flutter_local_notifications: ^19.2.1 - flutter_secure_storage: ^9.2.4 + flutter_local_notifications: ^21.0.0 + flutter_secure_storage: ^10.0.0 fluttertoast: ^9.0.0 hive: ^2.2.3 http: ^1.2.1 json_annotation: ^4.9.0 jwt_decoder: ^2.0.1 - local_auth: ^2.3.0 + local_auth: ^3.0.1 mobile_scanner: ^7.0.0 page_transition: ^2.2.1 path_provider: ^2.1.3 From d43c02dc45d7d72bdd940e1c6919bf432e7b32e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 5 May 2026 20:50:13 +0200 Subject: [PATCH 005/181] Upgrade Android Gradle plugin, configure Java home, and update project dependencies --- android/gradle.properties | 1 + android/settings.gradle.kts | 2 +- linux/flutter/generated_plugins.cmake | 1 + pubspec.lock | 80 +++++++++++++++++---------- 4 files changed, 55 insertions(+), 29 deletions(-) diff --git a/android/gradle.properties b/android/gradle.properties index f018a61..d0e3d2b 100644 --- a/android/gradle.properties +++ b/android/gradle.properties @@ -1,3 +1,4 @@ +org.gradle.java.home=/usr/lib/jvm/java-21-openjdk org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError android.useAndroidX=true android.enableJetifier=true diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts index bd7522f..c4b6403 100644 --- a/android/settings.gradle.kts +++ b/android/settings.gradle.kts @@ -18,7 +18,7 @@ pluginManagement { plugins { id("dev.flutter.flutter-plugin-loader") version "1.0.0" - id("com.android.application") version "8.7.3" apply false + id("com.android.application") version "8.9.1" apply false // START: FlutterFire Configuration id("com.google.gms.google-services") version("4.3.15") apply false // END: FlutterFire Configuration diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index 65240e9..7e7bd77 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -8,6 +8,7 @@ list(APPEND FLUTTER_PLUGIN_LIST ) list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni ) set(PLUGIN_BUNDLED_LIBRARIES) diff --git a/pubspec.lock b/pubspec.lock index bff702d..beead8c 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -13,10 +13,10 @@ packages: dependency: transitive description: name: _flutterfire_internals - sha256: f698de6eb8a0dd7a9a931bbfe13568e8b77e702eb2deb13dd83480c5373e7746 + sha256: bda3b7b55958bfd867addc40d067b4b11f7b8846d57671f5b5a6e7f9a56fe3ad url: "https://pub.dev" source: hosted - version: "1.3.68" + version: "1.3.69" analyzer: dependency: transitive description: @@ -133,10 +133,10 @@ packages: dependency: transitive description: name: built_value - sha256: "0730c18c770d05636a8f945c32a4d7d81cb6e0f0148c8db4ad12e7748f7e49af" + sha256: "34e4067d30ce212937df995f03b69992eea683539ceeac7f679a1f1eba055b56" url: "https://pub.dev" source: hosted - version: "8.12.5" + version: "8.12.6" characters: dependency: transitive description: @@ -221,10 +221,10 @@ packages: dependency: "direct main" description: name: dart_jsonwebtoken - sha256: cb79ed79baa02b4f59a597bf365873cbd83f9bb15273d63f7803802d21717c7d + sha256: ad84e60181696513d04d5f2078e0bbc20365b911f46f647797317414bdc88fbe url: "https://pub.dev" source: hosted - version: "3.4.0" + version: "3.4.1" dart_style: dependency: transitive description: @@ -309,10 +309,10 @@ packages: dependency: "direct main" description: name: firebase_core - sha256: "2f988dab915efde3b3105268dbd69efce0e8570d767a218ccd914afd0c10c8cc" + sha256: d5a94b884dcb1e6d3430298e94bfe002238094cdfd5e29202d536ee2120f9158 url: "https://pub.dev" source: hosted - version: "4.6.0" + version: "4.7.0" firebase_core_platform_interface: dependency: transitive description: @@ -325,34 +325,34 @@ packages: dependency: transitive description: name: firebase_core_web - sha256: "1399ab1f0ac3b503d8a9be64a4c997fc066bbf33f701f42866e5569f26205ebe" + sha256: dc5096257cd67292d34d78ceeb90836f02a4be921b5f3934311a02bb2376118c url: "https://pub.dev" source: hosted - version: "3.5.1" + version: "3.6.0" firebase_messaging: dependency: "direct main" description: name: firebase_messaging - sha256: "8dc372085b1647f05e3ec1b8bc1dada87c0062f93b2a6976f620eb85edc44f97" + sha256: e5c93e8e7a9b0513f94bb684d2cf100e32e7dcdf2949574386b1955fc9a9b96a url: "https://pub.dev" source: hosted - version: "16.1.3" + version: "16.2.0" firebase_messaging_platform_interface: dependency: transitive description: name: firebase_messaging_platform_interface - sha256: "6ea10f7df747542b17679d5939213c09163aab9c301b2f9b858cb55f38efdb54" + sha256: "8cbb7d842e5071bba836452aff262f7db4b14bb3a0d00c1896cf176df886d65a" url: "https://pub.dev" source: hosted - version: "4.7.8" + version: "4.7.9" firebase_messaging_web: dependency: transitive description: name: firebase_messaging_web - sha256: "1f9798c8021ccf22b7e43e7fba81becd42252cb168228379fcabb7c2ef7dd638" + sha256: "8750bacf50573c0383535fc3f9c58c6a2f9dff5320a16a82c30631b9dad894f1" url: "https://pub.dev" source: hosted - version: "4.1.4" + version: "4.1.5" fixnum: dependency: transitive description: @@ -545,10 +545,10 @@ packages: dependency: transitive description: name: hooks - sha256: e79ed1e8e1929bc6ecb6ec85f0cb519c887aa5b423705ded0d0f2d9226def388 + sha256: "025f060e86d2d4c3c47b56e33caf7f93bf9283340f26d23424ebcfccf34f621e" url: "https://pub.dev" source: hosted - version: "1.0.2" + version: "1.0.3" http: dependency: "direct main" description: @@ -597,6 +597,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.5" + jni: + dependency: transitive + description: + name: jni + sha256: c2230682d5bc2362c1c9e8d3c7f406d9cbba23ab3f2e203a025dd47e0fb2e68f + url: "https://pub.dev" + source: hosted + version: "1.0.0" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "8b59e590786050b1cd866677dddaf76b1ade5e7bc751abe04b86e84d379d3ba6" + url: "https://pub.dev" + source: hosted + version: "1.0.1" js: dependency: transitive description: @@ -673,10 +689,10 @@ packages: dependency: transitive description: name: local_auth_android - sha256: b41970749c2d43791790724b76917eeee1e90de76e6b0eec3edca03a329bf44c + sha256: b201c006fa769c23386f89aa6837ec0eb8179fcfb212eadcf87b422b3f9a6a78 url: "https://pub.dev" source: hosted - version: "2.0.7" + version: "2.0.8" local_auth_darwin: dependency: transitive description: @@ -809,10 +825,10 @@ packages: dependency: transitive description: name: path_provider_android - sha256: "149441ca6e4f38193b2e004c0ca6376a3d11f51fa5a77552d8bd4d2b0c0912ba" + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" url: "https://pub.dev" source: hosted - version: "2.2.23" + version: "2.3.1" path_provider_foundation: dependency: transitive description: @@ -925,6 +941,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.1" + record_use: + dependency: transitive + description: + name: record_use + sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + url: "https://pub.dev" + source: hosted + version: "0.6.0" shared_preferences: dependency: transitive description: @@ -1190,18 +1214,18 @@ packages: dependency: transitive description: name: vibration_platform_interface - sha256: "4134fbfcd427b59a7a91f8733292e4e9b29a7f1e8224ff0d80f5745fbf0743c6" + sha256: "258c273268f8aa40c88d29741137c536874a738779b92ddb8aa32ed093721ec5" url: "https://pub.dev" source: hosted - version: "0.1.1" + version: "0.1.2" vm_service: dependency: transitive description: name: vm_service - sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60" + sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" url: "https://pub.dev" source: hosted - version: "15.0.2" + version: "15.2.0" watcher: dependency: transitive description: @@ -1239,7 +1263,7 @@ packages: description: path: "." ref: HEAD - resolved-ref: b3511cc765cb349df2a9e7355a7dbb865145b079 + resolved-ref: d0e53878a160f2e174546a4fbb08577cfd143a85 url: "https://github.com/jsfraz/whisper_openapi_client_dart.git" source: git version: "0.0.1" @@ -1248,7 +1272,7 @@ packages: description: path: "." ref: HEAD - resolved-ref: "5e2d056568f13c1b72780d16a39d9e69bc1ce002" + resolved-ref: e7e2c398bd3da5a2813db301b94a1bc818d26bf5 url: "https://github.com/jsfraz/whisper_websocket_client_dart.git" source: git version: "1.0.0" From 0fbb429e8549a5899eac3781c47169c517a9c4e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Wed, 3 Jun 2026 16:34:32 +0200 Subject: [PATCH 006/181] Anhance QR code scanning logic in scan_invite_page.dart --- android/.gitignore | 1 + lib/pages/scan_invite_page.dart | 75 +++++++++++++++----- pubspec.lock | 120 ++++++++++++++++---------------- update.sh | 4 ++ 4 files changed, 122 insertions(+), 78 deletions(-) create mode 100755 update.sh diff --git a/android/.gitignore b/android/.gitignore index be3943c..73b6f93 100644 --- a/android/.gitignore +++ b/android/.gitignore @@ -1,5 +1,6 @@ gradle-wrapper.jar /.gradle +/build/ /captures/ /gradlew /gradlew.bat diff --git a/lib/pages/scan_invite_page.dart b/lib/pages/scan_invite_page.dart index 35009e7..dd8db36 100644 --- a/lib/pages/scan_invite_page.dart +++ b/lib/pages/scan_invite_page.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; @@ -18,33 +19,71 @@ class ScanInvitePage extends StatefulWidget { class _ScanInvitePageState extends State { final GlobalKey _qrKey = GlobalKey(); QRViewController? _qrController; + StreamSubscription? _scanSubscription; + bool _isProcessingScan = false; + final Set _shownToastForScan = {}; /// On creation of QR view void _onQRViewCreated(QRViewController controller) { _qrController = controller; - controller.scannedDataStream.listen((scanData) { - // Try to decode invite - try { - Map inviteMap = - jsonDecode(scanData.code!) as Map; - InviteData invite = InviteData.fromJson(inviteMap); - // Check if invite expired - if (invite.validUntil.difference(DateTime.now()).isNegative) { + _scanSubscription?.cancel(); + _scanSubscription = controller.scannedDataStream.listen(_onScan); + } + + bool _showScanToastOnce(String scanCode, String toastKey) { + if (!_shownToastForScan.add('$toastKey:$scanCode')) { + return false; + } + return true; + } + + Future _onScan(Barcode scanData) async { + if (_isProcessingScan || !mounted) return; + final scanCode = scanData.code; + if (scanCode == null) return; + + try { + final inviteMap = jsonDecode(scanCode) as Map; + final invite = InviteData.fromJson(inviteMap); + if (invite.validUntil.difference(DateTime.now()).isNegative) { + if (_showScanToastOnce(scanCode, 'inviteExpired')) { Fluttertoast.showToast( msg: 'inviteExpired'.tr(), - backgroundColor: Colors.red); - } else { - // Push registration page - Navigator.push(context, - MaterialPageRoute(builder: (context) => RegisterPage(invite))); - return; + backgroundColor: Colors.red, + ); } - } catch (e) { + return; + } + + _isProcessingScan = true; + await _qrController?.pauseCamera(); + if (!mounted) return; + + await Navigator.push( + context, + MaterialPageRoute(builder: (context) => RegisterPage(invite)), + ); + } catch (_) { + if (_showScanToastOnce(scanCode, 'invalidQr')) { Fluttertoast.showToast( - msg: 'invalidQr'.tr(), - backgroundColor: Colors.red); + msg: 'invalidQr'.tr(), + backgroundColor: Colors.red, + ); + } + } finally { + if (_isProcessingScan) { + _isProcessingScan = false; + if (mounted) { + await _qrController?.resumeCamera(); + } } - }); + } + } + + @override + void dispose() { + _scanSubscription?.cancel(); + super.dispose(); } @override diff --git a/pubspec.lock b/pubspec.lock index beead8c..2db2806 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -13,10 +13,10 @@ packages: dependency: transitive description: name: _flutterfire_internals - sha256: bda3b7b55958bfd867addc40d067b4b11f7b8846d57671f5b5a6e7f9a56fe3ad + sha256: "0d1f0adfabbab9f46a1a80ce84a4d8b852b6e4dbf53ce413b30e0cf7d3631b71" url: "https://pub.dev" source: hosted - version: "1.3.69" + version: "1.3.72" analyzer: dependency: transitive description: @@ -173,10 +173,10 @@ packages: dependency: transitive description: name: code_assets - sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687" + sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8 url: "https://pub.dev" source: hosted - version: "1.0.0" + version: "1.2.1" code_builder: dependency: transitive description: @@ -245,18 +245,18 @@ packages: dependency: transitive description: name: device_info_plus - sha256: b4fed1b2835da9d670d7bed7db79ae2a94b0f5ad6312268158a9b5479abbacdd + sha256: "6a642e1daa10190af89ba6cb6386c0df7d071a3592080bfe1e44faa63ae1df65" url: "https://pub.dev" source: hosted - version: "12.4.0" + version: "13.1.0" device_info_plus_platform_interface: dependency: transitive description: name: device_info_plus_platform_interface - sha256: e1ea89119e34903dca74b883d0dd78eb762814f97fb6c76f35e9ff74d261a18f + sha256: "04b173a92e2d9161dfead145667037c8d834db725ce2e7b942bfe18fd2f45a46" url: "https://pub.dev" source: hosted - version: "7.0.3" + version: "8.1.0" easy_localization: dependency: "direct main" description: @@ -297,6 +297,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" + ffi_leak_tracker: + dependency: transitive + description: + name: ffi_leak_tracker + sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" + url: "https://pub.dev" + source: hosted + version: "0.1.2" file: dependency: transitive description: @@ -309,50 +317,50 @@ packages: dependency: "direct main" description: name: firebase_core - sha256: d5a94b884dcb1e6d3430298e94bfe002238094cdfd5e29202d536ee2120f9158 + sha256: ec46a100a560d3bd5f97f2d89ba7492cb09b6dd0a4a28753d1258f360d6bd9f9 url: "https://pub.dev" source: hosted - version: "4.7.0" + version: "4.10.0" firebase_core_platform_interface: dependency: transitive description: name: firebase_core_platform_interface - sha256: "0ecda14c1bfc9ed8cac303dd0f8d04a320811b479362a9a4efb14fd331a473ce" + sha256: "4a120366dbf7d5a8ee9438978530b664b855728fb8dcc3a201017660817e555b" url: "https://pub.dev" source: hosted - version: "6.0.3" + version: "7.0.1" firebase_core_web: dependency: transitive description: name: firebase_core_web - sha256: dc5096257cd67292d34d78ceeb90836f02a4be921b5f3934311a02bb2376118c + sha256: "5ad1be848692ec148f2d6a8ad2a3838cb852ea5f3c9e6479a7afce479e1854f8" url: "https://pub.dev" source: hosted - version: "3.6.0" + version: "3.8.0" firebase_messaging: dependency: "direct main" description: name: firebase_messaging - sha256: e5c93e8e7a9b0513f94bb684d2cf100e32e7dcdf2949574386b1955fc9a9b96a + sha256: "9651e833454156b9f0927eaedccffba0f7f6a6e20ceddef82517211e7017e9c4" url: "https://pub.dev" source: hosted - version: "16.2.0" + version: "16.3.0" firebase_messaging_platform_interface: dependency: transitive description: name: firebase_messaging_platform_interface - sha256: "8cbb7d842e5071bba836452aff262f7db4b14bb3a0d00c1896cf176df886d65a" + sha256: "292bb5dc9c4a429078895406c347d7c7690deb858c1adeed8f4b4346f769dfa3" url: "https://pub.dev" source: hosted - version: "4.7.9" + version: "4.8.0" firebase_messaging_web: dependency: transitive description: name: firebase_messaging_web - sha256: "8750bacf50573c0383535fc3f9c58c6a2f9dff5320a16a82c30631b9dad894f1" + sha256: "08c565bc83729439f5de2dfea77b4832002b705eb2f840366cefa80e4e5c3c66" url: "https://pub.dev" source: hosted - version: "4.1.5" + version: "4.2.0" fixnum: dependency: transitive description: @@ -431,34 +439,34 @@ packages: dependency: transitive description: name: flutter_plugin_android_lifecycle - sha256: "38d1c268de9097ff59cf0e844ac38759fc78f76836d37edad06fa21e182055a0" + sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785" url: "https://pub.dev" source: hosted - version: "2.0.34" + version: "2.0.35" flutter_secure_storage: dependency: "direct main" description: name: flutter_secure_storage - sha256: da922f2aab2d733db7e011a6bcc4a825b844892d4edd6df83ff156b09a9b2e40 + sha256: "7686b1d6a29985dcbb808c59518226e603e3bfa7c0ddfd1a0d00e4cda77c868e" url: "https://pub.dev" source: hosted - version: "10.0.0" + version: "10.3.1" flutter_secure_storage_darwin: dependency: transitive description: name: flutter_secure_storage_darwin - sha256: "8878c25136a79def1668c75985e8e193d9d7d095453ec28730da0315dc69aee3" + sha256: "82329fa5cdf343773b1b6897dea959105a29f092454259edff92f9f6637e8149" url: "https://pub.dev" source: hosted - version: "0.2.0" + version: "0.3.2" flutter_secure_storage_linux: dependency: transitive description: name: flutter_secure_storage_linux - sha256: "2b5c76dce569ab752d55a1cee6a2242bcc11fdba927078fb88c503f150767cda" + sha256: a5f35ddab43cf5c8215d2feb4ce1957851f28c5c37e6f04335066a0602087bf5 url: "https://pub.dev" source: hosted - version: "3.0.0" + version: "3.0.1" flutter_secure_storage_platform_interface: dependency: transitive description: @@ -471,18 +479,18 @@ packages: dependency: transitive description: name: flutter_secure_storage_web - sha256: "6a1137df62b84b54261dca582c1c09ea72f4f9a4b2fcee21b025964132d5d0c3" + sha256: "073a62b3aeb866ab4ce795f960413948e51e5a42a9b0c8333b6daf5bb3208a1c" url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "2.1.1" flutter_secure_storage_windows: dependency: transitive description: name: flutter_secure_storage_windows - sha256: "3b7c8e068875dfd46719ff57c90d8c459c87f2302ed6b00ff006b3c9fcad1613" + sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1" url: "https://pub.dev" source: hosted - version: "4.1.0" + version: "4.2.2" flutter_test: dependency: "direct dev" description: flutter @@ -497,10 +505,10 @@ packages: dependency: "direct main" description: name: fluttertoast - sha256: "144ddd74d49c865eba47abe31cbc746c7b311c82d6c32e571fd73c4264b740e2" + sha256: "7903c9d5339173497bfecbc23bc4212f5a87e0edfac2e1693fb74465ea67da7e" url: "https://pub.dev" source: hosted - version: "9.0.0" + version: "9.1.0" frontend_server_client: dependency: transitive description: @@ -545,10 +553,10 @@ packages: dependency: transitive description: name: hooks - sha256: "025f060e86d2d4c3c47b56e33caf7f93bf9283340f26d23424ebcfccf34f621e" + sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba" url: "https://pub.dev" source: hosted - version: "1.0.3" + version: "2.0.2" http: dependency: "direct main" description: @@ -765,14 +773,6 @@ packages: url: "https://pub.dev" source: hosted version: "7.2.0" - native_toolchain_c: - dependency: transitive - description: - name: native_toolchain_c - sha256: "6ba77bb18063eebe9de401f5e6437e95e1438af0a87a3a39084fbd37c90df572" - url: "https://pub.dev" - source: hosted - version: "0.17.6" nested: dependency: transitive description: @@ -785,10 +785,10 @@ packages: dependency: transitive description: name: objective_c - sha256: "100a1c87616ab6ed41ec263b083c0ef3261ee6cd1dc3b0f35f8ddfa4f996fe52" + sha256: "6cb691c686fa2838c6deb34980d426145c2a5d537491cb83d463c33cdbc726ed" url: "https://pub.dev" source: hosted - version: "9.3.0" + version: "9.4.1" package_config: dependency: transitive description: @@ -801,10 +801,10 @@ packages: dependency: "direct main" description: name: page_transition - sha256: "9d2a780d7d68b53ae82fbcc43e06a16195e6775e9aae40e55dc0cbb593460f9d" + sha256: "61dac670e80ebdd7da847c21841e1dfd8f9ab483b3a0c5fddc877ad8d23b69ee" url: "https://pub.dev" source: hosted - version: "2.2.1" + version: "2.2.2" path: dependency: transitive description: @@ -1142,10 +1142,10 @@ packages: dependency: transitive description: name: url_launcher_android - sha256: "3bb000251e55d4a209aa0e2e563309dc9bb2befea2295fd0cec1f51760aac572" + sha256: "17bc677f0b301615530dd1d67e0a9828cafa2d0b6b6eae4cd3679b7eac4a273c" url: "https://pub.dev" source: hosted - version: "6.3.29" + version: "6.3.30" url_launcher_ios: dependency: transitive description: @@ -1182,10 +1182,10 @@ packages: dependency: transitive description: name: url_launcher_web - sha256: d0412fcf4c6b31ecfdb7762359b7206ffba3bbffd396c6d9f9c4616ece476c1f + sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34" url: "https://pub.dev" source: hosted - version: "2.4.2" + version: "2.4.3" url_launcher_windows: dependency: transitive description: @@ -1263,7 +1263,7 @@ packages: description: path: "." ref: HEAD - resolved-ref: d0e53878a160f2e174546a4fbb08577cfd143a85 + resolved-ref: fe1e740bba5505d14b0ec0086166b38271b3c153 url: "https://github.com/jsfraz/whisper_openapi_client_dart.git" source: git version: "0.0.1" @@ -1272,7 +1272,7 @@ packages: description: path: "." ref: HEAD - resolved-ref: e7e2c398bd3da5a2813db301b94a1bc818d26bf5 + resolved-ref: "94cedcaeac9b85a90eb1671c2da42962b6e2cf20" url: "https://github.com/jsfraz/whisper_websocket_client_dart.git" source: git version: "1.0.0" @@ -1280,18 +1280,18 @@ packages: dependency: transitive description: name: win32 - sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + sha256: ba6f4bba816c8d7e3c1580e170f3786d216951cc6b94babc3b814c08d2cb2738 url: "https://pub.dev" source: hosted - version: "5.15.0" + version: "6.3.0" win32_registry: dependency: transitive description: name: win32_registry - sha256: "6f1b564492d0147b330dd794fee8f512cec4977957f310f9951b5f9d83618dae" + sha256: "73b1d78920a9d6e03f8b4e43e612b87bf3152a0e5c5e5150267762b7c4116904" url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "3.0.3" xdg_directories: dependency: transitive description: @@ -1317,5 +1317,5 @@ packages: source: hosted version: "3.1.3" sdks: - dart: ">=3.10.3 <4.0.0" - flutter: ">=3.38.4" + dart: ">=3.11.0 <4.0.0" + flutter: ">=3.41.0" diff --git a/update.sh b/update.sh new file mode 100755 index 0000000..cf9eb01 --- /dev/null +++ b/update.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +flutter pub get +flutter pub upgrade --major-versions From debe0cb5a060f2a78b7f1e01fdaa6c9eb6e31462 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Wed, 3 Jun 2026 19:08:37 +0200 Subject: [PATCH 007/181] Media test --- android/app/src/main/AndroidManifest.xml | 10 + assets/translations/cs.json | 21 +- assets/translations/en.json | 21 +- ios/Runner/Info.plist | 6 + lib/models/invite_data.g.dart | 1 - lib/models/private_message.dart | 102 ++++- lib/models/private_message.g.dart | 28 +- lib/pages/chat_page.dart | 428 +++++++++++++++++-- lib/pages/media_viewer_page.dart | 137 ++++++ lib/utils/cache_utils.dart | 43 ++ lib/utils/media_utils.dart | 423 ++++++++++++++++++ lib/utils/message_notifier.dart | 66 +++ lib/utils/notification_service.dart | 4 +- lib/utils/singleton.dart | 2 + lib/utils/utils.dart | 44 +- lib/widgets/chat_bubble.dart | 44 +- lib/widgets/chat_list_item.dart | 26 +- lib/widgets/media_bubble.dart | 305 +++++++++++++ lib/widgets/voice_player.dart | 182 ++++++++ linux/flutter/generated_plugin_registrant.cc | 8 + linux/flutter/generated_plugins.cmake | 2 + pubspec.lock | 382 +++++++++++++++-- pubspec.yaml | 14 +- 23 files changed, 2209 insertions(+), 90 deletions(-) create mode 100644 lib/pages/media_viewer_page.dart create mode 100644 lib/utils/media_utils.dart create mode 100644 lib/widgets/media_bubble.dart create mode 100644 lib/widgets/voice_player.dart diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index bfe4c25..e276e5f 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -2,6 +2,16 @@ + + + + + + + + + UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight + NSCameraUsageDescription + Whisper needs camera access to capture photos and videos you send in chats. + NSMicrophoneUsageDescription + Whisper needs microphone access to record voice messages. + NSPhotoLibraryUsageDescription + Whisper needs photo library access to attach images and videos to your messages. CADisableMinimumFrameDurationOnPhone UIApplicationSupportsIndirectInputEvents diff --git a/lib/models/invite_data.g.dart b/lib/models/invite_data.g.dart index 383e75d..86b0ef2 100644 --- a/lib/models/invite_data.g.dart +++ b/lib/models/invite_data.g.dart @@ -12,7 +12,6 @@ InviteData _$InviteDataFromJson(Map json) => InviteData( DateTime.parse(json['validUntil'] as String), ); -// ignore: unused_element Map _$InviteDataToJson(InviteData instance) => { 'url': instance.url, diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index d17289c..3511ff6 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -1,9 +1,23 @@ +import 'package:easy_localization/easy_localization.dart'; import 'package:hive/hive.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../utils/singleton.dart'; part 'private_message.g.dart'; +/// Download status of a media attachment stored locally. +class MediaDownloadStatus { + /// Not yet downloaded/decrypted (recipient side, in progress). + static const int pending = 0; + + /// Downloaded, decrypted and stored encrypted-at-rest locally. + static const int ready = 1; + + /// Download or decryption failed; can be retried. + static const int failed = 2; +} + @HiveType(typeId: 3) class PrivateMessage extends HiveObject { @HiveField(0) @@ -17,9 +31,93 @@ class PrivateMessage extends HiveObject { @HiveField(4) bool read; - PrivateMessage(this.senderId, this.message, this.sentAt, this.receivedAt, this.read); + // Media attachment fields (all null for plain text messages). + + /// Server-side media id (used for download/confirm). May be null once the + /// file has been confirmed/deleted on the server but kept locally. + @HiveField(5) + String? mediaId; + + /// [MediaType.name] of the attachment, or null for text messages. + @HiveField(6) + String? mediaTypeStr; + + /// Absolute path to the encrypted-at-rest media file on the device. + @HiveField(7) + String? localPath; + + /// Size of the original (plaintext) media in bytes. + @HiveField(8) + int? mediaSize; + + /// Optional pixel width (images, gifs, videos). + @HiveField(9) + int? width; + + /// Optional pixel height (images, gifs, videos). + @HiveField(10) + int? height; + + /// Optional duration in milliseconds (videos, voice messages). + @HiveField(11) + int? durationMs; + + /// Download status, see [MediaDownloadStatus]. Defaults to ready (sent media). + @HiveField(12, defaultValue: MediaDownloadStatus.ready) + int downloadStatus; + + PrivateMessage( + this.senderId, + this.message, + this.sentAt, + this.receivedAt, + this.read, { + this.mediaId, + this.mediaTypeStr, + this.localPath, + this.mediaSize, + this.width, + this.height, + this.durationMs, + this.downloadStatus = MediaDownloadStatus.ready, + }); bool get isMe => senderId == Singleton().profile.user.id; int get notificationId => receivedAt.microsecondsSinceEpoch % 0x7FFFFFFF; -} \ No newline at end of file + + /// Whether this message carries a media attachment. + bool get isMedia => mediaTypeStr != null; + + /// The decoded [MediaType] of the attachment, or null for text messages. + MediaType? get mediaType { + if (mediaTypeStr == null) { + return null; + } + try { + return MediaType.values.byName(mediaTypeStr!); + } catch (_) { + return null; + } + } + + /// Short text used in chat list previews and notifications. Falls back to a + /// localized media label when a media message has no caption. + String get preview { + if (!isMedia || message.isNotEmpty) { + return message; + } + switch (mediaType) { + case MediaType.image: + return 'mediaPhoto'.tr(); + case MediaType.gif: + return 'mediaGif'.tr(); + case MediaType.video: + return 'mediaVideo'.tr(); + case MediaType.voice: + return 'mediaVoice'.tr(); + case null: + return message; + } + } +} diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index 63de9c4..ed67492 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -22,13 +22,21 @@ class PrivateMessageAdapter extends TypeAdapter { fields[2] as DateTime, fields[3] as DateTime, fields[4] as bool, + mediaId: fields[5] as String?, + mediaTypeStr: fields[6] as String?, + localPath: fields[7] as String?, + mediaSize: fields[8] as int?, + width: fields[9] as int?, + height: fields[10] as int?, + durationMs: fields[11] as int?, + downloadStatus: fields[12] == null ? 1 : fields[12] as int, ); } @override void write(BinaryWriter writer, PrivateMessage obj) { writer - ..writeByte(5) + ..writeByte(13) ..writeByte(0) ..write(obj.senderId) ..writeByte(1) @@ -38,7 +46,23 @@ class PrivateMessageAdapter extends TypeAdapter { ..writeByte(3) ..write(obj.receivedAt) ..writeByte(4) - ..write(obj.read); + ..write(obj.read) + ..writeByte(5) + ..write(obj.mediaId) + ..writeByte(6) + ..write(obj.mediaTypeStr) + ..writeByte(7) + ..write(obj.localPath) + ..writeByte(8) + ..write(obj.mediaSize) + ..writeByte(9) + ..write(obj.width) + ..writeByte(10) + ..write(obj.height) + ..writeByte(11) + ..write(obj.durationMs) + ..writeByte(12) + ..write(obj.downloadStatus); } @override diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 0b8e8af..39e7cb7 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1,17 +1,23 @@ +import 'dart:async'; import 'dart:convert'; +import 'dart:io'; import 'dart:typed_data'; import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; +import 'package:http/http.dart' show MultipartFile; import 'package:page_transition/page_transition.dart'; import 'package:provider/provider.dart'; +import 'package:whisper_websocket_client_dart/models/media_reference.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; import 'package:whisper_websocket_client_dart/models/new_private_message.dart'; import 'package:whisper_websocket_client_dart/models/ws_message.dart'; import '../models/private_message.dart'; import '../models/user.dart'; import '../utils/cache_utils.dart'; import '../utils/crypto_utils.dart'; +import '../utils/media_utils.dart'; import '../utils/message_notifier.dart'; import '../utils/singleton.dart'; import '../utils/utils.dart'; @@ -40,6 +46,12 @@ class _ChatPageState extends State { final ScrollController _scrollController = ScrollController(); // Indicates whether messages are being load for the first time bool _firstLoad = true; + // Voice recording state + bool _isRecording = false; + bool _cancelRecording = false; + MediaRecorderController? _recorderController; + Duration _recordDuration = Duration.zero; + Timer? _recordTimer; @override void initState() { @@ -122,6 +134,390 @@ class _ChatPageState extends State { }); } + /// Send a media attachment: encrypt for transport, upload, embed an encrypted + /// reference in the message, store the file encrypted-at-rest and add an + /// optimistic bubble. + Future _sendMedia(MediaType type, File file, + {String caption = '', int? durationMs}) async { + setState(() { + _isSending = true; + }); + try { + final bytes = await file.readAsBytes(); + + // Probe metadata depending on the media type. + int? width; + int? height; + int? duration = durationMs; + if (type == MediaType.image || type == MediaType.gif) { + final probe = await MediaUtils.imageDimensions(bytes); + width = probe.width; + height = probe.height; + } else if (type == MediaType.video) { + final probe = await MediaUtils.videoMetadata(file.path); + width = probe.width; + height = probe.height; + duration ??= probe.durationMs; + } + + await Utils.wsConnect(); + if (!Singleton().wsClient.isConnected) { + await Fluttertoast.showToast( + msg: 'wsOffline'.tr(), backgroundColor: Colors.red); + return; + } + + // Transport encryption with an ephemeral per-file key. + final transport = await MediaUtils.encryptForTransport(bytes); + + // Upload the ciphertext over HTTP. + final uploadResponse = await Utils.callApi( + () => Singleton().mediaApi.uploadMedia( + widget.user.id, + MultipartFile.fromBytes('file', transport.blob, + filename: 'media.bin'), + ), + rethrowErr: true, + ); + if (uploadResponse == null || uploadResponse.id == null) { + await Fluttertoast.showToast( + msg: 'mediaUploadFailed'.tr(), backgroundColor: Colors.red); + return; + } + final mediaId = uploadResponse.id!; + + // Build the encrypted reference and wrap it in the message envelope. + final reference = MediaReference( + mediaId, + transport.key, + type, + transport.blob.length, + width: width, + height: height, + durationMs: duration, + ); + final envelope = MediaUtils.buildMediaEnvelope(reference, caption); + + // E2E-encrypt the envelope for the recipient. + final data = await CryptoUtils.encryptMessageData( + envelope, bu.CryptoUtils.rsaPublicKeyFromPem(widget.user.publicKey)); + + // Send over the WebSocket. + final sentAt = Singleton().wsClient.sendMessage(WsMessage.privateMessage( + NewPrivateMessage(widget.user.id, data['encryptedData']!, + data['encryptedKey']!, data['nonce']!, data['mac']!))); + + // Persist the recipient if needed. + if (widget.user.publicKey != '' && + widget.user.username != '' && + !widget.user.isInBox) { + CacheUtils.addUser(widget.user); + } + + // Store the original media encrypted-at-rest for our own bubble. + final localPath = await MediaUtils.encryptAtRest(bytes); + + // Optimistic local message. + await MessageNotifier().addMessages(widget.user.id, [ + PrivateMessage( + Singleton().profile.user.id, + caption, + sentAt, + sentAt, + true, + mediaId: mediaId, + mediaTypeStr: type.name, + localPath: localPath, + mediaSize: bytes.length, + width: width, + height: height, + durationMs: duration, + downloadStatus: MediaDownloadStatus.ready, + ) + ]); + + // The caption (taken from the text field) was consumed -> clear it. + if (caption.isNotEmpty && _controllerMessage.text == caption) { + _controllerMessage.text = ''; + await CacheUtils.deleteMessageConcept(widget.user.id); + } + } catch (e) { + await Fluttertoast.showToast( + msg: e.toString(), backgroundColor: Colors.red); + } finally { + if (mounted) { + setState(() { + _isSending = false; + }); + } + } + } + + /// Pick media using [picker], detect its type (unless [forcedType] is set) + /// and send it, using any typed text as the caption. + Future _pickAndSend( + Future Function() picker, MediaType? forcedType) async { + try { + final file = await picker(); + if (file == null) { + return; + } + final type = forcedType ?? MediaUtils.detectType(file.path); + final caption = _controllerMessage.text.trim(); + await _sendMedia(type, file, caption: caption); + } catch (e) { + await Fluttertoast.showToast( + msg: e.toString(), backgroundColor: Colors.red); + } + } + + /// Show the attachment options bottom sheet. + void _showAttachSheet() { + showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (ctx) { + return SafeArea( + child: Wrap( + children: [ + ListTile( + leading: const Icon(Icons.photo_camera), + title: Text('attachCamera'.tr()), + onTap: () { + Navigator.pop(ctx); + _pickAndSend( + MediaUtils.pickImageFromCamera, MediaType.image); + }, + ), + ListTile( + leading: const Icon(Icons.videocam), + title: Text('attachVideoCamera'.tr()), + onTap: () { + Navigator.pop(ctx); + _pickAndSend( + MediaUtils.pickVideoFromCamera, MediaType.video); + }, + ), + ListTile( + leading: const Icon(Icons.photo_library), + title: Text('attachGallery'.tr()), + onTap: () { + Navigator.pop(ctx); + _pickAndSend(MediaUtils.pickMediaFromGallery, null); + }, + ), + ListTile( + leading: const Icon(Icons.gif_box), + title: Text('attachGif'.tr()), + onTap: () { + Navigator.pop(ctx); + _pickAndSend(MediaUtils.pickGif, MediaType.gif); + }, + ), + ListTile( + leading: const Icon(Icons.insert_drive_file), + title: Text('attachFile'.tr()), + onTap: () { + Navigator.pop(ctx); + _pickAndSend(MediaUtils.pickFile, null); + }, + ), + ], + ), + ); + }, + ); + } + + /// Start recording a voice message (hold-to-record). + Future _startRecording() async { + if (_isRecording || _isSending) { + return; + } + final controller = MediaRecorderController(); + if (!await controller.hasPermission()) { + await controller.dispose(); + await Fluttertoast.showToast( + msg: 'micPermissionDenied'.tr(), backgroundColor: Colors.red); + return; + } + try { + await controller.start(); + } catch (e) { + await controller.dispose(); + await Fluttertoast.showToast( + msg: e.toString(), backgroundColor: Colors.red); + return; + } + setState(() { + _recorderController = controller; + _isRecording = true; + _cancelRecording = false; + _recordDuration = Duration.zero; + }); + _recordTimer = Timer.periodic(const Duration(seconds: 1), (_) { + if (mounted) { + setState(() { + _recordDuration += const Duration(seconds: 1); + }); + } + }); + } + + /// Finish recording and send (unless the gesture was cancelled). + Future _stopRecording() async { + _recordTimer?.cancel(); + _recordTimer = null; + final controller = _recorderController; + _recorderController = null; + final cancelled = _cancelRecording; + setState(() { + _isRecording = false; + }); + if (controller == null) { + return; + } + if (cancelled) { + await controller.cancel(); + await controller.dispose(); + return; + } + final recorded = await controller.stop(); + await controller.dispose(); + if (recorded == null) { + return; + } + // Ignore accidental taps that produce a near-empty recording. + if (recorded.durationMs < 800) { + await MediaUtils.deleteLocalFile(recorded.file.path); + await Fluttertoast.showToast( + msg: 'voiceTooShort'.tr(), backgroundColor: Colors.orange); + return; + } + await _sendMedia(MediaType.voice, recorded.file, + durationMs: recorded.durationMs); + } + + String _formatRecordDuration(Duration d) { + final minutes = d.inMinutes.remainder(60).toString().padLeft(2, '0'); + final seconds = d.inSeconds.remainder(60).toString().padLeft(2, '0'); + return '$minutes:$seconds'; + } + + /// Default message input bar (attach + text field + mic/send). + Widget _buildInputBar() { + return Row( + children: [ + IconButton( + icon: const Icon(Icons.add), + tooltip: 'attachButton'.tr(), + onPressed: _isSending ? null : _showAttachSheet, + ), + Expanded( + child: Padding( + padding: const EdgeInsets.only(right: 5, left: 5), + child: TextField( + controller: _controllerMessage, + minLines: 1, + maxLines: 5, + textInputAction: TextInputAction.newline, + decoration: InputDecoration( + hintText: 'yourMessage'.tr(), + filled: true, + fillColor: Theme.of(context).brightness == Brightness.dark + ? Theme.of(context).colorScheme.surfaceBright + : Theme.of(context).colorScheme.surfaceDim, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(30), + borderSide: BorderSide.none, + ), + suffixIcon: ValueListenableBuilder( + valueListenable: _controllerMessage, + builder: (context, value, _) { + final hasText = value.text.trim().isNotEmpty; + if (hasText) { + return IconButton( + onPressed: _isSending ? null : _sendMessage, + icon: const Icon(Icons.send), + ); + } + // Hold-to-record voice message. + return GestureDetector( + onLongPressStart: (_) { + if (!_isSending) { + _startRecording(); + } + }, + onLongPressMoveUpdate: (details) { + final shouldCancel = + details.localOffsetFromOrigin.dx < -80; + if (shouldCancel != _cancelRecording) { + setState(() { + _cancelRecording = shouldCancel; + }); + } + }, + onLongPressEnd: (_) { + if (_isRecording) { + _stopRecording(); + } + }, + child: IconButton( + onPressed: _isSending + ? null + : () async { + await Fluttertoast.showToast( + msg: 'holdToRecord'.tr()); + }, + icon: const Icon(Icons.mic), + ), + ); + }, + ), + ), + ), + ), + ), + ], + ); + } + + /// Bar shown while recording a voice message. + Widget _buildRecordingBar() { + final color = + _cancelRecording ? Colors.red : Theme.of(context).colorScheme.primary; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + decoration: BoxDecoration( + color: Theme.of(context).brightness == Brightness.dark + ? Theme.of(context).colorScheme.surfaceBright + : Theme.of(context).colorScheme.surfaceDim, + borderRadius: BorderRadius.circular(30), + ), + child: Row( + children: [ + Icon(Icons.mic, color: color), + const SizedBox(width: 8), + Text(_formatRecordDuration(_recordDuration)), + const SizedBox(width: 16), + Expanded( + child: Text( + _cancelRecording + ? 'releaseToCancel'.tr() + : 'slideToCancel'.tr(), + style: TextStyle(color: Colors.grey[600]), + overflow: TextOverflow.ellipsis, + ), + ), + Icon( + _cancelRecording ? Icons.delete : Icons.arrow_back, + color: color, + ), + ], + ), + ); + } + /// Get ListView with content ListView _getContent(List messages) { _firstLoad = false; @@ -182,6 +578,8 @@ class _ChatPageState extends State { @override void dispose() { + _recordTimer?.cancel(); + _recorderController?.dispose(); _controllerMessage.dispose(); _scrollController.dispose(); super.dispose(); @@ -295,35 +693,7 @@ class _ChatPageState extends State { top: false, child: Padding( padding: const EdgeInsets.all(8.0), - child: Row( - children: [ - Expanded( - child: Padding( - padding: EdgeInsets.only(right: 5, left: 5), - // TODO certically expandable text field - child: TextField( - controller: _controllerMessage, - decoration: InputDecoration( - hintText: 'yourMessage'.tr(), - filled: true, - fillColor: Theme.of(context).brightness == - Brightness.dark - ? Theme.of(context).colorScheme.surfaceBright - : Theme.of(context).colorScheme.surfaceDim, - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(30), - borderSide: BorderSide.none, - ), - suffixIcon: IconButton( - onPressed: _isSending ? null : _sendMessage, - icon: const Icon(Icons.send), - ), - ), - ), - ), - ), - ], - ), + child: _isRecording ? _buildRecordingBar() : _buildInputBar(), ), ), ], diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart new file mode 100644 index 0000000..d1a10ca --- /dev/null +++ b/lib/pages/media_viewer_page.dart @@ -0,0 +1,137 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:chewie/chewie.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:video_player/video_player.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +import '../utils/media_utils.dart'; + +/// Fullscreen viewer for an image/gif or video stored encrypted-at-rest. +class MediaViewerPage extends StatefulWidget { + final String localPath; + final MediaType type; + final String? caption; + + const MediaViewerPage({ + required this.localPath, + required this.type, + this.caption, + super.key, + }); + + @override + State createState() => _MediaViewerPageState(); +} + +class _MediaViewerPageState extends State { + Uint8List? _imageBytes; + VideoPlayerController? _videoController; + ChewieController? _chewieController; + File? _tempFile; + bool _loading = true; + bool _error = false; + + bool get _isVideo => widget.type == MediaType.video; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + try { + if (_isVideo) { + _tempFile = await MediaUtils.materializeTempFile( + widget.localPath, MediaUtils.extensionForType(widget.type)); + final controller = VideoPlayerController.file(_tempFile!); + await controller.initialize(); + _videoController = controller; + _chewieController = ChewieController( + videoPlayerController: controller, + autoPlay: true, + looping: false, + allowFullScreen: true, + ); + } else { + _imageBytes = await MediaUtils.decryptAtRest(widget.localPath); + } + if (mounted) { + setState(() { + _loading = false; + }); + } + } catch (_) { + if (mounted) { + setState(() { + _loading = false; + _error = true; + }); + } + } + } + + @override + void dispose() { + _chewieController?.dispose(); + _videoController?.dispose(); + MediaUtils.deleteLocalFile(_tempFile?.path); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + backgroundColor: Colors.black, + foregroundColor: Colors.white, + iconTheme: const IconThemeData(color: Colors.white), + ), + body: Center( + child: _buildBody(), + ), + bottomNavigationBar: + (widget.caption != null && widget.caption!.isNotEmpty) + ? Container( + color: Colors.black, + padding: const EdgeInsets.all(16), + child: SafeArea( + top: false, + child: Text( + widget.caption!, + style: const TextStyle(color: Colors.white), + ), + ), + ) + : null, + ); + } + + Widget _buildBody() { + if (_loading) { + return const CircularProgressIndicator(); + } + if (_error) { + return Text('mediaError'.tr(), + style: const TextStyle(color: Colors.white)); + } + if (_isVideo && _chewieController != null) { + return AspectRatio( + aspectRatio: _videoController!.value.aspectRatio, + child: Chewie(controller: _chewieController!), + ); + } + if (_imageBytes != null) { + return InteractiveViewer( + minScale: 0.5, + maxScale: 4, + child: Image.memory(_imageBytes!, fit: BoxFit.contain), + ); + } + return Text('mediaError'.tr(), style: const TextStyle(color: Colors.white)); + } +} diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 9739e5d..7e29678 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -5,6 +5,7 @@ import '../models/app_theme.dart'; import '../models/private_message.dart'; import '../models/profile.dart'; import '../models/user.dart'; +import 'media_utils.dart'; import 'singleton.dart'; import 'utils.dart'; @@ -92,6 +93,8 @@ class CacheUtils { } Box biometryBox = await _openBiometryBox(); await biometryBox.deleteFromDisk(); + // Remove every locally stored media file. + await MediaUtils.clearMediaDir(); } /// Opens box with theme @@ -162,12 +165,50 @@ class CacheUtils { /// Delete user messages static Future deletePrivateMessagesWithUser(int userId) async { Box messageBox = await _openPrivateMessagesBox(); + // Delete on-disk media files for this conversation first. + await _deleteMediaFilesForUser(userId); await messageBox.delete(userId); Box userBox = await _openUserBox(); await userBox.delete(userId); await deleteMessageConcept(userId); } + /// Delete the encrypted-at-rest media files of all messages with [userId]. + static Future _deleteMediaFilesForUser(int userId) async { + final messages = await getPrivateMessages(userId); + for (final msg in messages) { + if (msg.localPath != null) { + await MediaUtils.deleteLocalFile(msg.localPath); + } + } + } + + /// Update the local media state of a stored message (download progress). + static Future updatePrivateMessageMedia(int userId, String mediaId, + {String? localPath, int? downloadStatus}) async { + Box box = await _openPrivateMessagesBox(); + List? messages = box.get(userId); + if (messages == null) { + return; + } + bool changed = false; + for (final dynamic m in messages) { + final msg = m as PrivateMessage; + if (msg.mediaId == mediaId) { + if (localPath != null) { + msg.localPath = localPath; + } + if (downloadStatus != null) { + msg.downloadStatus = downloadStatus; + } + changed = true; + } + } + if (changed) { + await box.put(userId, messages); + } + } + /// Opens box with users static Future _openUserBox() async { return Hive.openBox(_userKey); @@ -215,6 +256,8 @@ class CacheUtils { await userBox.clear(); await messageBox.clear(); await conceptBox.clear(); + // Remove every locally stored media file. + await MediaUtils.clearMediaDir(); } /// Opens box with message concepts diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart new file mode 100644 index 0000000..6f76bef --- /dev/null +++ b/lib/utils/media_utils.dart @@ -0,0 +1,423 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:cryptography/cryptography.dart' as cryptography; +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/foundation.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:mime/mime.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:record/record.dart'; +import 'package:uuid/uuid.dart'; +import 'package:video_player/video_player.dart'; +import 'package:whisper_websocket_client_dart/models/media_reference.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +import 'singleton.dart'; +import 'utils.dart'; + +/// Result of encrypting a file for transport: the uploadable [blob] +/// (`nonce || mac || ciphertext`) and the ephemeral symmetric [key] that goes +/// into the [MediaReference]. +class TransportEncryption { + final Uint8List blob; + final Uint8List key; + + const TransportEncryption(this.blob, this.key); +} + +/// Metadata extracted from a media file before sending. +class MediaProbe { + final int? width; + final int? height; + final int? durationMs; + + const MediaProbe({this.width, this.height, this.durationMs}); +} + +/// Arguments passed to the AES-GCM compute() workers. +class _GcmArgs { + final Uint8List data; + final Uint8List key; + + const _GcmArgs(this.data, this.key); +} + +/// AES-GCM nonce length (bytes). +const int _nonceLength = 12; + +/// AES-GCM MAC length (bytes). +const int _macLength = 16; + +/// Encrypt [data] with AES-256-GCM and return `nonce || mac || ciphertext`. +/// Top-level so it can run in a background isolate via [compute]. +Future _gcmEncrypt(_GcmArgs args) async { + final algorithm = cryptography.AesGcm.with256bits(); + final secretKey = cryptography.SecretKey(args.key); + final box = await algorithm.encrypt(args.data, secretKey: secretKey); + final nonce = box.nonce; + final mac = box.mac.bytes; + final out = Uint8List(nonce.length + mac.length + box.cipherText.length); + out.setRange(0, nonce.length, nonce); + out.setRange(nonce.length, nonce.length + mac.length, mac); + out.setRange(nonce.length + mac.length, out.length, box.cipherText); + return out; +} + +/// Decrypt a `nonce || mac || ciphertext` blob produced by [_gcmEncrypt]. +Future _gcmDecrypt(_GcmArgs args) async { + final blob = args.data; + final nonce = blob.sublist(0, _nonceLength); + final mac = blob.sublist(_nonceLength, _nonceLength + _macLength); + final cipher = blob.sublist(_nonceLength + _macLength); + final algorithm = cryptography.AesGcm.with256bits(); + final secretKey = cryptography.SecretKey(args.key); + final box = cryptography.SecretBox( + cipher, + nonce: nonce, + mac: cryptography.Mac(mac), + ); + final clear = await algorithm.decrypt(box, secretKey: secretKey); + return Uint8List.fromList(clear); +} + +/// Central helper for media attachments: transport + at-rest encryption, +/// pickers, the voice recorder, and metadata/thumbnail extraction. +/// +/// Two independent encryption layers are used (keys never leave the device +/// unencrypted): +/// * Transport: a random per-file AES-256-GCM key encrypts the bytes that are +/// uploaded to the server. The key travels (RSA+AES wrapped) inside the +/// message [MediaReference]. +/// * At-rest: downloaded/sent plaintext is re-encrypted with the app master +/// key ([Singleton.boxCollectionKey]) and stored on disk. +class MediaUtils { + MediaUtils._(); + + static const Uuid _uuid = Uuid(); + static final ImagePicker _imagePicker = ImagePicker(); + + /// Version marker used by the media message envelope. + static const int envelopeVersion = 1; + + // --------------------------------------------------------------------------- + // Transport encryption + // --------------------------------------------------------------------------- + + /// Encrypt [bytes] with a fresh random key for upload. + static Future encryptForTransport(Uint8List bytes) async { + final algorithm = cryptography.AesGcm.with256bits(); + final secretKey = await algorithm.newSecretKey(); + final keyBytes = Uint8List.fromList(await secretKey.extractBytes()); + final blob = await compute(_gcmEncrypt, _GcmArgs(bytes, keyBytes)); + return TransportEncryption(blob, keyBytes); + } + + /// Decrypt a downloaded [blob] using the transport [key] from the reference. + static Future decryptTransport(Uint8List blob, Uint8List key) { + return compute(_gcmDecrypt, _GcmArgs(blob, key)); + } + + // --------------------------------------------------------------------------- + // At-rest encryption (local persistence) + // --------------------------------------------------------------------------- + + /// Encrypt plaintext [bytes] with the app master key and write them to the + /// media directory. Returns the absolute path of the stored encrypted file. + static Future encryptAtRest(Uint8List bytes) async { + final key = Uint8List.fromList(Singleton().boxCollectionKey); + final blob = await compute(_gcmEncrypt, _GcmArgs(bytes, key)); + final dir = await mediaDir(); + final path = '$dir/${_uuid.v4()}'; + await File(path).writeAsBytes(blob, flush: true); + return path; + } + + /// Decrypt an at-rest file written by [encryptAtRest]. + static Future decryptAtRest(String path) async { + final blob = await File(path).readAsBytes(); + final key = Uint8List.fromList(Singleton().boxCollectionKey); + return compute(_gcmDecrypt, _GcmArgs(blob, key)); + } + + /// Decrypt an at-rest file into a temporary plaintext file (for the platform + /// video/audio players). The caller is responsible for deleting it on dispose. + static Future materializeTempFile(String path, String extension) async { + final bytes = await decryptAtRest(path); + final tmpDir = await getTemporaryDirectory(); + final file = File('${tmpDir.path}/whisper_media_${_uuid.v4()}$extension'); + await file.writeAsBytes(bytes, flush: true); + return file; + } + + // --------------------------------------------------------------------------- + // Filesystem helpers + // --------------------------------------------------------------------------- + + /// Directory where encrypted-at-rest media files live. + static Future mediaDir() async { + final dir = '${await Utils.getCacheDir()}/media'; + await Directory(dir).create(recursive: true); + return dir; + } + + /// Delete a single (encrypted) media file, ignoring errors. + static Future deleteLocalFile(String? path) async { + if (path == null) { + return; + } + try { + final file = File(path); + if (await file.exists()) { + await file.delete(); + } + } catch (e) { + if (kDebugMode) { + debugPrint('Failed to delete media file $path: $e'); + } + } + } + + /// Remove every locally stored media file (used on full cache wipe). + static Future clearMediaDir() async { + try { + final dir = Directory('${await Utils.getCacheDir()}/media'); + if (await dir.exists()) { + await dir.delete(recursive: true); + } + } catch (e) { + if (kDebugMode) { + debugPrint('Failed to clear media dir: $e'); + } + } + } + + // --------------------------------------------------------------------------- + // Type detection & extensions + // --------------------------------------------------------------------------- + + /// Detect the [MediaType] of a file from its mime type / extension. + static MediaType detectType(String path, {String? mimeType}) { + final mime = mimeType ?? lookupMimeType(path) ?? ''; + final lower = path.toLowerCase(); + if (mime == 'image/gif' || lower.endsWith('.gif')) { + return MediaType.gif; + } + if (mime.startsWith('video/')) { + return MediaType.video; + } + if (mime.startsWith('audio/')) { + return MediaType.voice; + } + return MediaType.image; + } + + /// Default file extension used when materializing a temp file for playback. + static String extensionForType(MediaType type) { + switch (type) { + case MediaType.image: + return '.jpg'; + case MediaType.gif: + return '.gif'; + case MediaType.video: + return '.mp4'; + case MediaType.voice: + return '.m4a'; + } + } + + /// Translation key for a short human label of a media type (used in previews + /// and notifications). + static String labelKeyForType(MediaType type) { + switch (type) { + case MediaType.image: + return 'mediaPhoto'; + case MediaType.gif: + return 'mediaGif'; + case MediaType.video: + return 'mediaVideo'; + case MediaType.voice: + return 'mediaVoice'; + } + } + + // --------------------------------------------------------------------------- + // Metadata & thumbnails + // --------------------------------------------------------------------------- + + /// Decode the pixel dimensions of an encoded image (png/jpg/gif/webp). + static Future imageDimensions(Uint8List bytes) async { + try { + final codec = await ui.instantiateImageCodec(bytes); + final frame = await codec.getNextFrame(); + final image = frame.image; + final probe = MediaProbe(width: image.width, height: image.height); + image.dispose(); + codec.dispose(); + return probe; + } catch (_) { + return const MediaProbe(); + } + } + + /// Read width/height/duration of a video by briefly initializing a controller. + static Future videoMetadata(String filePath) async { + final controller = VideoPlayerController.file(File(filePath)); + try { + await controller.initialize(); + final size = controller.value.size; + final duration = controller.value.duration; + return MediaProbe( + width: size.width.round(), + height: size.height.round(), + durationMs: duration.inMilliseconds, + ); + } catch (_) { + return const MediaProbe(); + } finally { + await controller.dispose(); + } + } + + // --------------------------------------------------------------------------- + // Message envelope codec + // --------------------------------------------------------------------------- + + /// Build the plaintext (pre-encryption) bytes for a media message: a JSON + /// envelope wrapping the [reference] and optional [caption]. + static Uint8List buildMediaEnvelope(MediaReference reference, String caption) { + final map = { + 'whisperMsg': envelopeVersion, + 'kind': 'media', + 'caption': caption, + 'media': reference.toJson(), + }; + return Uint8List.fromList(utf8.encode(jsonEncode(map))); + } + + /// Try to parse decrypted [plaintext] as a media envelope. Returns null when + /// the bytes are not a media envelope (i.e. a plain text message). + static ParsedMediaEnvelope? tryParseMediaEnvelope(Uint8List plaintext) { + try { + final decoded = jsonDecode(utf8.decode(plaintext)); + if (decoded is Map && + decoded['whisperMsg'] == envelopeVersion && + decoded['kind'] == 'media' && + decoded['media'] is Map) { + final reference = MediaReference.fromJson( + Map.from(decoded['media'] as Map)); + final caption = (decoded['caption'] as String?) ?? ''; + return ParsedMediaEnvelope(reference, caption); + } + } catch (_) { + // Not JSON / not a media envelope -> treat as plain text. + } + return null; + } + + // --------------------------------------------------------------------------- + // Pickers + // --------------------------------------------------------------------------- + + /// Capture a photo with the camera. + static Future pickImageFromCamera() async { + final picked = await _imagePicker.pickImage( + source: ImageSource.camera, imageQuality: 85); + return picked == null ? null : File(picked.path); + } + + /// Capture a video with the camera. + static Future pickVideoFromCamera() async { + final picked = await _imagePicker.pickVideo( + source: ImageSource.camera, + maxDuration: const Duration(minutes: 1)); + return picked == null ? null : File(picked.path); + } + + /// Pick a single image or video from the gallery. + static Future pickMediaFromGallery() async { + final picked = await _imagePicker.pickMedia(); + return picked == null ? null : File(picked.path); + } + + /// Pick a GIF file. + static Future pickGif() async { + final result = await FilePicker.platform.pickFiles( + type: FileType.custom, + allowedExtensions: const ['gif'], + ); + final path = result?.files.single.path; + return path == null ? null : File(path); + } + + /// Pick an arbitrary media (image/video) file. + static Future pickFile() async { + final result = await FilePicker.platform.pickFiles(type: FileType.media); + final path = result?.files.single.path; + return path == null ? null : File(path); + } +} + +/// Parsed media envelope: a [MediaReference] plus its caption. +class ParsedMediaEnvelope { + final MediaReference reference; + final String caption; + + const ParsedMediaEnvelope(this.reference, this.caption); +} + +/// Thin wrapper around the [AudioRecorder] for hold-to-record voice messages. +class MediaRecorderController { + final AudioRecorder _recorder = AudioRecorder(); + String? _path; + DateTime? _startedAt; + + Future hasPermission() => _recorder.hasPermission(); + + /// Start recording to a temporary .m4a file. + Future start() async { + final dir = await getTemporaryDirectory(); + _path = '${dir.path}/whisper_voice_${const Uuid().v4()}.m4a'; + await _recorder.start( + const RecordConfig(encoder: AudioEncoder.aacLc, numChannels: 1), + path: _path!, + ); + _startedAt = DateTime.now(); + } + + /// Stop recording and return the resulting file and its duration. + Future stop() async { + final path = await _recorder.stop(); + final durationMs = + _startedAt == null ? 0 : DateTime.now().difference(_startedAt!).inMilliseconds; + if (path == null) { + return null; + } + return RecordedVoice(File(path), durationMs); + } + + /// Abort recording and discard the partial file. + Future cancel() async { + try { + await _recorder.stop(); + } catch (_) { + // ignore + } + await MediaUtils.deleteLocalFile(_path); + } + + /// Live amplitude stream for the recording UI. + Stream amplitudeStream() => + _recorder.onAmplitudeChanged(const Duration(milliseconds: 200)); + + Future dispose() => _recorder.dispose(); +} + +/// A finished voice recording. +class RecordedVoice { + final File file; + final int durationMs; + + const RecordedVoice(this.file, this.durationMs); +} diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index ca451a8..f588f30 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -1,9 +1,11 @@ import 'package:flutter/material.dart'; +import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import '../utils/notification_service.dart'; import '../models/private_message.dart'; import '../models/user.dart'; import 'cache_utils.dart'; +import 'media_utils.dart'; import 'singleton.dart'; import 'utils.dart'; @@ -17,6 +19,70 @@ class MessageNotifier extends ChangeNotifier { MessageNotifier._internal(); + /// In-memory map of media references awaiting (or having failed) download, + /// keyed by media id. The transport key is intentionally never persisted to + /// disk, so tap-to-retry only works within the current session. + final Map _pendingMediaRefs = {}; + + /// Download, decrypt, store and confirm an incoming media attachment. + /// + /// The encrypted file is fetched over HTTP, decrypted with the transport key + /// from [reference], re-encrypted at rest with the app master key and the + /// owning message is updated. On success the server copy is confirmed (and + /// thus deleted); on failure the message is marked as failed for retry. + Future downloadMediaMessage( + int conversationUserId, MediaReference reference) async { + _pendingMediaRefs[reference.mediaId] = reference; + try { + final blob = await Utils.callApi( + () => Singleton().mediaApi.downloadMedia(reference.mediaId), + rethrowErr: true, + ); + if (blob == null) { + throw Exception('empty media download'); + } + final plaintext = + await MediaUtils.decryptTransport(blob, reference.key); + final localPath = await MediaUtils.encryptAtRest(plaintext); + await CacheUtils.updatePrivateMessageMedia( + conversationUserId, + reference.mediaId, + localPath: localPath, + downloadStatus: MediaDownloadStatus.ready, + ); + _pendingMediaRefs.remove(reference.mediaId); + notifyListeners(); + // Confirm receipt so the server can delete its copy. + await Utils.callApi( + () => Singleton().mediaApi.confirmMediaDownload(reference.mediaId)); + } catch (_) { + await CacheUtils.updatePrivateMessageMedia( + conversationUserId, + reference.mediaId, + downloadStatus: MediaDownloadStatus.failed, + ); + notifyListeners(); + } + } + + /// Retry a previously failed media download (current session only). + Future retryMediaDownload(int conversationUserId, String mediaId) async { + final reference = _pendingMediaRefs[mediaId]; + if (reference == null) { + return; + } + await CacheUtils.updatePrivateMessageMedia( + conversationUserId, + mediaId, + downloadStatus: MediaDownloadStatus.pending, + ); + notifyListeners(); + await downloadMediaMessage(conversationUserId, reference); + } + + /// Whether a failed media download can be retried this session. + bool canRetryMedia(String mediaId) => _pendingMediaRefs.containsKey(mediaId); + /// Add messages to cache Future addMessages(int userId, List messages) async { // Check if users exist diff --git a/lib/utils/notification_service.dart b/lib/utils/notification_service.dart index cbc0112..4c81049 100644 --- a/lib/utils/notification_service.dart +++ b/lib/utils/notification_service.dart @@ -72,7 +72,7 @@ class NotificationService { // Sort messages userMessages.sort((a, b) => b.receivedAt.compareTo(a.receivedAt)); return userMessages - .map((message) => '${user.username}: ${message.message}'); + .map((message) => '${user.username}: ${message.preview}'); }) .toList() .reversed @@ -130,7 +130,7 @@ class NotificationService { await _flutterLocalNotificationsPlugin.show( id: message.notificationId, title: user.username, - body: message.message, + body: message.preview, notificationDetails: platformChannelSpecifics, ); } diff --git a/lib/utils/singleton.dart b/lib/utils/singleton.dart index 7e81fbf..edd1037 100644 --- a/lib/utils/singleton.dart +++ b/lib/utils/singleton.dart @@ -66,5 +66,7 @@ class Singleton { FirebaseApi get firebaseApi => FirebaseApi(_api); + MediaApi get mediaApi => MediaApi(_api); + bool get offlineMode => _offlineMode; } diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index d4c304b..2342882 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -13,11 +13,13 @@ import '../utils/notification_service.dart'; import '../pages/chat_page.dart'; import 'package:whisper_openapi_client_dart/api.dart'; import 'package:basic_utils/basic_utils.dart' as bu; +import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import 'package:whisper_websocket_client_dart/models/private_message.dart'; import 'package:whisper_websocket_client_dart/models/ws_response.dart'; import 'package:whisper_websocket_client_dart/models/ws_response_type.dart'; import 'cache_utils.dart'; import 'crypto_utils.dart'; +import 'media_utils.dart'; import 'message_notifier.dart'; import 'singleton.dart'; import '../models/private_message.dart' as pm; @@ -148,6 +150,8 @@ class Utils { var messages = wsResponse.payload as List; messages.sort((a, b) => a.sentAt.compareTo(b.sentAt)); List decryptedMessages = []; + // Media references that still need to be downloaded after persisting. + List pendingMediaRefs = []; // Parallel decrypt all messages try { @@ -160,12 +164,35 @@ class Utils { message.mac, bu.CryptoUtils.rsaPrivateKeyFromPem( Singleton().profile.privateKey)); - return pm.PrivateMessage( + // Media message: decode the envelope and create a placeholder. + final envelope = + MediaUtils.tryParseMediaEnvelope(decryptedMessage); + if (envelope != null) { + final ref = envelope.reference; + final mediaMsg = pm.PrivateMessage( + message.senderId, + envelope.caption, + message.sentAt, + DateTime.now(), + false, + mediaId: ref.mediaId, + mediaTypeStr: ref.type.name, + mediaSize: ref.size, + width: ref.width, + height: ref.height, + durationMs: ref.durationMs, + downloadStatus: pm.MediaDownloadStatus.pending, + ); + return (mediaMsg, ref); + } + // Plain text message (legacy/unchanged path). + final textMsg = pm.PrivateMessage( message.senderId, utf8.decode(decryptedMessage), message.sentAt, DateTime.now(), false); + return (textMsg, null); } catch (e) { // Log individual message decryption errors if (kDebugMode) { @@ -179,7 +206,11 @@ class Utils { final results = await Future.wait(decryptionTasks); // Filter out failed decryptions (null values) - decryptedMessages = results.whereType().toList(); + final valid = + results.whereType<(pm.PrivateMessage, MediaReference?)>().toList(); + decryptedMessages = valid.map((e) => e.$1).toList(); + pendingMediaRefs = + valid.map((e) => e.$2).whereType().toList(); // Show toast only if all messages failed to decrypt if (decryptedMessages.isEmpty && messages.isNotEmpty) { @@ -191,8 +222,15 @@ class Utils { msg: 'decryptionFailed'.tr(), backgroundColor: Colors.red); } if (decryptedMessages.isNotEmpty) { + final conversationUserId = decryptedMessages.first.senderId; await MessageNotifier() - .addMessages(decryptedMessages.first.senderId, decryptedMessages); + .addMessages(conversationUserId, decryptedMessages); + + // Kick off media downloads now that placeholders are persisted. + for (final ref in pendingMediaRefs) { + // Fire-and-forget; updates the message + notifies on completion. + MessageNotifier().downloadMediaMessage(conversationUserId, ref); + } // Remove messages from notifications if user was not online when they were sent decryptedMessages.removeWhere((x) => !messages diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 6776d04..35d3146 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -2,6 +2,8 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import '../models/user.dart'; import '../models/private_message.dart'; +import '../utils/message_notifier.dart'; +import 'media_bubble.dart'; // TODO show options on bottom on holding the widget (like in Messenger - copy etc) class ChatBubble extends StatefulWidget { @@ -216,21 +218,37 @@ class _ChatBubbleState extends State { ), ), */ - Container( - decoration: BoxDecoration( - color: bubbleBackground(), - borderRadius: BorderRadius.circular(20), - ), - padding: const EdgeInsets.symmetric( - horizontal: 16, vertical: 10), - child: Text( - widget.message.message, - style: TextStyle( - color: bubbleTextColor(), + if (widget.message.isMedia) + MediaBubble( + message: widget.message, + bubbleColor: bubbleBackground(), + textColor: bubbleTextColor(), + canRetry: widget.message.mediaId != null && + MessageNotifier() + .canRetryMedia(widget.message.mediaId!), + onRetry: () { + if (widget.message.mediaId != null) { + MessageNotifier().retryMediaDownload( + widget.user.id, widget.message.mediaId!); + } + }, + ) + else + Container( + decoration: BoxDecoration( + color: bubbleBackground(), + borderRadius: BorderRadius.circular(20), + ), + padding: const EdgeInsets.symmetric( + horizontal: 16, vertical: 10), + child: Text( + widget.message.message, + style: TextStyle( + color: bubbleTextColor(), + ), + softWrap: true, ), - softWrap: true, ), - ), ], ), ), diff --git a/lib/widgets/chat_list_item.dart b/lib/widgets/chat_list_item.dart index 3ef7b93..a28944a 100644 --- a/lib/widgets/chat_list_item.dart +++ b/lib/widgets/chat_list_item.dart @@ -1,5 +1,6 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../models/user.dart'; @@ -49,9 +50,28 @@ class _ChatListItemState extends State { /// Return message with or without "me: " prefix String getTitle() { String meText = widget.lastMessage.isMe ? '${'meText'.tr()}: ' : ''; - String msg = widget.lastMessage.message.length <= 12 - ? widget.lastMessage.message - : '${widget.lastMessage.message.substring(0, 12)}...'; + // Use preview text (caption, or a localized label for media). + String preview = widget.lastMessage.preview; + // Prefix media messages with a small icon hint. + if (widget.lastMessage.isMedia) { + switch (widget.lastMessage.mediaType) { + case MediaType.image: + preview = '🖼 $preview'; + break; + case MediaType.gif: + preview = '🖼 $preview'; + break; + case MediaType.video: + preview = '🎬 $preview'; + break; + case MediaType.voice: + preview = '🎤 $preview'; + break; + case null: + break; + } + } + String msg = preview.length <= 14 ? preview : '${preview.substring(0, 14)}...'; return meText + msg; } diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart new file mode 100644 index 0000000..4bfbd3e --- /dev/null +++ b/lib/widgets/media_bubble.dart @@ -0,0 +1,305 @@ +import 'dart:typed_data'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:page_transition/page_transition.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +import '../models/private_message.dart'; +import '../pages/media_viewer_page.dart'; +import '../utils/media_utils.dart'; +import 'voice_player.dart'; + +/// Renders a media attachment inside a chat bubble: image/gif thumbnail, video +/// preview with a play overlay, or an inline voice player. Handles the +/// download/loading/failed states for incoming media. +class MediaBubble extends StatefulWidget { + final PrivateMessage message; + final Color bubbleColor; + final Color textColor; + final VoidCallback onRetry; + final bool canRetry; + + const MediaBubble({ + required this.message, + required this.bubbleColor, + required this.textColor, + required this.onRetry, + required this.canRetry, + super.key, + }); + + @override + State createState() => _MediaBubbleState(); +} + +class _MediaBubbleState extends State { + Future? _imageFuture; + + @override + void initState() { + super.initState(); + _prepareFutures(); + } + + @override + void didUpdateWidget(covariant MediaBubble oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.message.localPath != widget.message.localPath || + oldWidget.message.downloadStatus != widget.message.downloadStatus) { + _prepareFutures(); + } + } + + void _prepareFutures() { + _imageFuture = null; + final path = widget.message.localPath; + if (path == null) { + return; + } + final type = widget.message.mediaType; + if (type == MediaType.image || type == MediaType.gif) { + _imageFuture = MediaUtils.decryptAtRest(path); + } + } + + /// Constrained display size derived from the original media dimensions. + Size _displaySize() { + const maxW = 240.0; + const maxH = 320.0; + final w = widget.message.width; + final h = widget.message.height; + if (w == null || h == null || w <= 0 || h <= 0) { + return const Size(220, 220); + } + double dw = w.toDouble(); + double dh = h.toDouble(); + final scale = (maxW / dw).clamp(0.0, 1.0); + dw *= scale; + dh *= scale; + if (dh > maxH) { + final s = maxH / dh; + dh *= s; + dw *= s; + } + return Size(dw, dh); + } + + void _openViewer() { + final path = widget.message.localPath; + final type = widget.message.mediaType; + if (path == null || type == null) { + return; + } + Navigator.of(context).push( + PageTransition( + type: PageTransitionType.fade, + duration: const Duration(milliseconds: 200), + child: MediaViewerPage( + localPath: path, + type: type, + caption: widget.message.message, + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final type = widget.message.mediaType; + final hasCaption = widget.message.message.isNotEmpty; + + Widget media; + if (widget.message.downloadStatus == MediaDownloadStatus.pending) { + media = _placeholder(child: const CircularProgressIndicator()); + } else if (widget.message.downloadStatus == MediaDownloadStatus.failed) { + media = _failed(); + } else if (widget.message.localPath == null) { + media = _placeholder(child: const CircularProgressIndicator()); + } else { + switch (type) { + case MediaType.image: + case MediaType.gif: + media = _imageWidget(); + break; + case MediaType.video: + media = _videoWidget(); + break; + case MediaType.voice: + media = _voiceWidget(); + break; + case null: + media = _placeholder(child: const Icon(Icons.broken_image)); + } + } + + final isVoice = type == MediaType.voice; + if (isVoice) { + // Voice messages live inside the coloured bubble. + return Container( + decoration: BoxDecoration( + color: widget.bubbleColor, + borderRadius: BorderRadius.circular(20), + ), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + child: media, + ); + } + + // Visual media: rounded thumbnail with optional caption underneath. + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(16), + child: media, + ), + if (hasCaption) + Container( + margin: const EdgeInsets.only(top: 4), + decoration: BoxDecoration( + color: widget.bubbleColor, + borderRadius: BorderRadius.circular(16), + ), + padding: + const EdgeInsets.symmetric(horizontal: 14, vertical: 8), + child: Text( + widget.message.message, + style: TextStyle(color: widget.textColor), + ), + ), + ], + ); + } + + Widget _placeholder({required Widget child}) { + final size = _displaySize(); + return Container( + width: size.width, + height: size.height, + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(16), + ), + alignment: Alignment.center, + child: child, + ); + } + + Widget _failed() { + final size = _displaySize(); + return Container( + width: size.width, + height: size.height, + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(16), + ), + alignment: Alignment.center, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.error_outline, size: 32), + const SizedBox(height: 8), + Text('mediaDownloadFailed'.tr(), textAlign: TextAlign.center), + if (widget.canRetry) + TextButton.icon( + onPressed: widget.onRetry, + icon: const Icon(Icons.refresh), + label: Text('retry'.tr()), + ), + ], + ), + ); + } + + Widget _imageWidget() { + final size = _displaySize(); + return GestureDetector( + onTap: _openViewer, + child: FutureBuilder( + future: _imageFuture, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { + return _placeholder(child: const CircularProgressIndicator()); + } + if (!snapshot.hasData) { + return _placeholder(child: const Icon(Icons.broken_image)); + } + return Image.memory( + snapshot.data!, + width: size.width, + height: size.height, + fit: BoxFit.cover, + ); + }, + ), + ); + } + + Widget _videoWidget() { + final size = _displaySize(); + return GestureDetector( + onTap: _openViewer, + child: Stack( + alignment: Alignment.center, + children: [ + Container( + width: size.width, + height: size.height, + decoration: BoxDecoration( + gradient: const LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [Color(0xFF2B2B2B), Color(0xFF000000)], + ), + borderRadius: BorderRadius.circular(16), + ), + ), + Container( + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.45), + shape: BoxShape.circle, + ), + padding: const EdgeInsets.all(8), + child: + const Icon(Icons.play_arrow, color: Colors.white, size: 36), + ), + if (widget.message.durationMs != null) + Positioned( + right: 8, + bottom: 8, + child: Container( + padding: + const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(8), + ), + child: Text( + _formatDuration(widget.message.durationMs!), + style: const TextStyle(color: Colors.white, fontSize: 11), + ), + ), + ), + ], + ), + ); + } + + Widget _voiceWidget() { + return VoicePlayer( + localPath: widget.message.localPath!, + durationMs: widget.message.durationMs, + color: widget.textColor, + ); + } + + String _formatDuration(int ms) { + final d = Duration(milliseconds: ms); + final minutes = d.inMinutes.remainder(60).toString().padLeft(2, '0'); + final seconds = d.inSeconds.remainder(60).toString().padLeft(2, '0'); + return '$minutes:$seconds'; + } +} diff --git a/lib/widgets/voice_player.dart b/lib/widgets/voice_player.dart new file mode 100644 index 0000000..56093e0 --- /dev/null +++ b/lib/widgets/voice_player.dart @@ -0,0 +1,182 @@ +import 'dart:io'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:just_audio/just_audio.dart'; + +import '../utils/media_utils.dart'; + +/// Inline player for a voice message stored encrypted-at-rest. +/// +/// The encrypted file is decrypted into a temporary plaintext file for +/// playback and deleted again on dispose. +class VoicePlayer extends StatefulWidget { + final String localPath; + final int? durationMs; + final Color color; + + const VoicePlayer({ + required this.localPath, + required this.color, + this.durationMs, + super.key, + }); + + @override + State createState() => _VoicePlayerState(); +} + +class _VoicePlayerState extends State { + final AudioPlayer _player = AudioPlayer(); + File? _tempFile; + bool _loading = true; + bool _error = false; + + @override + void initState() { + super.initState(); + _prepare(); + } + + Future _prepare() async { + try { + _tempFile = await MediaUtils.materializeTempFile(widget.localPath, '.m4a'); + await _player.setFilePath(_tempFile!.path); + if (mounted) { + setState(() { + _loading = false; + }); + } + } catch (_) { + if (mounted) { + setState(() { + _loading = false; + _error = true; + }); + } + } + } + + @override + void dispose() { + _player.dispose(); + MediaUtils.deleteLocalFile(_tempFile?.path); + super.dispose(); + } + + String _format(Duration d) { + final minutes = d.inMinutes.remainder(60).toString().padLeft(2, '0'); + final seconds = d.inSeconds.remainder(60).toString().padLeft(2, '0'); + return '$minutes:$seconds'; + } + + @override + Widget build(BuildContext context) { + if (_error) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.error_outline, color: widget.color), + const SizedBox(width: 8), + Text('mediaError'.tr(), style: TextStyle(color: widget.color)), + ], + ); + } + + final total = _player.duration ?? + (widget.durationMs != null + ? Duration(milliseconds: widget.durationMs!) + : Duration.zero); + + return SizedBox( + width: 220, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + _loading + ? SizedBox( + width: 36, + height: 36, + child: Padding( + padding: const EdgeInsets.all(6), + child: CircularProgressIndicator( + strokeWidth: 2, + color: widget.color, + ), + ), + ) + : StreamBuilder( + stream: _player.playerStateStream, + builder: (context, snapshot) { + final playing = snapshot.data?.playing ?? false; + final completed = snapshot.data?.processingState == + ProcessingState.completed; + return IconButton( + color: widget.color, + icon: Icon((playing && !completed) + ? Icons.pause + : Icons.play_arrow), + onPressed: () async { + if (playing && !completed) { + await _player.pause(); + } else { + if (completed) { + await _player.seek(Duration.zero); + } + await _player.play(); + } + }, + ); + }, + ), + Expanded( + child: StreamBuilder( + stream: _player.positionStream, + builder: (context, snapshot) { + final position = snapshot.data ?? Duration.zero; + final max = total.inMilliseconds == 0 + ? 1.0 + : total.inMilliseconds.toDouble(); + final value = + position.inMilliseconds.clamp(0, max.toInt()).toDouble(); + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + SliderTheme( + data: SliderTheme.of(context).copyWith( + trackHeight: 2, + thumbShape: const RoundSliderThumbShape( + enabledThumbRadius: 6), + overlayShape: const RoundSliderOverlayShape( + overlayRadius: 12), + activeTrackColor: widget.color, + thumbColor: widget.color, + inactiveTrackColor: widget.color.withValues(alpha: 0.3), + ), + child: Slider( + min: 0, + max: max, + value: value, + onChanged: _loading + ? null + : (v) => _player + .seek(Duration(milliseconds: v.toInt())), + ), + ), + Align( + alignment: Alignment.centerRight, + child: Text( + _format(position.inMilliseconds > 0 ? position : total), + style: TextStyle(fontSize: 11, color: widget.color), + ), + ), + ], + ); + }, + ), + ), + ], + ), + ); + } +} diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc index 38dd0bc..8ac2ca5 100644 --- a/linux/flutter/generated_plugin_registrant.cc +++ b/linux/flutter/generated_plugin_registrant.cc @@ -6,13 +6,21 @@ #include "generated_plugin_registrant.h" +#include #include +#include #include void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); + file_selector_plugin_register_with_registrar(file_selector_linux_registrar); g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin"); flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar); + g_autoptr(FlPluginRegistrar) record_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "RecordLinuxPlugin"); + record_linux_plugin_register_with_registrar(record_linux_registrar); g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index 7e7bd77..6b9c45f 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -3,7 +3,9 @@ # list(APPEND FLUTTER_PLUGIN_LIST + file_selector_linux flutter_secure_storage_linux + record_linux url_launcher_linux ) diff --git a/pubspec.lock b/pubspec.lock index 2db2806..6ecefcd 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -49,6 +49,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.13.1" + audio_session: + dependency: transitive + description: + name: audio_session + sha256: "7217b229db57cc4dc577a8abb56b7429a5a212b978517a5be578704bfe5e568b" + url: "https://pub.dev" + source: hosted + version: "0.2.3" basic_utils: dependency: "direct main" description: @@ -153,6 +161,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.4" + chewie: + dependency: "direct main" + description: + name: chewie + sha256: "645fbca3f22309381edb5af59a4c8aa544a3d3872d7b7b7c986c2b18b3bdd265" + url: "https://pub.dev" + source: hosted + version: "1.10.0" cli_util: dependency: transitive description: @@ -201,6 +217,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.2" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937" + url: "https://pub.dev" + source: hosted + version: "0.3.5+2" crypto: dependency: "direct main" description: @@ -217,6 +241,22 @@ packages: url: "https://pub.dev" source: hosted version: "2.9.0" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + cupertino_icons: + dependency: transitive + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.dev" + source: hosted + version: "1.0.9" dart_jsonwebtoken: dependency: "direct main" description: @@ -245,18 +285,18 @@ packages: dependency: transitive description: name: device_info_plus - sha256: "6a642e1daa10190af89ba6cb6386c0df7d071a3592080bfe1e44faa63ae1df65" + sha256: b4fed1b2835da9d670d7bed7db79ae2a94b0f5ad6312268158a9b5479abbacdd url: "https://pub.dev" source: hosted - version: "13.1.0" + version: "12.4.0" device_info_plus_platform_interface: dependency: transitive description: name: device_info_plus_platform_interface - sha256: "04b173a92e2d9161dfead145667037c8d834db725ce2e7b942bfe18fd2f45a46" + sha256: e1ea89119e34903dca74b883d0dd78eb762814f97fb6c76f35e9ff74d261a18f url: "https://pub.dev" source: hosted - version: "8.1.0" + version: "7.0.3" easy_localization: dependency: "direct main" description: @@ -297,14 +337,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" - ffi_leak_tracker: - dependency: transitive - description: - name: ffi_leak_tracker - sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" - url: "https://pub.dev" - source: hosted - version: "0.1.2" file: dependency: transitive description: @@ -313,6 +345,46 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.1" + file_picker: + dependency: "direct main" + description: + name: file_picker + sha256: ab13ae8ef5580a411c458d6207b6774a6c237d77ac37011b13994879f68a8810 + url: "https://pub.dev" + source: hosted + version: "8.3.7" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: "2567f398e06ac72dcf2e98a0c95df2a9edd03c2c2e0cacd4780f20cdf56263a0" + url: "https://pub.dev" + source: hosted + version: "0.9.4" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: "5e0bbe9c312416f1787a68259ea1505b52f258c587f12920422671807c4d618a" + url: "https://pub.dev" + source: hosted + version: "0.9.5" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85" + url: "https://pub.dev" + source: hosted + version: "2.7.0" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: "62197474ae75893a62df75939c777763d39c2bc5f73ce5b88497208bc269abfd" + url: "https://pub.dev" + source: hosted + version: "0.9.3+5" firebase_core: dependency: "direct main" description: @@ -487,10 +559,10 @@ packages: dependency: transitive description: name: flutter_secure_storage_windows - sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1" + sha256: "3b7c8e068875dfd46719ff57c90d8c459c87f2302ed6b00ff006b3c9fcad1613" url: "https://pub.dev" source: hosted - version: "4.2.2" + version: "4.1.0" flutter_test: dependency: "direct dev" description: flutter @@ -557,6 +629,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.2" + html: + dependency: transitive + description: + name: html + sha256: "6d1264f2dffa1b1101c25a91dff0dc2daee4c18e87cd8538729773c073dbf602" + url: "https://pub.dev" + source: hosted + version: "0.15.6" http: dependency: "direct main" description: @@ -589,6 +669,70 @@ packages: url: "https://pub.dev" source: hosted version: "4.8.0" + image_picker: + dependency: "direct main" + description: + name: image_picker + sha256: "91c025426c2881c551100bce834e201c835a170151545f58d17da5180ca7d9ac" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + image_picker_android: + dependency: transitive + description: + name: image_picker_android + sha256: d5b3e1774af29c9ab00103afb0d4614070f924d2e0057ac867ec98800114793f + url: "https://pub.dev" + source: hosted + version: "0.8.13+17" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + sha256: "66257a3191ab360d23a55c8241c91a6e329d31e94efa7be9cf7a212e65850214" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: b9c4a438a9ff4f60808c9cf0039b93a42bb6c2211ef6ebb647394b2b3fa84588 + url: "https://pub.dev" + source: hosted + version: "0.8.13+6" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4" + url: "https://pub.dev" + source: hosted + version: "0.2.2" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: "86f0f15a309de7e1a552c12df9ce5b59fe927e71385329355aec4776c6a8ec91" + url: "https://pub.dev" + source: hosted + version: "0.2.2+1" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "567e056716333a1647c64bb6bd873cff7622233a5c3f694be28a583d4715690c" + url: "https://pub.dev" + source: hosted + version: "2.11.1" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae + url: "https://pub.dev" + source: hosted + version: "0.2.2" intl: dependency: transitive description: @@ -645,6 +789,30 @@ packages: url: "https://pub.dev" source: hosted version: "6.8.0" + just_audio: + dependency: "direct main" + description: + name: just_audio + sha256: "9694e4734f515f2a052493d1d7e0d6de219ee0427c7c29492e246ff32a219908" + url: "https://pub.dev" + source: hosted + version: "0.10.5" + just_audio_platform_interface: + dependency: transitive + description: + name: just_audio_platform_interface + sha256: "2532c8d6702528824445921c5ff10548b518b13f808c2e34c2fd54793b999a6a" + url: "https://pub.dev" + source: hosted + version: "4.6.0" + just_audio_web: + dependency: transitive + description: + name: just_audio_web + sha256: "6ba8a2a7e87d57d32f0f7b42856ade3d6a9fbe0f1a11fabae0a4f00bb73f0663" + url: "https://pub.dev" + source: hosted + version: "0.4.16" jwt_decoder: dependency: "direct main" description: @@ -758,7 +926,7 @@ packages: source: hosted version: "1.17.0" mime: - dependency: transitive + dependency: "direct main" description: name: mime sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" @@ -797,6 +965,22 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" + package_info_plus: + dependency: transitive + description: + name: package_info_plus + sha256: "468c26b4254ab01979fa5e4a98cb343ea3631b9acee6f21028997419a80e1a20" + url: "https://pub.dev" + source: hosted + version: "9.0.1" + package_info_plus_platform_interface: + dependency: transitive + description: + name: package_info_plus_platform_interface + sha256: "202a487f08836a592a6bd4f901ac69b3a8f146af552bbd14407b6b41e1c3f086" + url: "https://pub.dev" + source: hosted + version: "3.2.1" page_transition: dependency: "direct main" description: @@ -941,6 +1125,54 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.1" + record: + dependency: "direct main" + description: + name: record + sha256: "10911465138fafacef459a780564e883e01bd48eabf87ab20543684884492870" + url: "https://pub.dev" + source: hosted + version: "6.2.1" + record_android: + dependency: transitive + description: + name: record_android + sha256: eb1732e42d0d2a1895b8db86e4fc917287e6d8491b6ed59918aea8bed6c69de4 + url: "https://pub.dev" + source: hosted + version: "1.5.2" + record_ios: + dependency: transitive + description: + name: record_ios + sha256: c051fb48edd7a0e265daafb9108730dc827c27b551728a3fdfb3ef69efd89c73 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + record_linux: + dependency: transitive + description: + name: record_linux + sha256: "31181787bf7eccb0e298835836b69b3cd0a903863b75d70e937de3dec71cd8f3" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + record_macos: + dependency: transitive + description: + name: record_macos + sha256: cfe1b61435e27db418bf513dc36820d10c9f7eb1843786c2c9a52e07e2f4f627 + url: "https://pub.dev" + source: hosted + version: "1.2.2" + record_platform_interface: + dependency: transitive + description: + name: record_platform_interface + sha256: "8e56cbe06c6984137fb86132ff03459f29938d927496d9b2d0962e2d6345d488" + url: "https://pub.dev" + source: hosted + version: "1.6.0" record_use: dependency: transitive description: @@ -949,6 +1181,30 @@ packages: url: "https://pub.dev" source: hosted version: "0.6.0" + record_web: + dependency: transitive + description: + name: record_web + sha256: "7e9846981c1f2d111d86f0ae3309071f5bba8b624d1c977316706f08fc31d16d" + url: "https://pub.dev" + source: hosted + version: "1.3.0" + record_windows: + dependency: transitive + description: + name: record_windows + sha256: "223258060a1d25c62bae18282c16783f28581ec19401d17e56b5205b9f039d78" + url: "https://pub.dev" + source: hosted + version: "1.0.7" + rxdart: + dependency: transitive + description: + name: rxdart + sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962" + url: "https://pub.dev" + source: hosted + version: "0.28.0" shared_preferences: dependency: transitive description: @@ -1090,6 +1346,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.1" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: "63896c27e81b28f8cb4e69ead0d3e8f03f1d1e5fc531a3e579cabed6a2c7c9e5" + url: "https://pub.dev" + source: hosted + version: "3.4.0+1" term_glyph: dependency: transitive description: @@ -1194,6 +1458,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.5" + uuid: + dependency: "direct main" + description: + name: uuid + sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489" + url: "https://pub.dev" + source: hosted + version: "4.5.3" vector_math: dependency: transitive description: @@ -1218,6 +1490,46 @@ packages: url: "https://pub.dev" source: hosted version: "0.1.2" + video_player: + dependency: "direct main" + description: + name: video_player + sha256: "48a7bdaa38a3d50ec10c78627abdbfad863fdf6f0d6e08c7c3c040cfd80ae36f" + url: "https://pub.dev" + source: hosted + version: "2.11.1" + video_player_android: + dependency: transitive + description: + name: video_player_android + sha256: "877a6c7ba772456077d7bfd71314629b3fe2b73733ce503fc77c3314d43a0ca0" + url: "https://pub.dev" + source: hosted + version: "2.9.5" + video_player_avfoundation: + dependency: transitive + description: + name: video_player_avfoundation + sha256: "9338f3ec22774f88146b22f13273a446719b1da010fd200c4d1d97802156ac58" + url: "https://pub.dev" + source: hosted + version: "2.9.7" + video_player_platform_interface: + dependency: transitive + description: + name: video_player_platform_interface + sha256: "16eaed5268c571c31840dc58ef8da5f0cd4db2a98490c3b8f1cf70122546c6e0" + url: "https://pub.dev" + source: hosted + version: "6.7.0" + video_player_web: + dependency: transitive + description: + name: video_player_web + sha256: "9f3c00be2ef9b76a95d94ac5119fb843dca6f2c69e6c9968f6f2b6c9e7afbdeb" + url: "https://pub.dev" + source: hosted + version: "2.4.0" vm_service: dependency: transitive description: @@ -1226,6 +1538,22 @@ packages: url: "https://pub.dev" source: hosted version: "15.2.0" + wakelock_plus: + dependency: transitive + description: + name: wakelock_plus + sha256: ddf3db70eaa10c37558ff817519b85d527dbd21034fd5d8e1c2e85f31588f1c1 + url: "https://pub.dev" + source: hosted + version: "1.5.2" + wakelock_plus_platform_interface: + dependency: transitive + description: + name: wakelock_plus_platform_interface + sha256: b13f99e992e7ae6a152e16c5559d3c07ff445b13330192662494e614ca3e7d7b + url: "https://pub.dev" + source: hosted + version: "1.5.1" watcher: dependency: transitive description: @@ -1261,37 +1589,33 @@ packages: whisper_openapi_client_dart: dependency: "direct main" description: - path: "." - ref: HEAD - resolved-ref: fe1e740bba5505d14b0ec0086166b38271b3c153 - url: "https://github.com/jsfraz/whisper_openapi_client_dart.git" - source: git + path: "../whisper_openapi_client_dart" + relative: true + source: path version: "0.0.1" whisper_websocket_client_dart: dependency: "direct main" description: - path: "." - ref: HEAD - resolved-ref: "94cedcaeac9b85a90eb1671c2da42962b6e2cf20" - url: "https://github.com/jsfraz/whisper_websocket_client_dart.git" - source: git + path: "../whisper_websocket_client_dart" + relative: true + source: path version: "1.0.0" win32: dependency: transitive description: name: win32 - sha256: ba6f4bba816c8d7e3c1580e170f3786d216951cc6b94babc3b814c08d2cb2738 + sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e url: "https://pub.dev" source: hosted - version: "6.3.0" + version: "5.15.0" win32_registry: dependency: transitive description: name: win32_registry - sha256: "73b1d78920a9d6e03f8b4e43e612b87bf3152a0e5c5e5150267762b7c4116904" + sha256: "6f1b564492d0147b330dd794fee8f512cec4977957f310f9951b5f9d83618dae" url: "https://pub.dev" source: hosted - version: "3.0.3" + version: "2.1.0" xdg_directories: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 1ab7f25..a8921e2 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -10,11 +10,13 @@ environment: dependencies: basic_utils: ^5.7.0 bcrypt: ^1.1.3 + chewie: ">=1.7.0 <1.11.0" crypto: ^3.0.5 cryptography: ^2.7.0 dart_jsonwebtoken: ^3.2.0 easy_localization: ^3.0.7 email_validator: ^3.0.0 + file_picker: ^8.0.0 firebase_core: ^4.0.0 firebase_messaging: ^16.0.0 flutter: @@ -26,24 +28,28 @@ dependencies: fluttertoast: ^9.0.0 hive: ^2.2.3 http: ^1.2.1 + image_picker: ^1.2.2 json_annotation: ^4.9.0 + just_audio: ^0.10.5 jwt_decoder: ^2.0.1 local_auth: ^3.0.1 + mime: ^2.0.0 mobile_scanner: ^7.0.0 page_transition: ^2.2.1 path_provider: ^2.1.3 pointycastle: ^4.0.0 provider: ^6.1.2 qr_code_scanner_plus: ^2.0.6 + record: ^6.2.1 sprintf: ^7.0.0 url_launcher: ^6.3.1 + uuid: ^4.5.3 vibration: ^3.1.2 + video_player: ^2.11.1 whisper_openapi_client_dart: - git: - url: https://github.com/jsfraz/whisper_openapi_client_dart.git + path: ../whisper_openapi_client_dart whisper_websocket_client_dart: - git: - url: https://github.com/jsfraz/whisper_websocket_client_dart.git + path: ../whisper_websocket_client_dart dev_dependencies: flutter_test: From 021c646f59e881770dfcdfc3a5a62b048d2a974f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Wed, 3 Jun 2026 20:33:17 +0200 Subject: [PATCH 008/181] TODO --- README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/README.md b/README.md index 9d4597d..cf07be7 100644 --- a/README.md +++ b/README.md @@ -140,3 +140,20 @@ These secret keys will be used during application build to generate the necessar 4. Paste the base64 encoded content as the secret key value After setting these secret keys, the workflow will automatically build the APK on every push to the `main` branch and create a new GitHub Release with the version according to `pubspec.yaml`. + +## TODO + +- nelze ukončit nahrávání hlasové zprávy a odeslat ji, reimplementovat logiku +- nastavit maximální velikost přílohy HTTP požadavku +- při otevření přílohy možnost uložit dešifrovaně do zařízení +- opravit hrozně pomalé načítání náhledů obrázků u příjemce (kolečko se točí donekonečna, po kliknutí ale náhled funguje) +- při odesílání zprávy indikovat že se odesílá, nyní se neindikuje nic a uživatel může myslet že se zpráva vůbec neodeslala nebo se neodesílá vůbec nic (zpráva se zobrazí až po odeslání) +- videa nemají náhled, jen šedivou barvu +- opravit to, že po otevření chatu není vždy nascrollováno úplně dolů +- výběr GIFů nedělat ze souborů, ale ve stylu Discordu (výběr zdroje Tenor a Giphy) +- zarovnání hlasové zprávy, progressbar je moc nahoře +- postupný loading zpráv pro optimalizaci rychlosti +- možnost vybrat více fotek/souborů najednou a odeslat je jako album +- při odesílání souborů neumožnit odeslat fotky a videa, pouze všechny ostatní soubory +- nastavit verzi na serveru pro kontrolu kompatibility s klientem (+ knihovny) +- schopnost podle GitHub releasů zjistit aktuální verzi a upozornit uživatele na aktualizaci a stáhnout a nainstalovat ji (+ checksums) From 9e45332e562f9aae20b7945ad767837b5b0cd9d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Wed, 3 Jun 2026 20:49:01 +0200 Subject: [PATCH 009/181] More TODOs --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index cf07be7..1dd70ff 100644 --- a/README.md +++ b/README.md @@ -157,3 +157,5 @@ After setting these secret keys, the workflow will automatically build the APK o - při odesílání souborů neumožnit odeslat fotky a videa, pouze všechny ostatní soubory - nastavit verzi na serveru pro kontrolu kompatibility s klientem (+ knihovny) - schopnost podle GitHub releasů zjistit aktuální verzi a upozornit uživatele na aktualizaci a stáhnout a nainstalovat ji (+ checksums) +- pro nepodporované soubory pro náhled (PDF atd, zobrazovat ikonu přípony jako náhled +- potvrzení odeslání přílohy po vybrání (pro možnost dopsat k ní text) From fc8566325518667da090ef860d9fc2bb25425537 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 10 Nov 2026 23:11:35 +0100 Subject: [PATCH 010/181] Updated packages Flutter 3.47.9 / Dart 3.13.7 toolchain. Migrated file_picker to 13.x API. --- analysis_options.yaml | 6 + lib/utils/media_utils.dart | 8 +- pubspec.lock | 516 +++++++++++++++++++++---------------- pubspec.yaml | 16 +- 4 files changed, 312 insertions(+), 234 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index 0d29021..7e428b9 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -7,6 +7,12 @@ # The following line activates a set of recommended lints for Flutter apps, # packages, and plugins designed to encourage good coding practices. +analyzer: + exclude: + - build/** + - android/** + - ios/** + - linux/** include: package:flutter_lints/flutter.yaml linter: diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 6f76bef..1b561a9 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -343,18 +343,18 @@ class MediaUtils { /// Pick a GIF file. static Future pickGif() async { - final result = await FilePicker.platform.pickFiles( + final picked = await FilePicker.pickFile( type: FileType.custom, allowedExtensions: const ['gif'], ); - final path = result?.files.single.path; + final path = picked?.path; return path == null ? null : File(path); } /// Pick an arbitrary media (image/video) file. static Future pickFile() async { - final result = await FilePicker.platform.pickFiles(type: FileType.media); - final path = result?.files.single.path; + final picked = await FilePicker.pickFile(type: FileType.media); + final path = picked?.path; return path == null ? null : File(path); } } diff --git a/pubspec.lock b/pubspec.lock index 6ecefcd..03a1ddb 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -13,10 +13,10 @@ packages: dependency: transitive description: name: _flutterfire_internals - sha256: "0d1f0adfabbab9f46a1a80ce84a4d8b852b6e4dbf53ce413b30e0cf7d3631b71" + sha256: e6d8a6eb9da10e65906dda455eca96ee7a6303b835cad74d667b1ff3bedd5d18 url: "https://pub.dev" source: hosted - version: "1.3.72" + version: "1.3.79" analyzer: dependency: transitive description: @@ -25,14 +25,22 @@ packages: url: "https://pub.dev" source: hosted version: "6.4.1" + android_file_picker: + dependency: transitive + description: + name: android_file_picker + sha256: "04c1306eda42c23ecbf449c909f4fa05c5e66fc48cf5f994d8d08b9d45e5396b" + url: "https://pub.dev" + source: hosted + version: "2.1.5" archive: dependency: transitive description: name: archive - sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff + sha256: de5ac590b8155e4e676088d714bd41ea620449a6adc0f7950c5073874b287ddb url: "https://pub.dev" source: hosted - version: "4.0.9" + version: "4.6.0" args: dependency: transitive description: @@ -53,10 +61,10 @@ packages: dependency: transitive description: name: audio_session - sha256: "7217b229db57cc4dc577a8abb56b7429a5a212b978517a5be578704bfe5e568b" + sha256: f9e7711a0e24ca8b40f5d7ac374c3c6e55016f3157912badd18199cdbbca5c4d url: "https://pub.dev" source: hosted - version: "0.2.3" + version: "0.2.4" basic_utils: dependency: "direct main" description: @@ -101,10 +109,10 @@ packages: dependency: transitive description: name: build_daemon - sha256: bf05f6e12cfea92d3c09308d7bcdab1906cd8a179b023269eed00c071004b957 + sha256: "39ab65f7c60c19af64b9ef96e6a5d3ab48355f7dddfd98a9079d55a8cb6628fc" url: "https://pub.dev" source: hosted - version: "4.1.1" + version: "4.1.7" build_resolvers: dependency: transitive description: @@ -133,18 +141,18 @@ packages: dependency: transitive description: name: built_collection - sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100" + sha256: "44922ecebd8e3d0cef743dadd3b54df4e87e2a4c52a29465a1872aa9e192caa8" url: "https://pub.dev" source: hosted - version: "5.1.1" + version: "5.1.2" built_value: dependency: transitive description: name: built_value - sha256: "34e4067d30ce212937df995f03b69992eea683539ceeac7f679a1f1eba055b56" + sha256: f87ea98192116f7093cb214551ce1929caae0681fdba282b3d8b4462adee7bb7 url: "https://pub.dev" source: hosted - version: "8.12.6" + version: "8.13.0" characters: dependency: transitive description: @@ -165,10 +173,10 @@ packages: dependency: "direct main" description: name: chewie - sha256: "645fbca3f22309381edb5af59a4c8aa544a3d3872d7b7b7c986c2b18b3bdd265" + sha256: "7606034230e56f0258ef5a75260fdc1d69c66b4c3724f7cc9613bca954858dc3" url: "https://pub.dev" source: hosted - version: "1.10.0" + version: "1.17.4" cli_util: dependency: transitive description: @@ -181,26 +189,26 @@ packages: dependency: transitive description: name: clock - sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e url: "https://pub.dev" source: hosted - version: "1.1.2" + version: "1.1.3" code_assets: dependency: transitive description: name: code_assets - sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8 + sha256: "1ef22a0be3af9370bd9481ac76db114db92bfe75d5ca2b2d7bc911764478a4d9" url: "https://pub.dev" source: hosted - version: "1.2.1" + version: "2.2.0" code_builder: dependency: transitive description: name: code_builder - sha256: "6a6cab2ba4680d6423f34a9b972a4c9a94ebe1b62ecec4e1a1f2cba91fd1319d" + sha256: "811709c1badd02fc054039a13f66e0db1961865f9a314175f68c3eaeebec786f" url: "https://pub.dev" source: hosted - version: "4.11.1" + version: "4.13.0" collection: dependency: transitive description: @@ -221,18 +229,18 @@ packages: dependency: transitive description: name: cross_file - sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937" + sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6 url: "https://pub.dev" source: hosted - version: "0.3.5+2" + version: "0.3.5+5" crypto: dependency: "direct main" description: name: crypto - sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4 url: "https://pub.dev" source: hosted - version: "3.0.7" + version: "3.0.8" cryptography: dependency: "direct main" description: @@ -277,26 +285,26 @@ packages: dependency: transitive description: name: dbus - sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270 + sha256: f7db8504e715b835f5ebe5fe74604ccd961d504c73389a5d8e81bafc2e2f3612 url: "https://pub.dev" source: hosted - version: "0.7.12" + version: "0.8.0" device_info_plus: dependency: transitive description: name: device_info_plus - sha256: b4fed1b2835da9d670d7bed7db79ae2a94b0f5ad6312268158a9b5479abbacdd + sha256: ade1c36f8355d6284c98e4a47992ea263887ed3d1acb281e37635dd45f04c4aa url: "https://pub.dev" source: hosted - version: "12.4.0" + version: "13.3.0" device_info_plus_platform_interface: dependency: transitive description: name: device_info_plus_platform_interface - sha256: e1ea89119e34903dca74b883d0dd78eb762814f97fb6c76f35e9ff74d261a18f + sha256: "04b173a92e2d9161dfead145667037c8d834db725ce2e7b942bfe18fd2f45a46" url: "https://pub.dev" source: hosted - version: "7.0.3" + version: "8.1.0" easy_localization: dependency: "direct main" description: @@ -337,6 +345,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" + ffi_leak_tracker: + dependency: transitive + description: + name: ffi_leak_tracker + sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" + url: "https://pub.dev" + source: hosted + version: "0.1.2" file: dependency: transitive description: @@ -349,26 +365,58 @@ packages: dependency: "direct main" description: name: file_picker - sha256: ab13ae8ef5580a411c458d6207b6774a6c237d77ac37011b13994879f68a8810 + sha256: "079dc46b753abbddb7f77cd87e6ed9ecc62902580707514568321bdf8e050a86" + url: "https://pub.dev" + source: hosted + version: "13.3.3" + file_picker_darwin: + dependency: transitive + description: + name: file_picker_darwin + sha256: b7d3a6bd26a18c503d29070fc2d7b26fbfe918d08a6bcd984b6e806ff5ad923f + url: "https://pub.dev" + source: hosted + version: "2.5.1" + file_picker_linux: + dependency: transitive + description: + name: file_picker_linux + sha256: "9215ee8c672508cdd9a325202669f849e1baac883658626b3abed5d7777e6a4b" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + file_picker_platform_interface: + dependency: transitive + description: + name: file_picker_platform_interface + sha256: "336e7168306834a2b68e6168ed768e00d3fabeac23154d5793e277ca9f97cf20" + url: "https://pub.dev" + source: hosted + version: "4.2.0" + file_picker_web: + dependency: transitive + description: + name: file_picker_web + sha256: "50749a6da2984fc29609e102ad4d80fd1d07e6895150f8e4922086167d9d45d8" url: "https://pub.dev" source: hosted - version: "8.3.7" + version: "4.2.1" file_selector_linux: dependency: transitive description: name: file_selector_linux - sha256: "2567f398e06ac72dcf2e98a0c95df2a9edd03c2c2e0cacd4780f20cdf56263a0" + sha256: da76400e7872ce7637ffdce12749ec24169c25f6195c28372208e65a24bcd2ab url: "https://pub.dev" source: hosted - version: "0.9.4" + version: "0.9.4+1" file_selector_macos: dependency: transitive description: name: file_selector_macos - sha256: "5e0bbe9c312416f1787a68259ea1505b52f258c587f12920422671807c4d618a" + sha256: d785431f1910aac8a50e5c492cae912320158030a88703c67b9ef7f1f96fd7ba url: "https://pub.dev" source: hosted - version: "0.9.5" + version: "0.9.5+2" file_selector_platform_interface: dependency: transitive description: @@ -381,58 +429,58 @@ packages: dependency: transitive description: name: file_selector_windows - sha256: "62197474ae75893a62df75939c777763d39c2bc5f73ce5b88497208bc269abfd" + sha256: fbefc5fb92c6d3cbe8d284a2cd971b593bb07d2cd6da8557b81a862250b4acec url: "https://pub.dev" source: hosted - version: "0.9.3+5" + version: "0.9.3+6" firebase_core: dependency: "direct main" description: name: firebase_core - sha256: ec46a100a560d3bd5f97f2d89ba7492cb09b6dd0a4a28753d1258f360d6bd9f9 + sha256: "21551c1205441d9d155660ea0a409530b65a8d66ce88002bab3f38d94a8638fc" url: "https://pub.dev" source: hosted - version: "4.10.0" + version: "5.1.0" firebase_core_platform_interface: dependency: transitive description: name: firebase_core_platform_interface - sha256: "4a120366dbf7d5a8ee9438978530b664b855728fb8dcc3a201017660817e555b" + sha256: "9bfbc85faca09346471ac56fbcee00757ebcfd85887c6f602764eff0001902d8" url: "https://pub.dev" source: hosted - version: "7.0.1" + version: "8.1.1" firebase_core_web: dependency: transitive description: name: firebase_core_web - sha256: "5ad1be848692ec148f2d6a8ad2a3838cb852ea5f3c9e6479a7afce479e1854f8" + sha256: "0ec9832bfec1662629d6d09abd65021357634b2c10964970d3e96ab18c9458db" url: "https://pub.dev" source: hosted - version: "3.8.0" + version: "4.1.0" firebase_messaging: dependency: "direct main" description: name: firebase_messaging - sha256: "9651e833454156b9f0927eaedccffba0f7f6a6e20ceddef82517211e7017e9c4" + sha256: e19c73b369ae83f4580a0676597f9ac3a0cd91e1b18be69ea16299c153dd9310 url: "https://pub.dev" source: hosted - version: "16.3.0" + version: "17.0.1" firebase_messaging_platform_interface: dependency: transitive description: name: firebase_messaging_platform_interface - sha256: "292bb5dc9c4a429078895406c347d7c7690deb858c1adeed8f4b4346f769dfa3" + sha256: "1627f161b85bf842cba5227b02aafaad4e4ff9236a0a8490e6ec72b6fde294a5" url: "https://pub.dev" source: hosted - version: "4.8.0" + version: "4.11.1" firebase_messaging_web: dependency: transitive description: name: firebase_messaging_web - sha256: "08c565bc83729439f5de2dfea77b4832002b705eb2f840366cefa80e4e5c3c66" + sha256: "593d73330500896d9dd81680ee6207c69ad80f258712beb6de2e32dc14a9cb26" url: "https://pub.dev" source: hosted - version: "4.2.0" + version: "4.3.1" fixnum: dependency: transitive description: @@ -474,34 +522,42 @@ packages: dependency: "direct main" description: name: flutter_local_notifications - sha256: "0d9035862236fe38250fe1644d7ed3b8254e34a21b2c837c9f539fbb3bba5ef1" + sha256: e99e9c6078d1359ba131b2c1eb8d68837170836a01bf2cea3cf2fa13e62ac2ac url: "https://pub.dev" source: hosted - version: "21.0.0" + version: "23.0.0" flutter_local_notifications_linux: dependency: transitive description: name: flutter_local_notifications_linux - sha256: e0f25e243c6c44c825bbbc6b2b2e76f7d9222362adcfe9fd780bf01923c840bd + sha256: bcbcf3c15e33b6866805092308f5f6ef27e1191874f6a92ef59213a0812a79a2 url: "https://pub.dev" source: hosted - version: "8.0.0" + version: "9.0.0" flutter_local_notifications_platform_interface: dependency: transitive description: name: flutter_local_notifications_platform_interface - sha256: e7db3d5b49c2b7ecc68deba4aaaa67a348f92ee0fef34c8e4b4459dbef0d7307 + sha256: "4a49db4ce3d633ebc85c85b5fa959572600ec10bd097419c454579444308a0a0" url: "https://pub.dev" source: hosted - version: "11.0.0" + version: "13.0.0" + flutter_local_notifications_web: + dependency: transitive + description: + name: flutter_local_notifications_web + sha256: ef117694fbfcd82308ab0e324cfc9282fa50c192e24ec54a58173ae327ebc544 + url: "https://pub.dev" + source: hosted + version: "2.0.0" flutter_local_notifications_windows: dependency: transitive description: name: flutter_local_notifications_windows - sha256: "3a2654ba104fbb52c618ebed9def24ef270228470718c43b3a6afcd5c81bef0c" + sha256: c2d6efe9ba585d5f560d8b329131f00fe745834848e6221b22d1f62e0f0b16e2 url: "https://pub.dev" source: hosted - version: "3.0.0" + version: "4.0.0" flutter_localizations: dependency: transitive description: flutter @@ -519,34 +575,34 @@ packages: dependency: "direct main" description: name: flutter_secure_storage - sha256: "7686b1d6a29985dcbb808c59518226e603e3bfa7c0ddfd1a0d00e4cda77c868e" + sha256: d4e1fb6b2cb524868929e78dc0282fa000554b22060fb53789dc481c9fc95bb8 url: "https://pub.dev" source: hosted - version: "10.3.1" + version: "11.2.0" flutter_secure_storage_darwin: dependency: transitive description: name: flutter_secure_storage_darwin - sha256: "82329fa5cdf343773b1b6897dea959105a29f092454259edff92f9f6637e8149" + sha256: a031ceac9b070e62ef183cd7f7d1a8798ebde402d5049f0fe6eb3a51bd797a21 url: "https://pub.dev" source: hosted - version: "0.3.2" + version: "0.4.3" flutter_secure_storage_linux: dependency: transitive description: name: flutter_secure_storage_linux - sha256: a5f35ddab43cf5c8215d2feb4ce1957851f28c5c37e6f04335066a0602087bf5 + sha256: caa75bd78f017422912e3a904933113b2428eb79f981ac37acd2dd2a700458ea url: "https://pub.dev" source: hosted - version: "3.0.1" + version: "3.0.3" flutter_secure_storage_platform_interface: dependency: transitive description: name: flutter_secure_storage_platform_interface - sha256: "8ceea1223bee3c6ac1a22dabd8feefc550e4729b3675de4b5900f55afcb435d6" + sha256: "64951127f001f546891c86f414972bf49ef2c4c8a4c92c65f5790cc0c9100045" url: "https://pub.dev" source: hosted - version: "2.0.1" + version: "2.1.1" flutter_secure_storage_web: dependency: transitive description: @@ -559,10 +615,10 @@ packages: dependency: transitive description: name: flutter_secure_storage_windows - sha256: "3b7c8e068875dfd46719ff57c90d8c459c87f2302ed6b00ff006b3c9fcad1613" + sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1" url: "https://pub.dev" source: hosted - version: "4.1.0" + version: "4.2.2" flutter_test: dependency: "direct dev" description: flutter @@ -577,26 +633,26 @@ packages: dependency: "direct main" description: name: fluttertoast - sha256: "7903c9d5339173497bfecbc23bc4212f5a87e0edfac2e1693fb74465ea67da7e" + sha256: a5c39007e19fff5eeb7810d5be651c02bb5a1c06104bdd203b037bbfe49bd827 url: "https://pub.dev" source: hosted - version: "9.1.0" + version: "10.0.2" frontend_server_client: dependency: transitive description: name: frontend_server_client - sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + sha256: "2b56423afc7651a81da53ed3a4f9f51e92572293f54d0d54e19b759f13714849" url: "https://pub.dev" source: hosted - version: "4.0.0" + version: "4.2.0" glob: dependency: transitive description: name: glob - sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb" url: "https://pub.dev" source: hosted - version: "2.1.3" + version: "2.2.0" graphs: dependency: transitive description: @@ -625,18 +681,18 @@ packages: dependency: transitive description: name: hooks - sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba" + sha256: eaac480a35ec0814146c2c48d96aaa829e0e44a7662c88ae84c9edf4bc35651f url: "https://pub.dev" source: hosted - version: "2.0.2" + version: "2.2.0" html: dependency: transitive description: name: html - sha256: "6d1264f2dffa1b1101c25a91dff0dc2daee4c18e87cd8538729773c073dbf602" + sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699" url: "https://pub.dev" source: hosted - version: "0.15.6" + version: "0.15.7" http: dependency: "direct main" description: @@ -649,10 +705,10 @@ packages: dependency: transitive description: name: http_multi_server - sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + sha256: "361668bdd71f0ae2dc6d17b75a593520f3c414af6534f9eed1aa72049dd71d18" url: "https://pub.dev" source: hosted - version: "3.2.2" + version: "3.2.3" http_parser: dependency: transitive description: @@ -665,26 +721,26 @@ packages: dependency: transitive description: name: image - sha256: f9881ff4998044947ec38d098bc7c8316ae1186fa786eddffdb867b9bc94dfce + sha256: "89ed75b2f8231fe676808c5564f9590d728024ded7ac782a7ed8474f1c95b72a" url: "https://pub.dev" source: hosted - version: "4.8.0" + version: "4.12.0" image_picker: dependency: "direct main" description: name: image_picker - sha256: "91c025426c2881c551100bce834e201c835a170151545f58d17da5180ca7d9ac" + sha256: e71b1bd9e40124041128d60fc3034c7b1598e1bba4e570bba0c70301c817013a url: "https://pub.dev" source: hosted - version: "1.2.2" + version: "1.2.4" image_picker_android: dependency: transitive description: name: image_picker_android - sha256: d5b3e1774af29c9ab00103afb0d4614070f924d2e0057ac867ec98800114793f + sha256: "8a7823d5d3e884f7780829d85d92110d072bdcd9ed48e2be158d2abe91a912d4" url: "https://pub.dev" source: hosted - version: "0.8.13+17" + version: "0.8.13+25" image_picker_for_web: dependency: transitive description: @@ -697,10 +753,10 @@ packages: dependency: transitive description: name: image_picker_ios - sha256: b9c4a438a9ff4f60808c9cf0039b93a42bb6c2211ef6ebb647394b2b3fa84588 + sha256: f4e5650a81b268af3886bc789216ff6d56bdfa79934f93f1a5a8a303b8f60f77 url: "https://pub.dev" source: hosted - version: "0.8.13+6" + version: "0.8.13+15" image_picker_linux: dependency: transitive description: @@ -721,10 +777,10 @@ packages: dependency: transitive description: name: image_picker_platform_interface - sha256: "567e056716333a1647c64bb6bd873cff7622233a5c3f694be28a583d4715690c" + sha256: "2dee4b4e3be429db71472c9c559c981498070a61af1ba82e0e4986fc5dadc042" url: "https://pub.dev" source: hosted - version: "2.11.1" + version: "2.11.2" image_picker_windows: dependency: transitive description: @@ -737,34 +793,42 @@ packages: dependency: transitive description: name: intl - sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5" + sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867" url: "https://pub.dev" source: hosted - version: "0.20.2" + version: "0.20.3" io: dependency: transitive description: name: io - sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b + sha256: "2635216ca6a737e60de577ffa1a48a0bec76ca8a62917cfc1bb88c14c570646f" url: "https://pub.dev" source: hosted - version: "1.0.5" + version: "1.1.0" jni: dependency: transitive description: name: jni - sha256: c2230682d5bc2362c1c9e8d3c7f406d9cbba23ab3f2e203a025dd47e0fb2e68f + sha256: "2e91e6087291affd10b31b6c872f3e3ac7dc5d93b51b5ba485d930c8f08bde6c" url: "https://pub.dev" source: hosted - version: "1.0.0" + version: "1.1.2" jni_flutter: dependency: transitive description: name: jni_flutter - sha256: "8b59e590786050b1cd866677dddaf76b1ade5e7bc751abe04b86e84d379d3ba6" + sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191" url: "https://pub.dev" source: hosted - version: "1.0.1" + version: "1.0.4+1" + jni_util: + dependency: transitive + description: + name: jni_util + sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f" + url: "https://pub.dev" + source: hosted + version: "1.0.0" js: dependency: transitive description: @@ -793,10 +857,10 @@ packages: dependency: "direct main" description: name: just_audio - sha256: "9694e4734f515f2a052493d1d7e0d6de219ee0427c7c29492e246ff32a219908" + sha256: e60aa97b233ddea025e13dfac59195207f528fa5e9e4a4a49a8c0766701e5fe6 url: "https://pub.dev" source: hosted - version: "0.10.5" + version: "0.10.6" just_audio_platform_interface: dependency: transitive description: @@ -857,26 +921,26 @@ packages: dependency: "direct main" description: name: local_auth - sha256: ae6f382f638108c6becd134318d7c3f0a93875383a54010f61d7c97ac05d5137 + sha256: ecf24edf2283c509ecd217e3595f6f71034b68888d28ad1dae6bfa0857b816ac url: "https://pub.dev" source: hosted - version: "3.0.1" + version: "3.0.2" local_auth_android: dependency: transitive description: name: local_auth_android - sha256: b201c006fa769c23386f89aa6837ec0eb8179fcfb212eadcf87b422b3f9a6a78 + sha256: e2ceb84cdecefe1bc0ddd4ac308b0f6525bbfa0a60d0e552082b2970e1fb38c2 url: "https://pub.dev" source: hosted - version: "2.0.8" + version: "2.3.0" local_auth_darwin: dependency: transitive description: name: local_auth_darwin - sha256: a8c3d4e17454111f7fd31ff72a31222359f6059f7fe956c2dcfe0f88f49826d4 + sha256: "45a9db01b57082bc9d6115cb25eb8fc0b72f43e5f330819bdd8352ecdae87589" url: "https://pub.dev" source: hosted - version: "2.0.3" + version: "2.0.5" local_auth_platform_interface: dependency: transitive description: @@ -889,10 +953,10 @@ packages: dependency: transitive description: name: local_auth_windows - sha256: be12c5b8ba5e64896983123655c5f67d2484ecfcc95e367952ad6e3bff94cb16 + sha256: d72b8a441e5e6a679902f87c51529fcce65f442d77598484cf35454c3d733eda url: "https://pub.dev" source: hosted - version: "2.0.1" + version: "2.0.2" logging: dependency: transitive description: @@ -905,10 +969,10 @@ packages: dependency: transitive description: name: matcher - sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" url: "https://pub.dev" source: hosted - version: "0.12.19" + version: "0.12.20" material_color_utilities: dependency: transitive description: @@ -921,26 +985,26 @@ packages: dependency: transitive description: name: meta - sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" url: "https://pub.dev" source: hosted - version: "1.17.0" + version: "1.19.0" mime: dependency: "direct main" description: name: mime - sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6 url: "https://pub.dev" source: hosted - version: "2.0.0" + version: "2.1.0" mobile_scanner: dependency: "direct main" description: name: mobile_scanner - sha256: c92c26bf2231695b6d3477c8dcf435f51e28f87b1745966b1fe4c47a286171ce + sha256: "175c62fc813c2bd762757359a2088f8cbdb72020cf85d4cd27fc4d3fe59be058" url: "https://pub.dev" source: hosted - version: "7.2.0" + version: "7.5.0" nested: dependency: transitive description: @@ -953,10 +1017,10 @@ packages: dependency: transitive description: name: objective_c - sha256: "6cb691c686fa2838c6deb34980d426145c2a5d537491cb83d463c33cdbc726ed" + sha256: "322d5f1f0680534acaf557c5d68e97b40c3800ee5e15b63dcacc3c31504674c2" url: "https://pub.dev" source: hosted - version: "9.4.1" + version: "9.6.3" package_config: dependency: transitive description: @@ -969,18 +1033,18 @@ packages: dependency: transitive description: name: package_info_plus - sha256: "468c26b4254ab01979fa5e4a98cb343ea3631b9acee6f21028997419a80e1a20" + sha256: "73ef2cd5c11a7548f9b7f6fc2a4f6113de2e64aa2a70de63feede95548822908" url: "https://pub.dev" source: hosted - version: "9.0.1" + version: "10.2.2" package_info_plus_platform_interface: dependency: transitive description: name: package_info_plus_platform_interface - sha256: "202a487f08836a592a6bd4f901ac69b3a8f146af552bbd14407b6b41e1c3f086" + sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4 url: "https://pub.dev" source: hosted - version: "3.2.1" + version: "4.1.0" page_transition: dependency: "direct main" description: @@ -1001,10 +1065,10 @@ packages: dependency: "direct main" description: name: path_provider - sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 url: "https://pub.dev" source: hosted - version: "2.1.5" + version: "2.1.6" path_provider_android: dependency: transitive description: @@ -1025,18 +1089,18 @@ packages: dependency: transitive description: name: path_provider_linux - sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16" url: "https://pub.dev" source: hosted - version: "2.2.1" + version: "2.2.2" path_provider_platform_interface: dependency: transitive description: name: path_provider_platform_interface - sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda" url: "https://pub.dev" source: hosted - version: "2.1.2" + version: "2.1.3" path_provider_windows: dependency: transitive description: @@ -1049,18 +1113,18 @@ packages: dependency: transitive description: name: petitparser - sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + sha256: "2f1564aadb14215e478563b5406cb80729d022158c01dc50c96013c2f7eb4790" url: "https://pub.dev" source: hosted - version: "7.0.2" + version: "7.1.0" platform: dependency: transitive description: name: platform - sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + sha256: a36d119c13416516a7b5913fbe8af8531e11633d784c550b2125f76c758524ec url: "https://pub.dev" source: hosted - version: "3.1.6" + version: "3.2.0" plugin_platform_interface: dependency: transitive description: @@ -1081,18 +1145,18 @@ packages: dependency: transitive description: name: pool - sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d" + sha256: "4177f68c237ea2128d1bee66ac17b2ce05ba3dbaafcbdd54c5d40a39d0b6b11c" url: "https://pub.dev" source: hosted - version: "1.5.2" + version: "1.5.3" posix: dependency: transitive description: name: posix - sha256: "185ef7606574f789b40f289c233efa52e96dead518aed988e040a10737febb07" + sha256: "613646d076944f3acc125830af935b48d4b8a57a388691547bbfd25b434f4d63" url: "https://pub.dev" source: hosted - version: "6.5.0" + version: "6.5.4" provider: dependency: "direct main" description: @@ -1105,98 +1169,98 @@ packages: dependency: transitive description: name: pub_semver - sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" url: "https://pub.dev" source: hosted - version: "2.2.0" + version: "2.2.1" pubspec_parse: dependency: transitive description: name: pubspec_parse - sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082" + sha256: "9ac81c01ffd6a9cf9b2713288834fbaaf6aebde05ffdf02d380e68b8e06f27d8" url: "https://pub.dev" source: hosted - version: "1.5.0" + version: "1.7.0" qr_code_scanner_plus: dependency: "direct main" description: name: qr_code_scanner_plus - sha256: dae0596b2763c2fd0294f5cfddb1d3a21577ae4dc7fc1449eb5aafc957872f61 + sha256: a49eb677d59becaab21a27bf908f860fd033987777cdc04e621e4b75f97531fa url: "https://pub.dev" source: hosted - version: "2.1.1" + version: "2.3.2" record: dependency: "direct main" description: name: record - sha256: "10911465138fafacef459a780564e883e01bd48eabf87ab20543684884492870" + sha256: "7c4467dec63435c9206db183f8a4672cf8a62f5e5579e45803ceada8330756e7" url: "https://pub.dev" source: hosted - version: "6.2.1" + version: "7.1.2" record_android: dependency: transitive description: name: record_android - sha256: eb1732e42d0d2a1895b8db86e4fc917287e6d8491b6ed59918aea8bed6c69de4 + sha256: f5080279259c4ad769590f1c165762eaa4e414178adc2e2fab137103228e07ac url: "https://pub.dev" source: hosted - version: "1.5.2" + version: "2.2.0" record_ios: dependency: transitive description: name: record_ios - sha256: c051fb48edd7a0e265daafb9108730dc827c27b551728a3fdfb3ef69efd89c73 + sha256: "21d189f49a598af4697dac4cc9e48389ac0a1fb3e916622b5504a58d9b96313e" url: "https://pub.dev" source: hosted - version: "1.2.1" + version: "2.1.1" record_linux: dependency: transitive description: name: record_linux - sha256: "31181787bf7eccb0e298835836b69b3cd0a903863b75d70e937de3dec71cd8f3" + sha256: "00c847ba25684572674dacfbd4bcabee6c5d9a1fa948778ff34091c71c19250f" url: "https://pub.dev" source: hosted - version: "1.3.1" + version: "2.1.3" record_macos: dependency: transitive description: name: record_macos - sha256: cfe1b61435e27db418bf513dc36820d10c9f7eb1843786c2c9a52e07e2f4f627 + sha256: ced7495abf3d683e8a7dbe8fc96df8ea5722837a26f922b7cb7c5de11661bb46 url: "https://pub.dev" source: hosted - version: "1.2.2" + version: "2.1.1" record_platform_interface: dependency: transitive description: name: record_platform_interface - sha256: "8e56cbe06c6984137fb86132ff03459f29938d927496d9b2d0962e2d6345d488" + sha256: d94b37cadb8fe203e64b0e9893271c0b71b34f2550ee7fb0c6105d650e00c1f5 url: "https://pub.dev" source: hosted - version: "1.6.0" + version: "2.1.0" record_use: dependency: transitive description: name: record_use - sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + sha256: "1cb8564af8d43b464294411db9217f5ec04891c6f22ee2c32d73ae05e88a6bd2" url: "https://pub.dev" source: hosted - version: "0.6.0" + version: "1.1.1" record_web: dependency: transitive description: name: record_web - sha256: "7e9846981c1f2d111d86f0ae3309071f5bba8b624d1c977316706f08fc31d16d" + sha256: "7f6950be87abacb05cf77eb6ca200b60f2c2a6af5d50236b5f4baf53f92e755e" url: "https://pub.dev" source: hosted - version: "1.3.0" + version: "2.1.3" record_windows: dependency: transitive description: name: record_windows - sha256: "223258060a1d25c62bae18282c16783f28581ec19401d17e56b5205b9f039d78" + sha256: "8195489a47b5e8246985d6213ff65aae1b14e32a0ca45dc5f680e8d503296e1b" url: "https://pub.dev" source: hosted - version: "1.0.7" + version: "2.3.0" rxdart: dependency: transitive description: @@ -1209,26 +1273,26 @@ packages: dependency: transitive description: name: shared_preferences - sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf + sha256: "1e85e0dccf5b4a016077fea7dfbb4a7cb39c759ac1596fcf60c06deadb7da91f" url: "https://pub.dev" source: hosted - version: "2.5.5" + version: "2.5.6" shared_preferences_android: dependency: transitive description: name: shared_preferences_android - sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53 + sha256: "33b38b07d9ac7d16aff0426c61418752fd3e7a8c7dc8be786c875d6ce673b002" url: "https://pub.dev" source: hosted - version: "2.4.23" + version: "2.5.4" shared_preferences_foundation: dependency: transitive description: name: shared_preferences_foundation - sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f" + sha256: "4e396ac6f8751ab7d2d6e27f22f32c8350b07006028d534f5221503382f1fa69" url: "https://pub.dev" source: hosted - version: "2.5.6" + version: "2.6.1" shared_preferences_linux: dependency: transitive description: @@ -1265,10 +1329,10 @@ packages: dependency: transitive description: name: shelf - sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + sha256: e75e9cf311d7fd712048038cc17c25199c38536c20330d53e7db058b543d5a48 url: "https://pub.dev" source: hosted - version: "1.4.2" + version: "1.4.3" shelf_web_socket: dependency: transitive description: @@ -1318,10 +1382,10 @@ packages: dependency: transitive description: name: stack_trace - sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" url: "https://pub.dev" source: hosted - version: "1.12.1" + version: "1.12.2" stream_channel: dependency: transitive description: @@ -1334,10 +1398,10 @@ packages: dependency: transitive description: name: stream_transform - sha256: ad47125e588cfd37a9a7f86c7d6356dde8dfe89d071d293f80ca9e9273a33871 + sha256: a00e5f18bffc764f923e7dec1038527f7fe7a1791361a7117f0358193f13d53a url: "https://pub.dev" source: hosted - version: "2.1.1" + version: "2.1.2" string_scanner: dependency: transitive description: @@ -1350,10 +1414,10 @@ packages: dependency: transitive description: name: synchronized - sha256: "63896c27e81b28f8cb4e69ead0d3e8f03f1d1e5fc531a3e579cabed6a2c7c9e5" + sha256: a77637ebe1460f3b48cac89a790d2eb634f0a8593cab0d3f340c6db174ba9b94 url: "https://pub.dev" source: hosted - version: "3.4.0+1" + version: "3.6.1+1" term_glyph: dependency: transitive description: @@ -1366,18 +1430,18 @@ packages: dependency: transitive description: name: test_api - sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a" + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" url: "https://pub.dev" source: hosted - version: "0.7.10" + version: "0.7.12" timezone: dependency: transitive description: name: timezone - sha256: "784a5e34d2eb62e1326f24d6f600aaaee452eb8ca8ef2f384a59244e292d158b" + sha256: "9f4e5a1a0e4fef7dd3424842c0575db01bfb7a11730e8d55753fcd5c5c98767b" url: "https://pub.dev" source: hosted - version: "0.11.0" + version: "0.11.2" timing: dependency: transitive description: @@ -1398,42 +1462,42 @@ packages: dependency: "direct main" description: name: url_launcher - sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + sha256: e8cc955c97e06df9879140a1fe301f3d493f01b7c62dec7f46834be31d7e9fda url: "https://pub.dev" source: hosted - version: "6.3.2" + version: "6.3.3" url_launcher_android: dependency: transitive description: name: url_launcher_android - sha256: "17bc677f0b301615530dd1d67e0a9828cafa2d0b6b6eae4cd3679b7eac4a273c" + sha256: "611e87fb320b70d1dd721dc46af89c98aceccea9b31fde49e084591414e0c610" url: "https://pub.dev" source: hosted - version: "6.3.30" + version: "6.3.33" url_launcher_ios: dependency: transitive description: name: url_launcher_ios - sha256: "580fe5dfb51671ae38191d316e027f6b76272b026370708c2d898799750a02b0" + sha256: "8faa1aab294f1ab4040b43660c887b0418d5fa4f0cffef76a484e6aa1092eb4a" url: "https://pub.dev" source: hosted - version: "6.4.1" + version: "6.4.2" url_launcher_linux: dependency: transitive description: name: url_launcher_linux - sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a + sha256: "10f86fef4c2c43563fa6c211ff9cf757adf4d3ab762c56bd430664a947d70cd0" url: "https://pub.dev" source: hosted - version: "3.2.2" + version: "3.2.3" url_launcher_macos: dependency: transitive description: name: url_launcher_macos - sha256: "368adf46f71ad3c21b8f06614adb38346f193f3a59ba8fe9a2fd74133070ba18" + sha256: "5e835a3b869c2d70325349c81c5a45c28e20791265b67b2669da6b08c5cd5201" url: "https://pub.dev" source: hosted - version: "3.2.5" + version: "3.2.6" url_launcher_platform_interface: dependency: transitive description: @@ -1454,34 +1518,34 @@ packages: dependency: transitive description: name: url_launcher_windows - sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f" + sha256: "6c5ad3f22cd4c38e089b81963b3cd7bb83b111b2df5dce008bb066162f42e429" url: "https://pub.dev" source: hosted - version: "3.1.5" + version: "3.1.6" uuid: dependency: "direct main" description: name: uuid - sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489" + sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" url: "https://pub.dev" source: hosted - version: "4.5.3" + version: "4.6.0" vector_math: dependency: transitive description: name: vector_math - sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + sha256: fa49e1674cb84acb900141714e6c6e1f9ae099827c24d141430ff6819db4e1bc url: "https://pub.dev" source: hosted - version: "2.2.0" + version: "2.4.4" vibration: dependency: "direct main" description: name: vibration - sha256: "9bb06614c69260f8bd11c80fe01ed7988905cf00e3417d656c2647e41f261d87" + sha256: "3424f7856b971a2ce94d22be3a3abfb5b9b5984562fdedd621f4e67574be7254" url: "https://pub.dev" source: hosted - version: "3.1.8" + version: "3.2.1" vibration_platform_interface: dependency: transitive description: @@ -1494,34 +1558,34 @@ packages: dependency: "direct main" description: name: video_player - sha256: "48a7bdaa38a3d50ec10c78627abdbfad863fdf6f0d6e08c7c3c040cfd80ae36f" + sha256: "07ae1e03f2d4c8e2e9a75ee678f90acbc4506d4458a9c628512d119a1eee5754" url: "https://pub.dev" source: hosted - version: "2.11.1" + version: "2.14.1" video_player_android: dependency: transitive description: name: video_player_android - sha256: "877a6c7ba772456077d7bfd71314629b3fe2b73733ce503fc77c3314d43a0ca0" + sha256: d27054dea34d748a44f06d433a57005d2aac69944485b0abbaed3303dbcfa3f1 url: "https://pub.dev" source: hosted - version: "2.9.5" + version: "2.12.2" video_player_avfoundation: dependency: transitive description: name: video_player_avfoundation - sha256: "9338f3ec22774f88146b22f13273a446719b1da010fd200c4d1d97802156ac58" + sha256: "7d620d8c69d00c158a5c57bf3d2a051833b547631203ff724664fbf301024bc1" url: "https://pub.dev" source: hosted - version: "2.9.7" + version: "2.12.3" video_player_platform_interface: dependency: transitive description: name: video_player_platform_interface - sha256: "16eaed5268c571c31840dc58ef8da5f0cd4db2a98490c3b8f1cf70122546c6e0" + sha256: "92c0fbabe20c788e71fd10d26cea998d0d253282e65d145aed0818731cf593ce" url: "https://pub.dev" source: hosted - version: "6.7.0" + version: "6.9.0" video_player_web: dependency: transitive description: @@ -1534,26 +1598,26 @@ packages: dependency: transitive description: name: vm_service - sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" + sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78" url: "https://pub.dev" source: hosted - version: "15.2.0" + version: "15.4.0" wakelock_plus: dependency: transitive description: name: wakelock_plus - sha256: ddf3db70eaa10c37558ff817519b85d527dbd21034fd5d8e1c2e85f31588f1c1 + sha256: "39a1d99085cf3190d41305bca05f0c0d77522f355f7f99bb648ee231192d9d68" url: "https://pub.dev" source: hosted - version: "1.5.2" + version: "1.8.2" wakelock_plus_platform_interface: dependency: transitive description: name: wakelock_plus_platform_interface - sha256: b13f99e992e7ae6a152e16c5559d3c07ff445b13330192662494e614ca3e7d7b + sha256: "764c25504562abc8ac3406f5d175f126b276e6ba916c7c2675690b73368ca384" url: "https://pub.dev" source: hosted - version: "1.5.1" + version: "1.7.0" watcher: dependency: transitive description: @@ -1566,10 +1630,10 @@ packages: dependency: transitive description: name: web - sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + sha256: e119e82ac4795c7925103b7cf3768191f33941b99e7ccffbd6c645201d9f606b url: "https://pub.dev" source: hosted - version: "1.1.1" + version: "1.1.2" web_socket: dependency: transitive description: @@ -1604,18 +1668,26 @@ packages: dependency: transitive description: name: win32 - sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d url: "https://pub.dev" source: hosted - version: "5.15.0" + version: "6.4.0" win32_registry: dependency: transitive description: name: win32_registry - sha256: "6f1b564492d0147b330dd794fee8f512cec4977957f310f9951b5f9d83618dae" + sha256: "73b1d78920a9d6e03f8b4e43e612b87bf3152a0e5c5e5150267762b7c4116904" url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "3.0.3" + windows_file_picker: + dependency: transitive + description: + name: windows_file_picker + sha256: cd1be37ada0abcfaa55bddb7410e8515844e35cd77669c35d9a28a15722299d8 + url: "https://pub.dev" + source: hosted + version: "2.0.2" xdg_directories: dependency: transitive description: @@ -1628,18 +1700,18 @@ packages: dependency: transitive description: name: xml - sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + sha256: "0fe8cc98946def31cbcbc8734aa4067031e6f65ea3a78a508060bfed2200bfeb" url: "https://pub.dev" source: hosted - version: "6.6.1" + version: "7.1.0" yaml: dependency: transitive description: name: yaml - sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea url: "https://pub.dev" source: hosted - version: "3.1.3" + version: "3.1.4" sdks: - dart: ">=3.11.0 <4.0.0" - flutter: ">=3.41.0" + dart: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" diff --git a/pubspec.yaml b/pubspec.yaml index a8921e2..2983ea8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -10,22 +10,22 @@ environment: dependencies: basic_utils: ^5.7.0 bcrypt: ^1.1.3 - chewie: ">=1.7.0 <1.11.0" + chewie: ^1.17.4 crypto: ^3.0.5 cryptography: ^2.7.0 dart_jsonwebtoken: ^3.2.0 easy_localization: ^3.0.7 email_validator: ^3.0.0 - file_picker: ^8.0.0 - firebase_core: ^4.0.0 - firebase_messaging: ^16.0.0 + file_picker: ^13.3.3 + firebase_core: ^5.1.0 + firebase_messaging: ^17.0.1 flutter: sdk: flutter flutter_colorpicker: ^1.1.0 flutter_launcher_icons: ^0.14.3 - flutter_local_notifications: ^21.0.0 - flutter_secure_storage: ^10.0.0 - fluttertoast: ^9.0.0 + flutter_local_notifications: ^23.0.0 + flutter_secure_storage: ^11.2.0 + fluttertoast: ^10.0.2 hive: ^2.2.3 http: ^1.2.1 image_picker: ^1.2.2 @@ -40,7 +40,7 @@ dependencies: pointycastle: ^4.0.0 provider: ^6.1.2 qr_code_scanner_plus: ^2.0.6 - record: ^6.2.1 + record: ^7.1.2 sprintf: ^7.0.0 url_launcher: ^6.3.1 uuid: ^4.5.3 From e38f3199f8b517b411515b2565a31f8bfc60f545 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Wed, 11 Nov 2026 02:58:20 +0100 Subject: [PATCH 011/181] chore(ci): add Flutter CI and agent rules - flutter-ci.yml: format on changed files, analyze, test, secret scan - skip CI for fork pull requests, which cannot read repository secrets - exclude build_runner output from analysis - adapt media upload and download call sites to the regenerated client --- .github/dependabot.yml | 17 +++++++++ .github/workflows/flutter-ci.yml | 61 ++++++++++++++++++++++++++++++++ AGENTS.md | 39 ++++++++++++++++++++ README.md | 27 +++++++++----- analysis_options.yaml | 2 ++ lefthook.yml | 5 +++ lib/pages/chat_page.dart | 16 ++++----- lib/utils/message_notifier.dart | 23 ++++++------ 8 files changed, 161 insertions(+), 29 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/flutter-ci.yml create mode 100644 AGENTS.md create mode 100644 lefthook.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..e104ae1 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,17 @@ +version: 2 +updates: + - package-ecosystem: pub + directory: / + schedule: + interval: weekly + open-pull-requests-limit: 5 + + - package-ecosystem: gradle + directory: /android + schedule: + interval: monthly + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/flutter-ci.yml b/.github/workflows/flutter-ci.yml new file mode 100644 index 0000000..7e4338b --- /dev/null +++ b/.github/workflows/flutter-ci.yml @@ -0,0 +1,61 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + ci: + name: Analyze and test + # Fork pull requests cannot read repository secrets, so analysis cannot run. + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + + - name: Create Firebase options + env: + FIREBASE_OPTIONS_DART_BASE64: ${{ secrets.FIREBASE_OPTIONS_DART_BASE64 }} + run: | + if [ -z "$FIREBASE_OPTIONS_DART_BASE64" ]; then + echo "FIREBASE_OPTIONS_DART_BASE64 secret is required for analysis" + exit 1 + fi + echo "$FIREBASE_OPTIONS_DART_BASE64" | base64 -d > lib/firebase_options.dart + + - name: Get dependencies + run: flutter pub get + + - name: Format (changed files) + run: | + BASE="origin/${{ github.base_ref || 'main' }}" + git fetch origin "${{ github.base_ref || 'main' }}" 2>/dev/null || true + FILES=$(git diff --name-only --diff-filter=ACMR "$BASE"...HEAD -- '*.dart' | tr '\n' ' ') + if [ -z "$FILES" ]; then + echo "No changed Dart files." + exit 0 + fi + dart format --output=none --set-exit-if-changed $FILES + + - name: Analyze + # Infos are not fatal: the legacy UI has known lints. Errors and warnings block. + run: flutter analyze --no-fatal-infos + + - name: Test + run: flutter test + + - name: Secret scan + uses: gitleaks/gitleaks-action@v2 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..76357b1 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,39 @@ +# whisper — agent contract + +Flutter 3.47 / Dart 3.13 client for Whisper. Talks to `whisper-server` over HTTP (generated `whisper_openapi_client_dart`) +and WebSocket (`whisper_websocket_client_dart`). + +## Commands + +- deps: `flutter pub get` +- analyze: `flutter analyze --no-fatal-infos` (errors and warnings block, infos do not) +- format: `dart format` on the files you touched +- test: `flutter test` +- build: `flutter build apk --release` (requires `firebase_options.dart`, `google-services.json`, `firebase.json`) + +## Hard rules + +1. Never commit secrets, keys, `.env*`, `firebase_options.dart`, `google-services.json` or `firebase.json`. +2. Do not edit `whisper_openapi_client_dart/lib` or `whisper_websocket_client_dart/lib` by hand. Contract changes go through `whisper-server` and regeneration (skill `contract-change`). +3. `lib/media_download.dart` is a hand-written extension of the generated client — when the download changes, edit this file, not the generated `downloadMedia`. +4. Crypto: never lower RSA 4096, AES-256-GCM or PBKDF2 parameters. No key may leave the device in plaintext and no seed may be constant. +5. Do not weaken the app lock (password, biometrics), not even "temporarily for debugging". +6. Never disable a test, lint or the analyzer to get CI green. Fix it, or file an issue and escalate. +7. Force-push only to your own feature branch, never to `main`. + +## Where it hurts + +- **Media upload**: `uploadMedia(file, receiverId)` — the argument order comes from the generator, not from logic. Verify call sites after regenerating the client. +- **Path dependencies**: `pubspec.yaml` pulls both clients via `path:`, so CI cannot see which client version the app actually uses. Pinning to a tag is phase 2 debt. +- **Firebase**: analysis fails without `lib/firebase_options.dart`. CI decodes it from a secret. + +## Definition of done + +- New non-trivial logic has a test (`test/`). +- `flutter analyze --no-fatal-infos` reports no errors and no warnings. +- Formatting is clean on the files you touched. +- A contract change ships the regenerated client and the updated call sites in one PR. + +## When unsure + +Stop and ask. Security decisions (keys, encryption, auth) are not up for guessing. diff --git a/README.md b/README.md index 1dd70ff..faa9444 100644 --- a/README.md +++ b/README.md @@ -117,18 +117,27 @@ flutterfire configure \ Then select your Firebase project. This will generate the necessary `firebase.json` and `lib/firebase_options.dart` files. -## Continuous Integration a Deployment (CI/CD) +## Continuous Integration and Deployment (CI/CD) -The application uses GitHub Actions to automatically build and release the APK file when pushing to the `main` branch. For this process to work correctly, the following secret keys must be set in the repository settings (Settings > Secrets and variables > Actions): +Two GitHub Actions workflows run in this repository: -- `FIREBASE_JSON_BASE64` - base64 encoded contents of the `firebase.json` file -- `FIREBASE_OPTIONS_DART_BASE64` - base64 encoded contents of the `lib/firebase_options.dart` file (required) -- `GOOGLE_SERVICES_JSON_BASE64` - base64 encoded contents of the `android/app/google-services.json` file - +- `flutter-ci.yml` — on pull requests and on pushes to `main`: format check on changed files, `flutter analyze`, `flutter test`, secret scan. +- `build_and_release.yml` — on pushes to `main`: builds the release APK and publishes a GitHub Release tagged `v`, where the version comes from `pubspec.yaml`. + +Required repository secrets (Settings > Secrets and variables > Actions): + +| Secret | Used by | Description | +| --- | --- | --- | +| `FIREBASE_OPTIONS_DART_BASE64` | `flutter-ci.yml`, `build_and_release.yml` | base64 of `lib/firebase_options.dart`. Required: analysis fails without it. | +| `FIREBASE_JSON_BASE64` | `build_and_release.yml` | base64 of `firebase.json`. | +| `GOOGLE_SERVICES_JSON_BASE64` | `build_and_release.yml` | base64 of `android/app/google-services.json`. | +| `GOOGLE_SERVICE_INFO_PLIST_BASE64` | not wired yet | base64 of `ios/Runner/GoogleService-Info.plist`. Add it to the build before shipping iOS releases. | +| `GITHUB_TOKEN` | both | Provided automatically by GitHub. Used by the secret scan. | + +Pull requests from forks cannot read repository secrets, so CI is skipped for them. + +These files are not included in the repository for security reasons. The base64 encoding ensures safe transmission and prevents issues with special characters. -These secret keys will be used during application build to generate the necessary Firebase configuration files, which are not included in the repository for security reasons. The base64 encoding ensures safe transmission and prevents issues with special characters. ### Procedure for setting up CI/CD diff --git a/analysis_options.yaml b/analysis_options.yaml index 7e428b9..b0dab33 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -13,6 +13,8 @@ analyzer: - android/** - ios/** - linux/** + # Generated by build_runner. + - "**/*.g.dart" include: package:flutter_lints/flutter.yaml linter: diff --git a/lefthook.yml b/lefthook.yml new file mode 100644 index 0000000..9518c3d --- /dev/null +++ b/lefthook.yml @@ -0,0 +1,5 @@ +pre-commit: + parallel: true + commands: + gitleaks: + run: gitleaks git --pre-commit --staged --redact --no-banner diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 39e7cb7..d566839 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -173,18 +173,18 @@ class _ChatPageState extends State { // Upload the ciphertext over HTTP. final uploadResponse = await Utils.callApi( () => Singleton().mediaApi.uploadMedia( - widget.user.id, MultipartFile.fromBytes('file', transport.blob, filename: 'media.bin'), + widget.user.id, ), rethrowErr: true, ); - if (uploadResponse == null || uploadResponse.id == null) { + if (uploadResponse == null) { await Fluttertoast.showToast( msg: 'mediaUploadFailed'.tr(), backgroundColor: Colors.red); return; } - final mediaId = uploadResponse.id!; + final mediaId = uploadResponse.id; // Build the encrypted reference and wrap it in the message envelope. final reference = MediaReference( @@ -285,8 +285,7 @@ class _ChatPageState extends State { title: Text('attachCamera'.tr()), onTap: () { Navigator.pop(ctx); - _pickAndSend( - MediaUtils.pickImageFromCamera, MediaType.image); + _pickAndSend(MediaUtils.pickImageFromCamera, MediaType.image); }, ), ListTile( @@ -294,8 +293,7 @@ class _ChatPageState extends State { title: Text('attachVideoCamera'.tr()), onTap: () { Navigator.pop(ctx); - _pickAndSend( - MediaUtils.pickVideoFromCamera, MediaType.video); + _pickAndSend(MediaUtils.pickVideoFromCamera, MediaType.video); }, ), ListTile( @@ -502,9 +500,7 @@ class _ChatPageState extends State { const SizedBox(width: 16), Expanded( child: Text( - _cancelRecording - ? 'releaseToCancel'.tr() - : 'slideToCancel'.tr(), + _cancelRecording ? 'releaseToCancel'.tr() : 'slideToCancel'.tr(), style: TextStyle(color: Colors.grey[600]), overflow: TextOverflow.ellipsis, ), diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index f588f30..150de34 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:whisper_openapi_client_dart/media_download.dart'; import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import '../utils/notification_service.dart'; @@ -35,14 +36,13 @@ class MessageNotifier extends ChangeNotifier { _pendingMediaRefs[reference.mediaId] = reference; try { final blob = await Utils.callApi( - () => Singleton().mediaApi.downloadMedia(reference.mediaId), + () => Singleton().mediaApi.downloadMediaBytes(reference.mediaId), rethrowErr: true, ); if (blob == null) { throw Exception('empty media download'); } - final plaintext = - await MediaUtils.decryptTransport(blob, reference.key); + final plaintext = await MediaUtils.decryptTransport(blob, reference.key); final localPath = await MediaUtils.encryptAtRest(plaintext); await CacheUtils.updatePrivateMessageMedia( conversationUserId, @@ -66,7 +66,8 @@ class MessageNotifier extends ChangeNotifier { } /// Retry a previously failed media download (current session only). - Future retryMediaDownload(int conversationUserId, String mediaId) async { + Future retryMediaDownload( + int conversationUserId, String mediaId) async { final reference = _pendingMediaRefs[mediaId]; if (reference == null) { return; @@ -88,8 +89,8 @@ class MessageNotifier extends ChangeNotifier { // Check if users exist for (var msg in messages) { if (!await CacheUtils.userExists(msg.senderId)) { - var user = - await Utils.callApi(() => Singleton().userApi.getUserById(msg.senderId)); + var user = await Utils.callApi( + () => Singleton().userApi.getUserById(msg.senderId)); if (user != null) { // Save user to cache await CacheUtils.addUser(User.fromModel(user)); @@ -103,8 +104,10 @@ class MessageNotifier extends ChangeNotifier { /// Get all messages by user ID Future> getMessages(int userId) async { - var messages = await CacheUtils.getPrivateMessages(userId, markAsRead: true); - await NotificationService().removeNotificationsById(messages.map((x) => x.notificationId).toList()); + var messages = + await CacheUtils.getPrivateMessages(userId, markAsRead: true); + await NotificationService().removeNotificationsById( + messages.map((x) => x.notificationId).toList()); return messages; } @@ -116,8 +119,8 @@ class MessageNotifier extends ChangeNotifier { for (var e in messages.entries) { // User does not exists in cache if (!e.key.isInBox) { - var user = - await Utils.callApi(() => Singleton().userApi.getUserById(e.key.id)); + var user = await Utils.callApi( + () => Singleton().userApi.getUserById(e.key.id)); if (user != null) { // Save user to cache await CacheUtils.addUser(User.fromModel(user)); From 20ebddf6a6e818f650c3ff1fb2b516d92cfdeb5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Wed, 11 Nov 2026 03:34:48 +0100 Subject: [PATCH 012/181] docs: drop the TODO list from the README The backlog is tracked outside the repository now; keeping a second copy in the README only made it drift. --- README.md | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/README.md b/README.md index faa9444..4839c0d 100644 --- a/README.md +++ b/README.md @@ -149,22 +149,3 @@ These files are not included in the repository for security reasons. The base64 4. Paste the base64 encoded content as the secret key value After setting these secret keys, the workflow will automatically build the APK on every push to the `main` branch and create a new GitHub Release with the version according to `pubspec.yaml`. - -## TODO - -- nelze ukončit nahrávání hlasové zprávy a odeslat ji, reimplementovat logiku -- nastavit maximální velikost přílohy HTTP požadavku -- při otevření přílohy možnost uložit dešifrovaně do zařízení -- opravit hrozně pomalé načítání náhledů obrázků u příjemce (kolečko se točí donekonečna, po kliknutí ale náhled funguje) -- při odesílání zprávy indikovat že se odesílá, nyní se neindikuje nic a uživatel může myslet že se zpráva vůbec neodeslala nebo se neodesílá vůbec nic (zpráva se zobrazí až po odeslání) -- videa nemají náhled, jen šedivou barvu -- opravit to, že po otevření chatu není vždy nascrollováno úplně dolů -- výběr GIFů nedělat ze souborů, ale ve stylu Discordu (výběr zdroje Tenor a Giphy) -- zarovnání hlasové zprávy, progressbar je moc nahoře -- postupný loading zpráv pro optimalizaci rychlosti -- možnost vybrat více fotek/souborů najednou a odeslat je jako album -- při odesílání souborů neumožnit odeslat fotky a videa, pouze všechny ostatní soubory -- nastavit verzi na serveru pro kontrolu kompatibility s klientem (+ knihovny) -- schopnost podle GitHub releasů zjistit aktuální verzi a upozornit uživatele na aktualizaci a stáhnout a nainstalovat ji (+ checksums) -- pro nepodporované soubory pro náhled (PDF atd, zobrazovat ikonu přípony jako náhled -- potvrzení odeslání přílohy po vybrání (pro možnost dopsat k ní text) From 5b2539f160140caea05c1a6fc3e5e4a8acc213d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Wed, 11 Nov 2026 17:07:22 +0100 Subject: [PATCH 013/181] feat: phase 2 (Linux desktop E2E) --- .github/workflows/build_and_release.yml | 4 + .github/workflows/flutter-e2e.yml | 55 +++++++ AGENTS.md | 1 + integration_test/app_e2e_test.dart | 166 +++++++++++++++++++++ integration_test/fake_server.dart | 187 ++++++++++++++++++++++++ pubspec.lock | 39 +++++ pubspec.yaml | 2 + 7 files changed, 454 insertions(+) create mode 100644 .github/workflows/flutter-e2e.yml create mode 100644 integration_test/app_e2e_test.dart create mode 100644 integration_test/fake_server.dart diff --git a/.github/workflows/build_and_release.yml b/.github/workflows/build_and_release.yml index 84dff6b..ff21b92 100644 --- a/.github/workflows/build_and_release.yml +++ b/.github/workflows/build_and_release.yml @@ -6,7 +6,11 @@ on: - main jobs: + e2e: + uses: ./.github/workflows/flutter-e2e.yml + build: + needs: e2e runs-on: ubuntu-latest permissions: contents: write diff --git a/.github/workflows/flutter-e2e.yml b/.github/workflows/flutter-e2e.yml new file mode 100644 index 0000000..7c6da16 --- /dev/null +++ b/.github/workflows/flutter-e2e.yml @@ -0,0 +1,55 @@ +name: Flutter E2E + +on: + schedule: + - cron: '0 2 * * *' + workflow_dispatch: + workflow_call: + +permissions: + contents: read + +jobs: + e2e: + name: Linux desktop integration tests + runs-on: ubuntu-latest + steps: + - name: Checkout app + uses: actions/checkout@v7 + with: + path: whisper + + - name: Checkout OpenAPI client + uses: actions/checkout@v7 + with: + repository: jsfraz/whisper_openapi_client_dart + ref: ${{ github.ref_name }} + path: whisper_openapi_client_dart + + - name: Checkout WebSocket client + uses: actions/checkout@v7 + with: + repository: jsfraz/whisper_websocket_client_dart + ref: ${{ github.ref_name }} + path: whisper_websocket_client_dart + + - name: Install Linux desktop dependencies + run: | + sudo apt-get update + sudo apt-get install -y clang cmake ninja-build pkg-config xvfb \ + libgtk-3-dev liblzma-dev libsecret-1-dev + + - uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + + - name: Get dependencies + working-directory: whisper + run: | + flutter config --enable-linux-desktop + flutter pub get + + - name: Run E2E + working-directory: whisper + run: xvfb-run -a flutter test integration_test -d linux diff --git a/AGENTS.md b/AGENTS.md index 76357b1..d269fbd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,6 +9,7 @@ and WebSocket (`whisper_websocket_client_dart`). - analyze: `flutter analyze --no-fatal-infos` (errors and warnings block, infos do not) - format: `dart format` on the files you touched - test: `flutter test` +- e2e: `flutter test integration_test -d linux` (needs Linux desktop toolchain) - build: `flutter build apk --release` (requires `firebase_options.dart`, `google-services.json`, `firebase.json`) ## Hard rules diff --git a/integration_test/app_e2e_test.dart b/integration_test/app_e2e_test.dart new file mode 100644 index 0000000..6a0c4b7 --- /dev/null +++ b/integration_test/app_e2e_test.dart @@ -0,0 +1,166 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:basic_utils/basic_utils.dart' as bu; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:http/http.dart' as http; +import 'package:integration_test/integration_test.dart'; +import 'package:pointycastle/export.dart'; +import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper/utils/crypto_utils.dart'; +import 'package:whisper/utils/media_utils.dart'; +import 'package:whisper/utils/utils.dart'; +import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:whisper_websocket_client_dart/models/new_private_message.dart'; +import 'package:whisper_websocket_client_dart/models/private_message.dart'; +import 'package:whisper_websocket_client_dart/models/ws_message.dart'; +import 'package:whisper_websocket_client_dart/models/ws_response.dart'; +import 'package:whisper_websocket_client_dart/ws_client.dart'; + +import 'fake_server.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + late FakeServer server; + late AsymmetricKeyPair keys; + + setUpAll(() async { + server = await FakeServer.start(); + Directory cacheDir = Directory(await Utils.getCacheDir()); + await cacheDir.create(recursive: true); + Hive.init(cacheDir.path); + keys = await CryptoUtils.getRSAKeyPair(); + }); + + tearDownAll(() async { + Box box = await Hive.openBox('hash'); + await box.clear(); + await Hive.close(); + await server.stop(); + }); + + ApiClient client(String? accessToken) { + HttpBearerAuth? auth; + if (accessToken != null) { + auth = HttpBearerAuth()..accessToken = accessToken; + } + return ApiClient(basePath: server.url, authentication: auth); + } + + testWidgets('invite registration creates a user', (tester) async { + final apiClient = client(null); + final user = await AuthenticationApi(apiClient).createUser( + createUserInput: CreateUserInput( + inviteCode: 'i' * 64, + publicKey: bu.CryptoUtils.encodeRSAPublicKeyToPem( + keys.publicKey as bu.RSAPublicKey), + username: 'e2euser', + ), + ); + + expect(user, isNotNull); + expect(user!.username, 'e2euser'); + expect(user.id, greaterThan(0)); + }); + + testWidgets('login with RSA JWT and refresh', (tester) async { + final apiClient = client(null); + final jwt = await CryptoUtils.generateRsaJwt( + 1, keys.privateKey as bu.RSAPrivateKey); + final auth = await AuthenticationApi(apiClient).authUser( + authUserInput: AuthUserInput(token: jwt), + ); + + expect(auth!.accessToken, isNotEmpty); + expect(auth.refreshToken, isNotEmpty); + + final refreshed = await AuthenticationApi(apiClient).refreshUserAccessToken( + refreshUserAccessTokenInput: + RefreshUserAccessTokenInput(refreshToken: auth.refreshToken), + ); + expect(refreshed!.accessToken, isNotEmpty); + }); + + testWidgets('message is encrypted, sent over WS and decrypted by receiver', + (tester) async { + final receiverToken = + await WebSocketAuthenticationApi(client('access-1')).webSocketAuth(); + final senderToken = + await WebSocketAuthenticationApi(client('access-2')).webSocketAuth(); + + final received = Completer(); + final receiver = WsClient(server.wsUrl, onReceived: received.complete); + await receiver.connect( + receiverToken!.accessToken, const Duration(seconds: 5)); + final sender = WsClient(server.wsUrl); + await sender.connect(senderToken!.accessToken, const Duration(seconds: 5)); + + final encrypted = await CryptoUtils.encryptMessageData( + Uint8List.fromList(utf8.encode('hello over websocket')), + keys.publicKey as RSAPublicKey); + sender.sendMessage(WsMessage.privateMessage(NewPrivateMessage( + 1, + encrypted['encryptedData']!, + encrypted['encryptedKey']!, + encrypted['nonce']!, + encrypted['mac']!, + ))); + + final response = await received.future.timeout(const Duration(seconds: 5)); + final message = (response.payload as List).single; + expect(message.senderId, 2); + + final plaintext = await CryptoUtils.decryptMessageData( + message.content, + message.key, + message.nonce, + message.mac, + keys.privateKey as RSAPrivateKey, + ); + expect(utf8.decode(plaintext), 'hello over websocket'); + sender.disconnect(); + receiver.disconnect(); + }); + + testWidgets('media upload sends only ciphertext and receiver decrypts it', + (tester) async { + final plaintext = Uint8List.fromList(utf8.encode('top secret attachment')); + final encrypted = await MediaUtils.encryptForTransport(plaintext); + + final upload = await MediaApi(client('access-1')).uploadMedia( + http.MultipartFile.fromBytes('file', encrypted.blob, + filename: 'blob.bin'), + 2, + ); + expect(upload!.id, isNotEmpty); + + final download = await http.get( + Uri.parse('${server.url}/api/media/${upload.id}'), + headers: {'Authorization': 'Bearer access-2'}, + ); + expect(download.statusCode, 200); + expect(download.bodyBytes, isNot(equals(plaintext))); + expect(download.bodyBytes, encrypted.blob); + expect(await MediaUtils.decryptTransport(download.bodyBytes, encrypted.key), + plaintext); + + await MediaApi(client('access-2')).confirmMediaDownload(upload.id); + }); + + testWidgets('local password unlocks with a stable derived key', + (tester) async { + const password = 'correct horse battery staple'; + await CacheUtils.setPasswordHash(password); + + expect(await CacheUtils.isCorrectPassword(password), isTrue); + expect(await CacheUtils.isCorrectPassword('wrong password'), isFalse); + + final first = await CryptoUtils.pbkdf2(password); + final second = await CryptoUtils.pbkdf2(password); + expect(first, second); + }); +} diff --git a/integration_test/fake_server.dart b/integration_test/fake_server.dart new file mode 100644 index 0000000..2454421 --- /dev/null +++ b/integration_test/fake_server.dart @@ -0,0 +1,187 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:mime/mime.dart'; + +/// Minimal in-process backend for the Flutter E2E scenarios. It mirrors the +/// server contract closely enough to exercise the real generated API client, +/// the WebSocket client and the app crypto. +class FakeServer { + FakeServer._(this._server); + + final HttpServer _server; + final Map _wsTokens = {}; + final Map _sockets = {}; + final Map _media = {}; + final Map _mediaReceivers = {}; + int _nextUserId = 1; + int _nextMediaId = 1; + + String get url => 'http://127.0.0.1:${_server.port}'; + String get wsUrl => 'ws://127.0.0.1:${_server.port}/ws'; + + static Future start() async { + final server = FakeServer._( + await HttpServer.bind(InternetAddress.loopbackIPv4, 0), + ); + server._server.listen(server._handle); + return server; + } + + Future stop() async { + for (final socket in _sockets.values) { + await socket.close(); + } + await _server.close(force: true); + } + + Future _handle(HttpRequest request) async { + final path = request.uri.path; + if (path == '/ws') { + await _handleWebSocket(request); + return; + } + try { + if (path == '/api/auth/register') { + final body = await _readJson(request); + _json(request.response, { + 'id': _nextUserId++, + 'username': body['username'], + 'publicKey': body['publicKey'], + 'admin': false, + }); + } else if (path == '/api/auth') { + _json(request.response, { + 'accessToken': 'access-1', + 'refreshToken': 'refresh-1', + }); + } else if (path == '/api/auth/refresh') { + _json(request.response, {'accessToken': 'access-1'}); + } else if (path == '/api/wsauth') { + final userId = _userId(request); + final token = 'ws-$userId-${_wsTokens.length}'; + _wsTokens[token] = userId; + _json(request.response, {'accessToken': token}); + } else if (path == '/api/media' && request.method == 'POST') { + await _handleUpload(request); + } else if (path.startsWith('/api/media/')) { + final id = path.substring('/api/media/'.length); + if (request.method == 'GET') { + _handleDownload(request, id); + } else if (request.method == 'DELETE') { + _media.remove(id); + _mediaReceivers.remove(id); + request.response.statusCode = HttpStatus.noContent; + } else { + request.response.statusCode = HttpStatus.methodNotAllowed; + } + } else { + request.response.statusCode = HttpStatus.notFound; + } + } catch (e) { + request.response.statusCode = HttpStatus.internalServerError; + request.response.write('$e'); + } finally { + await request.response.close(); + } + } + + Future _handleUpload(HttpRequest request) async { + final boundary = request.headers.contentType?.parameters['boundary']; + if (boundary == null) { + request.response.statusCode = HttpStatus.badRequest; + return; + } + Uint8List? file; + var receiverId = 0; + await for (final part in MimeMultipartTransformer(boundary).bind(request)) { + final disposition = part.headers['content-disposition'] ?? ''; + final bytes = await part + .fold>([], (buffer, chunk) => buffer..addAll(chunk)); + if (disposition.contains('name="receiverId"')) { + receiverId = int.parse(utf8.decode(bytes)); + } else if (disposition.contains('name="file"') && + disposition.contains('filename=')) { + file = Uint8List.fromList(bytes); + } + } + if (file == null) { + request.response.statusCode = HttpStatus.badRequest; + return; + } + final id = 'media-${_nextMediaId++}'; + _media[id] = file; + _mediaReceivers[id] = receiverId; + _json(request.response, {'id': id}); + } + + void _handleDownload(HttpRequest request, String id) { + final file = _media[id]; + if (file == null) { + request.response.statusCode = HttpStatus.notFound; + return; + } + if (_userId(request) != _mediaReceivers[id]) { + request.response.statusCode = HttpStatus.forbidden; + return; + } + request.response.headers.contentType = ContentType.binary; + request.response.add(file); + } + + Future _handleWebSocket(HttpRequest request) async { + final token = request.uri.queryParameters['wsAccessToken']; + final userId = _wsTokens.remove(token); + if (userId == null) { + request.response.statusCode = HttpStatus.unauthorized; + return; + } + final socket = await WebSocketTransformer.upgrade(request); + _sockets[userId] = socket; + socket.listen((data) { + final text = data is String ? data : utf8.decode(data as List); + final message = jsonDecode(text) as Map; + if (message['type'] != 'message') { + return; + } + final payload = message['payload'] as Map; + final receiverId = payload['receiverId'] as int; + final response = jsonEncode({ + 'type': 'messages', + 'payload': [ + { + 'senderId': userId, + 'content': payload['content'], + 'key': payload['key'], + 'nonce': payload['nonce'], + 'mac': payload['mac'], + 'sentAt': payload['sentAt'], + 'recipientOnline': true, + } + ], + }); + final receiver = _sockets[receiverId]; + if (receiver != null) { + receiver.add(utf8.encode(response)); + } + }, onDone: () => _sockets.remove(userId)); + } + + Future> _readJson(HttpRequest request) async { + final body = await utf8.decoder.bind(request).join(); + return jsonDecode(body) as Map; + } + + int _userId(HttpRequest request) { + final header = request.headers.value(HttpHeaders.authorizationHeader) ?? ''; + final token = header.replaceFirst('Bearer ', ''); + return int.tryParse(token.replaceFirst('access-', '')) ?? 0; + } + + void _json(HttpResponse response, Object body) { + response.headers.contentType = ContentType.json; + response.write(jsonEncode(body)); + } +} diff --git a/pubspec.lock b/pubspec.lock index 03a1ddb..357efd4 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -502,6 +502,11 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" + flutter_driver: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" flutter_launcher_icons: dependency: "direct main" description: @@ -645,6 +650,11 @@ packages: url: "https://pub.dev" source: hosted version: "4.2.0" + fuchsia_remote_debug_protocol: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" glob: dependency: transitive description: @@ -789,6 +799,11 @@ packages: url: "https://pub.dev" source: hosted version: "0.2.2" + integration_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" intl: dependency: transitive description: @@ -1157,6 +1172,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.5.4" + process: + dependency: transitive + description: + name: process + sha256: "4242ba3508d37e01808bdf71ad1d5bb93a8d671bf2e7450e6b1b353fb0808891" + url: "https://pub.dev" + source: hosted + version: "5.0.6" provider: dependency: "direct main" description: @@ -1410,6 +1433,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.1" + sync_http: + dependency: transitive + description: + name: sync_http + sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961" + url: "https://pub.dev" + source: hosted + version: "0.3.1" synchronized: dependency: transitive description: @@ -1650,6 +1681,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.3" + webdriver: + dependency: transitive + description: + name: webdriver + sha256: "28b82ec894fed45dd71c23ba62d1af973ed97dd59a4f5790a4d38b0b13e5657e" + url: "https://pub.dev" + source: hosted + version: "3.2.0" whisper_openapi_client_dart: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 2983ea8..f3110a9 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -54,6 +54,8 @@ dependencies: dev_dependencies: flutter_test: sdk: flutter + integration_test: + sdk: flutter flutter_lints: ^6.0.0 hive_generator: ^2.0.1 build_runner: ^2.4.12 From 2304e420e9d6cf8702331364faf404cc3a58e973 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Wed, 11 Nov 2026 19:35:50 +0100 Subject: [PATCH 014/181] docs: add phase 3 ADRs --- docs/adr/0001-local-encryption.md | 25 +++++++++++++++++++++++++ docs/adr/0002-client-versioning.md | 25 +++++++++++++++++++++++++ docs/adr/README.md | 8 ++++++++ 3 files changed, 58 insertions(+) create mode 100644 docs/adr/0001-local-encryption.md create mode 100644 docs/adr/0002-client-versioning.md create mode 100644 docs/adr/README.md diff --git a/docs/adr/0001-local-encryption.md b/docs/adr/0001-local-encryption.md new file mode 100644 index 0000000..ff0e2f8 --- /dev/null +++ b/docs/adr/0001-local-encryption.md @@ -0,0 +1,25 @@ +# 0001 - Encrypt on the device, server sees ciphertext + +Status: accepted (2026-11-11) + +## Context + +Messages and media pass through a self-hosted server that must not be able to +read them. There is no key escrow and no password reset that would recover +content. + +## Decision + +- Messages: AES-256-GCM content, AES key wrapped with the recipient's RSA-4096 + public key; the server only routes the envelope. +- Media: a random per-file AES-256-GCM key encrypts the uploaded bytes; the key + travels inside the encrypted message. Downloads are decrypted on the device + and stored encrypted at rest with the app master key. +- The app master key is derived from the local password with PBKDF2 and is kept + in secure storage for biometric unlock. + +## Consequences + +- A lost private key means the history is unreadable. +- The server cannot scan or transcode attachments. +- RSA-4096, AES-256-GCM and PBKDF2 parameters are a hard floor. diff --git a/docs/adr/0002-client-versioning.md b/docs/adr/0002-client-versioning.md new file mode 100644 index 0000000..81919f5 --- /dev/null +++ b/docs/adr/0002-client-versioning.md @@ -0,0 +1,25 @@ +# 0002 - Pin clients to tags once releases exist + +Status: accepted (2026-11-11); supersedes the `path:` setup once a server tag exists + +## Context + +`pubspec.yaml` pulls `whisper_openapi_client_dart` and +`whisper_websocket_client_dart` through `path: ../...`. CI has to check out the +sibling repositories, and nothing records which client version the app used. + +## Decision + +Keep `path:` while the clients have no release tags; both repositories are +checked out next to the app locally and in CI. As soon as the server publishes +its first `v*` tag, the clients get matching tags and the app pins those tags +instead of `path:`. The generated client is still regenerated in one sequence +with the server spec. + +## Consequences + +- Today CI depends on sibling checkouts and the branch name. +- The Flutter E2E workflow already checks the clients out explicitly; that + mirrors what a tag pin will replace. +- A spec change still ships the regenerated client and updated call sites in + one change. diff --git a/docs/adr/README.md b/docs/adr/README.md new file mode 100644 index 0000000..b98636a --- /dev/null +++ b/docs/adr/README.md @@ -0,0 +1,8 @@ +# Architecture Decision Records + +| ADR | Decision | +| --- | --- | +| [0001](0001-local-encryption.md) | Encrypt on the device; the server sees ciphertext only | +| [0002](0002-client-versioning.md) | Pin clients to tags once releases exist | + +Cross-cutting decisions live in the Notion Engineering Standard. From 28f9f42723b64a55d6c726fb4d61731923e6b072 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Wed, 11 Nov 2026 19:39:37 +0100 Subject: [PATCH 015/181] docs: keep ADRs within the 15-line limit --- docs/adr/0001-local-encryption.md | 25 +++++++++---------------- docs/adr/0002-client-versioning.md | 24 ++++++++---------------- 2 files changed, 17 insertions(+), 32 deletions(-) diff --git a/docs/adr/0001-local-encryption.md b/docs/adr/0001-local-encryption.md index ff0e2f8..e6dae48 100644 --- a/docs/adr/0001-local-encryption.md +++ b/docs/adr/0001-local-encryption.md @@ -3,23 +3,16 @@ Status: accepted (2026-11-11) ## Context - -Messages and media pass through a self-hosted server that must not be able to -read them. There is no key escrow and no password reset that would recover -content. +Messages and media pass through a self-hosted server that must not read them. +There is no key escrow and no password reset that could recover content. ## Decision - -- Messages: AES-256-GCM content, AES key wrapped with the recipient's RSA-4096 - public key; the server only routes the envelope. -- Media: a random per-file AES-256-GCM key encrypts the uploaded bytes; the key - travels inside the encrypted message. Downloads are decrypted on the device - and stored encrypted at rest with the app master key. -- The app master key is derived from the local password with PBKDF2 and is kept - in secure storage for biometric unlock. +Messages use AES-256-GCM content with the AES key wrapped by the recipient's +RSA-4096 public key. Media uses a random per-file AES-256-GCM key that travels +inside the encrypted message; the download is decrypted on the device and +stored encrypted at rest with the PBKDF2-derived app key. Biometrics only +unlock that key from secure storage. ## Consequences - -- A lost private key means the history is unreadable. -- The server cannot scan or transcode attachments. -- RSA-4096, AES-256-GCM and PBKDF2 parameters are a hard floor. +A lost private key means unreadable history; the server cannot scan or +transcode attachments; RSA-4096, AES-256-GCM and PBKDF2 are a hard floor. diff --git a/docs/adr/0002-client-versioning.md b/docs/adr/0002-client-versioning.md index 81919f5..e612315 100644 --- a/docs/adr/0002-client-versioning.md +++ b/docs/adr/0002-client-versioning.md @@ -3,23 +3,15 @@ Status: accepted (2026-11-11); supersedes the `path:` setup once a server tag exists ## Context - -`pubspec.yaml` pulls `whisper_openapi_client_dart` and -`whisper_websocket_client_dart` through `path: ../...`. CI has to check out the -sibling repositories, and nothing records which client version the app used. +`pubspec.yaml` pulls both Dart clients through `path: ../...`. CI must check out +sibling repositories and nothing records which client version the app used. ## Decision - -Keep `path:` while the clients have no release tags; both repositories are -checked out next to the app locally and in CI. As soon as the server publishes -its first `v*` tag, the clients get matching tags and the app pins those tags -instead of `path:`. The generated client is still regenerated in one sequence -with the server spec. +Keep `path:` while the clients have no release tags; local and CI checkouts put +them next to the app. After the first server `v*` tag, tag the clients and pin +the app to those tags. Generated code is still regenerated in one sequence with +the server spec. ## Consequences - -- Today CI depends on sibling checkouts and the branch name. -- The Flutter E2E workflow already checks the clients out explicitly; that - mirrors what a tag pin will replace. -- A spec change still ships the regenerated client and updated call sites in - one change. +CI depends on sibling checkouts and the branch name today; the Flutter E2E +workflow already mirrors what a tag pin will replace. From 0c5a3b9af08665e3f64e9f5bea6e45ad754ab299 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 02:00:35 +0100 Subject: [PATCH 016/181] chore(android): upgrade toolchain to AGP 9.5.1 and Gradle 9.9.1 Gradle 8.12 is below Flutter 3.47's minimum and flutter_local_notifications 23 requires compileSdk 37, which needs AGP 9. - Gradle 9.9.1, AGP 9.5.1, Kotlin 2.4.21, google-services 4.6.0 - compileSdk 37, Java 11, Kotlin compilerOptions DSL - drop Jetifier, enable the resValues build feature (off by default in AGP 9) --- android/app/build.gradle.kts | 19 +++++++++++-------- android/gradle.properties | 6 +++++- .../gradle/wrapper/gradle-wrapper.properties | 2 +- android/settings.gradle.kts | 6 +++--- 4 files changed, 20 insertions(+), 13 deletions(-) diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index c5e8c48..e51247f 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -10,20 +10,17 @@ plugins { android { namespace = "cz.josefraz.whisper" - compileSdk = flutter.compileSdkVersion + // flutter_local_notifications 23 requires compiling against API 37. + compileSdk = 37 ndkVersion = flutter.ndkVersion // ndkVersion = "27.0.12077973" compileOptions { // Flag to enable support for the new language APIs isCoreLibraryDesugaringEnabled = true - // Sets Java compatibility to Java 8 - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 - } - - kotlinOptions { - jvmTarget = JavaVersion.VERSION_1_8.toString() + // Sets Java compatibility to Java 11 + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 } defaultConfig { @@ -52,6 +49,12 @@ android { } } +kotlin { + compilerOptions { + jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_11) + } +} + dependencies { coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5") } diff --git a/android/gradle.properties b/android/gradle.properties index d0e3d2b..814264e 100644 --- a/android/gradle.properties +++ b/android/gradle.properties @@ -1,4 +1,8 @@ org.gradle.java.home=/usr/lib/jvm/java-21-openjdk org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError android.useAndroidX=true -android.enableJetifier=true +# This builtInKotlin flag was added automatically by Flutter migrator +android.builtInKotlin=false +# This newDsl flag was added automatically by Flutter migrator +android.newDsl=false +android.defaults.buildfeatures.resvalues=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index ac3b479..1e395d3 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts index c4b6403..5b15e75 100644 --- a/android/settings.gradle.kts +++ b/android/settings.gradle.kts @@ -18,11 +18,11 @@ pluginManagement { plugins { id("dev.flutter.flutter-plugin-loader") version "1.0.0" - id("com.android.application") version "8.9.1" apply false + id("com.android.application") version "9.5.1" apply false // START: FlutterFire Configuration - id("com.google.gms.google-services") version("4.3.15") apply false + id("com.google.gms.google-services") version("4.6.0") apply false // END: FlutterFire Configuration - id("org.jetbrains.kotlin.android") version "2.1.0" apply false + id("org.jetbrains.kotlin.android") version "2.4.21" apply false } include(":app") From 5881e8202d23a2bb46f7160e4ea96dc29514aa0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 02:00:35 +0100 Subject: [PATCH 017/181] feat(mcp): wire Dart/Flutter MCP tooling for agent workflows - mcp_toolkit 7.0.1 initialised in debug builds only - README/AGENTS document the global OpenCode MCP setup and its limits - ignore .flutter_mcp and .mcp_screenshots --- .gitignore | 2 + AGENTS.md | 18 ++++++++ README.md | 41 ++++++++++++++++++ lib/main.dart | 14 +++++++ pubspec.lock | 112 ++++++++++++++++++++++++++++++++++++++++++++++++++ pubspec.yaml | 1 + 6 files changed, 188 insertions(+) diff --git a/.gitignore b/.gitignore index 74190ac..0ad2648 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,8 @@ migrate_working_dir/ .dart_tool/ .flutter-plugins .flutter-plugins-dependencies +.flutter_mcp/ +.mcp_screenshots/ .pub-cache/ .pub/ /build/ diff --git a/AGENTS.md b/AGENTS.md index d269fbd..1fe8569 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,6 +12,24 @@ and WebSocket (`whisper_websocket_client_dart`). - e2e: `flutter test integration_test -d linux` (needs Linux desktop toolchain) - build: `flutter build apk --release` (requires `firebase_options.dart`, `google-services.json`, `firebase.json`) +## AI / MCP tooling + +OpenCode has two Flutter MCP servers wired globally (config in `~/.config/opencode/opencode.json`, +not in this repository). Use them for the fast loop, but the shell gates below still define done. + +| Server | Role | +|---|---| +| `dart` | `analyze_files`, symbol resolution, `run_tests`, `pub`, hot reload/restart, DTD connection, widget inspector | +| `flutter-mcp-toolkit` | screenshots, semantic snapshot, tap/type, recent logs — UI verification of a running debug build | + +1. At session start register roots: `whisper`, `../whisper_openapi_client_dart`, `../whisper_websocket_client_dart`. +2. MCP-driven runs use a fixed port so the toolkit can attach: `flutter run -d linux --device-vmservice-port=8181`. One running instance only. +3. UI work: `fmt_semantic_snapshot` → `ref` → `fmt_tap_widget`/`fmt_enter_text`, then hot reload after every widget change. Pixel capture is unsupported on Linux desktop (needs the app permission bridge), so use `fmt_hot_reload_flutter`, not `fmt_hot_reload_and_capture`. +4. Never call `fmt_evaluate_dart_expression`; it is denied in the OpenCode `permissions` config and there is no server-side flag for it. +5. Toolkit and debug builds only with test data — never with a real account. +6. `pub add`/`pub remove` and any `pubspec.yaml` change need explicit confirmation. `dart_fix` is disabled on purpose: it would rewrite the generated clients. +7. `flutter analyze --no-fatal-infos` from the shell remains the definition-of-done gate; MCP analysis does not replace it. + ## Hard rules 1. Never commit secrets, keys, `.env*`, `firebase_options.dart`, `google-services.json` or `firebase.json`. diff --git a/README.md b/README.md index 4839c0d..ed4ce8c 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,47 @@ Also see [Wiki](https://github.com/jsfraz/whisper/wiki)! You can download the app [here in the releases](https://github.com/jsfraz/whisper/releases). +## AI / MCP tooling + +This project is developed with [OpenCode](https://opencode.ai). MCP servers are configured +globally in `~/.config/opencode/opencode.json` — there is no MCP config in this repository. + +| Server | What it gives the agent | +|---|---| +| `dart` (official Dart & Flutter MCP server) | analyzer diagnostics, symbol resolution, tests, `pub`, hot reload/restart, DTD connection to a running app, widget inspector | +| `flutter-mcp-toolkit` | screenshots, semantic snapshot, tap/type, recent logs — UI verification against a running debug build | +| `context7` | library documentation lookup | + +Pins: `dart mcp-server` comes with Dart 3.13.7; `flutter-mcp-toolkit` **v7.0.1** is the +linux-x64 release binary in `~/.local/bin` (sha256 verified against `checksums.txt`); +`mcp_toolkit` is pinned to **7.0.1** in `pubspec.yaml`. Releases 7.0.2 and 7.1.0 ship no +binaries yet, so upgrade the server and the package together. + +```jsonc +"dart": { + "type": "local", + "command": ["dart", "mcp-server", "--enable", "all", "--disable", "create_project,dart_fix"] +}, +"flutter-mcp-toolkit": { + "type": "local", + "command": ["flutter-mcp-toolkit-server", "--resources", "--images", "--save-images", + "--no-dynamics", "--scan-ports", "8181"] +} +``` + +Verify with `opencode mcp list` (both `connected`); restart the session after config changes. +For a runtime session: `flutter run -d linux --device-vmservice-port=8181`, then discover the app +with `fmt_discover_debug_apps` and pass its `targetId`/`uri` to the toolkit tools. + +Known limitations (Linux desktop, verified): +- Pixel capture is app-owned and off: `fmt_get_screenshots` / `fmt_capture_ui_snapshot` / + `fmt_hot_reload_and_capture` return `visual_capture_unsupported` unless the app wires the + optional permission bridge (`initializeFlutterPermissionToolkit`). Semantic snapshot, tap/type, + logs and `fmt_hot_reload_flutter` work regardless. +- `fmt_evaluate_dart_expression` is denied in the OpenCode `permissions` config; the toolkit has + no server flag for it, so the deny rule is the only enforcement. +- The toolkit only runs in debug builds and must never be used with a real account. + ## Dependencies - [basic_utils](https://pub.dev/packages/basic_utils) diff --git a/lib/main.dart b/lib/main.dart index f5ff8fd..847d947 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -2,9 +2,11 @@ import 'dart:io'; import 'package:easy_localization/easy_localization.dart'; import 'package:firebase_core/firebase_core.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:hive/hive.dart'; +import 'package:mcp_toolkit/mcp_toolkit.dart'; import 'package:provider/provider.dart'; import 'firebase_options.dart'; import '../utils/message_notifier.dart'; @@ -25,6 +27,18 @@ void main() async { // Initialize Flutter widgets WidgetsFlutterBinding.ensureInitialized(); + // MCP toolkit exposes app internals over the debug VM service. Debug only; + // never use it with a real account (see AGENTS.md). + if (kDebugMode) { + try { + MCPToolkitBinding.instance + ..initialize() + ..initializeFlutterToolkit(); + } catch (e) { + debugPrint('MCP toolkit init failed: $e'); + } + } + if (Platform.isAndroid || Platform.isIOS) { await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, diff --git a/pubspec.lock b/pubspec.lock index 357efd4..c924f32 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -273,6 +273,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.4.1" + dart_mcp: + dependency: transitive + description: + name: dart_mcp + sha256: "852b51da915d679be8d051e2e3b6c68ed19fe685f1c676bb35272a2d73ceac7a" + url: "https://pub.dev" + source: hosted + version: "0.5.2" dart_style: dependency: transitive description: @@ -289,6 +297,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.8.0" + decimal: + dependency: transitive + description: + name: decimal + sha256: "2c3c8b74f2948066d3f42585477aec9cfc48fefd7a723a4d4274a6c71a5c0df7" + url: "https://pub.dev" + source: hosted + version: "3.2.6" device_info_plus: dependency: transitive description: @@ -329,6 +345,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.0" + equatable: + dependency: transitive + description: + name: equatable + sha256: "3bce007a596ff8b3119c45d68aaef631272537c03d30e5d4534dd24bf4c5eaa2" + url: "https://pub.dev" + source: hosted + version: "2.1.0" fake_async: dependency: transitive description: @@ -568,6 +592,14 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_mcp_toolkit_core: + dependency: transitive + description: + name: flutter_mcp_toolkit_core + sha256: "60b7b4fe760f038d45f076b0898e0f2719c8af68038943989e4a4cae89531737" + url: "https://pub.dev" + source: hosted + version: "7.1.0" flutter_plugin_android_lifecycle: dependency: transitive description: @@ -642,6 +674,14 @@ packages: url: "https://pub.dev" source: hosted version: "10.0.2" + from_json_to_json: + dependency: transitive + description: + name: from_json_to_json + sha256: a29219df65cd20b1b17be8141ee51b3103d1cd95b192b7512139f3ae44775f49 + url: "https://pub.dev" + source: hosted + version: "0.5.0" frontend_server_client: dependency: transitive description: @@ -804,6 +844,22 @@ packages: description: flutter source: sdk version: "0.0.0" + intentcall_core: + dependency: transitive + description: + name: intentcall_core + sha256: "5943bf2101129d2c1c7e011d5987bc873e83506c4de0245b400159011054d51a" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + intentcall_schema: + dependency: transitive + description: + name: intentcall_schema + sha256: be0df75cb88f5d40b3d0928843e8c722564014e5e6806c33eec5b8d4f1a3b56f + url: "https://pub.dev" + source: hosted + version: "1.2.0" intl: dependency: transitive description: @@ -820,6 +876,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" + is_dart_empty_or_not: + dependency: transitive + description: + name: is_dart_empty_or_not + sha256: "1454632c2b961175d4c2807310713cbcbd054a51e63c545dc86c3eb9b2b061b0" + url: "https://pub.dev" + source: hosted + version: "0.4.0" jni: dependency: transitive description: @@ -860,6 +924,22 @@ packages: url: "https://pub.dev" source: hosted version: "4.9.0" + json_rpc_2: + dependency: transitive + description: + name: json_rpc_2 + sha256: "82dfd37d3b2e5030ae4729e1d7f5538cbc45eb1c73d618b9272931facac3bec1" + url: "https://pub.dev" + source: hosted + version: "4.1.0" + json_schema_builder: + dependency: transitive + description: + name: json_schema_builder + sha256: "657db3229ba10305c48e8686e8b3aca16e12e639c3a7b96687a6eeb7836b6e1b" + url: "https://pub.dev" + source: hosted + version: "0.1.7" json_serializable: dependency: "direct dev" description: @@ -996,6 +1076,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.13.0" + mcp_toolkit: + dependency: "direct main" + description: + name: mcp_toolkit + sha256: "9e49e48582625980d0ae73001f44509b1d304d5c7cc415b7f6aaa67a9f0114d2" + url: "https://pub.dev" + source: hosted + version: "7.0.1" meta: dependency: transitive description: @@ -1212,6 +1300,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.2" + rational: + dependency: transitive + description: + name: rational + sha256: cb808fb6f1a839e6fc5f7d8cb3b0a10e1db48b3be102de73938c627f0b636336 + url: "https://pub.dev" + source: hosted + version: "2.2.3" record: dependency: "direct main" description: @@ -1292,6 +1388,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.28.0" + schemantic: + dependency: transitive + description: + name: schemantic + sha256: "1252e78063c2d124831337bf8e9d146cbd6d9cf575f5346a9c85c5911c430239" + url: "https://pub.dev" + source: hosted + version: "0.2.3" shared_preferences: dependency: transitive description: @@ -1489,6 +1593,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" + universal_io: + dependency: transitive + description: + name: universal_io + sha256: f63cbc48103236abf48e345e07a03ce5757ea86285ed313a6a032596ed9301e2 + url: "https://pub.dev" + source: hosted + version: "2.3.1" url_launcher: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index f3110a9..ba8c891 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -33,6 +33,7 @@ dependencies: just_audio: ^0.10.5 jwt_decoder: ^2.0.1 local_auth: ^3.0.1 + mcp_toolkit: 7.0.1 mime: ^2.0.0 mobile_scanner: ^7.0.0 page_transition: ^2.2.1 From 922f79b92542307f7202369ba944102b9ac720ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 18:07:24 +0100 Subject: [PATCH 018/181] chore(deps): upgrade resolvable packages within current constraints record 7.2.0 (replaces record_ios/macos with record_darwin), objective_c, shared_preferences and other in-range bumps. Major versions stay blocked by hive_generator (analyzer <7) and by the mcp_toolkit 7.0.1 pin. --- pubspec.lock | 64 +++++++++++++++++++++++----------------------------- 1 file changed, 28 insertions(+), 36 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index c924f32..5d72b3b 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -29,10 +29,10 @@ packages: dependency: transitive description: name: android_file_picker - sha256: "04c1306eda42c23ecbf449c909f4fa05c5e66fc48cf5f994d8d08b9d45e5396b" + sha256: e7e02f9bab7e014e5b47e4cef135a8f5c66f5c14fd90986e415e758f6a1762e1 url: "https://pub.dev" source: hosted - version: "2.1.5" + version: "2.1.6" archive: dependency: transitive description: @@ -551,10 +551,10 @@ packages: dependency: "direct main" description: name: flutter_local_notifications - sha256: e99e9c6078d1359ba131b2c1eb8d68837170836a01bf2cea3cf2fa13e62ac2ac + sha256: "58f9ea245d7194363c05f7a012bbc73291736c2d8b5f555a8e0ea3f9121868b4" url: "https://pub.dev" source: hosted - version: "23.0.0" + version: "23.0.1" flutter_local_notifications_linux: dependency: transitive description: @@ -583,10 +583,10 @@ packages: dependency: transitive description: name: flutter_local_notifications_windows - sha256: c2d6efe9ba585d5f560d8b329131f00fe745834848e6221b22d1f62e0f0b16e2 + sha256: "8e80ac29433c71e267493b397457e3a8430c5c1d9c76bb58a6971c016cdba3d7" url: "https://pub.dev" source: hosted - version: "4.0.0" + version: "4.0.1" flutter_localizations: dependency: transitive description: flutter @@ -1120,10 +1120,10 @@ packages: dependency: transitive description: name: objective_c - sha256: "322d5f1f0680534acaf557c5d68e97b40c3800ee5e15b63dcacc3c31504674c2" + sha256: c965d264fd4b0b4dd402dce9d049b70656bf98d3ca108b9bc55d2544ceadbe5e url: "https://pub.dev" source: hosted - version: "9.6.3" + version: "9.6.4" package_config: dependency: transitive description: @@ -1312,50 +1312,42 @@ packages: dependency: "direct main" description: name: record - sha256: "7c4467dec63435c9206db183f8a4672cf8a62f5e5579e45803ceada8330756e7" + sha256: "3bbb68002de8bb2fc7178b6c955254fa882e2fe4c33fa98db4b98dd662d8a1d6" url: "https://pub.dev" source: hosted - version: "7.1.2" + version: "7.2.0" record_android: dependency: transitive description: name: record_android - sha256: f5080279259c4ad769590f1c165762eaa4e414178adc2e2fab137103228e07ac + sha256: "68c8cb40628a460b2a8bdf746697bd798a71cca7b03b8dac20e752d50425900f" url: "https://pub.dev" source: hosted - version: "2.2.0" - record_ios: + version: "2.3.0" + record_darwin: dependency: transitive description: - name: record_ios - sha256: "21d189f49a598af4697dac4cc9e48389ac0a1fb3e916622b5504a58d9b96313e" + name: record_darwin + sha256: "6ff6477febaa928ae3a294014f1254c766aaf6bb8f288f02cbe7cda1b9e9be87" url: "https://pub.dev" source: hosted - version: "2.1.1" + version: "2.0.0" record_linux: dependency: transitive description: name: record_linux - sha256: "00c847ba25684572674dacfbd4bcabee6c5d9a1fa948778ff34091c71c19250f" + sha256: a2c1680b908c899e8198ad46e553adbfba4d66fe41c1314705cf3afb888f8033 url: "https://pub.dev" source: hosted - version: "2.1.3" - record_macos: - dependency: transitive - description: - name: record_macos - sha256: ced7495abf3d683e8a7dbe8fc96df8ea5722837a26f922b7cb7c5de11661bb46 - url: "https://pub.dev" - source: hosted - version: "2.1.1" + version: "2.2.0" record_platform_interface: dependency: transitive description: name: record_platform_interface - sha256: d94b37cadb8fe203e64b0e9893271c0b71b34f2550ee7fb0c6105d650e00c1f5 + sha256: "970b2a2c4ac4dc666adca8a41fefc3c4b0c62ef1dfc3c46ba5400def7155ac1a" url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "2.2.0" record_use: dependency: transitive description: @@ -1368,18 +1360,18 @@ packages: dependency: transitive description: name: record_web - sha256: "7f6950be87abacb05cf77eb6ca200b60f2c2a6af5d50236b5f4baf53f92e755e" + sha256: "15852c45e3ac621090d919373faa5400ddffaf28403525359041132526a02b1d" url: "https://pub.dev" source: hosted - version: "2.1.3" + version: "2.2.0" record_windows: dependency: transitive description: name: record_windows - sha256: "8195489a47b5e8246985d6213ff65aae1b14e32a0ca45dc5f680e8d503296e1b" + sha256: c708162ff3195e4b8898242410b66233a5081699f519226c4afe985d1eb877e0 url: "https://pub.dev" source: hosted - version: "2.3.0" + version: "2.4.0" rxdart: dependency: transitive description: @@ -1408,18 +1400,18 @@ packages: dependency: transitive description: name: shared_preferences_android - sha256: "33b38b07d9ac7d16aff0426c61418752fd3e7a8c7dc8be786c875d6ce673b002" + sha256: "137dedccacb394b8f470d6c9b435ffc3d33faaa6ce2949c4f54a61007d64396d" url: "https://pub.dev" source: hosted - version: "2.5.4" + version: "2.5.5" shared_preferences_foundation: dependency: transitive description: name: shared_preferences_foundation - sha256: "4e396ac6f8751ab7d2d6e27f22f32c8350b07006028d534f5221503382f1fa69" + sha256: "89435cb71ecb1ad1bf29ef73a381f871a06f433d4182b7e2ba7243b02b2c544b" url: "https://pub.dev" source: hosted - version: "2.6.1" + version: "2.6.2" shared_preferences_linux: dependency: transitive description: From a519145fd941d06580b810d89a680b4fb9a7500f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 18:07:26 +0100 Subject: [PATCH 019/181] fix(push): register with FCM and use the FID from onRegistered getToken() and onTokenRefresh are deprecated in firebase_messaging 17; the replacement registers the app instance and delivers its Firebase Installation ID. The server now sends to that FID. --- lib/pages/home_page.dart | 55 ++++++++++++++++++---------------------- 1 file changed, 25 insertions(+), 30 deletions(-) diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index dd71350..0bdbd5b 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -38,7 +38,7 @@ class _HomePageState extends State { List _serverInvites = []; Map _chats = {}; bool _firstLoad = true; - String? _pendingFcmToken; // Store pending token + String? _pendingFid; // Store pending FID @override void initState() { @@ -56,23 +56,23 @@ class _HomePageState extends State { // Request FCM notification permissions FirebaseMessaging.instance.requestPermission(provisional: true); - // FCM token refresh - store token and send when online - FirebaseMessaging.instance.onTokenRefresh.listen((fcmToken) async { - _pendingFcmToken = fcmToken; - await _sendFcmTokenWhenOnline(fcmToken); + // FID registration - store FID and send when online + FirebaseMessaging.instance.onRegistered.listen((fid) async { + _pendingFid = fid; + await _sendPushTargetWhenOnline(fid); }).onError((err) { if (kDebugMode) { - debugPrint('Error getting FCM token: $err'); + debugPrint('Error getting FID: $err'); } }); // Enable FCM notifications FirebaseMessaging.instance.setAutoInitEnabled(true); - // Set initial FCM token - _setFcmToken(); + // Register with FCM, the FID arrives via onRegistered + _registerForPush(); - // Listen to offline mode changes to send pending tokens + // Listen to offline mode changes to send the pending FID _listenToConnectivityChanges(); } @@ -83,38 +83,33 @@ class _HomePageState extends State { _webSocketManager.stopConnectionCheck(); } - /// Listen to connectivity changes and send pending FCM token + /// Listen to connectivity changes and send the pending FID void _listenToConnectivityChanges() { - // Check periodically if we came back online and have a pending token + // Check periodically if we came back online and have a pending FID Timer.periodic(Duration(seconds: 30), (timer) { - if (!Singleton().offlineMode && _pendingFcmToken != null) { - _sendFcmTokenWhenOnline(_pendingFcmToken!); + if (!Singleton().offlineMode && _pendingFid != null) { + _sendPushTargetWhenOnline(_pendingFid!); } }); } - /// Set FCM token on server with offline mode handling - Future _setFcmToken() async { + /// Register with FCM, the FID arrives via onRegistered + Future _registerForPush() async { try { - var token = await FirebaseMessaging.instance.getToken(); - if (token == null) { - return; - } - _pendingFcmToken = token; - await _sendFcmTokenWhenOnline(token); + await FirebaseMessaging.instance.register(); } catch (e) { if (kDebugMode) { - debugPrint('Error setting FCM token: $e'); + debugPrint('Error registering with FCM: $e'); } } } - - /// Send FCM token when online, store when offline - Future _sendFcmTokenWhenOnline(String token) async { + + /// Send FID when online, store when offline + Future _sendPushTargetWhenOnline(String fid) async { // Skip if in offline mode if (Singleton().offlineMode) { if (kDebugMode) { - debugPrint('Offline mode - FCM token will be sent when online'); + debugPrint('Offline mode - FID will be sent when online'); } return; } @@ -122,17 +117,17 @@ class _HomePageState extends State { try { await Utils.callApi( () => Singleton().firebaseApi.setFirebaseToken( - setFirebaseTokenInput: SetFirebaseTokenInput(token: token)), + setFirebaseTokenInput: SetFirebaseTokenInput(token: fid)), useSecurity: true, ).timeout( Duration(seconds: 10), onTimeout: () => null, ); } catch (e) { - // Error occurred, keep token pending - _pendingFcmToken = token; + // Error occurred, keep FID pending + _pendingFid = fid; if (kDebugMode) { - debugPrint('Error sending FCM token: $e'); + debugPrint('Error sending FID: $e'); } } } From 9c4bc7338734d46816d816c961300542099fea10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 18:51:48 +0100 Subject: [PATCH 020/181] fix(push): enable FID registration on Android The installation-ID API stays off unless firebase_messaging_installation_id_enabled sits at application level; meta-data under is ignored. Also clear the pending FID once the server accepted it, so the 30s retry loop stops re-sending. --- android/app/src/main/AndroidManifest.xml | 4 ++++ lib/pages/home_page.dart | 9 +++++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index e276e5f..2dd77e1 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -17,6 +17,10 @@ android:label="@string/app_name" android:name="${applicationName}" android:icon="@mipmap/launcher_icon"> + + { () => Singleton().firebaseApi.setFirebaseToken( setFirebaseTokenInput: SetFirebaseTokenInput(token: fid)), useSecurity: true, - ).timeout( - Duration(seconds: 10), - onTimeout: () => null, - ); + ).timeout(Duration(seconds: 10)); + // Sent; the retry loop only covers values that never made it + if (_pendingFid == fid) { + _pendingFid = null; + } } catch (e) { // Error occurred, keep FID pending _pendingFid = fid; From dd33bc6a49be7d0f3fb8e2e6e9221af9078df59d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 19:00:54 +0100 Subject: [PATCH 021/181] fix(notifications): deliver FCM pushes through the app's channel Firebase reads default_notification_channel_id at application level, so the copy under was ignored and pushes landed in the silent fallback channel. The referenced channel is now created at startup, otherwise Firebase logs a missing-channel warning and falls back anyway. --- android/app/src/main/AndroidManifest.xml | 22 ++++++++++------------ lib/utils/notification_service.dart | 12 ++++++++++++ 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 2dd77e1..228e18a 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -21,6 +21,16 @@ + + + + - - - - - - diff --git a/lib/utils/notification_service.dart b/lib/utils/notification_service.dart index 4c81049..6fd0286 100644 --- a/lib/utils/notification_service.dart +++ b/lib/utils/notification_service.dart @@ -25,6 +25,18 @@ class NotificationService { await _flutterLocalNotificationsPlugin.initialize( settings: initializationSettings); + + // FCM posts notifications into this channel, so it must exist before a push arrives + await _flutterLocalNotificationsPlugin + .resolvePlatformSpecificImplementation< + AndroidFlutterLocalNotificationsPlugin>() + ?.createNotificationChannel(AndroidNotificationChannel( + 'whisper_firebase_messages', + 'Whisper', + description: 'notificationChannelDesc'.tr(), + importance: Importance.max, + sound: const RawResourceAndroidNotificationSound('notification'), + )); } /// Show notifications. From 49b633503241f7fccff2d176d2db9ad34b28169f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 19:37:06 +0100 Subject: [PATCH 022/181] fix(notifications): use a monochrome status-bar icon app_icon.png is an opaque RGB launcher icon, so Android (which draws only the alpha channel) rendered it as a solid square. The new ic_stat_whisper set is a white ghost silhouette with transparent eyes/smile/whistle, used by both FCM and local notifications. --- android/app/src/main/AndroidManifest.xml | 2 +- .../main/res/drawable-hdpi/ic_stat_whisper.png | Bin 0 -> 1309 bytes .../main/res/drawable-mdpi/ic_stat_whisper.png | Bin 0 -> 790 bytes .../main/res/drawable-xhdpi/ic_stat_whisper.png | Bin 0 -> 1844 bytes .../main/res/drawable-xxhdpi/ic_stat_whisper.png | Bin 0 -> 2969 bytes .../res/drawable-xxxhdpi/ic_stat_whisper.png | Bin 0 -> 4239 bytes lib/utils/notification_service.dart | 2 +- 7 files changed, 2 insertions(+), 2 deletions(-) create mode 100644 android/app/src/main/res/drawable-hdpi/ic_stat_whisper.png create mode 100644 android/app/src/main/res/drawable-mdpi/ic_stat_whisper.png create mode 100644 android/app/src/main/res/drawable-xhdpi/ic_stat_whisper.png create mode 100644 android/app/src/main/res/drawable-xxhdpi/ic_stat_whisper.png create mode 100644 android/app/src/main/res/drawable-xxxhdpi/ic_stat_whisper.png diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 228e18a..4f57a39 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -24,7 +24,7 @@ + android:resource="@drawable/ic_stat_whisper" /> diff --git a/android/app/src/main/res/drawable-hdpi/ic_stat_whisper.png b/android/app/src/main/res/drawable-hdpi/ic_stat_whisper.png new file mode 100644 index 0000000000000000000000000000000000000000..f924b623b7a7e0908c9861839e64ef7b2e692dea GIT binary patch literal 1309 zcmV+&1>*XNP)Q-92Z{y>o9<3l8U;z4uz{zt>)C?X|bj zBS~riGPAPMUI23d0b^#Sntn60Rxf(22Oxz5k^e6Pt^)>v6~KAGnLhj^a0ECA>;?9i z*-y@A4y@$gl3OLd?~wGiq%rkQrzCBcbW5Gget=joO1etYyA?%~k|zA!syumLPVY#% zyl+qrrtt4glEyO-lak6lEL3KoC23UBqb|EpTE?C&v$Z00wv@|wAuQDul%%G=Uv$QC z^=FZps8rkHFXcMxz=UOnGBE!ah3qG4eJTTUrP@yUUs|S0Wu{{=$6(=Lj%_cn2514* zNNACgpVjnrqHa8)<4a&QPy)*R=59w{=fG8K^n$^zgxFl1(1|B)cg2bKX#fpdX#ocB-Qcap__FtZar z-hgX?4}4s{e4+DdGut0|s43~7=ZU&pBuV=uJtS#S%`9t4(#4Wi`S)T?&v#K0ACOm% zO`u_BlajUoTWC9BZqkxemaGAeN%|D{9QclO>^bf{^GL^{6~H3k8Q^wF*8_WiZ-JHB zGDXxqXJ#!)O;fw3odbLgT<8O<2{Q6fKcT+~7y-^FMe}ap43`~C_dReKDeP7F0kAN$ zQBp*8$`cVaVrq0n8Yr{&F@IkI%m>!GjJdQ+jsUdL%ubUIk?o*TyNrEWvp;Esj|?j9 zXOgs3(r*7A_4npn_Y_h(Cl!*GXm+QK;5#De0!fFJCil3c2Qsj4xZb9+qfqWAktFX2 z2AEzOLGKwF;C)~r$+;WAdf+41xdXUIsY-0+OBE+n14>ErfJbV;hTp`78Gcg-u=Hmi zuqxwSNxGDH47k(G#>p-*rT_w(Zk?xmRuTF+kOs+7^Xy<7l;$*Q`(%h=gR4MY% z4WxWAQ0X59-U6OAvkxm1IU86^+B)WwN|}Z()4Mb@DiH zij=HA2HrEXLzyKbvrfB7t5R5@oAQo;W)R$P!L3Sr_)t9gc97q=6?iSx3%I`lLby*s T$VaC!00000NkvXXu0mjfuqkFK literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/drawable-mdpi/ic_stat_whisper.png b/android/app/src/main/res/drawable-mdpi/ic_stat_whisper.png new file mode 100644 index 0000000000000000000000000000000000000000..5575b53cf27e4c9f7c98b1d1d01d3b38cc732c24 GIT binary patch literal 790 zcmV+x1L^#UP)Ft$=pu<(O~5R9vb*nnEbg4mytnU31`g-kd**y+<~wud-e8WXgNPWH=lg(z zz%n4P4*U`kmlvH`DC!{RCG{osOZ9Je%es12T~YVev;PO)<@}ub>m1N=j#*h%Pgaas z;3%HISq^Tg+v;Qv=p^^H%DXpOBx=l~<*fod&(lRRE{5KoqN{*En+luh-Q*SwHQ=Vd zneU(9NqmN~1pEx#n^m%#$6J$0&R2nlfookv2)qF72gX3-?gsD?u-cfcY0G&vb#CNy zq>*J{B_eDIK39^qonfBJFb}F5g@!gZ)I+IrD$i^uZ4>odbV1u3 zYetvE2;eaAAnH?TeKIp&SKm`F%)GDbAJo(8KMOFP83K0~kD~Cn2Usbd#hmpcIm|PS zfrhnj2#n^0-xS9=2E}*-u|@xepx4wd?EB5SdPTix-{@Xd52x;DiP3KKn%M+VKP;OqL0_v+&k1`< z)P3p5)#9Y;2Q=Q)W5Bt>X-(KV@D1=Ia3#+y(Va0&P$X*xn*y0-z3N5uKsi&_-z zqK(UXk(^PVR8Ok^7JA-K%t5=!oqCsj%}<_zE~45o>Cfm^+nlK>cfm-)rhCnVa8d@-ediR-ee{OX|`N?=xj~kNSNoZX}1V zs}B^NJJmz#QS~wPes6xikEjQ7z3V#?_Lt!aU=#QgxY)u|hk%QIN7Tsg$<(^af6s?4 UO|j>F0{{R307*qoM6N<$f(e*_DF6Tf literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/drawable-xhdpi/ic_stat_whisper.png b/android/app/src/main/res/drawable-xhdpi/ic_stat_whisper.png new file mode 100644 index 0000000000000000000000000000000000000000..13163be3792977e420add1c67e1213ede89a8249 GIT binary patch literal 1844 zcmV-42g~@0P)>4;M>VECVB$ycK`F6Djfutw;)5D7#)zQtgGePR zQPc!A5{(Ze8WYgOXf(hJs01(#$cI{M2?F9rZwu|c=lpz_S$EGpoPEA}Yge+f_da{p zn*Ulev(}n5Cvgm`?+lQDZc52%F{Ejj3h-2eR@VTVfi1u}!0EtT`8*Fi z1?&U<1U!;bI$ZJ2kd4qgt_r9L=mch-I${O4%`LY3j92!^hA+21N4q% zL|Ul`kLTB_H>v+}IrY>1l>kGmmB0S>ZM^g^Rzu?@L%WyemtmOk!wodor#qw z;A7hSpa@(v5B>3`m|m*in^=hgezrW{Tm&8cKLD?(SM_;w!7@9R5*7GsPZ0Q;qVGL5 zwqf97+FaHr;6zej*j-}`N)`A{d0YqV1x_vR9ZoD+u7kjKau7@rwQF$k;~wBeK#vm- z9?seTSP09*omaYV=cas+NPuccoDF9tpjY-Du&35>6(6?o|w9oL=j0DdthPd~*7 zpA39$0Jw33=lTEyuy#TKJ(~I2WwQAn6oHIN-X!tlRA@$EuD#trs;xBb{xt$vzr2Ys z1ml0lWRlUI;#jEmPNV1uGzvUD216uK;Yn7q^bymk!}!zaNoW+STeIG`Dg+_q~%YD#X3_(wmz0Y>wI^Ym_4F%6)xwiy{!&T2|3iI2#j{!clKQ}q)L|HP)qB*d)UzwO zTht?^-!?4s>NM)eDL-)|#!qT0LDoSG`c(rCzUoK;5R^qMl_gplww5 zv|xz$n`+Fd(nMe@&CY0)PY&-gXevEhu6go$nk(0;s?B4-CgAG~qDjqJ+Pvh##$6mA$}6l$tV>Z7XE(e|10{>{?oT)BUIg!T8-SeKEdm}{Pke=ZEu z)xcB|)Fv8Zf+SlwjaO1@j&I-qS#*N4s1vAs@eGYYRWTdC{Hl+Xt$x2Uc$#{t#5 zO5eY$fY+mYajW(Fln9sh=^|*Q%jsd!0Q|>FsSWCf%J-vH-yduPKgd7F!q_lW)9ESF zgP*Bqk{4y{1>Ot%geE_l1+GpheOH|wc@k=wU*@Bvd56b@X(`s#MP|3F`fR!1UvS)4 z-al2|TZ3l*2y{yA@uTE4VAv)be~HAn?ZWdrXa2n$O673S5~|y0%z;akS*d z`sb<#9ln73qvSX)H2Ave{?ga&HVZZQ-%?{5g?ri7uvq^_U^UGipr%NRXMn@NZ_E2E z%L}~Gu1>L|WZ5AX5uQ&z{7y8b$ppli@kwJJeA}GLT-j&g@Z}3Gj|sP{=NF!B>L=A- zsgI8sfrIM3>bK1CW`|8s)11mIozIO!$)>daF5rhWDQi@qYx)ClLrN*mtva=p%zrmH zn_Ti(L#`YgBJa7M0QRSp9_usSc5+d9Kk(xvV3VBIt29u+zoWj%DgxSMu^n?t zJa%QF8u97QfGdh*?kwP~o+_vic%!s;I{gT9ZY iz$hvfo2rB3P5%QGeluB~fNxX)0000}sAFcORyB{9aB_`pao0U?43VB(Xa zi3-L95ff1ZXoHbJc+>~b3Z)=e3Q`O7MJw&S_k8{_YjscedB5&$iC?m_&)IwStjAun zX4aaSZA>5}8DKyqyIccgW-67fcv)*#c9^jCMf!s)r2=4P<1NbNN^7YENh5%O+OU;1 zGzCej!uCp$G!-}!I0iV{f6oN=0`|>#ssU?&4ZtekSzsx!%*>u^M`w^2sDi>;N=lgl zoCbUlco%R)A9S|>%Yg@hdw@Tg*}7)5cPPZ0%>FNw^m9qCsUBmJM*SG`W4v^XH7Hlc zi;@;edUrC0vQhoPK`6PP0DXHI;w znp3C9t$LB%iqu6f*O4|=XnhKBCvX-p>i>6i2p9)OfZqb=lX$0-QFvPgsfeGdz^~c4 zl#?TP{vB{0Fh&P)T}xAQV)9wo_etIO2Zakp!WRWlotbT#lXc3$NK zLP;N$be)-vky=JmG}WG@s+o;TIve;6$s{LkJTY8^EEkyB9U*I@f(;eqUS7Zq;BjDo z|G(qJIQ^mK=Z(N|z)HZp*=>hr0-HOp?*r4l!Z(X@Aju+NZ{SBRYeQqH6FO^J9|F!L znd9WdGs8udB-`ndE^(RbBpD9^J{w(sUSOLAW#fU}fPVmo(wp^+mx(mF)-MJ{CltE|mxnn89=IQPh?FL+Qke4~5OlUWjr&PGQZICjq}T(2Pq+^1m8>F# zalcXo+$hD_E-;j&?@2m1tM@2Lcb3ZZgQ(+9Npmtfvy^f`z0ipi$x<~+i>Oe}G3qTX z8p^ySuTxpnEa~1-*}X&>Oc1YeyZWWF)iNoYRW?U`A->=ZRGztqhB19fv$V@f8w6nKfE z=jayU6JG+BdYxl&)8i`4Yz^=P#r#^Q2wg1n7d#G7kyJ6WnxwY?^Gk)hLDTuDY+Nx2 zN8QQvb1!s4=DEPz%uJFhmF&g|!0seLyRo1cwjV2LKd75Y2&XrjG>h8nz%%H~1ZFGw zoxCZ>)YHDeu|3j>#M((gGZqLyVLjarxWbh82EJ})wHUT5g)L+Lwy&c9?moKrtDMeQ zMrYgydRICx(e%4P$bS4b*;F{_+e*%=TZHrdroTnJ-UC$hEQ9Rke<*2sMrRL6*Yrsz zWWUSnteOfR^k?7{`Wy8|RJ1j_*;!D-^$-f$0&Jc%c6JZa0gl7r0o^oro6m!)_i`&u9D+6YDPxT;jBQKTbPjU+L%VLXD?; zs7%1?z-NFD01r5W5ou3^Mb(^E#AbH`3xLb%Jy*Tl&y_sXxX_2$ohF)MSpLPRRVgQP zxun%uxmZ)!@A||*WIM|t(Q}e6%cYd`;}Wm!5VBts^5nUhztYBmHoy4C*63Z zRY^~}20ID%!XloLbdc9GMcH~lNmC^)kaVM@N0l;t{o++g_bIJ#J298eWr+0gsggFS zbIT2xmnq9jhcK~<<32i%$HMxK02WKS$jlxOMUj$PTY<%X;EJ3B9Ocg)N}B)Ql{Eh! zDb&rRZgvwX@LdV40GB0aL$d$18AW2qw9w6LVj zP7q}`Dfyo;@9;@e{M?dBe``~e<(XTQH8ohd>UC5l{nB~rCUp~Xyg%1TPS7OnD(U$? zlq998lTS(7tHgXLD~=HtrlJPQbABpbuI^bcvxlUUqI~x3G)d2PAxD&1;q}+Q%#3Ix zow`k&mFLp_CFur9?^FY;P~rC)DPT%=z2Pb_fBqwq{-C7DseT;o_rKAF98uB}PE)AYBhEV}C$IOcen=!Crt?-LQ2-p z$m-gkH1+%l@HgOL;0oYsGy9&Tn}9ELAVb{0!OXrSX(XnQ>Y!pR^kM3*i)@Ex8&G<| z8%jJ~>pahp^j%4JOS;6bO_%g6P|@vQ;gt@;e+&Y_M~u!-RuXuNAG7`XqowjWw)*+f3?G(fL z$woAryOhR9AEpR`rvexI{a=*I2gXPt%^hZTy;}8JZ8<4=wOOw9$!=!hq(>zku$;Fj@w|36Bh zoYT$hC8a@e+ZWzcK}ud-lI8>NWq32B-5{F71AacGbU)-d!(Z&(q|x@Sq;=m5%go)NnUXJ2cA5jd=R?GT>CYTT+tm4-LkHMlHM6?YxER78 z8)KohN)i3wwt=e{6i$=$cPG@&_r#zrutn0hB<)eEdoQI=SKOrZU5`c|JZXjXN`t%a zC?(1Eb6)35dZhtR7v?X#A8cD;=F47VXY<)KZd%d4qp8IGG17MNYs~D4Py$Q<5@;JpYocEOo;S1Ar8~{<&w9S1CuWCcRR#>%9_ zbDx~4P8m~u!oJnfa_hE=nUAP%pqu|jC?fRRNqfa+lDf|k(gfZ{QvUd9U>UH&Cj^7R zDru6iV{`T%WgwXWr#rM5u_trSoZrwtvNqYsC)@IE2`b-rO!#N|CL8|)81+^OjP_R2 P00000NkvXXu0mjf!BMsl literal 0 HcmV?d00001 diff --git a/android/app/src/main/res/drawable-xxxhdpi/ic_stat_whisper.png b/android/app/src/main/res/drawable-xxxhdpi/ic_stat_whisper.png new file mode 100644 index 0000000000000000000000000000000000000000..754eea67c85cea2db1f9917402933f9ea22e9f9b GIT binary patch literal 4239 zcmV;A5OD8_P) zf3RIub;m#J-j@I|!Bin&paH^=M$w9bmNqQ~H4an}gc+Giq1ZvGsHMLhO&O=Z)ER9D zXG;GlOhI63s~r(7qS8{e1q-Mnl%|jx8X*!W1`-l}BzgCJ`^Vbroqf+c_xHIk?~(VN zIq$rC&OUpuz4otl*8c8&jCle{mj1PL%m|VW4`il_Fmn!78QJfU)SytbfT=+hn&N20 z&tc-24a|uGNVU5Gn3+v>2-5&w1}p+zLA!Ddcpi8X*k@)>cZs9H94e6gRsfmOF|$_b z-YVeLz-xe40>=YK04wkUSkfWdUBF(vAhrUVf&T=406b`B+e_(804k?Ho0#8UKEQPbxNq9Ozyk#xDFMJW$W&6n1o_F8|wq)l1I zs+#{?!jxRb!1pArugcq;gi>EG>2OImWf__4iZ7#F5LZiDmgli9)Y7b!SvZp30$d9m z1GG{ajc(7+VT2Xd05$@bn%Q?$qscn5V&rd^B<24Ba67L2N!_brKVAx29E`Ut=%Yd7KH&fL5 z`C%~(4&mME1aJ#*k(uopr4WWvR7v@_0qcN$xS!@gK;-pK;H*&!Vc-H#VGl0@zKSb< z60a2p650v@*o}L02P%Yt3P70$6SxC7jRRBpfyn#6Q*^-^#5x*upll`!;Ik|!A3X1q zxF`39RQm^dS?jw1Bu$vvq@)eNg?JM@kd+^pz;$tfq(4nM>RT^;bwQGv$<99$A9P>r z*3O_1u9HQ;d1iKV=&aX+Jr$U2eBrZE_XCHg-!C>he^kW$!!y81z$5fADEFg8OM}Wa zcp!94Rgfc(JPvMTJ z!_x1C+TR_~6+MUhkG9gKE9$1qc<4&J>zV2iegTf?ik1SO?$s4l-pB^tp8@Wp@M+Ki9g-7Gj{Rl4Yt!St6bdrQg$NQ*2iI zR{)!UL#x6KDM-ZeP2g7GQJijgChkovhZ`62G`^OO$AM#UQ+r*FvV_7XfmfT^rmk*l z6_e^8Oq0?1#Plc=+*6XCmGrI->Ap$Q<086#CCf+M)3><60?=*Mu@kvILjutW54vWr;$6 zSkgh=l;23_SE)X>T9p2EDelD`(q5d-8%odBiHLJUpR!z6qbyMfXGA58^zuPC{(n0@ z7}Y`9jySKC7jUOIC)52KaGw7J^$yBPalQcDn9{0ThXAzF{cF8I2O1LLG2I3HFbzDNJcCO2e~iDn$Mba|;@S#qO=)$Ce=6PoAufBPOW1x9x_nEj z{nHgOx*bc_&&z>R@_RL4ivC+u+d8i?Ang9xmL+t#7C6q#lv>&JjX1v^cq#SR{+8l7 z6gW=pYqn;DmCrZ70yrvrzAi*uM*&Bqv^vG#NU|P>6A$XrMbKH^80k#^$r5-&IuA`W zDj|fwq{n>eL~?zc3%msHpX)AwN!&qpUP`NzIoM3HUQAJm>Oi!npPPB7Fuy*ZM(a_{ z&p?=ddnBz(X)ID<`ZZNhz>k)+P2)F1w@F%=$$0+3! z(z&kM7fpRJ@D)kx&1|2UO`2IN9sA^V`PV3xDUIW8IO04K_^PB6lPs;0EN9?+r$aLN z>r8*Oq(y1WHIom(lC%_GH?@NLT>^Q0w*X(lEt2IppXOqG<>PG3IYb)I;%4tRa8lJ_ zz}s-fNA8@f3lZP5zzJryty}=BfQNvC$B=j~Kqt)Rgio)u#^sZWap3i4_5(@Hi6lr1 zXFH5b`DAgnvfsH^ayDn%!nTj~3uRfxsS>|KRKEWVb-n6Nm zPct5s1zNx?A#e8kV`AihN0l>f0keqQ(e#t-+5*OlN^j^><(mtr9ii{X(z$Jw-yRkQ z;Bg}=_pZ3mpiue~_*+`o#C4!WS~XHre6xuuT=qJharwql08@Dj*g??^)uFJQ_7U#b z`GR18$BSwmg%CR34*XwSY{cY%neD|n?Rnr)5;Ndiz)g7J26K2WcXKg$)WrMg8-VXp z&#c(=telzc2^Ua#Lgt}T;9(GR02|EgbThjMI2rgCiW=2oZWTm}qSiNozsLPGzmEIw zKgZ~;ICQ!(oePhE3Tnvvlh1lsCP2*oKak>UDEZja@ApdjpHle!v2{(%4V3fwJxS+g z@&-fVXh|<=q>zL!u#(t1gMBj2g2Q(XJ9V=_Bhr6a$Whp(!!ElJ;(^kF zmvn=q%jC@OwhE{YyJE?A&XPv!CS$*(e=HYru82tdHhgk?*ya{foGXCaC0%M}Urq_f zj)aqH-#7F*e98ZvnSd*CX2NRVr&D~#C7GAwOQ)vwgma4a;db^Tz&4x!{4lV^%(j&U zP4WZ}sFhuB;O_Yk0H0!XW<<<6+?xHKAxv;)A(R#Tt*xn*fg^P$S=WpS>Ov|Gi1JuIRN+%4&-NTZX0A=vFIws{-{x$xWMtm`FN zdcj60)8tJ)MobfU)y|}-Tv(FbFF!Nro*2Q7I8CElY0>>eFVNZ9slpt+Fg;usJtdE4 zlcbNz=b+09oKRtb^itA5EkH$~<}F~2q|Zq@xXW`lW{Mmo@8{+^?v<%S97h}LRnFZ8|j##bhQ^ogv(n(qa1fSUnaNj!vKkN)=65K;(KRFk%J(3 zMO!2tT$a02Aw(a zM8P~E>3!+{lSjyF=+^TsL zcpBe}LBNh|AL^wzkxKX$_sj5&1CPabUSA8W0gg`bpMm?S)};71nAyiuT)&T7K5Ox1 zT4&-!t?&``i?E!2f)n1Jfj&Php`sOhx>SJP({~W)A^KIth1090dG>ncbDHAA^5?U}+XlKgj1;*5b^&fp*f$TfuJ+Sp&v_ zsqDzz5L2b28^WmADCu}rym!b4?&Xs1Ej`mOLRY_$>#_>nCg5YIkE`*0f+pDilPY;l zZe)j*j&6wMNv{NcIqhh25KLQBizr;vs~Ox07wZ7-0hgh@I{gRKz=-F!I3J30+hg`cJ&>5ft+<|9H$m!$k1B5AW+(cuI8K)TnE ze_ccBo#%-68&Pr9#~XT25>{$Haa@Rd8Do-Sz9G7w-T1lyfY;%DJrq0tUaVqEft#{t zJ7Frt`{VSi(dX{!eX-z@AdTeGJ)eR_H{ZsCs5JMOS&*a7&h9nwJe>lZloWXjKEu~( z?Q&e(3!HCekK?-PtAh4TLyY~;%sFZVqu-XUg)YJZx*!e4kK$97 zFf+f(!oSDN?w0Sb+PAeh$i}VlfrjI8roepMx-x3`H`DL6xH+2VCC=xln92KMx>jxh zVRC-N%>FJZztal*N(`dF2zwsB=q^^5%ol_`|04=&$mz^{zsa|2J03gtK70C3wusFZ^7RYpdgop^8X~& z{C&d+)t3@e-!HtsT*Lg{y!CEy^AjhG!OXlw%U+-5{dS5aMor*%Livo~A?T^Z)CWrL zrv4-5pXC#Xyxy12C*YI)`Mq-36LGgTcsJC*yP^xs?5gPVM|sojrxwT3{kP*aX5cN_ z=Kx}m-HUf8;L7c^g-*C14#J6K;A^Pw0nRY9&kr-;R-tPFWVL@W@NourOwASKtAK(U zzNU1q(=)G4=k360W_EAtmPS@S^lkyM&Ejw2HKwk`)WO3UWc!#pu##uAG4(2w?!o^WbCq%C#&eZ%b+ zl?qk+w_>hi@EM^h^@wXE zxAGuRK}@Q{1zr9wTtpLiD!1z$lsrZY>5(b-$ucDf41O5{DYcqRJr4M1M*vf3i zXT;_FognBQi_=Pig0hlg(c9Ma|6{n7^Kd%;H_dF#6tvhSW(Dw3;8#-IJ8=)_C(Ud} zgzGc^!y~H|r^=gZ)Z$*qx%oLBl=ORQ?{2!jKd4~C)%KpDqPwZ$pfa-MWt`j;UrK6|nRcp2`TkD)18+A1w}sE8TDXjudm_TD*3MoHda**%Vr6{(F5#N init() async { const AndroidInitializationSettings initializationSettingsAndroid = - AndroidInitializationSettings('app_icon'); + AndroidInitializationSettings('ic_stat_whisper'); const LinuxInitializationSettings initializationSettingsLinux = LinuxInitializationSettings( defaultActionName: 'whisper_message'); // TODO other options From 6dceba3230b53ed1b1701bdbfff2fc941f6c9713 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 20:11:49 +0100 Subject: [PATCH 023/181] feat(chat): per-chat theme override Chat Info gets a theme row that opens the existing color picker and stores the seed color per contact in the theme Hive box (chatTheme:), plus a reset row back to the global theme. ChatPage wraps its body in a Theme seeded with the override and reloads it when returning from Chat Info. --- assets/translations/cs.json | 2 + assets/translations/en.json | 2 + lib/pages/chat_info_page.dart | 95 +++++++++++++++- lib/pages/chat_page.dart | 200 +++++++++++++++++++--------------- lib/utils/cache_utils.dart | 23 ++++ test/chat_theme_test.dart | 33 ++++++ 6 files changed, 265 insertions(+), 90 deletions(-) create mode 100644 test/chat_theme_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 7978cf3..ffe9a5c 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -49,6 +49,8 @@ "enterUsername": "Uživatelské jméno vaší oběti", "settingsPage": "Nastavení", "themeSettings": "Motiv", + "chatTheme": "Téma chatu", + "useGlobalTheme": "Použít globální motiv", "notificationSettings": "Oznámení", "biometrySettings": "Ověření otiskem prstu", "wikiLink": "Wiki", diff --git a/assets/translations/en.json b/assets/translations/en.json index 75e2a60..e868be9 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -49,6 +49,8 @@ "enterUsername": "Your victim's username", "settingsPage": "Settings", "themeSettings": "Theme", + "chatTheme": "Chat theme", + "useGlobalTheme": "Use global theme", "notificationSettings": "Notifications", "biometrySettings": "Fingerprint authentication", "wikiLink": "Wiki", diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index c8ac05b..c47f1f0 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -1,11 +1,13 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import '../utils/cache_utils.dart'; import '../utils/message_notifier.dart'; import '../utils/dialog_utils.dart'; +import '../utils/singleton.dart'; import 'home_page.dart'; class ChatInfoPage extends StatefulWidget { - const ChatInfoPage(this.userId,{super.key}); + const ChatInfoPage(this.userId, {super.key}); final int userId; @override @@ -13,6 +15,41 @@ class ChatInfoPage extends StatefulWidget { } class _ChatInfoPageState extends State { + Color? _chatThemeColor; + + @override + void initState() { + super.initState(); + _loadChatTheme(); + } + + Future _loadChatTheme() async { + Color? color = await CacheUtils.getChatTheme(widget.userId); + if (mounted) { + setState(() { + _chatThemeColor = color; + }); + } + } + + /// Pick a per-chat theme color + Future _pickChatTheme() async { + Color? color = await showDialog( + context: context, + builder: (context) => DialogUtils.colorPickerDialog( + context, _chatThemeColor ?? Singleton().appTheme.color)); + if (color == null || !mounted) { + return; + } + await CacheUtils.setChatTheme(widget.userId, color); + await _loadChatTheme(); + } + + /// Drop the per-chat theme and fall back to the global one + Future _clearChatTheme() async { + await CacheUtils.clearChatTheme(widget.userId); + await _loadChatTheme(); + } @override Widget build(BuildContext context) { @@ -23,7 +60,61 @@ class _ChatInfoPageState extends State { body: SafeArea( child: Column( children: [ - // TODO Theme + // Chat theme + TextButton( + onPressed: _pickChatTheme, + child: Row( + children: [ + Icon( + Icons.palette, + size: 24, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'chatTheme'.tr(), + ), + ), + if (_chatThemeColor != null) + Padding( + padding: EdgeInsets.only(left: 10), + child: Container( + width: 16, + height: 16, + decoration: BoxDecoration( + color: _chatThemeColor, + shape: BoxShape.circle, + ), + ), + ), + SizedBox( + width: 24, + ), + ], + ), + ), + // Drop the override + if (_chatThemeColor != null) + TextButton( + onPressed: _clearChatTheme, + child: Row( + children: [ + Icon( + Icons.restart_alt, + size: 24, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'useGlobalTheme'.tr(), + ), + ), + SizedBox( + width: 24, + ), + ], + ), + ), // TODO Media diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index d566839..7fe1237 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -52,6 +52,8 @@ class _ChatPageState extends State { MediaRecorderController? _recorderController; Duration _recordDuration = Duration.zero; Timer? _recordTimer; + // Per-chat theme override, null means the global theme + Color? _chatThemeColor; @override void initState() { @@ -60,6 +62,17 @@ class _ChatPageState extends State { _loadMessages(); // Load concept message getConceptMessage(); + // Load per-chat theme + _loadChatTheme(); + } + + Future _loadChatTheme() async { + Color? color = await CacheUtils.getChatTheme(widget.user.id); + if (mounted) { + setState(() { + _chatThemeColor = color; + }); + } } Future getConceptMessage() async { @@ -596,103 +609,114 @@ class _ChatPageState extends State { } } }, - child: Scaffold( - extendBodyBehindAppBar: true, - appBar: PreferredSize( - preferredSize: Size( - double.infinity, - 56.0, - ), - child: ClipRRect( - child: BackdropFilter( - filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), - child: AppBar( - automaticallyImplyLeading: false, - backgroundColor: Theme.of(context) - .colorScheme - .surface - .withValues(alpha: 0.2), - leading: Row( - children: [ - IconButton( - icon: const Icon(Icons.arrow_back), - onPressed: () => Navigator.pop(context), - ), - CircleAvatar( - radius: 18, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 16, - color: widget.user.avatarTextColor, + child: Theme( + data: _chatThemeColor == null + ? Theme.of(context) + : ThemeData.from( + colorScheme: ColorScheme.fromSeed( + seedColor: _chatThemeColor!, + brightness: Theme.of(context).brightness), + useMaterial3: Singleton().appTheme.useMaterial3), + child: Scaffold( + extendBodyBehindAppBar: true, + appBar: PreferredSize( + preferredSize: Size( + double.infinity, + 56.0, + ), + child: ClipRRect( + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), + child: AppBar( + automaticallyImplyLeading: false, + backgroundColor: Theme.of(context) + .colorScheme + .surface + .withValues(alpha: 0.2), + leading: Row( + children: [ + IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () => Navigator.pop(context), + ), + CircleAvatar( + radius: 18, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 16, + color: widget.user.avatarTextColor, + ), ), ), + ], + ), + leadingWidth: 96, // Increase width to accommodate both icons + // Title + title: Text(widget.user.username), + // Action buttons + actions: [ + IconButton( + icon: const Icon(Icons.info), + tooltip: 'infoButton'.tr(), + onPressed: () async { + // Push info page + await Navigator.of(context).push(PageTransition( + duration: const Duration(milliseconds: 300), + reverseDuration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + type: PageTransitionType.rightToLeftJoined, + child: ChatInfoPage(widget.user.id), + childCurrent: widget)); + // The theme may have changed while the info page was open + await _loadChatTheme(); + }, ), ], ), - leadingWidth: 96, // Increase width to accommodate both icons - // Title - title: Text(widget.user.username), - // Action buttons - actions: [ - IconButton( - icon: const Icon(Icons.info), - tooltip: 'infoButton'.tr(), - onPressed: () { - // Push info page - Navigator.of(context).push(PageTransition( - duration: const Duration(milliseconds: 300), - reverseDuration: const Duration(milliseconds: 300), - curve: Curves.easeInOut, - type: PageTransitionType.rightToLeftJoined, - child: ChatInfoPage(widget.user.id), - childCurrent: widget)); - }, - ), - ], ), ), ), - ), - body: Column( - children: [ - // Messages and avatar list - Expanded( - child: FutureBuilder>( - future: notifier.getMessages(widget.user.id), - builder: (context, snapshot) { - if (snapshot.connectionState == ConnectionState.waiting && - _firstLoad) { - return Center( - child: Transform.scale( - scale: 1.5, - child: CircularProgressIndicator(), - ), - ); - } - // Set data - if (snapshot.hasData) { - WidgetsBinding.instance.addPostFrameCallback((_) { - _scrollController - .jumpTo(_scrollController.position.maxScrollExtent); - }); - _messages = snapshot.data!; - } - // Return messages - return _getContent(_messages); - }), - ), - SafeArea( - top: false, - child: Padding( - padding: const EdgeInsets.all(8.0), - child: _isRecording ? _buildRecordingBar() : _buildInputBar(), + body: Column( + children: [ + // Messages and avatar list + Expanded( + child: FutureBuilder>( + future: notifier.getMessages(widget.user.id), + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting && + _firstLoad) { + return Center( + child: Transform.scale( + scale: 1.5, + child: CircularProgressIndicator(), + ), + ); + } + // Set data + if (snapshot.hasData) { + WidgetsBinding.instance.addPostFrameCallback((_) { + _scrollController.jumpTo( + _scrollController.position.maxScrollExtent); + }); + _messages = snapshot.data!; + } + // Return messages + return _getContent(_messages); + }), ), - ), - ], + SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: _isRecording ? _buildRecordingBar() : _buildInputBar(), + ), + ), + ], + ), ), ), ); diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 7e29678..9b11766 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -1,3 +1,5 @@ +import 'dart:ui' show Color; + import 'package:bcrypt/bcrypt.dart'; import 'package:hive/hive.dart'; import '../utils/biometric_auth.dart'; @@ -5,6 +7,7 @@ import '../models/app_theme.dart'; import '../models/private_message.dart'; import '../models/profile.dart'; import '../models/user.dart'; +import 'color_utils.dart'; import 'media_utils.dart'; import 'singleton.dart'; import 'utils.dart'; @@ -17,6 +20,7 @@ class CacheUtils { static const _userKey = 'user'; static const _messageConceptKey = 'messageConcept'; static const _biometry = 'biometry'; + static const _chatThemeKeyPrefix = 'chatTheme:'; /// Opens box with password hash static Future _openPasswordHashBox() async { @@ -114,6 +118,25 @@ class CacheUtils { await box.put(_themeKey, theme); } + /// Returns per-chat theme color, null means the global theme is used + static Future getChatTheme(int userId) async { + Box box = await _openThemeBox(); + String? hex = box.get('$_chatThemeKeyPrefix$userId'); + return hex == null ? null : ColorUtils.colorFromHex(hex); + } + + /// Sets per-chat theme color + static Future setChatTheme(int userId, Color color) async { + Box box = await _openThemeBox(); + await box.put('$_chatThemeKeyPrefix$userId', ColorUtils.colorToHex(color)); + } + + /// Clears per-chat theme color, the chat falls back to the global theme + static Future clearChatTheme(int userId) async { + Box box = await _openThemeBox(); + await box.delete('$_chatThemeKeyPrefix$userId'); + } + /// Opens box with biometry static Future _openBiometryBox() async { return Hive.openBox(_biometry); diff --git a/test/chat_theme_test.dart b/test/chat_theme_test.dart new file mode 100644 index 0000000..5d3eab7 --- /dev/null +++ b/test/chat_theme_test.dart @@ -0,0 +1,33 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/utils/cache_utils.dart'; + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_chat_theme_test'); + Hive.init(dir.path); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('per-chat theme is stored, read and cleared', () async { + expect(await CacheUtils.getChatTheme(7), isNull); + + await CacheUtils.setChatTheme(7, const Color(0xFF3366CC)); + expect(await CacheUtils.getChatTheme(7), const Color(0xFF3366CC)); + + // Another chat is not affected + expect(await CacheUtils.getChatTheme(8), isNull); + + await CacheUtils.clearChatTheme(7); + expect(await CacheUtils.getChatTheme(7), isNull); + }); +} From 9657ec4bb718102164026277595881547ac67457 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 20:18:46 +0100 Subject: [PATCH 024/181] feat(chat): theme Chat Info with the per-chat color Chat Info now shares the same seeded theme as the conversation, so its text and app bar follow the chat color. The ThemeData construction moved to ThemeUtils so both pages build it the same way. --- lib/pages/chat_info_page.dart | 160 ++++++++++++++++++---------------- lib/pages/chat_page.dart | 9 +- lib/utils/theme_utils.dart | 18 ++++ 3 files changed, 103 insertions(+), 84 deletions(-) create mode 100644 lib/utils/theme_utils.dart diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index c47f1f0..6218671 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -4,6 +4,7 @@ import '../utils/cache_utils.dart'; import '../utils/message_notifier.dart'; import '../utils/dialog_utils.dart'; import '../utils/singleton.dart'; +import '../utils/theme_utils.dart'; import 'home_page.dart'; class ChatInfoPage extends StatefulWidget { @@ -53,60 +54,101 @@ class _ChatInfoPageState extends State { @override Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - title: Text('chatInfoPage'.tr()), - ), - body: SafeArea( - child: Column( - children: [ - // Chat theme - TextButton( - onPressed: _pickChatTheme, - child: Row( - children: [ - Icon( - Icons.palette, - size: 24, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'chatTheme'.tr(), + return Theme( + data: ThemeUtils.chatTheme(context, _chatThemeColor), + child: Scaffold( + appBar: AppBar( + title: Text('chatInfoPage'.tr()), + ), + body: SafeArea( + child: Column( + children: [ + // Chat theme + TextButton( + onPressed: _pickChatTheme, + child: Row( + children: [ + Icon( + Icons.palette, + size: 24, ), - ), - if (_chatThemeColor != null) Padding( - padding: EdgeInsets.only(left: 10), - child: Container( - width: 16, - height: 16, - decoration: BoxDecoration( - color: _chatThemeColor, - shape: BoxShape.circle, + padding: EdgeInsets.only(left: 5), + child: Text( + 'chatTheme'.tr(), + ), + ), + if (_chatThemeColor != null) + Padding( + padding: EdgeInsets.only(left: 10), + child: Container( + width: 16, + height: 16, + decoration: BoxDecoration( + color: _chatThemeColor, + shape: BoxShape.circle, + ), ), ), + SizedBox( + width: 24, ), - SizedBox( - width: 24, - ), - ], + ], + ), ), - ), - // Drop the override - if (_chatThemeColor != null) + // Drop the override + if (_chatThemeColor != null) + TextButton( + onPressed: _clearChatTheme, + child: Row( + children: [ + Icon( + Icons.restart_alt, + size: 24, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'useGlobalTheme'.tr(), + ), + ), + SizedBox( + width: 24, + ), + ], + ), + ), + + // TODO Media + + // Delete chat TextButton( - onPressed: _clearChatTheme, + onPressed: () async { + await DialogUtils.yesNoDialog( + context, + 'deleteChatConfirm'.tr(), + 'deleteChatConfirmText'.tr(), () async { + MessageNotifier().deleteChat(widget.userId); + // Redirect to home page and clear navigation stack + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute(builder: (context) => const HomePage()), + (route) => false, + ); + }); + }, child: Row( children: [ Icon( - Icons.restart_alt, + Icons.delete_forever, size: 24, + color: Colors.red, ), Padding( padding: EdgeInsets.only(left: 5), child: Text( - 'useGlobalTheme'.tr(), + 'deleteChat'.tr(), + style: TextStyle(color: Colors.red), ), ), SizedBox( @@ -115,44 +157,8 @@ class _ChatInfoPageState extends State { ], ), ), - - // TODO Media - - // Delete chat - TextButton( - onPressed: () async { - await DialogUtils.yesNoDialog(context, 'deleteChatConfirm'.tr(), - 'deleteChatConfirmText'.tr(), () async { - MessageNotifier().deleteChat(widget.userId); - // Redirect to home page and clear navigation stack - Navigator.pushAndRemoveUntil( - context, - MaterialPageRoute(builder: (context) => const HomePage()), - (route) => false, - ); - }); - }, - child: Row( - children: [ - Icon( - Icons.delete_forever, - size: 24, - color: Colors.red, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'deleteChat'.tr(), - style: TextStyle(color: Colors.red), - ), - ), - SizedBox( - width: 24, - ), - ], - ), - ), - ], + ], + ), ), ), ); diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 7fe1237..6f1ac19 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -20,6 +20,7 @@ import '../utils/crypto_utils.dart'; import '../utils/media_utils.dart'; import '../utils/message_notifier.dart'; import '../utils/singleton.dart'; +import '../utils/theme_utils.dart'; import '../utils/utils.dart'; import '../widgets/chat_bubble.dart'; import 'package:basic_utils/basic_utils.dart' as bu; @@ -610,13 +611,7 @@ class _ChatPageState extends State { } }, child: Theme( - data: _chatThemeColor == null - ? Theme.of(context) - : ThemeData.from( - colorScheme: ColorScheme.fromSeed( - seedColor: _chatThemeColor!, - brightness: Theme.of(context).brightness), - useMaterial3: Singleton().appTheme.useMaterial3), + data: ThemeUtils.chatTheme(context, _chatThemeColor), child: Scaffold( extendBodyBehindAppBar: true, appBar: PreferredSize( diff --git a/lib/utils/theme_utils.dart b/lib/utils/theme_utils.dart new file mode 100644 index 0000000..d5bba93 --- /dev/null +++ b/lib/utils/theme_utils.dart @@ -0,0 +1,18 @@ +import 'package:flutter/material.dart'; + +import 'singleton.dart'; + +class ThemeUtils { + /// Theme seeded with the per-chat color, or the inherited theme without an override. + /// + /// Brightness and Material 3 always follow the global theme. + static ThemeData chatTheme(BuildContext context, Color? seed) { + if (seed == null) { + return Theme.of(context); + } + return ThemeData.from( + colorScheme: ColorScheme.fromSeed( + seedColor: seed, brightness: Theme.of(context).brightness), + useMaterial3: Singleton().appTheme.useMaterial3); + } +} From f974a6ec780b4fdfb3631eec3dfb107a9f7a69e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 20:30:08 +0100 Subject: [PATCH 025/181] feat(chat): shared media grid in Chat Info Shows image, GIF and video messages that already have a local file, newest first, in a three-column grid; tapping opens MediaViewerPage. Voice messages and attachments that are still downloading are left out. Thumbnails are decrypted on demand; videos show a play tile because there is no thumbnail generator. --- assets/translations/cs.json | 1 + assets/translations/en.json | 1 + lib/pages/chat_info_page.dart | 151 ++++++++++++++++++++++++++++++++- test/chat_info_media_test.dart | 32 +++++++ 4 files changed, 183 insertions(+), 2 deletions(-) create mode 100644 test/chat_info_media_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index ffe9a5c..a484e6b 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -105,5 +105,6 @@ "mediaPhoto": "Fotka", "mediaGif": "GIF", "mediaVideo": "Video", + "mediaTitle": "Média", "mediaVoice": "Hlasová zpráva" } \ No newline at end of file diff --git a/assets/translations/en.json b/assets/translations/en.json index e868be9..6c097c8 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -105,5 +105,6 @@ "mediaPhoto": "Photo", "mediaGif": "GIF", "mediaVideo": "Video", + "mediaTitle": "Media", "mediaVoice": "Voice message" } \ No newline at end of file diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 6218671..36b2910 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -1,27 +1,50 @@ import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:page_transition/page_transition.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import '../models/private_message.dart'; import '../utils/cache_utils.dart'; import '../utils/message_notifier.dart'; import '../utils/dialog_utils.dart'; +import '../utils/media_utils.dart'; import '../utils/singleton.dart'; import '../utils/theme_utils.dart'; import 'home_page.dart'; +import 'media_viewer_page.dart'; class ChatInfoPage extends StatefulWidget { const ChatInfoPage(this.userId, {super.key}); final int userId; + /// Media messages with a local file that the viewer can open, newest first. + /// Voice messages and attachments that are still downloading are left out. + @visibleForTesting + static List sharedMedia(List messages) { + final media = messages + .where((m) => + m.localPath != null && + m.mediaType != null && + m.mediaType != MediaType.voice && + m.downloadStatus == MediaDownloadStatus.ready) + .toList(); + media.sort((a, b) => b.sentAt.compareTo(a.sentAt)); + return media; + } + @override State createState() => _ChatInfoPageState(); } class _ChatInfoPageState extends State { Color? _chatThemeColor; + List _media = []; @override void initState() { super.initState(); _loadChatTheme(); + _loadMedia(); } Future _loadChatTheme() async { @@ -33,6 +56,16 @@ class _ChatInfoPageState extends State { } } + Future _loadMedia() async { + List messages = + await CacheUtils.getPrivateMessages(widget.userId); + if (mounted) { + setState(() { + _media = ChatInfoPage.sharedMedia(messages); + }); + } + } + /// Pick a per-chat theme color Future _pickChatTheme() async { Color? color = await showDialog( @@ -52,6 +85,25 @@ class _ChatInfoPageState extends State { await _loadChatTheme(); } + void _openMedia(PrivateMessage message) { + final path = message.localPath; + final type = message.mediaType; + if (path == null || type == null) { + return; + } + Navigator.of(context).push( + PageTransition( + type: PageTransitionType.fade, + duration: const Duration(milliseconds: 200), + child: MediaViewerPage( + localPath: path, + type: type, + caption: message.message, + ), + ), + ); + } + @override Widget build(BuildContext context) { return Theme( @@ -61,7 +113,7 @@ class _ChatInfoPageState extends State { title: Text('chatInfoPage'.tr()), ), body: SafeArea( - child: Column( + child: ListView( children: [ // Chat theme TextButton( @@ -119,7 +171,31 @@ class _ChatInfoPageState extends State { ), ), - // TODO Media + // Shared media + if (_media.isNotEmpty) ...[ + Padding( + padding: EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Text( + 'mediaTitle'.tr(), + style: TextStyle(fontSize: 16), + ), + ), + GridView.builder( + shrinkWrap: true, + physics: NeverScrollableScrollPhysics(), + padding: EdgeInsets.symmetric(horizontal: 8), + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 3, + mainAxisSpacing: 4, + crossAxisSpacing: 4, + ), + itemCount: _media.length, + itemBuilder: (context, index) => _MediaTile( + message: _media[index], + onTap: () => _openMedia(_media[index]), + ), + ), + ], // Delete chat TextButton( @@ -164,3 +240,74 @@ class _ChatInfoPageState extends State { ); } } + +/// Square thumbnail of one shared media message. +class _MediaTile extends StatefulWidget { + const _MediaTile({required this.message, required this.onTap}); + + final PrivateMessage message; + final VoidCallback onTap; + + @override + State<_MediaTile> createState() => _MediaTileState(); +} + +class _MediaTileState extends State<_MediaTile> { + Uint8List? _bytes; + bool _error = false; + + @override + void initState() { + super.initState(); + _loadImage(); + } + + Future _loadImage() async { + // Videos have no thumbnail generator, the play icon is enough. + if (widget.message.mediaType == MediaType.video) { + return; + } + final path = widget.message.localPath; + if (path == null) { + return; + } + try { + Uint8List bytes = await MediaUtils.decryptAtRest(path); + if (mounted) { + setState(() { + _bytes = bytes; + }); + } + } catch (_) { + if (mounted) { + setState(() { + _error = true; + }); + } + } + } + + @override + Widget build(BuildContext context) { + final isVideo = widget.message.mediaType == MediaType.video; + return GestureDetector( + onTap: widget.onTap, + child: Container( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + child: _bytes != null + ? Image.memory(_bytes!, fit: BoxFit.cover) + : Center( + child: _error + ? Icon(Icons.broken_image, size: 24) + : isVideo + ? Icon(Icons.play_arrow, size: 32) + : SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ), + ), + ); + } +} diff --git a/test/chat_info_media_test.dart b/test/chat_info_media_test.dart new file mode 100644 index 0000000..0c39100 --- /dev/null +++ b/test/chat_info_media_test.dart @@ -0,0 +1,32 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/pages/chat_info_page.dart'; + +PrivateMessage message(String? type, String? path, DateTime sentAt, + {int? downloadStatus}) { + return PrivateMessage(1, '', sentAt, sentAt, false, + mediaTypeStr: type, + localPath: path, + downloadStatus: downloadStatus ?? MediaDownloadStatus.ready); +} + +void main() { + test('shared media keeps only ready, viewable media with a local file', () { + final now = DateTime(2026, 11, 12, 12); + final media = ChatInfoPage.sharedMedia([ + message('image', '/tmp/a.jpg', now), + message('video', '/tmp/b.mp4', now.subtract(const Duration(minutes: 1))), + // Voice messages are not part of the overview + message('voice', '/tmp/c.m4a', now.subtract(const Duration(minutes: 2))), + // Not downloaded yet + message('image', null, now.subtract(const Duration(minutes: 3))), + // Still downloading + message('image', '/tmp/d.jpg', now.subtract(const Duration(minutes: 4)), + downloadStatus: MediaDownloadStatus.pending), + // Plain text + message(null, null, now.subtract(const Duration(minutes: 5))), + ]); + + expect(media.map((m) => m.localPath), ['/tmp/a.jpg', '/tmp/b.mp4']); + }); +} From 9d65a7fbdee4ed573c4ea5d81c0ef363b4654831 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 21:19:26 +0100 Subject: [PATCH 026/181] feat(chat): KLIPY GIF picker and keyboard GIF insertion The attachment sheet's GIF entry no longer opens the file picker: it opens a KLIPY page with trending GIFs and debounced search, then downloads the chosen animated webp/gif and sends it through the normal E2E media pipeline. The app key comes from --dart-define=KLIPY_API_KEY; without it the page explains that GIF search is not configured. The message field also accepts image/gif and image/webp inserted by the system keyboard (Gboard), mapping both to GIF media. --- assets/translations/cs.json | 8 ++ assets/translations/en.json | 8 ++ lib/pages/chat_page.dart | 52 ++++++++++- lib/pages/gif_picker_page.dart | 164 +++++++++++++++++++++++++++++++++ lib/utils/klipy_client.dart | 117 +++++++++++++++++++++++ lib/utils/media_utils.dart | 33 +++---- test/klipy_client_test.dart | 54 +++++++++++ 7 files changed, 416 insertions(+), 20 deletions(-) create mode 100644 lib/pages/gif_picker_page.dart create mode 100644 lib/utils/klipy_client.dart create mode 100644 test/klipy_client_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index a484e6b..0630141 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -92,6 +92,14 @@ "attachVideoCamera": "Natočit video", "attachGallery": "Galerie fotek a videí", "attachGif": "GIF", + "gifTitle": "GIFy", + "gifSearchHint": "Hledat na KLIPY", + "gifNoResults": "Žádné GIFy nenalezeny", + "gifLoadFailed": "GIFy se nepodařilo načíst", + "gifNotConfigured": "Hledání GIFů není nakonfigurované (chybí KLIPY_API_KEY).", + "gifDownloadFailed": "GIF se nepodařilo odeslat", + "gifFromKeyboardFailed": "GIF z klávesnice se nepodařilo načíst", + "poweredByKlipy": "Powered by KLIPY", "attachFile": "Soubor", "holdToRecord": "Podržením nahrajete hlasovou zprávu", "slideToCancel": "Posunutím zrušíte", diff --git a/assets/translations/en.json b/assets/translations/en.json index 6c097c8..a82d50a 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -92,6 +92,14 @@ "attachVideoCamera": "Record a video", "attachGallery": "Photo & video gallery", "attachGif": "GIF", + "gifTitle": "GIFs", + "gifSearchHint": "Search KLIPY", + "gifNoResults": "No GIFs found", + "gifLoadFailed": "Could not load GIFs", + "gifNotConfigured": "GIF search is not configured (KLIPY_API_KEY is missing).", + "gifDownloadFailed": "Could not send the GIF", + "gifFromKeyboardFailed": "This keyboard GIF could not be read", + "poweredByKlipy": "Powered by KLIPY", "attachFile": "File", "holdToRecord": "Hold to record a voice message", "slideToCancel": "Slide to cancel", diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 6f1ac19..fac92eb 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1,12 +1,12 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; -import 'dart:typed_data'; import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:http/http.dart' show MultipartFile; +import 'package:http/http.dart' as http; import 'package:page_transition/page_transition.dart'; import 'package:provider/provider.dart'; import 'package:whisper_websocket_client_dart/models/media_reference.dart'; @@ -17,6 +17,7 @@ import '../models/private_message.dart'; import '../models/user.dart'; import '../utils/cache_utils.dart'; import '../utils/crypto_utils.dart'; +import '../utils/klipy_client.dart'; import '../utils/media_utils.dart'; import '../utils/message_notifier.dart'; import '../utils/singleton.dart'; @@ -25,6 +26,7 @@ import '../utils/utils.dart'; import '../widgets/chat_bubble.dart'; import 'package:basic_utils/basic_utils.dart' as bu; import 'chat_info_page.dart'; +import 'gif_picker_page.dart'; class ChatPage extends StatefulWidget { const ChatPage(this.user, {super.key}); @@ -187,7 +189,7 @@ class _ChatPageState extends State { // Upload the ciphertext over HTTP. final uploadResponse = await Utils.callApi( () => Singleton().mediaApi.uploadMedia( - MultipartFile.fromBytes('file', transport.blob, + http.MultipartFile.fromBytes('file', transport.blob, filename: 'media.bin'), widget.user.id, ), @@ -285,6 +287,44 @@ class _ChatPageState extends State { } } + /// Pick a GIF from KLIPY, download it and send it as a GIF message. + Future _pickKlipyGif() async { + final gif = await Navigator.of(context).push( + MaterialPageRoute(builder: (context) => const GifPickerPage())); + if (gif == null || !mounted) { + return; + } + try { + final response = await http + .get(Uri.parse(gif.sendUrl)) + .timeout(const Duration(seconds: 20)); + if (response.statusCode != 200) { + throw Exception('KLIPY download failed: ${response.statusCode}'); + } + final extension = gif.sendUrl.endsWith('.webp') ? 'webp' : 'gif'; + final file = + await MediaUtils.writeTempBytes(response.bodyBytes, extension); + await _sendMedia(MediaType.gif, file); + } catch (e) { + await Fluttertoast.showToast( + msg: 'gifDownloadFailed'.tr(), backgroundColor: Colors.red); + } + } + + /// GIF/WebP inserted straight from the keyboard (Gboard image keyboard). + Future _onKeyboardContentInserted( + KeyboardInsertedContent content) async { + final bytes = content.data; + if (bytes == null || bytes.isEmpty) { + await Fluttertoast.showToast( + msg: 'gifFromKeyboardFailed'.tr(), backgroundColor: Colors.red); + return; + } + final extension = content.mimeType == 'image/webp' ? 'webp' : 'gif'; + final file = await MediaUtils.writeTempBytes(bytes, extension); + await _sendMedia(MediaType.gif, file); + } + /// Show the attachment options bottom sheet. void _showAttachSheet() { showModalBottomSheet( @@ -323,7 +363,7 @@ class _ChatPageState extends State { title: Text('attachGif'.tr()), onTap: () { Navigator.pop(ctx); - _pickAndSend(MediaUtils.pickGif, MediaType.gif); + _pickKlipyGif(); }, ), ListTile( @@ -433,6 +473,10 @@ class _ChatPageState extends State { minLines: 1, maxLines: 5, textInputAction: TextInputAction.newline, + contentInsertionConfiguration: ContentInsertionConfiguration( + allowedMimeTypes: const ['image/gif', 'image/webp'], + onContentInserted: _onKeyboardContentInserted, + ), decoration: InputDecoration( hintText: 'yourMessage'.tr(), filled: true, diff --git a/lib/pages/gif_picker_page.dart b/lib/pages/gif_picker_page.dart new file mode 100644 index 0000000..48a26b1 --- /dev/null +++ b/lib/pages/gif_picker_page.dart @@ -0,0 +1,164 @@ +import 'dart:async'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import '../utils/klipy_client.dart'; + +/// KLIPY GIF picker: trending on open, debounced search on typing. +/// Pops the chosen [KlipyGif], or null when dismissed. +class GifPickerPage extends StatefulWidget { + const GifPickerPage({super.key}); + + @override + State createState() => _GifPickerPageState(); +} + +class _GifPickerPageState extends State { + final TextEditingController _searchController = TextEditingController(); + List _gifs = []; + bool _loading = true; + bool _failed = false; + Timer? _debounce; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void dispose() { + _debounce?.cancel(); + _searchController.dispose(); + super.dispose(); + } + + Future _load({String query = ''}) async { + setState(() { + _loading = true; + _failed = false; + }); + try { + final gifs = query.isEmpty + ? await KlipyClient.trending() + : await KlipyClient.search(query); + if (!mounted) { + return; + } + setState(() { + _gifs = gifs; + _loading = false; + }); + } catch (_) { + if (!mounted) { + return; + } + setState(() { + _failed = true; + _loading = false; + }); + } + } + + void _onSearchChanged(String value) { + _debounce?.cancel(); + _debounce = Timer(const Duration(milliseconds: 400), () { + _load(query: value.trim()); + }); + } + + Widget _body() { + if (!KlipyClient.isConfigured) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text('gifNotConfigured'.tr(), textAlign: TextAlign.center), + )); + } + if (_loading) { + return const Center(child: CircularProgressIndicator()); + } + if (_failed) { + return Center(child: Text('gifLoadFailed'.tr())); + } + if (_gifs.isEmpty) { + return Center(child: Text('gifNoResults'.tr())); + } + return GridView.builder( + padding: const EdgeInsets.all(4), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + mainAxisSpacing: 4, + crossAxisSpacing: 4, + childAspectRatio: 1, + ), + itemCount: _gifs.length, + itemBuilder: (context, index) { + final gif = _gifs[index]; + return GestureDetector( + onTap: () => Navigator.of(context).pop(gif), + child: Container( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + child: Image.network( + gif.previewUrl, + fit: BoxFit.cover, + // Short-lived failures just retry on the next fetch. + errorBuilder: (context, error, stackTrace) => + const Icon(Icons.broken_image), + ), + ), + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text('gifTitle'.tr()), + bottom: PreferredSize( + preferredSize: const Size.fromHeight(56), + child: Padding( + padding: const EdgeInsets.fromLTRB(8, 0, 8, 8), + child: TextField( + controller: _searchController, + onChanged: _onSearchChanged, + textInputAction: TextInputAction.search, + onSubmitted: (value) => _load(query: value.trim()), + decoration: InputDecoration( + hintText: 'gifSearchHint'.tr(), + prefixIcon: const Icon(Icons.search), + isDense: true, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(30), + borderSide: BorderSide.none, + ), + filled: true, + fillColor: + Theme.of(context).colorScheme.surfaceContainerHighest, + ), + ), + ), + ), + ), + body: _body(), + // KLIPY attribution is required by their terms. + bottomNavigationBar: SafeArea( + child: InkWell( + onTap: () => launchUrl(Uri.parse('https://klipy.com')), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Text( + 'poweredByKlipy'.tr(), + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ), + ), + ); + } +} diff --git a/lib/utils/klipy_client.dart b/lib/utils/klipy_client.dart new file mode 100644 index 0000000..4956d13 --- /dev/null +++ b/lib/utils/klipy_client.dart @@ -0,0 +1,117 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; + +/// One KLIPY GIF resolved to the formats this app uses. +class KlipyGif { + const KlipyGif( + {required this.title, required this.previewUrl, required this.sendUrl}); + + final String title; + + /// Small animated image for the picker grid. + final String previewUrl; + + /// Medium animated image that is downloaded and sent as a GIF message. + final String sendUrl; +} + +class KlipyException implements Exception { + KlipyException(this.message); + final String message; + + @override + String toString() => 'KlipyException: $message'; +} + +/// Minimal KLIPY GIF API client (search + trending). +/// +/// The app key is a free KLIPY key passed at build time: +/// `flutter run --dart-define=KLIPY_API_KEY=...`. +class KlipyClient { + static const String apiKey = String.fromEnvironment('KLIPY_API_KEY'); + static const String _host = 'api.klipy.com'; + static const Duration _timeout = Duration(seconds: 10); + + static bool get isConfigured => apiKey.isNotEmpty; + + /// Most popular GIFs, localized by KLIPY. + static Future> trending({int page = 1}) async { + return _fetch(_uri('trending', _query(page))); + } + + /// GIFs matching [query]. + static Future> search(String query, {int page = 1}) async { + return _fetch(_uri('search', {..._query(page), 'q': query})); + } + + static Uri _uri(String path, Map query) { + return Uri.https(_host, '/api/v1/$apiKey/gifs/$path', query); + } + + static Map _query(int page) { + return { + 'page': '$page', + 'per_page': '24', + 'content_filter': 'high', + 'format_filter': 'gif,webp', + }; + } + + static Future> _fetch(Uri uri) async { + final response = await http.get(uri).timeout(_timeout); + if (response.statusCode != 200) { + throw KlipyException('KLIPY returned ${response.statusCode}'); + } + return parse(response.body); + } + + /// Parses a KLIPY search/trending payload. Public for the unit test. + static List parse(String body) { + final json = jsonDecode(body); + if (json is! Map) { + return []; + } + final data = json['data']; + final items = data is Map ? data['data'] : null; + if (items is! List) { + return []; + } + final gifs = []; + for (final item in items) { + if (item is! Map) { + continue; + } + final file = item['file']; + if (file is! Map) { + continue; + } + final preview = _url(file, 'sm') ?? _url(file, 'md'); + final send = _url(file, 'md') ?? _url(file, 'sm'); + if (preview == null || send == null) { + continue; + } + gifs.add(KlipyGif( + title: item['title'] as String? ?? '', + previewUrl: preview, + sendUrl: send, + )); + } + return gifs; + } + + /// Animated WebP first (much smaller than GIF), GIF as the fallback. + static String? _url(Map file, String size) { + final bucket = file[size]; + if (bucket is! Map) { + return null; + } + for (final format in const ['webp', 'gif']) { + final url = bucket[format]?['url']; + if (url is String && url.isNotEmpty) { + return url; + } + } + return null; + } +} diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 1b561a9..8b324ed 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -106,7 +106,8 @@ class MediaUtils { // --------------------------------------------------------------------------- /// Encrypt [bytes] with a fresh random key for upload. - static Future encryptForTransport(Uint8List bytes) async { + static Future encryptForTransport( + Uint8List bytes) async { final algorithm = cryptography.AesGcm.with256bits(); final secretKey = await algorithm.newSecretKey(); final keyBytes = Uint8List.fromList(await secretKey.extractBytes()); @@ -162,6 +163,15 @@ class MediaUtils { return dir; } + /// Writes plaintext bytes to a temporary file, e.g. for keyboard-inserted + /// or downloaded GIFs that then go through the media pipeline. + static Future writeTempBytes(Uint8List bytes, String extension) async { + final dir = await mediaDir(); + final file = File('$dir/send_${_uuid.v4()}.$extension'); + await file.writeAsBytes(bytes, flush: true); + return file; + } + /// Delete a single (encrypted) media file, ignoring errors. static Future deleteLocalFile(String? path) async { if (path == null) { @@ -286,7 +296,8 @@ class MediaUtils { /// Build the plaintext (pre-encryption) bytes for a media message: a JSON /// envelope wrapping the [reference] and optional [caption]. - static Uint8List buildMediaEnvelope(MediaReference reference, String caption) { + static Uint8List buildMediaEnvelope( + MediaReference reference, String caption) { final map = { 'whisperMsg': envelopeVersion, 'kind': 'media', @@ -330,8 +341,7 @@ class MediaUtils { /// Capture a video with the camera. static Future pickVideoFromCamera() async { final picked = await _imagePicker.pickVideo( - source: ImageSource.camera, - maxDuration: const Duration(minutes: 1)); + source: ImageSource.camera, maxDuration: const Duration(minutes: 1)); return picked == null ? null : File(picked.path); } @@ -341,16 +351,6 @@ class MediaUtils { return picked == null ? null : File(picked.path); } - /// Pick a GIF file. - static Future pickGif() async { - final picked = await FilePicker.pickFile( - type: FileType.custom, - allowedExtensions: const ['gif'], - ); - final path = picked?.path; - return path == null ? null : File(path); - } - /// Pick an arbitrary media (image/video) file. static Future pickFile() async { final picked = await FilePicker.pickFile(type: FileType.media); @@ -389,8 +389,9 @@ class MediaRecorderController { /// Stop recording and return the resulting file and its duration. Future stop() async { final path = await _recorder.stop(); - final durationMs = - _startedAt == null ? 0 : DateTime.now().difference(_startedAt!).inMilliseconds; + final durationMs = _startedAt == null + ? 0 + : DateTime.now().difference(_startedAt!).inMilliseconds; if (path == null) { return null; } diff --git a/test/klipy_client_test.dart b/test/klipy_client_test.dart new file mode 100644 index 0000000..6d84964 --- /dev/null +++ b/test/klipy_client_test.dart @@ -0,0 +1,54 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/klipy_client.dart'; + +void main() { + test('parse prefers animated webp and keeps md as the sent format', () { + const body = ''' +{ + "result": true, + "data": { + "data": [ + { + "title": "Hello", + "slug": "hello-hi-662", + "file": { + "hd": {"gif": {"url": "https://x/hd.gif"}}, + "md": { + "gif": {"url": "https://x/md.gif"}, + "webp": {"url": "https://x/md.webp"} + }, + "sm": { + "gif": {"url": "https://x/sm.gif"}, + "webp": {"url": "https://x/sm.webp"} + } + } + }, + { + "title": "No medium", + "file": { + "sm": {"gif": {"url": "https://x/small.gif"}} + } + }, + {"title": "Broken", "file": {}}, + "not an object" + ] + } +} +'''; + + final gifs = KlipyClient.parse(body); + + expect(gifs.length, 2); + expect(gifs[0].title, 'Hello'); + expect(gifs[0].previewUrl, 'https://x/sm.webp'); + expect(gifs[0].sendUrl, 'https://x/md.webp'); + // Falls back to the small size when there is no medium one. + expect(gifs[1].previewUrl, 'https://x/small.gif'); + expect(gifs[1].sendUrl, 'https://x/small.gif'); + }); + + test('parse returns an empty list for unexpected payloads', () { + expect(KlipyClient.parse('{}'), isEmpty); + expect(KlipyClient.parse('{"data": null}'), isEmpty); + }); +} From 148f18345f9dc7139bed874ca95f108d33ecc218 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 21:46:34 +0100 Subject: [PATCH 027/181] revert(chat): drop the KLIPY picker, GIFs come from the keyboard only The client-side KLIPY integration is gone (client, picker page, test and the GIF entry in the attachment sheet), so the app no longer talks to a third-party provider: a server-side proxy was rejected as too much new surface for the metadata it would hide. Keyboard-inserted GIF/WebP still works; there is no file-based GIF upload anymore. --- assets/translations/cs.json | 8 -- assets/translations/en.json | 8 -- lib/pages/chat_page.dart | 34 ------- lib/pages/gif_picker_page.dart | 164 --------------------------------- lib/utils/klipy_client.dart | 117 ----------------------- test/klipy_client_test.dart | 54 ----------- 6 files changed, 385 deletions(-) delete mode 100644 lib/pages/gif_picker_page.dart delete mode 100644 lib/utils/klipy_client.dart delete mode 100644 test/klipy_client_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 0630141..b5435fb 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -91,15 +91,7 @@ "attachCamera": "Vyfotit", "attachVideoCamera": "Natočit video", "attachGallery": "Galerie fotek a videí", - "attachGif": "GIF", - "gifTitle": "GIFy", - "gifSearchHint": "Hledat na KLIPY", - "gifNoResults": "Žádné GIFy nenalezeny", - "gifLoadFailed": "GIFy se nepodařilo načíst", - "gifNotConfigured": "Hledání GIFů není nakonfigurované (chybí KLIPY_API_KEY).", - "gifDownloadFailed": "GIF se nepodařilo odeslat", "gifFromKeyboardFailed": "GIF z klávesnice se nepodařilo načíst", - "poweredByKlipy": "Powered by KLIPY", "attachFile": "Soubor", "holdToRecord": "Podržením nahrajete hlasovou zprávu", "slideToCancel": "Posunutím zrušíte", diff --git a/assets/translations/en.json b/assets/translations/en.json index a82d50a..0e5e76c 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -91,15 +91,7 @@ "attachCamera": "Take a photo", "attachVideoCamera": "Record a video", "attachGallery": "Photo & video gallery", - "attachGif": "GIF", - "gifTitle": "GIFs", - "gifSearchHint": "Search KLIPY", - "gifNoResults": "No GIFs found", - "gifLoadFailed": "Could not load GIFs", - "gifNotConfigured": "GIF search is not configured (KLIPY_API_KEY is missing).", - "gifDownloadFailed": "Could not send the GIF", "gifFromKeyboardFailed": "This keyboard GIF could not be read", - "poweredByKlipy": "Powered by KLIPY", "attachFile": "File", "holdToRecord": "Hold to record a voice message", "slideToCancel": "Slide to cancel", diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index fac92eb..1abfaf6 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -17,7 +17,6 @@ import '../models/private_message.dart'; import '../models/user.dart'; import '../utils/cache_utils.dart'; import '../utils/crypto_utils.dart'; -import '../utils/klipy_client.dart'; import '../utils/media_utils.dart'; import '../utils/message_notifier.dart'; import '../utils/singleton.dart'; @@ -26,7 +25,6 @@ import '../utils/utils.dart'; import '../widgets/chat_bubble.dart'; import 'package:basic_utils/basic_utils.dart' as bu; import 'chat_info_page.dart'; -import 'gif_picker_page.dart'; class ChatPage extends StatefulWidget { const ChatPage(this.user, {super.key}); @@ -287,30 +285,6 @@ class _ChatPageState extends State { } } - /// Pick a GIF from KLIPY, download it and send it as a GIF message. - Future _pickKlipyGif() async { - final gif = await Navigator.of(context).push( - MaterialPageRoute(builder: (context) => const GifPickerPage())); - if (gif == null || !mounted) { - return; - } - try { - final response = await http - .get(Uri.parse(gif.sendUrl)) - .timeout(const Duration(seconds: 20)); - if (response.statusCode != 200) { - throw Exception('KLIPY download failed: ${response.statusCode}'); - } - final extension = gif.sendUrl.endsWith('.webp') ? 'webp' : 'gif'; - final file = - await MediaUtils.writeTempBytes(response.bodyBytes, extension); - await _sendMedia(MediaType.gif, file); - } catch (e) { - await Fluttertoast.showToast( - msg: 'gifDownloadFailed'.tr(), backgroundColor: Colors.red); - } - } - /// GIF/WebP inserted straight from the keyboard (Gboard image keyboard). Future _onKeyboardContentInserted( KeyboardInsertedContent content) async { @@ -358,14 +332,6 @@ class _ChatPageState extends State { _pickAndSend(MediaUtils.pickMediaFromGallery, null); }, ), - ListTile( - leading: const Icon(Icons.gif_box), - title: Text('attachGif'.tr()), - onTap: () { - Navigator.pop(ctx); - _pickKlipyGif(); - }, - ), ListTile( leading: const Icon(Icons.insert_drive_file), title: Text('attachFile'.tr()), diff --git a/lib/pages/gif_picker_page.dart b/lib/pages/gif_picker_page.dart deleted file mode 100644 index 48a26b1..0000000 --- a/lib/pages/gif_picker_page.dart +++ /dev/null @@ -1,164 +0,0 @@ -import 'dart:async'; - -import 'package:easy_localization/easy_localization.dart'; -import 'package:flutter/material.dart'; -import 'package:url_launcher/url_launcher.dart'; - -import '../utils/klipy_client.dart'; - -/// KLIPY GIF picker: trending on open, debounced search on typing. -/// Pops the chosen [KlipyGif], or null when dismissed. -class GifPickerPage extends StatefulWidget { - const GifPickerPage({super.key}); - - @override - State createState() => _GifPickerPageState(); -} - -class _GifPickerPageState extends State { - final TextEditingController _searchController = TextEditingController(); - List _gifs = []; - bool _loading = true; - bool _failed = false; - Timer? _debounce; - - @override - void initState() { - super.initState(); - _load(); - } - - @override - void dispose() { - _debounce?.cancel(); - _searchController.dispose(); - super.dispose(); - } - - Future _load({String query = ''}) async { - setState(() { - _loading = true; - _failed = false; - }); - try { - final gifs = query.isEmpty - ? await KlipyClient.trending() - : await KlipyClient.search(query); - if (!mounted) { - return; - } - setState(() { - _gifs = gifs; - _loading = false; - }); - } catch (_) { - if (!mounted) { - return; - } - setState(() { - _failed = true; - _loading = false; - }); - } - } - - void _onSearchChanged(String value) { - _debounce?.cancel(); - _debounce = Timer(const Duration(milliseconds: 400), () { - _load(query: value.trim()); - }); - } - - Widget _body() { - if (!KlipyClient.isConfigured) { - return Center( - child: Padding( - padding: const EdgeInsets.all(24), - child: Text('gifNotConfigured'.tr(), textAlign: TextAlign.center), - )); - } - if (_loading) { - return const Center(child: CircularProgressIndicator()); - } - if (_failed) { - return Center(child: Text('gifLoadFailed'.tr())); - } - if (_gifs.isEmpty) { - return Center(child: Text('gifNoResults'.tr())); - } - return GridView.builder( - padding: const EdgeInsets.all(4), - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 2, - mainAxisSpacing: 4, - crossAxisSpacing: 4, - childAspectRatio: 1, - ), - itemCount: _gifs.length, - itemBuilder: (context, index) { - final gif = _gifs[index]; - return GestureDetector( - onTap: () => Navigator.of(context).pop(gif), - child: Container( - color: Theme.of(context).colorScheme.surfaceContainerHighest, - child: Image.network( - gif.previewUrl, - fit: BoxFit.cover, - // Short-lived failures just retry on the next fetch. - errorBuilder: (context, error, stackTrace) => - const Icon(Icons.broken_image), - ), - ), - ); - }, - ); - } - - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - title: Text('gifTitle'.tr()), - bottom: PreferredSize( - preferredSize: const Size.fromHeight(56), - child: Padding( - padding: const EdgeInsets.fromLTRB(8, 0, 8, 8), - child: TextField( - controller: _searchController, - onChanged: _onSearchChanged, - textInputAction: TextInputAction.search, - onSubmitted: (value) => _load(query: value.trim()), - decoration: InputDecoration( - hintText: 'gifSearchHint'.tr(), - prefixIcon: const Icon(Icons.search), - isDense: true, - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(30), - borderSide: BorderSide.none, - ), - filled: true, - fillColor: - Theme.of(context).colorScheme.surfaceContainerHighest, - ), - ), - ), - ), - ), - body: _body(), - // KLIPY attribution is required by their terms. - bottomNavigationBar: SafeArea( - child: InkWell( - onTap: () => launchUrl(Uri.parse('https://klipy.com')), - child: Padding( - padding: const EdgeInsets.symmetric(vertical: 8), - child: Text( - 'poweredByKlipy'.tr(), - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.bodySmall, - ), - ), - ), - ), - ); - } -} diff --git a/lib/utils/klipy_client.dart b/lib/utils/klipy_client.dart deleted file mode 100644 index 4956d13..0000000 --- a/lib/utils/klipy_client.dart +++ /dev/null @@ -1,117 +0,0 @@ -import 'dart:convert'; - -import 'package:http/http.dart' as http; - -/// One KLIPY GIF resolved to the formats this app uses. -class KlipyGif { - const KlipyGif( - {required this.title, required this.previewUrl, required this.sendUrl}); - - final String title; - - /// Small animated image for the picker grid. - final String previewUrl; - - /// Medium animated image that is downloaded and sent as a GIF message. - final String sendUrl; -} - -class KlipyException implements Exception { - KlipyException(this.message); - final String message; - - @override - String toString() => 'KlipyException: $message'; -} - -/// Minimal KLIPY GIF API client (search + trending). -/// -/// The app key is a free KLIPY key passed at build time: -/// `flutter run --dart-define=KLIPY_API_KEY=...`. -class KlipyClient { - static const String apiKey = String.fromEnvironment('KLIPY_API_KEY'); - static const String _host = 'api.klipy.com'; - static const Duration _timeout = Duration(seconds: 10); - - static bool get isConfigured => apiKey.isNotEmpty; - - /// Most popular GIFs, localized by KLIPY. - static Future> trending({int page = 1}) async { - return _fetch(_uri('trending', _query(page))); - } - - /// GIFs matching [query]. - static Future> search(String query, {int page = 1}) async { - return _fetch(_uri('search', {..._query(page), 'q': query})); - } - - static Uri _uri(String path, Map query) { - return Uri.https(_host, '/api/v1/$apiKey/gifs/$path', query); - } - - static Map _query(int page) { - return { - 'page': '$page', - 'per_page': '24', - 'content_filter': 'high', - 'format_filter': 'gif,webp', - }; - } - - static Future> _fetch(Uri uri) async { - final response = await http.get(uri).timeout(_timeout); - if (response.statusCode != 200) { - throw KlipyException('KLIPY returned ${response.statusCode}'); - } - return parse(response.body); - } - - /// Parses a KLIPY search/trending payload. Public for the unit test. - static List parse(String body) { - final json = jsonDecode(body); - if (json is! Map) { - return []; - } - final data = json['data']; - final items = data is Map ? data['data'] : null; - if (items is! List) { - return []; - } - final gifs = []; - for (final item in items) { - if (item is! Map) { - continue; - } - final file = item['file']; - if (file is! Map) { - continue; - } - final preview = _url(file, 'sm') ?? _url(file, 'md'); - final send = _url(file, 'md') ?? _url(file, 'sm'); - if (preview == null || send == null) { - continue; - } - gifs.add(KlipyGif( - title: item['title'] as String? ?? '', - previewUrl: preview, - sendUrl: send, - )); - } - return gifs; - } - - /// Animated WebP first (much smaller than GIF), GIF as the fallback. - static String? _url(Map file, String size) { - final bucket = file[size]; - if (bucket is! Map) { - return null; - } - for (final format in const ['webp', 'gif']) { - final url = bucket[format]?['url']; - if (url is String && url.isNotEmpty) { - return url; - } - } - return null; - } -} diff --git a/test/klipy_client_test.dart b/test/klipy_client_test.dart deleted file mode 100644 index 6d84964..0000000 --- a/test/klipy_client_test.dart +++ /dev/null @@ -1,54 +0,0 @@ -import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/klipy_client.dart'; - -void main() { - test('parse prefers animated webp and keeps md as the sent format', () { - const body = ''' -{ - "result": true, - "data": { - "data": [ - { - "title": "Hello", - "slug": "hello-hi-662", - "file": { - "hd": {"gif": {"url": "https://x/hd.gif"}}, - "md": { - "gif": {"url": "https://x/md.gif"}, - "webp": {"url": "https://x/md.webp"} - }, - "sm": { - "gif": {"url": "https://x/sm.gif"}, - "webp": {"url": "https://x/sm.webp"} - } - } - }, - { - "title": "No medium", - "file": { - "sm": {"gif": {"url": "https://x/small.gif"}} - } - }, - {"title": "Broken", "file": {}}, - "not an object" - ] - } -} -'''; - - final gifs = KlipyClient.parse(body); - - expect(gifs.length, 2); - expect(gifs[0].title, 'Hello'); - expect(gifs[0].previewUrl, 'https://x/sm.webp'); - expect(gifs[0].sendUrl, 'https://x/md.webp'); - // Falls back to the small size when there is no medium one. - expect(gifs[1].previewUrl, 'https://x/small.gif'); - expect(gifs[1].sendUrl, 'https://x/small.gif'); - }); - - test('parse returns an empty list for unexpected payloads', () { - expect(KlipyClient.parse('{}'), isEmpty); - expect(KlipyClient.parse('{"data": null}'), isEmpty); - }); -} From 0c91f6a9c31e59e84f054d183940e90bd6ddc8b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 22:02:59 +0100 Subject: [PATCH 028/181] fix(media): scale the image/GIF viewer to the full screen Image.memory was laid out at the bitmap's intrinsic size, so a 320px GIF sat as a small tile in the middle of the black viewer. SizedBox.expand + BoxFit.contain fills the screen (letterboxed) and keeps pinch-zoom working. --- lib/pages/media_viewer_page.dart | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index d1a10ca..0f332a3 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -129,7 +129,9 @@ class _MediaViewerPageState extends State { return InteractiveViewer( minScale: 0.5, maxScale: 4, - child: Image.memory(_imageBytes!, fit: BoxFit.contain), + child: SizedBox.expand( + child: Image.memory(_imageBytes!, fit: BoxFit.contain), + ), ); } return Text('mediaError'.tr(), style: const TextStyle(color: Colors.white)); From 3d1fb93f2ef76b5ac4145ffb1d2d8911e1abb49a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 23:05:34 +0100 Subject: [PATCH 029/181] feat(settings): change the local password There is no server password (auth is RSA), so this changes the app lock and the at-rest encryption key: the profile box and every media file are re-encrypted under the key derived from the new password, then the bcrypt hash is swapped. Media is staged as .new files and only swapped in after the profile is written, and the profile box is backed up first, so a failure keeps the old password valid. Biometric unlock stores a copy of the key and is updated (or disabled) after the change. Also fixes writeTempBytes writing plaintext GIFs into the encrypted media dir. --- assets/translations/cs.json | 12 +- assets/translations/en.json | 12 +- lib/pages/settings_page.dart | 486 +++++++++++++----------- lib/utils/cache_utils.dart | 59 +++ lib/utils/media_utils.dart | 69 +++- lib/widgets/change_password_dialog.dart | 146 +++++++ test/media_rekey_test.dart | 20 + 7 files changed, 571 insertions(+), 233 deletions(-) create mode 100644 lib/widgets/change_password_dialog.dart create mode 100644 test/media_rekey_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index b5435fb..86b4cd9 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -106,5 +106,13 @@ "mediaGif": "GIF", "mediaVideo": "Video", "mediaTitle": "Média", - "mediaVoice": "Hlasová zpráva" -} \ No newline at end of file + "mediaVoice": "Hlasová zpráva", + "changePassword": "Změnit heslo", + "currentPassword": "Současné heslo", + "newPassword": "Nové heslo", + "confirmPassword": "Potvrďte nové heslo", + "passwordMismatch": "Hesla se neshodují", + "wrongCurrentPassword": "Současné heslo není správné", + "passwordChanged": "Heslo změněno", + "passwordChangeFailed": "Heslo se nepodařilo změnit" +} diff --git a/assets/translations/en.json b/assets/translations/en.json index 0e5e76c..12ac11a 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -106,5 +106,13 @@ "mediaGif": "GIF", "mediaVideo": "Video", "mediaTitle": "Media", - "mediaVoice": "Voice message" -} \ No newline at end of file + "mediaVoice": "Voice message", + "changePassword": "Change password", + "currentPassword": "Current password", + "newPassword": "New password", + "confirmPassword": "Confirm new password", + "passwordMismatch": "Passwords do not match", + "wrongCurrentPassword": "Current password is incorrect", + "passwordChanged": "Password changed", + "passwordChangeFailed": "Password could not be changed" +} diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 70d215f..9116d3b 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -13,6 +13,7 @@ import '../utils/dialog_utils.dart'; import '../utils/message_notifier.dart'; import '../utils/utils.dart'; import 'scan_invite_button_page.dart'; +import '../widgets/change_password_dialog.dart'; class SettingsPage extends StatefulWidget { const SettingsPage({super.key}); @@ -79,259 +80,292 @@ class _SettingsPageState extends State { title: Text('settingsPage'.tr()), ), body: SafeArea( - child: Column( - children: [ - // Theme - TextButton( - onPressed: () { - showDialog(context: context, builder: DialogUtils.themeDialog); - }, - child: Row( - children: [ - Icon( - Icons.palette, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'themeSettings'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), + child: SingleChildScrollView( + child: Column( + children: [ + // Theme + TextButton( + onPressed: () { + showDialog( + context: context, builder: DialogUtils.themeDialog); + }, + child: Row( + children: [ + Icon( + Icons.palette, + size: 24, + color: Theme.of(context).colorScheme.secondary, ), - ), - ], + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'themeSettings'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.secondary), + ), + ), + ], + ), ), - ), - // Notifications - TextButton( - onPressed: null, - child: Row( - children: [ - Icon( - Icons.notifications, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'notificationSettings'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), + // Notifications + TextButton( + onPressed: null, + child: Row( + children: [ + Icon( + Icons.notifications, + size: 24, + color: Theme.of(context).colorScheme.secondary, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'notificationSettings'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.secondary), + ), ), - ), - Spacer(), - Switch( - value: Singleton().profile.enableNotifications, - onChanged: (value) async { - setState(() { - Singleton().profile.enableNotifications = - !Singleton().profile.enableNotifications; - }); - await Singleton().profile.save(); - }, - ) - ], + Spacer(), + Switch( + value: Singleton().profile.enableNotifications, + onChanged: (value) async { + setState(() { + Singleton().profile.enableNotifications = + !Singleton().profile.enableNotifications; + }); + await Singleton().profile.save(); + }, + ) + ], + ), ), - ), - Divider(thickness: 1, indent: 10, endIndent: 10), + Divider(thickness: 1, indent: 10, endIndent: 10), - // Biometric authentication - TextButton( - onPressed: null, - child: Row( - children: [ - Icon( - Icons.fingerprint, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'biometrySettings'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), + // Biometric authentication + TextButton( + onPressed: null, + child: Row( + children: [ + Icon( + Icons.fingerprint, + size: 24, + color: Theme.of(context).colorScheme.secondary, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'biometrySettings'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.secondary), + ), ), - ), - Spacer(), - Switch( - value: _isBiometryEnabled, - onChanged: _toggleBiometry, - ) - ], + Spacer(), + Switch( + value: _isBiometryEnabled, + onChanged: _toggleBiometry, + ) + ], + ), ), - ), - Divider(thickness: 1, indent: 10, endIndent: 10), + Divider(thickness: 1, indent: 10, endIndent: 10), - // How it works - TextButton( - onPressed: () async { - var url = Uri.parse('https://github.com/jsfraz/whisper/wiki'); - if (!await launchUrl(url)) { - await Fluttertoast.showToast( - msg: sprintf('urlError'.tr(), [url.toString()]), - backgroundColor: Colors.red); - } - }, - child: Row( - children: [ - Icon( - Icons.help, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'wikiLink'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), + // How it works + TextButton( + onPressed: () async { + var url = Uri.parse('https://github.com/jsfraz/whisper/wiki'); + if (!await launchUrl(url)) { + await Fluttertoast.showToast( + msg: sprintf('urlError'.tr(), [url.toString()]), + backgroundColor: Colors.red); + } + }, + child: Row( + children: [ + Icon( + Icons.help, + size: 24, + color: Theme.of(context).colorScheme.secondary, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'wikiLink'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.secondary), + ), ), - ), - SizedBox( - width: 24, - ), - ], + SizedBox( + width: 24, + ), + ], + ), ), - ), - // Repo - TextButton( - onPressed: () async { - var url = Uri.parse('https://github.com/jsfraz/whisper'); - if (!await launchUrl(url)) { - await Fluttertoast.showToast( - msg: sprintf('urlError'.tr(), [url.toString()]), - backgroundColor: Colors.red); - } - }, - child: Row( - children: [ - Icon( - Icons.code, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'repoLink'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), + // Repo + TextButton( + onPressed: () async { + var url = Uri.parse('https://github.com/jsfraz/whisper'); + if (!await launchUrl(url)) { + await Fluttertoast.showToast( + msg: sprintf('urlError'.tr(), [url.toString()]), + backgroundColor: Colors.red); + } + }, + child: Row( + children: [ + Icon( + Icons.code, + size: 24, + color: Theme.of(context).colorScheme.secondary, ), - ), - SizedBox( - width: 24, - ), - ], + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'repoLink'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.secondary), + ), + ), + SizedBox( + width: 24, + ), + ], + ), ), - ), - Divider(thickness: 1, indent: 10, endIndent: 10), + Divider(thickness: 1, indent: 10, endIndent: 10), - // TODO change password + // Change password + TextButton( + onPressed: () async { + final changed = await showDialog( + context: context, + builder: (context) => const ChangePasswordDialog()); + if (changed == true) { + await Fluttertoast.showToast(msg: 'passwordChanged'.tr()); + } + }, + child: Row( + children: [ + Icon( + Icons.password, + size: 24, + color: Theme.of(context).colorScheme.secondary, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'changePassword'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.secondary), + ), + ), + SizedBox( + width: 24, + ), + ], + ), + ), - // Divider(thickness: 1, indent: 10, endIndent: 10), + Divider(thickness: 1, indent: 10, endIndent: 10), - // Danger zone title - Padding( - padding: EdgeInsets.only(bottom: 5), - child: Text( - 'dangerZone'.tr(), - style: TextStyle( - color: Colors.red, - fontWeight: FontWeight.bold, - fontSize: 16), + // Danger zone title + Padding( + padding: EdgeInsets.only(bottom: 5), + child: Text( + 'dangerZone'.tr(), + style: TextStyle( + color: Colors.red, + fontWeight: FontWeight.bold, + fontSize: 16), + ), ), - ), - // Delete all chats - TextButton( - onPressed: () async { - await DialogUtils.yesNoDialog( - context, - 'deleteAllChatsConfirm'.tr(), - 'deleteAllChatsConfirmText'.tr(), () async { - MessageNotifier().deleteAllChats(); - Navigator.pop(context); - }); - }, - child: Row( - children: [ - Icon( - Icons.delete_forever, - size: 24, - color: Colors.red, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'deleteAllChats'.tr(), - style: TextStyle(color: Colors.red), + // Delete all chats + TextButton( + onPressed: () async { + await DialogUtils.yesNoDialog( + context, + 'deleteAllChatsConfirm'.tr(), + 'deleteAllChatsConfirmText'.tr(), () async { + MessageNotifier().deleteAllChats(); + Navigator.pop(context); + }); + }, + child: Row( + children: [ + Icon( + Icons.delete_forever, + size: 24, + color: Colors.red, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'deleteAllChats'.tr(), + style: TextStyle(color: Colors.red), + ), + ), + SizedBox( + width: 24, ), - ), - SizedBox( - width: 24, - ), - ], + ], + ), ), - ), - // Logout (delete account) - TextButton( - onPressed: () async { - await DialogUtils.yesNoDialog( - context, 'logoutConfirm'.tr(), 'logoutConfirmText'.tr(), - () async { - // Delete everything and close app - try { - await Utils.callApi(() => Singleton().userApi.deleteMe()); - await CacheUtils.deleteCache(); - await Fluttertoast.showToast( - msg: 'accountDeleted1'.tr(), - backgroundColor: Colors.grey); - if (Platform.isIOS) { - // Apple (https://stackoverflow.com/a/57534684/19371130) - Navigator.pushReplacement( - context, - MaterialPageRoute( - builder: (context) => ScanInviteButtonPage())); - } else if (Platform.isAndroid) { - // Android - SystemNavigator.pop(); + // Logout (delete account) + TextButton( + onPressed: () async { + await DialogUtils.yesNoDialog( + context, 'logoutConfirm'.tr(), 'logoutConfirmText'.tr(), + () async { + // Delete everything and close app + try { + await Utils.callApi(() => Singleton().userApi.deleteMe()); + await CacheUtils.deleteCache(); + await Fluttertoast.showToast( + msg: 'accountDeleted1'.tr(), + backgroundColor: Colors.grey); + if (Platform.isIOS) { + // Apple (https://stackoverflow.com/a/57534684/19371130) + Navigator.pushReplacement( + context, + MaterialPageRoute( + builder: (context) => ScanInviteButtonPage())); + } else if (Platform.isAndroid) { + // Android + SystemNavigator.pop(); + } + } catch (e) { + await Fluttertoast.showToast( + msg: e.toString(), backgroundColor: Colors.red); } - } catch (e) { - await Fluttertoast.showToast( - msg: e.toString(), backgroundColor: Colors.red); - } - }); - }, - child: Row( - children: [ - Icon( - Icons.logout, - size: 24, - color: Colors.red, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'logoutAndDelete'.tr(), - style: TextStyle(color: Colors.red), + }); + }, + child: Row( + children: [ + Icon( + Icons.logout, + size: 24, + color: Colors.red, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'logoutAndDelete'.tr(), + style: TextStyle(color: Colors.red), + ), + ), + SizedBox( + width: 24, ), - ), - SizedBox( - width: 24, - ), - ], + ], + ), ), - ), - ], + ], + ), ), ), ); diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 9b11766..9eb9ab1 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -1,3 +1,4 @@ +import 'dart:io'; import 'dart:ui' show Color; import 'package:bcrypt/bcrypt.dart'; @@ -8,6 +9,7 @@ import '../models/private_message.dart'; import '../models/profile.dart'; import '../models/user.dart'; import 'color_utils.dart'; +import 'crypto_utils.dart'; import 'media_utils.dart'; import 'singleton.dart'; import 'utils.dart'; @@ -118,6 +120,63 @@ class CacheUtils { await box.put(_themeKey, theme); } + /// Changes the local password (app lock + at-rest encryption key). + /// + /// Returns false when [currentPassword] is wrong. Media files are staged + /// under the new key first and only swapped in after the profile box has been + /// rewritten, so a failure leaves the old password valid and the data intact. + static Future changePassword( + String currentPassword, String newPassword) async { + if (!await isCorrectPassword(currentPassword)) { + return false; + } + final List oldKey = List.from(Singleton().boxCollectionKey); + final List newKey = await CryptoUtils.pbkdf2(newPassword); + final Profile loaded = await getProfile(); + // A fresh instance: the loaded one is still attached to the box we are + // about to replace, and Hive refuses to store it in a second box. + final Profile profile = Profile( + loaded.url, + loaded.user, + loaded.publicKey, + loaded.privateKey, + loaded.accessToken, + loaded.refreshToken, + loaded.enableNotifications); + // Hive stores the collection as `_encrypted/_encrypted_.hive`. + final File boxFile = File( + '${await Utils.getCacheDir()}_encrypted/_encrypted_$_profileKey.hive'); + final File backup = File('${boxFile.path}.bak'); + + final List staged = await MediaUtils.stageRekey(oldKey, newKey); + try { + await Hive.close(); + if (await boxFile.exists()) { + await boxFile.rename(backup.path); + } + Singleton().boxCollectionKey = newKey; + await setProfile(profile); + await setPasswordHash(newPassword); + } catch (e) { + // Roll back to the old key and the old profile box. + await Hive.close(); + Singleton().boxCollectionKey = oldKey; + if (await boxFile.exists()) { + await boxFile.delete(); + } + if (await backup.exists()) { + await backup.rename(boxFile.path); + } + await MediaUtils.discardRekey(staged); + rethrow; + } + if (await backup.exists()) { + await backup.delete(); + } + await MediaUtils.commitRekey(staged); + return true; + } + /// Returns per-chat theme color, null means the global theme is used static Future getChatTheme(int userId) async { Box box = await _openThemeBox(); diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 8b324ed..9e483b7 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -142,6 +142,68 @@ class MediaUtils { return compute(_gcmDecrypt, _GcmArgs(blob, key)); } + /// Encrypt bytes with an explicit AES-GCM key (no singleton lookup). + static Future encryptWith(Uint8List bytes, List key) { + return compute(_gcmEncrypt, _GcmArgs(bytes, Uint8List.fromList(key))); + } + + /// Decrypt a blob with an explicit AES-GCM key (no singleton lookup). + static Future decryptWith(Uint8List blob, List key) { + return compute(_gcmDecrypt, _GcmArgs(blob, Uint8List.fromList(key))); + } + + /// Phase 1 of a password change: decrypts every at-rest media file with + /// [oldKey] and writes `.new` encrypted with [newKey]. Originals stay + /// untouched until [commitRekey], so an interrupted change loses nothing. + static Future> stageRekey( + List oldKey, List newKey) async { + final dir = Directory(await mediaDir()); + final staged = []; + try { + await for (final entity in dir.list()) { + if (entity is! File || entity.path.endsWith('.new')) { + continue; + } + final blob = await entity.readAsBytes(); + final Uint8List plain; + try { + plain = await decryptWith(blob, oldKey); + } catch (e) { + // A file that does not decrypt with the current key is already + // unreadable; leave it alone instead of failing the whole change. + debugPrint('rekey skipped ${entity.path}: $e'); + continue; + } + final encrypted = await encryptWith(plain, newKey); + final target = '${entity.path}.new'; + await File(target).writeAsBytes(encrypted, flush: true); + staged.add(target); + } + } catch (e) { + await discardRekey(staged); + rethrow; + } + return staged; + } + + /// Phase 2: replaces the originals with the staged files. + static Future commitRekey(List staged) async { + for (final path in staged) { + await File(path).rename(path.substring(0, path.length - '.new'.length)); + } + } + + /// Drops staged files after a failed key change. + static Future discardRekey(List staged) async { + for (final path in staged) { + try { + await File(path).delete(); + } catch (_) { + // Staged files are disposable. + } + } + } + /// Decrypt an at-rest file into a temporary plaintext file (for the platform /// video/audio players). The caller is responsible for deleting it on dispose. static Future materializeTempFile(String path, String extension) async { @@ -164,10 +226,11 @@ class MediaUtils { } /// Writes plaintext bytes to a temporary file, e.g. for keyboard-inserted - /// or downloaded GIFs that then go through the media pipeline. + /// GIFs that then go through the media pipeline. Never into [mediaDir], + /// which must only hold encrypted files. static Future writeTempBytes(Uint8List bytes, String extension) async { - final dir = await mediaDir(); - final file = File('$dir/send_${_uuid.v4()}.$extension'); + final tmpDir = await getTemporaryDirectory(); + final file = File('${tmpDir.path}/whisper_send_${_uuid.v4()}.$extension'); await file.writeAsBytes(bytes, flush: true); return file; } diff --git a/lib/widgets/change_password_dialog.dart b/lib/widgets/change_password_dialog.dart new file mode 100644 index 0000000..8a6c9c9 --- /dev/null +++ b/lib/widgets/change_password_dialog.dart @@ -0,0 +1,146 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +import '../utils/biometric_auth.dart'; +import '../utils/cache_utils.dart'; +import '../utils/singleton.dart'; + +/// Changes the local password: verifies the current one, re-encrypts the +/// profile and media under the key derived from the new one, and keeps +/// biometric unlock in sync. +class ChangePasswordDialog extends StatefulWidget { + const ChangePasswordDialog({super.key}); + + @override + State createState() => _ChangePasswordDialogState(); +} + +class _ChangePasswordDialogState extends State { + final TextEditingController _current = TextEditingController(); + final TextEditingController _next = TextEditingController(); + final TextEditingController _confirmation = TextEditingController(); + bool _busy = false; + String? _error; + + @override + void dispose() { + _current.dispose(); + _next.dispose(); + _confirmation.dispose(); + super.dispose(); + } + + Future _submit() async { + final next = _next.text; + if (next.length < 8 || next.length > 64) { + setState(() { + _error = 'invalidPassword'.tr(); + }); + return; + } + if (next != _confirmation.text) { + setState(() { + _error = 'passwordMismatch'.tr(); + }); + return; + } + + setState(() { + _busy = true; + _error = null; + }); + try { + final changed = await CacheUtils.changePassword(_current.text, next); + if (!mounted) { + return; + } + if (!changed) { + setState(() { + _busy = false; + _error = 'wrongCurrentPassword'.tr(); + }); + return; + } + // Biometrics store a copy of the derived key; it must follow the change, + // otherwise fingerprint unlock would open the boxes with a stale key. + if (await CacheUtils.isBiometryEnabled()) { + if (!mounted) { + return; + } + final stored = await BiometricAuth.storeEncryptionKey( + Singleton().boxCollectionKey, context); + if (!stored) { + await BiometricAuth.clearEncryptionKey(); + await CacheUtils.setBiometryEnabled(false); + } + if (!mounted) { + return; + } + } + if (!mounted) { + return; + } + Navigator.of(context).pop(true); + } catch (e) { + debugPrint('change password failed: $e'); + if (!mounted) { + return; + } + setState(() { + _busy = false; + }); + await Fluttertoast.showToast( + msg: 'passwordChangeFailed'.tr(), backgroundColor: Colors.red); + } + } + + Widget _field(TextEditingController controller, String label) { + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: TextField( + controller: controller, + obscureText: true, + enabled: !_busy, + decoration: InputDecoration(labelText: label), + ), + ); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text('changePassword'.tr()), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _field(_current, 'currentPassword'.tr()), + _field(_next, 'newPassword'.tr()), + _field(_confirmation, 'confirmPassword'.tr()), + if (_error != null) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(_error!, + style: + TextStyle(color: Theme.of(context).colorScheme.error)), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: _busy ? null : () => Navigator.of(context).pop(false), + child: Text('noText'.tr()), + ), + TextButton( + onPressed: _busy ? null : _submit, + child: _busy + ? const SizedBox( + width: 18, height: 18, child: CircularProgressIndicator()) + : Text('okText'.tr()), + ), + ], + ); + } +} diff --git a/test/media_rekey_test.dart b/test/media_rekey_test.dart new file mode 100644 index 0000000..33e66f6 --- /dev/null +++ b/test/media_rekey_test.dart @@ -0,0 +1,20 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/media_utils.dart'; + +void main() { + test('re-encrypted media only decrypts with the new key', () async { + final plain = Uint8List.fromList(List.generate(256, (i) => i % 251)); + final oldKey = List.filled(32, 1); + final newKey = List.filled(32, 2); + + final blob = await MediaUtils.encryptWith(plain, oldKey); + final reencrypted = await MediaUtils.encryptWith( + await MediaUtils.decryptWith(blob, oldKey), newKey); + + expect(await MediaUtils.decryptWith(reencrypted, newKey), plain); + await expectLater( + MediaUtils.decryptWith(reencrypted, oldKey), throwsA(anything)); + }); +} From 96b51a0effbbb5b99914a047bb3704d031035d8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 12 Nov 2026 23:48:03 +0100 Subject: [PATCH 030/181] feat(crypto): random PBKDF2 salt with a one-time migration The salt was md5(password), so two installs with the same password derived the same key. Registration and password changes now use a random 32-byte salt and rotate it; it lives in secure storage because it must be readable before the boxes open. Installs created before this migrate on the next password unlock: the legacy key is derived once, the profile and media are re-encrypted, and the random salt is stored. Biometrics keeps a copy of the derived key, so it is turned off during that migration with a notice. Also fixes a critical issue in the same file: the RSA key generator was seeded with a constant byte sequence, making every generated keypair predictable. New keys are seeded from Random.secure(). --- assets/translations/cs.json | 4 ++- assets/translations/en.json | 4 ++- integration_test/app_e2e_test.dart | 5 +-- lib/pages/password_page.dart | 33 ++++++++++++++++-- lib/pages/register_page.dart | 7 ++-- lib/utils/cache_utils.dart | 55 ++++++++++++++++++++++++++++-- lib/utils/crypto_utils.dart | 27 +++++++++++---- test/pbkdf2_salt_test.dart | 41 ++++++++++++++++++++++ 8 files changed, 159 insertions(+), 17 deletions(-) create mode 100644 test/pbkdf2_salt_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 86b4cd9..68e6757 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -114,5 +114,7 @@ "passwordMismatch": "Hesla se neshodují", "wrongCurrentPassword": "Současné heslo není správné", "passwordChanged": "Heslo změněno", - "passwordChangeFailed": "Heslo se nepodařilo změnit" + "passwordChangeFailed": "Heslo se nepodařilo změnit", + "biometricsDisabledAfterMigration": "Biometrika byla vypnuta. Odemkni heslem a znovu ji zapni v nastavení.", + "passwordMigrationFailed": "Lokální data se nepodařilo otevřít. Heslo neodpovídá uloženým datům." } diff --git a/assets/translations/en.json b/assets/translations/en.json index 12ac11a..ebdef71 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -114,5 +114,7 @@ "passwordMismatch": "Passwords do not match", "wrongCurrentPassword": "Current password is incorrect", "passwordChanged": "Password changed", - "passwordChangeFailed": "Password could not be changed" + "passwordChangeFailed": "Password could not be changed", + "biometricsDisabledAfterMigration": "Biometrics were turned off. Unlock with your password and enable them again in settings.", + "passwordMigrationFailed": "Local data could not be opened. The password does not match the stored data." } diff --git a/integration_test/app_e2e_test.dart b/integration_test/app_e2e_test.dart index 6a0c4b7..2cc3030 100644 --- a/integration_test/app_e2e_test.dart +++ b/integration_test/app_e2e_test.dart @@ -159,8 +159,9 @@ void main() { expect(await CacheUtils.isCorrectPassword(password), isTrue); expect(await CacheUtils.isCorrectPassword('wrong password'), isFalse); - final first = await CryptoUtils.pbkdf2(password); - final second = await CryptoUtils.pbkdf2(password); + final salt = CryptoUtils.generateSalt(); + final first = await CryptoUtils.pbkdf2(password, salt); + final second = await CryptoUtils.pbkdf2(password, salt); expect(first, second); }); } diff --git a/lib/pages/password_page.dart b/lib/pages/password_page.dart index 1724911..524660b 100644 --- a/lib/pages/password_page.dart +++ b/lib/pages/password_page.dart @@ -113,8 +113,36 @@ class _PasswordPageState extends State { if (password) { await Fluttertoast.showToast( msg: 'passwordPlsWait'.tr(), backgroundColor: Colors.grey); + // Installs created before random salts re-encrypt their data once here. + bool migrated = false; + try { + migrated = + await CacheUtils.migrateSalt(_controllerLocalPassword.text); + } catch (e) { + debugPrint('salt migration failed: $e'); + } + if (migrated && await CacheUtils.isBiometryEnabled()) { + // The stored biometric key was derived with the old salt, so it can + // no longer open the re-encrypted boxes. + await BiometricAuth.clearEncryptionKey(); + await CacheUtils.setBiometryEnabled(false); + await Fluttertoast.showToast( + msg: 'biometricsDisabledAfterMigration'.tr(), + backgroundColor: Colors.orange); + } + final List? salt = await CacheUtils.getSalt(); + if (salt == null && !migrated) { + await Fluttertoast.showToast( + msg: 'passwordMigrationFailed'.tr(), backgroundColor: Colors.red); + setState(() { + _isButtonDisabled = false; + }); + return; + } // Derive key from password - List key = await CryptoUtils.pbkdf2(_controllerLocalPassword.text); + List key = migrated + ? List.from(Singleton().boxCollectionKey) + : await CryptoUtils.pbkdf2(_controllerLocalPassword.text, salt!); // Add key to singleton Singleton().boxCollectionKey = key; // Add profile to singleton @@ -221,7 +249,8 @@ class _PasswordPageState extends State { padding: const EdgeInsets.only(top: 20), child: IconButton( icon: const Icon(Icons.fingerprint, size: 40), - onPressed: _isButtonDisabled ? null : _authenticateWithBiometric, + onPressed: + _isButtonDisabled ? null : _authenticateWithBiometric, ), ), ), diff --git a/lib/pages/register_page.dart b/lib/pages/register_page.dart index 91eb05c..c7b7338 100644 --- a/lib/pages/register_page.dart +++ b/lib/pages/register_page.dart @@ -132,11 +132,14 @@ class _RegisterPageState extends State { true); // Add profile to singleton Singleton().profile = profile; + // A random salt must exist before anything is encrypted with the key + final List salt = CryptoUtils.generateSalt(); + await CacheUtils.setSalt(salt); // Save password hash to cache CacheUtils.setPasswordHash(_controllerLocalPassword.text); - // Generování klíče z hesla a uložení do singletonu + // Derive the key from the password and store it in the singleton List key = - await CryptoUtils.pbkdf2(_controllerLocalPassword.text); + await CryptoUtils.pbkdf2(_controllerLocalPassword.text, salt); Singleton().boxCollectionKey = key; // Save profile to cache diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 9eb9ab1..2fedaee 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -1,7 +1,9 @@ +import 'dart:convert'; import 'dart:io'; import 'dart:ui' show Color; import 'package:bcrypt/bcrypt.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:hive/hive.dart'; import '../utils/biometric_auth.dart'; import '../models/app_theme.dart'; @@ -22,6 +24,8 @@ class CacheUtils { static const _userKey = 'user'; static const _messageConceptKey = 'messageConcept'; static const _biometry = 'biometry'; + static const String _saltStorageKey = 'whisper_pbkdf2_salt'; + static const FlutterSecureStorage _secureStorage = FlutterSecureStorage(); static const _chatThemeKeyPrefix = 'chatTheme:'; /// Opens box with password hash @@ -47,6 +51,22 @@ class CacheUtils { return BCrypt.checkpw(password, hash!); } + /// Returns the PBKDF2 salt, or null for installs created before salts became + /// random (those still derive it from the password). + static Future?> getSalt() async { + final String? stored = await _secureStorage.read(key: _saltStorageKey); + if (stored == null || stored.isEmpty) { + return null; + } + return base64.decode(stored); + } + + /// Stores the PBKDF2 salt. + static Future setSalt(List salt) async { + await _secureStorage.write( + key: _saltStorageKey, value: base64.encode(salt)); + } + /// Opens encrypted box static Future _openBoxCollection(Set boxNames) async { return BoxCollection.open('_encrypted', boxNames, @@ -88,6 +108,7 @@ class CacheUtils { await passwordBox.deleteFromDisk(); Box themeBox = await _openThemeBox(); await themeBox.deleteFromDisk(); + await _secureStorage.delete(key: _saltStorageKey); Box privateMessagesBox = await _openPrivateMessagesBox(); await privateMessagesBox.deleteFromDisk(); Box userBox = await _openUserBox(); @@ -131,7 +152,37 @@ class CacheUtils { return false; } final List oldKey = List.from(Singleton().boxCollectionKey); - final List newKey = await CryptoUtils.pbkdf2(newPassword); + final List salt = CryptoUtils.generateSalt(); + final List newKey = await CryptoUtils.pbkdf2(newPassword, salt); + await _rekeyData(oldKey, newKey); + await setSalt(salt); + await setPasswordHash(newPassword); + return true; + } + + /// One-time migration from the legacy `md5(password)` salt to a random one. + /// Returns true when the data was re-encrypted; false when there is nothing + /// to migrate. + static Future migrateSalt(String password) async { + if (await getSalt() != null) { + return false; + } + if (!await isCorrectPassword(password)) { + return false; + } + final List oldKey = await CryptoUtils.legacyPbkdf2(password); + final List salt = CryptoUtils.generateSalt(); + final List newKey = await CryptoUtils.pbkdf2(password, salt); + Singleton().boxCollectionKey = oldKey; + await _rekeyData(oldKey, newKey); + await setSalt(salt); + return true; + } + + /// Re-encrypts the profile box and every at-rest media file from [oldKey] to + /// [newKey]. Media is staged first and swapped in only after the profile is + /// written; the profile box is backed up, so a failure keeps [oldKey] valid. + static Future _rekeyData(List oldKey, List newKey) async { final Profile loaded = await getProfile(); // A fresh instance: the loaded one is still attached to the box we are // about to replace, and Hive refuses to store it in a second box. @@ -156,7 +207,6 @@ class CacheUtils { } Singleton().boxCollectionKey = newKey; await setProfile(profile); - await setPasswordHash(newPassword); } catch (e) { // Roll back to the old key and the old profile box. await Hive.close(); @@ -174,7 +224,6 @@ class CacheUtils { await backup.delete(); } await MediaUtils.commitRekey(staged); - return true; } /// Returns per-chat theme color, null means the global theme is used diff --git a/lib/utils/crypto_utils.dart b/lib/utils/crypto_utils.dart index 6c0b25f..c8a0619 100644 --- a/lib/utils/crypto_utils.dart +++ b/lib/utils/crypto_utils.dart @@ -21,26 +21,40 @@ class CryptoUtils { static Future> getRSAKeyPair() async { final secureRandom = FortunaRandom(); + // Seed from the platform CSPRNG: a constant seed would make every keypair + // predictable and identical across installs. secureRandom.seed(KeyParameter( - Uint8List.fromList(List.generate(32, (i) => i)), + Uint8List.fromList( + List.generate(32, (_) => Random.secure().nextInt(256))), )); // Seed with random bytes return await compute(_getRSAKeyPair, secureRandom); } /// PBKDF2 password derivation (https://pub.dev/documentation/cryptography/latest/cryptography/Pbkdf2-class.html) - static Future> pbkdf2(String password) async { + static Future> pbkdf2(String password, List salt) async { final pbkdf2 = cryptography.Pbkdf2( macAlgorithm: cryptography.Hmac.sha256(), iterations: 310000, bits: 256, ); - List salt = md5.convert(utf8.encode(password)).bytes; // TODO Secure salt? final key = await pbkdf2.deriveKeyFromPassword(password: password, nonce: salt); return await key.extractBytes(); } + /// Legacy derivation with the old `md5(password)` salt. Only used to open + /// data created before salts became random, then migrated away from. + static Future> legacyPbkdf2(String password) { + return pbkdf2(password, md5.convert(utf8.encode(password)).bytes); + } + + /// Random 32-byte PBKDF2 salt. + static List generateSalt() { + final random = Random.secure(); + return List.generate(32, (_) => random.nextInt(256)); + } + /// Encrypt by RSA public key asynchronously. static Future rsaEncrypt( Uint8List message, RSAPublicKey publicKey) async { @@ -103,10 +117,11 @@ class CryptoUtils { // Generate a random nonce (initialization vector) final secureRandom = FortunaRandom(); secureRandom.seed(KeyParameter( - Uint8List.fromList(List.generate(32, (i) => Random.secure().nextInt(256))), + Uint8List.fromList( + List.generate(32, (i) => Random.secure().nextInt(256))), )); - final nonce = Uint8List.fromList( - List.generate(12, (_) => secureRandom.nextUint8())); + final nonce = + Uint8List.fromList(List.generate(12, (_) => secureRandom.nextUint8())); // Encrypt data using AES-GCM final secretBox = await aesAlgorithm.encrypt( diff --git a/test/pbkdf2_salt_test.dart b/test/pbkdf2_salt_test.dart new file mode 100644 index 0000000..c3642f8 --- /dev/null +++ b/test/pbkdf2_salt_test.dart @@ -0,0 +1,41 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/crypto_utils.dart'; + +void main() { + test('same password and salt derive the same key', () async { + final salt = List.filled(32, 7); + final first = + await CryptoUtils.pbkdf2('correct horse battery staple', salt); + final second = + await CryptoUtils.pbkdf2('correct horse battery staple', salt); + + expect(first, second); + expect(first.length, 32); + }); + + test('a different salt derives a different key', () async { + final a = await CryptoUtils.pbkdf2( + 'correct horse battery staple', List.filled(32, 1)); + final b = await CryptoUtils.pbkdf2( + 'correct horse battery staple', List.filled(32, 2)); + + expect(a, isNot(b)); + }); + + test('generated salts are random 32-byte values', () { + final a = CryptoUtils.generateSalt(); + final b = CryptoUtils.generateSalt(); + + expect(a.length, 32); + expect(a, isNot(b)); + }); + + test('legacy derivation still matches the old md5 salt scheme', () async { + // Guards the migration path for installs created before random salts. + final legacy = + await CryptoUtils.legacyPbkdf2('correct horse battery staple'); + expect(legacy.length, 32); + expect( + legacy, await CryptoUtils.legacyPbkdf2('correct horse battery staple')); + }); +} From d6fd637d0e30baa94127506b63c146bc66b83b0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 00:41:07 +0100 Subject: [PATCH 031/181] feat(notifications): open the chat on tap and extend the notification options Linux gets a theme icon and keeps the action name, single-message notifications use a big-text style so previews are not truncated, and the tap response carries the sender id. A single message opens its chat (right away when Home is alive, otherwise after unlocking); the grouped summary opens Home. The awaited init cannot block startup. --- lib/main.dart | 12 ++++--- lib/pages/home_page.dart | 40 +++++++++++++++++++++ lib/utils/notification_service.dart | 56 +++++++++++++++++++++++++++-- lib/utils/singleton.dart | 2 ++ 4 files changed, 103 insertions(+), 7 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index 847d947..96fca35 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -45,12 +45,16 @@ void main() async { ); } - // Local notifications - NotificationService().init(); - - // Load locale + // Load locale (the notification service needs it for the channel texts) await EasyLocalization.ensureInitialized(); + // Local notifications. A failure here must not block the app. + try { + await NotificationService().init(); + } catch (e) { + debugPrint('Notification init failed: $e'); + } + if (Platform.isAndroid || Platform.isIOS) { // Lock orientation (https://stackoverflow.com/a/52720581/19371130) SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index e384a65..8f6c775 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -13,6 +13,7 @@ import '../widgets/chat_list_item.dart'; import '../models/private_message.dart'; import '../utils/cache_utils.dart'; import '../utils/message_notifier.dart'; +import '../utils/notification_service.dart'; import 'search_user_page.dart'; import 'settings_page.dart'; import '../utils/dialog_utils.dart'; @@ -50,6 +51,10 @@ class _HomePageState extends State { } // Get all conversations with their last messages _getConversations(); + // Open the chat a notification tap pointed at (after unlocking) + _openPendingChat(); + // Taps arriving while Home is alive open the chat right away + NotificationService.onChatSelected = _openChat; // Start checking WebSocket connection _webSocketManager.startConnectionCheck(); @@ -78,6 +83,9 @@ class _HomePageState extends State { @override void dispose() { + if (NotificationService.onChatSelected == _openChat) { + NotificationService.onChatSelected = null; + } super.dispose(); // Stop checking WebSocket connection _webSocketManager.stopConnectionCheck(); @@ -195,6 +203,38 @@ class _HomePageState extends State { } } + /// Open the chat of [userId] on top of Home. + Future _openChat(int userId) async { + final user = await CacheUtils.getUserById(userId); + if (user == null || !mounted) { + return; + } + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) { + return; + } + Navigator.of(context).push(PageTransition( + duration: const Duration(milliseconds: 300), + reverseDuration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + type: PageTransitionType.bottomToTopJoined, + child: ChatPage(user), + childCurrent: widget)); + }); + } + + /// Open the chat a notification tap pointed at. This also covers a locked + /// app: the tap is remembered and the chat opens after the password page + /// replaced itself with HomePage. + Future _openPendingChat() async { + final userId = Singleton().pendingChatUserId; + if (userId == null) { + return; + } + Singleton().pendingChatUserId = null; + await _openChat(userId); + } + /// Shows new invite dialog. Future _createNewInvite(BuildContext context) async { await showDialog(context: context, builder: DialogUtils.inviteDialog) diff --git a/lib/utils/notification_service.dart b/lib/utils/notification_service.dart index ea734a6..f1c85bd 100644 --- a/lib/utils/notification_service.dart +++ b/lib/utils/notification_service.dart @@ -1,22 +1,38 @@ import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:sprintf/sprintf.dart'; import '../utils/cache_utils.dart'; import '../models/user.dart'; import '../models/private_message.dart'; +import 'singleton.dart'; // https://www.scaler.com/topics/flutter-local-notification/ class NotificationService { + /// Set by HomePage while it is alive, so a tap on a single message + /// notification can open the chat immediately instead of being queued. + static void Function(int userId)? onChatSelected; + final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); /// Init notification settings Future init() async { + // Local notifications are only set up for the platforms that have their + // settings below. iOS/macOS need the Darwin settings tracked in the + // "Android / iOS permissions" backlog item. + if (defaultTargetPlatform != TargetPlatform.android && + defaultTargetPlatform != TargetPlatform.linux) { + return; + } + const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('ic_stat_whisper'); - const LinuxInitializationSettings initializationSettingsLinux = + final LinuxInitializationSettings initializationSettingsLinux = LinuxInitializationSettings( - defaultActionName: 'whisper_message'); // TODO other options + defaultActionName: 'whisper_message', + defaultIcon: ThemeLinuxIcon('mail-unread'), + ); final InitializationSettings initializationSettings = InitializationSettings( @@ -24,7 +40,18 @@ class NotificationService { linux: initializationSettingsLinux); await _flutterLocalNotificationsPlugin.initialize( - settings: initializationSettings); + settings: initializationSettings, + onDidReceiveNotificationResponse: _onNotificationTap); + + // Tapping a notification while the app was closed launches it through here + // (Android only, the Linux implementation does not support it). + if (defaultTargetPlatform == TargetPlatform.android) { + final launchDetails = await _flutterLocalNotificationsPlugin + .getNotificationAppLaunchDetails(); + if (launchDetails?.didNotificationLaunchApp ?? false) { + _setPendingChat(launchDetails!.notificationResponse?.payload); + } + } // FCM posts notifications into this channel, so it must exist before a push arrives await _flutterLocalNotificationsPlugin @@ -39,6 +66,26 @@ class NotificationService { )); } + /// Remember the chat a notification points at. The app may still be locked, + /// so HomePage opens it once it is on screen (i.e. after unlocking). + void _onNotificationTap(NotificationResponse response) => + _setPendingChat(response.payload); + + /// The payload of a single message notification is the sender id; grouped + /// notifications carry none and just open HomePage. + void _setPendingChat(String? payload) { + final userId = int.tryParse(payload ?? ''); + if (userId == null) { + return; + } + final onChatSelected = NotificationService.onChatSelected; + if (onChatSelected != null) { + onChatSelected(userId); + return; + } + Singleton().pendingChatUserId = userId; + } + /// Show notifications. Future showMessagesNotification(List messages) async { final Map> groupedMessagesById = {}; @@ -136,6 +183,8 @@ class NotificationService { enableVibration: true, playSound: true, sound: RawResourceAndroidNotificationSound('notification'), + // Message previews are long, don't let Android truncate them + styleInformation: BigTextStyleInformation(message.preview), ); NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics); @@ -144,6 +193,7 @@ class NotificationService { title: user.username, body: message.preview, notificationDetails: platformChannelSpecifics, + payload: message.senderId.toString(), ); } diff --git a/lib/utils/singleton.dart b/lib/utils/singleton.dart index edd1037..46560dd 100644 --- a/lib/utils/singleton.dart +++ b/lib/utils/singleton.dart @@ -23,6 +23,8 @@ class Singleton { late WsClient wsClient; // Current route late Route currentRoute; + // Chat a notification tap asked for, opened by HomePage once it is shown + int? pendingChatUserId; // Offline mode bool _offlineMode = false; From 3489889e1f2e5d8e924dd6b26c8b4c1055a0b270 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 00:41:07 +0100 Subject: [PATCH 032/181] feat(chat): long-press message actions Long-pressing a bubble opens a sheet with copy, forward, save attachment and delete for me. The attachment viewer has the same actions minus copy in its overflow menu. Sending moved out of ChatPage into ChatSender so the forward page can send text and media to any recipient; deleting a message is local only and drops its media file. --- assets/translations/cs.json | 14 ++- assets/translations/en.json | 14 ++- lib/pages/chat_info_page.dart | 5 +- lib/pages/chat_page.dart | 150 ++++--------------------------- lib/pages/forward_page.dart | 122 +++++++++++++++++++++++++ lib/pages/media_viewer_page.dart | 84 ++++++++++++----- lib/pages/search_user_page.dart | 10 ++- lib/utils/cache_utils.dart | 17 ++++ lib/utils/chat_sender.dart | 142 +++++++++++++++++++++++++++++ lib/utils/message_actions.dart | 125 ++++++++++++++++++++++++++ lib/widgets/chat_bubble.dart | 36 +++++--- lib/widgets/media_bubble.dart | 16 ++-- test/delete_message_test.dart | 43 +++++++++ test/message_actions_test.dart | 69 ++++++++++++++ 14 files changed, 662 insertions(+), 185 deletions(-) create mode 100644 lib/pages/forward_page.dart create mode 100644 lib/utils/chat_sender.dart create mode 100644 lib/utils/message_actions.dart create mode 100644 test/delete_message_test.dart create mode 100644 test/message_actions_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 68e6757..6272fba 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -116,5 +116,17 @@ "passwordChanged": "Heslo změněno", "passwordChangeFailed": "Heslo se nepodařilo změnit", "biometricsDisabledAfterMigration": "Biometrika byla vypnuta. Odemkni heslem a znovu ji zapni v nastavení.", - "passwordMigrationFailed": "Lokální data se nepodařilo otevřít. Heslo neodpovídá uloženým datům." + "passwordMigrationFailed": "Lokální data se nepodařilo otevřít. Heslo neodpovídá uloženým datům.", + "copyMessage": "Kopírovat", + "forwardMessage": "Přeposlat", + "saveAttachment": "Uložit přílohu", + "deleteMessageForMe": "Smazat pro mě", + "deleteMessageConfirm": "Smazat zprávu", + "deleteMessageConfirmText": "Zpráva se smaže jen z tohoto zařízení. Druhá strana si ji nechá.", + "copiedText": "Zkopírováno", + "attachmentSaved": "Příloha uložena", + "attachmentSaveFailed": "Uložení přílohy se nepovedlo", + "forwardTo": "Přeposlat komu", + "forwarded": "Přeposláno", + "noChatsToForward": "Zatím žádné chaty, vyhledej uživatele" } diff --git a/assets/translations/en.json b/assets/translations/en.json index ebdef71..278788a 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -116,5 +116,17 @@ "passwordChanged": "Password changed", "passwordChangeFailed": "Password could not be changed", "biometricsDisabledAfterMigration": "Biometrics were turned off. Unlock with your password and enable them again in settings.", - "passwordMigrationFailed": "Local data could not be opened. The password does not match the stored data." + "passwordMigrationFailed": "Local data could not be opened. The password does not match the stored data.", + "copyMessage": "Copy", + "forwardMessage": "Forward", + "saveAttachment": "Save attachment", + "deleteMessageForMe": "Delete for me", + "deleteMessageConfirm": "Delete message", + "deleteMessageConfirmText": "The message will be deleted only from this device. The other side keeps it.", + "copiedText": "Copied", + "attachmentSaved": "Attachment saved", + "attachmentSaveFailed": "Saving the attachment failed", + "forwardTo": "Forward to", + "forwarded": "Forwarded", + "noChatsToForward": "No chats yet, search for a user" } diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 36b2910..63fadc9 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -96,9 +96,8 @@ class _ChatInfoPageState extends State { type: PageTransitionType.fade, duration: const Duration(milliseconds: 200), child: MediaViewerPage( - localPath: path, - type: type, - caption: message.message, + message: message, + conversationUserId: widget.userId, ), ), ); diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 1abfaf6..e8b4519 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1,29 +1,20 @@ import 'dart:async'; -import 'dart:convert'; import 'dart:io'; import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:http/http.dart' as http; import 'package:page_transition/page_transition.dart'; import 'package:provider/provider.dart'; -import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; -import 'package:whisper_websocket_client_dart/models/new_private_message.dart'; -import 'package:whisper_websocket_client_dart/models/ws_message.dart'; import '../models/private_message.dart'; import '../models/user.dart'; import '../utils/cache_utils.dart'; -import '../utils/crypto_utils.dart'; +import '../utils/chat_sender.dart'; import '../utils/media_utils.dart'; import '../utils/message_notifier.dart'; -import '../utils/singleton.dart'; import '../utils/theme_utils.dart'; -import '../utils/utils.dart'; import '../widgets/chat_bubble.dart'; -import 'package:basic_utils/basic_utils.dart' as bu; import 'chat_info_page.dart'; class ChatPage extends StatefulWidget { @@ -91,61 +82,23 @@ class _ChatPageState extends State { /// Send message Future _sendMessage() async { - debugPrint(_controllerMessage.text.length.toString()); - if (_controllerMessage.text.isEmpty) { + final text = _controllerMessage.text; + if (text.isEmpty) { return; } setState(() { _isSending = true; }); - await Utils.wsConnect(); - // Send message - if (Singleton().wsClient.isConnected) { - // Encrypt message content - Map data; - try { - data = await CryptoUtils.encryptMessageData( - utf8.encode(_controllerMessage.text), - bu.CryptoUtils.rsaPublicKeyFromPem(widget.user.publicKey)); - } catch (e) { - await Fluttertoast.showToast( - msg: e.toString(), backgroundColor: Colors.red); - setState(() { - _isSending = false; - }); - return; - } - DateTime sentAt; - try { - sentAt = Singleton().wsClient.sendMessage(WsMessage.privateMessage( - NewPrivateMessage(widget.user.id, data['encryptedData']!, - data['encryptedKey']!, data['nonce']!, data['mac']!))); - // Save user to cache - if (widget.user.publicKey != '' && - widget.user.username != '' && - !widget.user.isInBox) { - CacheUtils.addUser(widget.user); - } - // Add message to cache - await MessageNotifier().addMessages(widget.user.id, [ - PrivateMessage(Singleton().profile.user.id, _controllerMessage.text, - sentAt, sentAt, true) - ]); - // Reset text - _controllerMessage.text = ''; - // Delete concept - await CacheUtils.deleteMessageConcept(widget.user.id); - } catch (e) { - await Fluttertoast.showToast( - msg: e.toString(), backgroundColor: Colors.red); - } - } else { - await Fluttertoast.showToast( - msg: 'wsOffline'.tr(), backgroundColor: Colors.red); + if (await ChatSender.sendText(widget.user, text)) { + _controllerMessage.text = ''; + // Delete concept + await CacheUtils.deleteMessageConcept(widget.user.id); + } + if (mounted) { + setState(() { + _isSending = false; + }); } - setState(() { - _isSending = false; - }); } /// Send a media attachment: encrypt for transport, upload, embed an encrypted @@ -174,84 +127,11 @@ class _ChatPageState extends State { duration ??= probe.durationMs; } - await Utils.wsConnect(); - if (!Singleton().wsClient.isConnected) { - await Fluttertoast.showToast( - msg: 'wsOffline'.tr(), backgroundColor: Colors.red); - return; - } - - // Transport encryption with an ephemeral per-file key. - final transport = await MediaUtils.encryptForTransport(bytes); - - // Upload the ciphertext over HTTP. - final uploadResponse = await Utils.callApi( - () => Singleton().mediaApi.uploadMedia( - http.MultipartFile.fromBytes('file', transport.blob, - filename: 'media.bin'), - widget.user.id, - ), - rethrowErr: true, - ); - if (uploadResponse == null) { - await Fluttertoast.showToast( - msg: 'mediaUploadFailed'.tr(), backgroundColor: Colors.red); - return; - } - final mediaId = uploadResponse.id; - - // Build the encrypted reference and wrap it in the message envelope. - final reference = MediaReference( - mediaId, - transport.key, - type, - transport.blob.length, - width: width, - height: height, - durationMs: duration, - ); - final envelope = MediaUtils.buildMediaEnvelope(reference, caption); - - // E2E-encrypt the envelope for the recipient. - final data = await CryptoUtils.encryptMessageData( - envelope, bu.CryptoUtils.rsaPublicKeyFromPem(widget.user.publicKey)); - - // Send over the WebSocket. - final sentAt = Singleton().wsClient.sendMessage(WsMessage.privateMessage( - NewPrivateMessage(widget.user.id, data['encryptedData']!, - data['encryptedKey']!, data['nonce']!, data['mac']!))); - - // Persist the recipient if needed. - if (widget.user.publicKey != '' && - widget.user.username != '' && - !widget.user.isInBox) { - CacheUtils.addUser(widget.user); - } - - // Store the original media encrypted-at-rest for our own bubble. - final localPath = await MediaUtils.encryptAtRest(bytes); - - // Optimistic local message. - await MessageNotifier().addMessages(widget.user.id, [ - PrivateMessage( - Singleton().profile.user.id, - caption, - sentAt, - sentAt, - true, - mediaId: mediaId, - mediaTypeStr: type.name, - localPath: localPath, - mediaSize: bytes.length, - width: width, - height: height, - durationMs: duration, - downloadStatus: MediaDownloadStatus.ready, - ) - ]); + final sent = await ChatSender.sendMedia(widget.user, type, bytes, + caption: caption, width: width, height: height, durationMs: duration); // The caption (taken from the text field) was consumed -> clear it. - if (caption.isNotEmpty && _controllerMessage.text == caption) { + if (sent && caption.isNotEmpty && _controllerMessage.text == caption) { _controllerMessage.text = ''; await CacheUtils.deleteMessageConcept(widget.user.id); } diff --git a/lib/pages/forward_page.dart b/lib/pages/forward_page.dart new file mode 100644 index 0000000..415225a --- /dev/null +++ b/lib/pages/forward_page.dart @@ -0,0 +1,122 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +import '../models/private_message.dart'; +import '../models/user.dart'; +import '../utils/chat_sender.dart'; +import '../utils/media_utils.dart'; +import '../utils/message_notifier.dart'; +import '../widgets/user_list_item.dart'; +import 'search_user_page.dart'; + +/// Picks the destination of a forwarded message: an existing conversation or a +/// user found by search. Sends the message and closes itself. +class ForwardPage extends StatefulWidget { + const ForwardPage(this.message, {super.key}); + final PrivateMessage message; + + @override + State createState() => _ForwardPageState(); +} + +class _ForwardPageState extends State { + List _chats = []; + bool _sending = false; + + @override + void initState() { + super.initState(); + _loadChats(); + } + + Future _loadChats() async { + final chats = await MessageNotifier().getLatestPrivateMessages(); + if (mounted) { + setState(() { + _chats = chats.keys.toList(); + }); + } + } + + Future _forward(User to) async { + if (_sending) { + return; + } + setState(() { + _sending = true; + }); + try { + final message = widget.message; + bool sent; + if (message.isMedia) { + final path = message.localPath; + final type = message.mediaType; + if (path == null || type == null) { + // Save/forward are hidden for attachments that are not on disk + return; + } + final bytes = await MediaUtils.decryptAtRest(path); + sent = await ChatSender.sendMedia(to, type, bytes, + caption: message.message, + width: message.width, + height: message.height, + durationMs: message.durationMs); + } else { + sent = await ChatSender.sendText(to, message.message); + } + if (!mounted) { + return; + } + if (sent) { + Fluttertoast.showToast(msg: 'forwarded'.tr()); + Navigator.pop(context); + } + } catch (e) { + Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); + } finally { + if (mounted) { + setState(() { + _sending = false; + }); + } + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text('forwardTo'.tr()), + actions: [ + IconButton( + icon: const Icon(Icons.search), + tooltip: 'searchUserPage'.tr(), + onPressed: () { + Navigator.of(context).push(MaterialPageRoute( + builder: (_) => SearchUserPage(onUserSelected: (user) { + // Close the search page, _forward closes this one + Navigator.pop(context); + _forward(user); + }))); + }, + ), + ], + ), + body: SafeArea( + child: _chats.isEmpty + ? Center(child: Text('noChatsToForward'.tr())) + : ListView.builder( + itemCount: _chats.length, + itemBuilder: (context, index) { + return Padding( + padding: const EdgeInsets.only(bottom: 10), + child: UserListItem( + _chats[index], () => _forward(_chats[index])), + ); + }, + ), + ), + ); + } +} diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index 0f332a3..e58207b 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -7,18 +7,20 @@ import 'package:flutter/material.dart'; import 'package:video_player/video_player.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import '../models/private_message.dart'; import '../utils/media_utils.dart'; +import '../utils/message_actions.dart'; /// Fullscreen viewer for an image/gif or video stored encrypted-at-rest. class MediaViewerPage extends StatefulWidget { - final String localPath; - final MediaType type; - final String? caption; + final PrivateMessage message; + + /// The other side of the conversation (needed by the delete action). + final int conversationUserId; const MediaViewerPage({ - required this.localPath, - required this.type, - this.caption, + required this.message, + required this.conversationUserId, super.key, }); @@ -34,7 +36,9 @@ class _MediaViewerPageState extends State { bool _loading = true; bool _error = false; - bool get _isVideo => widget.type == MediaType.video; + MediaType get _type => widget.message.mediaType ?? MediaType.image; + + bool get _isVideo => _type == MediaType.video; @override void initState() { @@ -44,9 +48,13 @@ class _MediaViewerPageState extends State { Future _load() async { try { + final localPath = widget.message.localPath; + if (localPath == null) { + throw Exception('no local media'); + } if (_isVideo) { _tempFile = await MediaUtils.materializeTempFile( - widget.localPath, MediaUtils.extensionForType(widget.type)); + localPath, MediaUtils.extensionForType(_type)); final controller = VideoPlayerController.file(_tempFile!); await controller.initialize(); _videoController = controller; @@ -57,7 +65,7 @@ class _MediaViewerPageState extends State { allowFullScreen: true, ); } else { - _imageBytes = await MediaUtils.decryptAtRest(widget.localPath); + _imageBytes = await MediaUtils.decryptAtRest(localPath); } if (mounted) { setState(() { @@ -82,32 +90,62 @@ class _MediaViewerPageState extends State { super.dispose(); } + /// Overflow menu of the viewer: the same actions as the bubble sheet, except + /// copy (the caption is already visible). + PopupMenuButton _buildActions() { + return PopupMenuButton( + icon: const Icon(Icons.more_vert), + onSelected: (value) { + switch (value) { + case 'save': + MessageActions.save(widget.message); + break; + case 'forward': + MessageActions.forward(context, widget.message); + break; + case 'delete': + MessageActions.delete( + context, widget.message, widget.conversationUserId, + onDeleted: () => Navigator.pop(context)); + break; + } + }, + itemBuilder: (context) => [ + if (MessageActions.canSave(widget.message)) + PopupMenuItem(value: 'save', child: Text('saveAttachment'.tr())), + PopupMenuItem(value: 'forward', child: Text('forwardMessage'.tr())), + PopupMenuItem(value: 'delete', child: Text('deleteMessageForMe'.tr())), + ], + ); + } + @override Widget build(BuildContext context) { + final caption = widget.message.message; return Scaffold( backgroundColor: Colors.black, appBar: AppBar( backgroundColor: Colors.black, foregroundColor: Colors.white, iconTheme: const IconThemeData(color: Colors.white), + actions: [_buildActions()], ), body: Center( child: _buildBody(), ), - bottomNavigationBar: - (widget.caption != null && widget.caption!.isNotEmpty) - ? Container( - color: Colors.black, - padding: const EdgeInsets.all(16), - child: SafeArea( - top: false, - child: Text( - widget.caption!, - style: const TextStyle(color: Colors.white), - ), - ), - ) - : null, + bottomNavigationBar: caption.isNotEmpty + ? Container( + color: Colors.black, + padding: const EdgeInsets.all(16), + child: SafeArea( + top: false, + child: Text( + caption, + style: const TextStyle(color: Colors.white), + ), + ), + ) + : null, ); } diff --git a/lib/pages/search_user_page.dart b/lib/pages/search_user_page.dart index 1184727..43e3e43 100644 --- a/lib/pages/search_user_page.dart +++ b/lib/pages/search_user_page.dart @@ -7,7 +7,10 @@ import '../widgets/user_list_item.dart'; import 'chat_page.dart'; class SearchUserPage extends StatefulWidget { - const SearchUserPage({super.key}); + const SearchUserPage({this.onUserSelected, super.key}); + + /// When set, a tapped user is passed here instead of opening the chat. + final void Function(User)? onUserSelected; @override State createState() => _SearchUserPageState(); @@ -113,6 +116,11 @@ class _SearchUserPageState extends State { return Padding( padding: const EdgeInsets.only(bottom: 10), child: UserListItem(_users[index], () async { + final onUserSelected = widget.onUserSelected; + if (onUserSelected != null) { + onUserSelected(_users[index]); + return; + } Navigator.pushAndRemoveUntil( context, MaterialPageRoute( diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 2fedaee..7d075e5 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -293,6 +293,23 @@ class CacheUtils { : messages.map((e) => e as PrivateMessage).toList(); } + /// Delete a single message locally (and its media file). Nothing is sent to + /// the server, so the other side keeps the message. + static Future deletePrivateMessage( + int userId, PrivateMessage message) async { + Box box = await _openPrivateMessagesBox(); + List? messages = box.get(userId); + if (messages == null) { + return; + } + messages.removeWhere((m) => + m is PrivateMessage && + m.senderId == message.senderId && + m.sentAt == message.sentAt); + await box.put(userId, messages); + await MediaUtils.deleteLocalFile(message.localPath); + } + /// Delete user messages static Future deletePrivateMessagesWithUser(int userId) async { Box messageBox = await _openPrivateMessagesBox(); diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart new file mode 100644 index 0000000..3a78a7b --- /dev/null +++ b/lib/utils/chat_sender.dart @@ -0,0 +1,142 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:basic_utils/basic_utils.dart' as bu; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:http/http.dart' as http; +import 'package:whisper_websocket_client_dart/models/media_reference.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:whisper_websocket_client_dart/models/new_private_message.dart'; +import 'package:whisper_websocket_client_dart/models/ws_message.dart'; + +import '../models/private_message.dart'; +import '../models/user.dart'; +import 'cache_utils.dart'; +import 'crypto_utils.dart'; +import 'media_utils.dart'; +import 'message_notifier.dart'; +import 'singleton.dart'; +import 'utils.dart'; + +/// Sends messages to an arbitrary recipient. Shared by the chat page and the +/// forward page so both use one encrypted, persisted send path. +/// +/// Each method reports its own errors with a toast and returns whether the +/// message was sent. +class ChatSender { + /// Send a text message to [recipient]. + static Future sendText(User recipient, String text) async { + try { + await Utils.wsConnect(); + if (!Singleton().wsClient.isConnected) { + Fluttertoast.showToast( + msg: 'wsOffline'.tr(), backgroundColor: Colors.red); + return false; + } + final data = await CryptoUtils.encryptMessageData(utf8.encode(text), + bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); + final sentAt = Singleton().wsClient.sendMessage(WsMessage.privateMessage( + NewPrivateMessage(recipient.id, data['encryptedData']!, + data['encryptedKey']!, data['nonce']!, data['mac']!))); + await _persist(recipient, [ + PrivateMessage(Singleton().profile.user.id, text, sentAt, sentAt, true) + ]); + return true; + } catch (e) { + Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); + return false; + } + } + + /// Send [bytes] as a media attachment of [type] to [recipient]. The caller + /// supplies the probed metadata so `null` there is meaningful. + static Future sendMedia(User recipient, MediaType type, Uint8List bytes, + {String caption = '', int? width, int? height, int? durationMs}) async { + try { + await Utils.wsConnect(); + if (!Singleton().wsClient.isConnected) { + Fluttertoast.showToast( + msg: 'wsOffline'.tr(), backgroundColor: Colors.red); + return false; + } + + // Transport encryption with an ephemeral per-file key. + final transport = await MediaUtils.encryptForTransport(bytes); + + // Upload the ciphertext over HTTP. + final uploadResponse = await Utils.callApi( + () => Singleton().mediaApi.uploadMedia( + http.MultipartFile.fromBytes('file', transport.blob, + filename: 'media.bin'), + recipient.id, + ), + rethrowErr: true, + ); + if (uploadResponse == null) { + Fluttertoast.showToast( + msg: 'mediaUploadFailed'.tr(), backgroundColor: Colors.red); + return false; + } + final mediaId = uploadResponse.id; + + // Build the encrypted reference and wrap it in the message envelope. + final reference = MediaReference( + mediaId, + transport.key, + type, + transport.blob.length, + width: width, + height: height, + durationMs: durationMs, + ); + final envelope = MediaUtils.buildMediaEnvelope(reference, caption); + + // E2E-encrypt the envelope for the recipient. + final data = await CryptoUtils.encryptMessageData( + envelope, bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); + + // Send over the WebSocket. + final sentAt = Singleton().wsClient.sendMessage(WsMessage.privateMessage( + NewPrivateMessage(recipient.id, data['encryptedData']!, + data['encryptedKey']!, data['nonce']!, data['mac']!))); + + // Store the original media encrypted-at-rest for our own bubble. + final localPath = await MediaUtils.encryptAtRest(bytes); + + await _persist(recipient, [ + PrivateMessage( + Singleton().profile.user.id, + caption, + sentAt, + sentAt, + true, + mediaId: mediaId, + mediaTypeStr: type.name, + localPath: localPath, + mediaSize: bytes.length, + width: width, + height: height, + durationMs: durationMs, + downloadStatus: MediaDownloadStatus.ready, + ) + ]); + return true; + } catch (e) { + Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); + return false; + } + } + + /// Store the recipient and the sent message in the local cache. + static Future _persist( + User recipient, List messages) async { + if (recipient.publicKey != '' && + recipient.username != '' && + !recipient.isInBox) { + await CacheUtils.addUser(recipient); + } + await MessageNotifier().addMessages(recipient.id, messages); + } +} diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart new file mode 100644 index 0000000..293d787 --- /dev/null +++ b/lib/utils/message_actions.dart @@ -0,0 +1,125 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +import '../models/private_message.dart'; +import '../pages/forward_page.dart'; +import 'cache_utils.dart'; +import 'dialog_utils.dart'; +import 'media_utils.dart'; +import 'message_notifier.dart'; + +/// Actions for a single message, offered by the bubble long-press sheet and by +/// the attachment viewer's overflow menu. +class MessageActions { + /// Whether [message] can be saved or forwarded (the file must be on disk). + static bool canSave(PrivateMessage message) => + message.isMedia && message.localPath != null; + + /// Bubble long-press sheet with all actions that apply to [message]. + /// [conversationUserId] is the other side of the conversation. + static Future showSheet( + BuildContext context, PrivateMessage message, int conversationUserId, + {VoidCallback? onDeleted}) { + return showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (ctx) { + return SafeArea( + child: Wrap( + children: [ + if (message.message.isNotEmpty) + ListTile( + leading: const Icon(Icons.copy), + title: Text('copyMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + copy(message); + }, + ), + ListTile( + leading: const Icon(Icons.forward), + title: Text('forwardMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + forward(context, message); + }, + ), + if (canSave(message)) + ListTile( + leading: const Icon(Icons.download), + title: Text('saveAttachment'.tr()), + onTap: () { + Navigator.pop(ctx); + save(message); + }, + ), + ListTile( + leading: const Icon(Icons.delete), + title: Text('deleteMessageForMe'.tr()), + onTap: () { + Navigator.pop(ctx); + delete(context, message, conversationUserId, + onDeleted: onDeleted); + }, + ), + ], + ), + ); + }, + ); + } + + /// Copy the message text (the caption for media messages). + static Future copy(PrivateMessage message) async { + await Clipboard.setData(ClipboardData(text: message.message)); + Fluttertoast.showToast(msg: 'copiedText'.tr()); + } + + /// Save the decrypted attachment wherever the user picks. + static Future save(PrivateMessage message) async { + final path = message.localPath; + final type = message.mediaType; + if (path == null || type == null) { + return; + } + try { + final bytes = await MediaUtils.decryptAtRest(path); + final saved = await FilePicker.saveFile( + dialogTitle: 'saveAttachment'.tr(), + fileName: + 'whisper_${message.sentAt.millisecondsSinceEpoch}${MediaUtils.extensionForType(type)}', + bytes: bytes, + ); + if (saved == null) { + return; + } + Fluttertoast.showToast(msg: 'attachmentSaved'.tr()); + } catch (_) { + Fluttertoast.showToast( + msg: 'attachmentSaveFailed'.tr(), backgroundColor: Colors.red); + } + } + + /// Pick a chat (or a user) and send the message there. + static Future forward( + BuildContext context, PrivateMessage message) async { + await Navigator.of(context) + .push(MaterialPageRoute(builder: (_) => ForwardPage(message))); + } + + /// Delete the message only on this device, after a confirmation. + static void delete( + BuildContext context, PrivateMessage message, int conversationUserId, + {VoidCallback? onDeleted}) { + DialogUtils.yesNoDialog( + context, 'deleteMessageConfirm'.tr(), 'deleteMessageConfirmText'.tr(), + () async { + await CacheUtils.deletePrivateMessage(conversationUserId, message); + MessageNotifier().notify(); + onDeleted?.call(); + }); + } +} diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 35d3146..87a9bcc 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -2,10 +2,11 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import '../models/user.dart'; import '../models/private_message.dart'; +import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; import 'media_bubble.dart'; -// TODO show options on bottom on holding the widget (like in Messenger - copy etc) +// Long-press opens the message actions sheet (copy, forward, save, delete). class ChatBubble extends StatefulWidget { final PrivateMessage? previousMessage; final PrivateMessage message; @@ -56,7 +57,9 @@ class _ChatBubbleState extends State { ? widget.previousMessage!.sentAt : widget.previousMessage!.receivedAt; - final currentTime = widget.message.isMe ? widget.message.sentAt : widget.message.receivedAt; + final currentTime = widget.message.isMe + ? widget.message.sentAt + : widget.message.receivedAt; final difference = currentTime.difference(previousTime).inMinutes; return difference >= 10; @@ -119,8 +122,9 @@ class _ChatBubbleState extends State { top: isFromSameUser() ? 4 : 16, ), child: Column( - crossAxisAlignment: - widget.message.isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start, + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, children: [ AnimatedSize( duration: const Duration(milliseconds: 200), @@ -131,11 +135,13 @@ class _ChatBubbleState extends State { children: [ if (_showTooltip && !shouldShowTime()) Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + padding: const EdgeInsets.symmetric( + horizontal: 16, vertical: 8), child: Center( child: Text( - formatDate( - widget.message.isMe ? widget.message.sentAt : widget.message.receivedAt), + formatDate(widget.message.isMe + ? widget.message.sentAt + : widget.message.receivedAt), style: TextStyle( fontSize: 12, color: Colors.grey[600], @@ -145,11 +151,13 @@ class _ChatBubbleState extends State { ), if (shouldShowTime()) Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + padding: const EdgeInsets.symmetric( + horizontal: 16, vertical: 8), child: Center( child: Text( - formatDate( - widget.message.isMe ? widget.message.sentAt : widget.message.receivedAt), + formatDate(widget.message.isMe + ? widget.message.sentAt + : widget.message.receivedAt), style: TextStyle( fontSize: 12, color: Colors.grey[600], @@ -167,9 +175,12 @@ class _ChatBubbleState extends State { _showTooltip = !_showTooltip; }); }, + onLongPress: () => MessageActions.showSheet( + context, widget.message, widget.user.id), child: Align( - alignment: - widget.message.isMe ? Alignment.centerRight : Alignment.centerLeft, + alignment: widget.message.isMe + ? Alignment.centerRight + : Alignment.centerLeft, child: Row( mainAxisAlignment: widget.message.isMe ? MainAxisAlignment.end @@ -221,6 +232,7 @@ class _ChatBubbleState extends State { if (widget.message.isMedia) MediaBubble( message: widget.message, + conversationUserId: widget.user.id, bubbleColor: bubbleBackground(), textColor: bubbleTextColor(), canRetry: widget.message.mediaId != null && diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 4bfbd3e..c611d78 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -19,6 +19,7 @@ class MediaBubble extends StatefulWidget { final Color textColor; final VoidCallback onRetry; final bool canRetry; + final int conversationUserId; const MediaBubble({ required this.message, @@ -26,6 +27,7 @@ class MediaBubble extends StatefulWidget { required this.textColor, required this.onRetry, required this.canRetry, + required this.conversationUserId, super.key, }); @@ -96,9 +98,8 @@ class _MediaBubbleState extends State { type: PageTransitionType.fade, duration: const Duration(milliseconds: 200), child: MediaViewerPage( - localPath: path, - type: type, - caption: widget.message.message, + message: widget.message, + conversationUserId: widget.conversationUserId, ), ), ); @@ -162,8 +163,7 @@ class _MediaBubbleState extends State { color: widget.bubbleColor, borderRadius: BorderRadius.circular(16), ), - padding: - const EdgeInsets.symmetric(horizontal: 14, vertical: 8), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), child: Text( widget.message.message, style: TextStyle(color: widget.textColor), @@ -263,16 +263,14 @@ class _MediaBubbleState extends State { shape: BoxShape.circle, ), padding: const EdgeInsets.all(8), - child: - const Icon(Icons.play_arrow, color: Colors.white, size: 36), + child: const Icon(Icons.play_arrow, color: Colors.white, size: 36), ), if (widget.message.durationMs != null) Positioned( right: 8, bottom: 8, child: Container( - padding: - const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), decoration: BoxDecoration( color: Colors.black.withValues(alpha: 0.6), borderRadius: BorderRadius.circular(8), diff --git a/test/delete_message_test.dart b/test/delete_message_test.dart new file mode 100644 index 0000000..451eca5 --- /dev/null +++ b/test/delete_message_test.dart @@ -0,0 +1,43 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; + +void main() { + late Directory dir; + late PrivateMessage keep; + late PrivateMessage drop; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_delete_message_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + keep = PrivateMessage( + 2, 'keep me', DateTime(2026, 1, 1), DateTime(2026, 1, 1), true); + drop = PrivateMessage( + 1, 'drop me', DateTime(2026, 1, 2), DateTime(2026, 1, 2), true); + await CacheUtils.addPrivateMessages(1, [keep, drop]); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('deletePrivateMessage removes only the matching message', () async { + await CacheUtils.deletePrivateMessage(1, drop); + + final messages = await CacheUtils.getPrivateMessages(1); + expect(messages.length, 1); + expect(messages.single.message, 'keep me'); + // The other conversation is untouched + expect(await CacheUtils.getPrivateMessages(2), isEmpty); + }); +} diff --git a/test/message_actions_test.dart b/test/message_actions_test.dart new file mode 100644 index 0000000..5baec80 --- /dev/null +++ b/test/message_actions_test.dart @@ -0,0 +1,69 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/message_actions.dart'; + +void main() { + setUpAll(() async { + // easy_localization reads the locale from shared_preferences + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + }); + + testWidgets('the sheet offers only the actions that apply', (tester) async { + // Swapped between the two steps; the app is built once so the localization + // asset is loaded only once. + var message = + PrivateMessage(2, 'hello', DateTime(2026), DateTime(2026), true); + + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Builder(builder: (inner) { + return Scaffold( + body: Center( + child: ElevatedButton( + onPressed: () => MessageActions.showSheet(inner, message, 5), + child: const Text('open'), + ), + ), + ); + }), + ); + }), + )); + await tester.pumpAndSettle(); + + // Text message: copy, forward, delete. Nothing to save. + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('Copy'), findsOneWidget); + expect(find.text('Forward'), findsOneWidget); + expect(find.text('Delete for me'), findsOneWidget); + expect(find.text('Save attachment'), findsNothing); + + // Close the sheet + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + // Attachment on disk without a caption: save, forward, delete, no copy. + message = PrivateMessage(2, '', DateTime(2026), DateTime(2026), true, + localPath: '/tmp/whisper_media_test', mediaTypeStr: 'image'); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('Save attachment'), findsOneWidget); + expect(find.text('Forward'), findsOneWidget); + expect(find.text('Delete for me'), findsOneWidget); + expect(find.text('Copy'), findsNothing); + }); +} From 83a4c5e6b9d832ca31d00c76b917f4dd9a8d943b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 01:20:15 +0100 Subject: [PATCH 033/181] feat(chat): same icons in the attachment viewer menu as in the bubble sheet The icon set lives on MessageActions so the two menus cannot drift apart. --- lib/pages/media_viewer_page.dart | 21 ++++++++++++++++++--- lib/utils/message_actions.dart | 15 +++++++++++---- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index e58207b..f07cd30 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -112,13 +112,28 @@ class _MediaViewerPageState extends State { }, itemBuilder: (context) => [ if (MessageActions.canSave(widget.message)) - PopupMenuItem(value: 'save', child: Text('saveAttachment'.tr())), - PopupMenuItem(value: 'forward', child: Text('forwardMessage'.tr())), - PopupMenuItem(value: 'delete', child: Text('deleteMessageForMe'.tr())), + _menuItem('save', MessageActions.saveIcon, 'saveAttachment'.tr()), + _menuItem('forward', MessageActions.forwardIcon, 'forwardMessage'.tr()), + _menuItem( + 'delete', MessageActions.deleteIcon, 'deleteMessageForMe'.tr()), ], ); } + /// Menu row with the same icon the bubble sheet uses for this action. + PopupMenuItem _menuItem(String value, IconData icon, String label) { + return PopupMenuItem( + value: value, + child: Row( + children: [ + Icon(icon), + const SizedBox(width: 12), + Text(label), + ], + ), + ); + } + @override Widget build(BuildContext context) { final caption = widget.message.message; diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 293d787..c6e2420 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -14,6 +14,13 @@ import 'message_notifier.dart'; /// Actions for a single message, offered by the bubble long-press sheet and by /// the attachment viewer's overflow menu. class MessageActions { + /// Icons shared by the bubble sheet and the viewer's overflow menu, so both + /// offer the same actions with the same icons. + static const IconData copyIcon = Icons.copy; + static const IconData forwardIcon = Icons.forward; + static const IconData saveIcon = Icons.download; + static const IconData deleteIcon = Icons.delete; + /// Whether [message] can be saved or forwarded (the file must be on disk). static bool canSave(PrivateMessage message) => message.isMedia && message.localPath != null; @@ -32,7 +39,7 @@ class MessageActions { children: [ if (message.message.isNotEmpty) ListTile( - leading: const Icon(Icons.copy), + leading: const Icon(copyIcon), title: Text('copyMessage'.tr()), onTap: () { Navigator.pop(ctx); @@ -40,7 +47,7 @@ class MessageActions { }, ), ListTile( - leading: const Icon(Icons.forward), + leading: const Icon(forwardIcon), title: Text('forwardMessage'.tr()), onTap: () { Navigator.pop(ctx); @@ -49,7 +56,7 @@ class MessageActions { ), if (canSave(message)) ListTile( - leading: const Icon(Icons.download), + leading: const Icon(saveIcon), title: Text('saveAttachment'.tr()), onTap: () { Navigator.pop(ctx); @@ -57,7 +64,7 @@ class MessageActions { }, ), ListTile( - leading: const Icon(Icons.delete), + leading: const Icon(deleteIcon), title: Text('deleteMessageForMe'.tr()), onTap: () { Navigator.pop(ctx); From 9cbbe119ec5d548b3987e86bd496b3544877a70f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 01:26:50 +0100 Subject: [PATCH 034/181] feat(media): swipe between a conversation's attachments in the viewer The viewer pages through the same list the Chat Info gallery shows (newest first) and starts at the tapped attachment, so a bubble and a gallery tile open the same sequence. The filter moved from ChatInfoPage to MessageNotifier.viewableMedia since both now use it; each page decodes and releases its own file. --- lib/pages/chat_info_page.dart | 17 +-- lib/pages/media_viewer_page.dart | 181 +++++++++++++++++++++---------- lib/utils/message_notifier.dart | 15 +++ test/chat_info_media_test.dart | 4 +- 4 files changed, 140 insertions(+), 77 deletions(-) diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 63fadc9..25e861e 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -17,21 +17,6 @@ class ChatInfoPage extends StatefulWidget { const ChatInfoPage(this.userId, {super.key}); final int userId; - /// Media messages with a local file that the viewer can open, newest first. - /// Voice messages and attachments that are still downloading are left out. - @visibleForTesting - static List sharedMedia(List messages) { - final media = messages - .where((m) => - m.localPath != null && - m.mediaType != null && - m.mediaType != MediaType.voice && - m.downloadStatus == MediaDownloadStatus.ready) - .toList(); - media.sort((a, b) => b.sentAt.compareTo(a.sentAt)); - return media; - } - @override State createState() => _ChatInfoPageState(); } @@ -61,7 +46,7 @@ class _ChatInfoPageState extends State { await CacheUtils.getPrivateMessages(widget.userId); if (mounted) { setState(() { - _media = ChatInfoPage.sharedMedia(messages); + _media = MessageNotifier.viewableMedia(messages); }); } } diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index f07cd30..da229fc 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -8,14 +8,18 @@ import 'package:video_player/video_player.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; +import '../utils/cache_utils.dart'; import '../utils/media_utils.dart'; import '../utils/message_actions.dart'; +import '../utils/message_notifier.dart'; -/// Fullscreen viewer for an image/gif or video stored encrypted-at-rest. +/// Fullscreen viewer for the media of one conversation, stored +/// encrypted-at-rest. Swiping moves between the attachments. class MediaViewerPage extends StatefulWidget { final PrivateMessage message; - /// The other side of the conversation (needed by the delete action). + /// The other side of the conversation: the source of the other attachments + /// and what the delete action needs. final int conversationUserId; const MediaViewerPage({ @@ -29,64 +33,40 @@ class MediaViewerPage extends StatefulWidget { } class _MediaViewerPageState extends State { - Uint8List? _imageBytes; - VideoPlayerController? _videoController; - ChewieController? _chewieController; - File? _tempFile; - bool _loading = true; - bool _error = false; + List _media = []; + PageController? _controller; + int _index = 0; - MediaType get _type => widget.message.mediaType ?? MediaType.image; - - bool get _isVideo => _type == MediaType.video; + PrivateMessage get _current => _media[_index]; @override void initState() { super.initState(); - _load(); + _loadMedia(); } - Future _load() async { - try { - final localPath = widget.message.localPath; - if (localPath == null) { - throw Exception('no local media'); - } - if (_isVideo) { - _tempFile = await MediaUtils.materializeTempFile( - localPath, MediaUtils.extensionForType(_type)); - final controller = VideoPlayerController.file(_tempFile!); - await controller.initialize(); - _videoController = controller; - _chewieController = ChewieController( - videoPlayerController: controller, - autoPlay: true, - looping: false, - allowFullScreen: true, - ); - } else { - _imageBytes = await MediaUtils.decryptAtRest(localPath); - } - if (mounted) { - setState(() { - _loading = false; - }); - } - } catch (_) { - if (mounted) { - setState(() { - _loading = false; - _error = true; - }); - } + /// The viewer pages through the same attachments the gallery shows, starting + /// at the one that was tapped. + Future _loadMedia() async { + final messages = + await CacheUtils.getPrivateMessages(widget.conversationUserId); + final media = MessageNotifier.viewableMedia(messages); + final index = media.indexWhere((m) => + m.senderId == widget.message.senderId && + m.sentAt == widget.message.sentAt); + if (!mounted) { + return; } + setState(() { + _media = media.isEmpty ? [widget.message] : media; + _index = index < 0 ? 0 : index; + _controller = PageController(initialPage: _index); + }); } @override void dispose() { - _chewieController?.dispose(); - _videoController?.dispose(); - MediaUtils.deleteLocalFile(_tempFile?.path); + _controller?.dispose(); super.dispose(); } @@ -98,20 +78,19 @@ class _MediaViewerPageState extends State { onSelected: (value) { switch (value) { case 'save': - MessageActions.save(widget.message); + MessageActions.save(_current); break; case 'forward': - MessageActions.forward(context, widget.message); + MessageActions.forward(context, _current); break; case 'delete': - MessageActions.delete( - context, widget.message, widget.conversationUserId, + MessageActions.delete(context, _current, widget.conversationUserId, onDeleted: () => Navigator.pop(context)); break; } }, itemBuilder: (context) => [ - if (MessageActions.canSave(widget.message)) + if (MessageActions.canSave(_current)) _menuItem('save', MessageActions.saveIcon, 'saveAttachment'.tr()), _menuItem('forward', MessageActions.forwardIcon, 'forwardMessage'.tr()), _menuItem( @@ -136,18 +115,28 @@ class _MediaViewerPageState extends State { @override Widget build(BuildContext context) { - final caption = widget.message.message; + final controller = _controller; + final caption = controller == null ? '' : _current.message; return Scaffold( backgroundColor: Colors.black, appBar: AppBar( backgroundColor: Colors.black, foregroundColor: Colors.white, iconTheme: const IconThemeData(color: Colors.white), - actions: [_buildActions()], - ), - body: Center( - child: _buildBody(), + actions: controller == null ? null : [_buildActions()], ), + body: controller == null + ? const Center(child: CircularProgressIndicator()) + : PageView.builder( + controller: controller, + itemCount: _media.length, + onPageChanged: (index) => setState(() { + _index = index; + }), + itemBuilder: (context, index) => Center( + child: _MediaPage(_media[index]), + ), + ), bottomNavigationBar: caption.isNotEmpty ? Container( color: Colors.black, @@ -163,8 +152,82 @@ class _MediaViewerPageState extends State { : null, ); } +} + +/// One attachment of the viewer: decodes its own file and releases it again +/// when the page is swiped away. +class _MediaPage extends StatefulWidget { + const _MediaPage(this.message); + final PrivateMessage message; + + @override + State<_MediaPage> createState() => _MediaPageState(); +} - Widget _buildBody() { +class _MediaPageState extends State<_MediaPage> { + Uint8List? _imageBytes; + VideoPlayerController? _videoController; + ChewieController? _chewieController; + File? _tempFile; + bool _loading = true; + bool _error = false; + + MediaType get _type => widget.message.mediaType ?? MediaType.image; + + bool get _isVideo => _type == MediaType.video; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + try { + final localPath = widget.message.localPath; + if (localPath == null) { + throw Exception('no local media'); + } + if (_isVideo) { + _tempFile = await MediaUtils.materializeTempFile( + localPath, MediaUtils.extensionForType(_type)); + final controller = VideoPlayerController.file(_tempFile!); + await controller.initialize(); + _videoController = controller; + _chewieController = ChewieController( + videoPlayerController: controller, + autoPlay: true, + looping: false, + allowFullScreen: true, + ); + } else { + _imageBytes = await MediaUtils.decryptAtRest(localPath); + } + if (mounted) { + setState(() { + _loading = false; + }); + } + } catch (_) { + if (mounted) { + setState(() { + _loading = false; + _error = true; + }); + } + } + } + + @override + void dispose() { + _chewieController?.dispose(); + _videoController?.dispose(); + MediaUtils.deleteLocalFile(_tempFile?.path); + super.dispose(); + } + + @override + Widget build(BuildContext context) { if (_loading) { return const CircularProgressIndicator(); } diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index 150de34..312211e 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:whisper_openapi_client_dart/media_download.dart'; import 'package:whisper_websocket_client_dart/models/media_reference.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../utils/notification_service.dart'; import '../models/private_message.dart'; @@ -20,6 +21,20 @@ class MessageNotifier extends ChangeNotifier { MessageNotifier._internal(); + /// The media messages of a conversation that the viewer can open, newest + /// first: a local file, a known type, fully downloaded, not voice. + static List viewableMedia(List messages) { + final media = messages + .where((m) => + m.localPath != null && + m.mediaType != null && + m.mediaType != MediaType.voice && + m.downloadStatus == MediaDownloadStatus.ready) + .toList(); + media.sort((a, b) => b.sentAt.compareTo(a.sentAt)); + return media; + } + /// In-memory map of media references awaiting (or having failed) download, /// keyed by media id. The transport key is intentionally never persisted to /// disk, so tap-to-retry only works within the current session. diff --git a/test/chat_info_media_test.dart b/test/chat_info_media_test.dart index 0c39100..6d20131 100644 --- a/test/chat_info_media_test.dart +++ b/test/chat_info_media_test.dart @@ -1,6 +1,6 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:whisper/models/private_message.dart'; -import 'package:whisper/pages/chat_info_page.dart'; +import 'package:whisper/utils/message_notifier.dart'; PrivateMessage message(String? type, String? path, DateTime sentAt, {int? downloadStatus}) { @@ -13,7 +13,7 @@ PrivateMessage message(String? type, String? path, DateTime sentAt, void main() { test('shared media keeps only ready, viewable media with a local file', () { final now = DateTime(2026, 11, 12, 12); - final media = ChatInfoPage.sharedMedia([ + final media = MessageNotifier.viewableMedia([ message('image', '/tmp/a.jpg', now), message('video', '/tmp/b.mp4', now.subtract(const Duration(minutes: 1))), // Voice messages are not part of the overview From f6198309b863f663e6a6213495f59ce157b7ec67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 01:52:08 +0100 Subject: [PATCH 035/181] feat(chat): open Chat Info from the header avatar and name The page push moved into _openChatInfo so the avatar, the name and the info button share it, including the theme reload when coming back. --- lib/pages/chat_page.dart | 55 +++++++++++++++++++++++----------------- 1 file changed, 32 insertions(+), 23 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index e8b4519..062e495 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -80,6 +80,19 @@ class _ChatPageState extends State { setState(() {}); } + /// Open the chat info page (avatar and name in the header, info button). + Future _openChatInfo() async { + await Navigator.of(context).push(PageTransition( + duration: const Duration(milliseconds: 300), + reverseDuration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + type: PageTransitionType.rightToLeftJoined, + child: ChatInfoPage(widget.user.id), + childCurrent: widget)); + // The theme may have changed while the info page was open + await _loadChatTheme(); + } + /// Send message Future _sendMessage() async { final text = _controllerMessage.text; @@ -524,16 +537,19 @@ class _ChatPageState extends State { icon: const Icon(Icons.arrow_back), onPressed: () => Navigator.pop(context), ), - CircleAvatar( - radius: 18, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 16, - color: widget.user.avatarTextColor, + GestureDetector( + onTap: _openChatInfo, + child: CircleAvatar( + radius: 18, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 16, + color: widget.user.avatarTextColor, + ), ), ), ), @@ -541,24 +557,17 @@ class _ChatPageState extends State { ), leadingWidth: 96, // Increase width to accommodate both icons // Title - title: Text(widget.user.username), + title: GestureDetector( + onTap: _openChatInfo, + behavior: HitTestBehavior.opaque, + child: Text(widget.user.username), + ), // Action buttons actions: [ IconButton( icon: const Icon(Icons.info), tooltip: 'infoButton'.tr(), - onPressed: () async { - // Push info page - await Navigator.of(context).push(PageTransition( - duration: const Duration(milliseconds: 300), - reverseDuration: const Duration(milliseconds: 300), - curve: Curves.easeInOut, - type: PageTransitionType.rightToLeftJoined, - child: ChatInfoPage(widget.user.id), - childCurrent: widget)); - // The theme may have changed while the info page was open - await _loadChatTheme(); - }, + onPressed: _openChatInfo, ), ], ), From 01c2c1fd7934eb0ac149e9d29eefe956dc9a0629 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 02:45:14 +0100 Subject: [PATCH 036/181] feat(chat): send and open any file type The File entry in the attachment sheet now offers every file, non-media uploads travel as MediaType.file with their original name, and a document bubble shows icon, name and size. The viewer has a file page (name, size, save, and a text preview for text extensions up to 256 KB), documents show an extension tile in the Chat Info gallery, and uploading more than the server's 25 MiB limit is refused up front with a message. --- assets/translations/cs.json | 5 +- assets/translations/en.json | 5 +- lib/models/invite_data.dart | 5 +- lib/models/private_message.dart | 7 ++ lib/models/private_message.g.dart | 7 +- lib/pages/chat_info_page.dart | 38 +++++++++-- lib/pages/chat_page.dart | 15 ++++- lib/pages/forward_page.dart | 3 +- lib/pages/media_viewer_page.dart | 76 +++++++++++++++++++++- lib/utils/chat_sender.dart | 8 ++- lib/utils/media_utils.dart | 67 ++++++++++++++++++-- lib/utils/message_actions.dart | 2 +- lib/utils/theme_notifier.dart | 3 +- lib/utils/utils.dart | 6 +- lib/utils/websocket_manager.dart | 2 +- lib/widgets/chat_list_item.dart | 6 +- lib/widgets/invite_list_item.dart | 2 +- lib/widgets/media_bubble.dart | 50 ++++++++++++++- lib/widgets/select_user_list_item.dart | 2 +- lib/widgets/voice_player.dart | 15 +++-- test/crypto_test.dart | 11 ++-- test/date_format_test.dart | 2 +- test/file_media_test.dart | 88 ++++++++++++++++++++++++++ 23 files changed, 380 insertions(+), 45 deletions(-) create mode 100644 test/file_media_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 6272fba..6ba893d 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -128,5 +128,8 @@ "attachmentSaveFailed": "Uložení přílohy se nepovedlo", "forwardTo": "Přeposlat komu", "forwarded": "Přeposláno", - "noChatsToForward": "Zatím žádné chaty, vyhledej uživatele" + "noChatsToForward": "Zatím žádné chaty, vyhledej uživatele", + "mediaFile": "Soubor", + "fileTooLarge": "Soubor je příliš velký, maximum je", + "fileTooLargeToPreview": "Soubor je pro náhled příliš velký, ulož si ho." } diff --git a/assets/translations/en.json b/assets/translations/en.json index 278788a..0aefe93 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -128,5 +128,8 @@ "attachmentSaveFailed": "Saving the attachment failed", "forwardTo": "Forward to", "forwarded": "Forwarded", - "noChatsToForward": "No chats yet, search for a user" + "noChatsToForward": "No chats yet, search for a user", + "mediaFile": "File", + "fileTooLarge": "File is too large, the maximum is", + "fileTooLargeToPreview": "The file is too large to preview, save it instead." } diff --git a/lib/models/invite_data.dart b/lib/models/invite_data.dart index 20f0ec8..6697962 100644 --- a/lib/models/invite_data.dart +++ b/lib/models/invite_data.dart @@ -12,5 +12,6 @@ class InviteData { String code; DateTime validUntil; - factory InviteData.fromJson(Map json) => _$InviteDataFromJson(json); -} \ No newline at end of file + factory InviteData.fromJson(Map json) => + _$InviteDataFromJson(json); +} diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index 3511ff6..3ac2bfa 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -66,6 +66,10 @@ class PrivateMessage extends HiveObject { @HiveField(12, defaultValue: MediaDownloadStatus.ready) int downloadStatus; + /// Original file name including the extension (documents etc.). + @HiveField(13) + String? fileName; + PrivateMessage( this.senderId, this.message, @@ -80,6 +84,7 @@ class PrivateMessage extends HiveObject { this.height, this.durationMs, this.downloadStatus = MediaDownloadStatus.ready, + this.fileName, }); bool get isMe => senderId == Singleton().profile.user.id; @@ -116,6 +121,8 @@ class PrivateMessage extends HiveObject { return 'mediaVideo'.tr(); case MediaType.voice: return 'mediaVoice'.tr(); + case MediaType.file: + return fileName ?? 'mediaFile'.tr(); case null: return message; } diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index ed67492..3e96378 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -30,13 +30,14 @@ class PrivateMessageAdapter extends TypeAdapter { height: fields[10] as int?, durationMs: fields[11] as int?, downloadStatus: fields[12] == null ? 1 : fields[12] as int, + fileName: fields[13] as String?, ); } @override void write(BinaryWriter writer, PrivateMessage obj) { writer - ..writeByte(13) + ..writeByte(14) ..writeByte(0) ..write(obj.senderId) ..writeByte(1) @@ -62,7 +63,9 @@ class PrivateMessageAdapter extends TypeAdapter { ..writeByte(11) ..write(obj.durationMs) ..writeByte(12) - ..write(obj.downloadStatus); + ..write(obj.downloadStatus) + ..writeByte(13) + ..write(obj.fileName); } @override diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 25e861e..eff8b85 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -247,8 +247,9 @@ class _MediaTileState extends State<_MediaTile> { } Future _loadImage() async { - // Videos have no thumbnail generator, the play icon is enough. - if (widget.message.mediaType == MediaType.video) { + // Videos and documents have no thumbnail, an icon is enough. + if (widget.message.mediaType == MediaType.video || + widget.message.mediaType == MediaType.file) { return; } final path = widget.message.localPath; @@ -274,6 +275,7 @@ class _MediaTileState extends State<_MediaTile> { @override Widget build(BuildContext context) { final isVideo = widget.message.mediaType == MediaType.video; + final isFile = widget.message.mediaType == MediaType.file; return GestureDetector( onTap: widget.onTap, child: Container( @@ -285,13 +287,35 @@ class _MediaTileState extends State<_MediaTile> { ? Icon(Icons.broken_image, size: 24) : isVideo ? Icon(Icons.play_arrow, size: 32) - : SizedBox( - width: 18, - height: 18, - child: CircularProgressIndicator(strokeWidth: 2), - ), + : isFile + ? _fileTile() + : SizedBox( + width: 18, + height: 18, + child: + CircularProgressIndicator(strokeWidth: 2), + ), ), ), ); } + + /// Documents: extension badge instead of a thumbnail. + Widget _fileTile() { + final name = widget.message.fileName ?? ''; + final dot = name.lastIndexOf('.'); + final extension = + dot > 0 && dot < name.length - 1 ? name.substring(dot + 1) : ''; + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.insert_drive_file, size: 24), + if (extension.isNotEmpty) + Text( + extension.toUpperCase(), + style: const TextStyle(fontSize: 10, fontWeight: FontWeight.bold), + ), + ], + ); + } } diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 062e495..d386b60 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -125,6 +125,15 @@ class _ChatPageState extends State { try { final bytes = await file.readAsBytes(); + // Refuse what the server would reject anyway, before uploading it. + if (bytes.length > MediaUtils.maxUploadBytes) { + await Fluttertoast.showToast( + msg: + '${'fileTooLarge'.tr()} ${MediaUtils.formatBytes(MediaUtils.maxUploadBytes)}', + backgroundColor: Colors.red); + return; + } + // Probe metadata depending on the media type. int? width; int? height; @@ -141,7 +150,11 @@ class _ChatPageState extends State { } final sent = await ChatSender.sendMedia(widget.user, type, bytes, - caption: caption, width: width, height: height, durationMs: duration); + caption: caption, + width: width, + height: height, + durationMs: duration, + fileName: MediaUtils.baseName(file.path)); // The caption (taken from the text field) was consumed -> clear it. if (sent && caption.isNotEmpty && _controllerMessage.text == caption) { diff --git a/lib/pages/forward_page.dart b/lib/pages/forward_page.dart index 415225a..49b08c1 100644 --- a/lib/pages/forward_page.dart +++ b/lib/pages/forward_page.dart @@ -61,7 +61,8 @@ class _ForwardPageState extends State { caption: message.message, width: message.width, height: message.height, - durationMs: message.durationMs); + durationMs: message.durationMs, + fileName: message.fileName); } else { sent = await ChatSender.sendText(to, message.message); } diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index da229fc..0fa87ae 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -1,3 +1,4 @@ +import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; @@ -172,10 +173,15 @@ class _MediaPageState extends State<_MediaPage> { bool _loading = true; bool _error = false; + /// Decrypted text preview of a text file, null when there is none. + String? _text; + MediaType get _type => widget.message.mediaType ?? MediaType.image; bool get _isVideo => _type == MediaType.video; + bool get _isFile => _type == MediaType.file; + @override void initState() { super.initState(); @@ -188,7 +194,15 @@ class _MediaPageState extends State<_MediaPage> { if (localPath == null) { throw Exception('no local media'); } - if (_isVideo) { + if (_isFile) { + // Only text files get a preview, everything else just shows its name. + final size = widget.message.mediaSize ?? 0; + if (MediaUtils.isTextFile(widget.message.fileName) && + size <= MediaUtils.maxTextPreviewBytes) { + final bytes = await MediaUtils.decryptAtRest(localPath); + _text = utf8.decode(bytes, allowMalformed: true); + } + } else if (_isVideo) { _tempFile = await MediaUtils.materializeTempFile( localPath, MediaUtils.extensionForType(_type)); final controller = VideoPlayerController.file(_tempFile!); @@ -235,6 +249,9 @@ class _MediaPageState extends State<_MediaPage> { return Text('mediaError'.tr(), style: const TextStyle(color: Colors.white)); } + if (_isFile) { + return _filePage(); + } if (_isVideo && _chewieController != null) { return AspectRatio( aspectRatio: _videoController!.value.aspectRatio, @@ -252,4 +269,61 @@ class _MediaPageState extends State<_MediaPage> { } return Text('mediaError'.tr(), style: const TextStyle(color: Colors.white)); } + + /// File page: name, size, save button and a text preview when we have one. + Widget _filePage() { + final message = widget.message; + final name = message.fileName ?? 'mediaFile'.tr(); + final text = _text; + return Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.insert_drive_file, color: Colors.white, size: 64), + const SizedBox(height: 12), + Text( + name, + textAlign: TextAlign.center, + style: const TextStyle(color: Colors.white, fontSize: 16), + ), + if (message.mediaSize != null) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + MediaUtils.formatBytes(message.mediaSize!), + style: const TextStyle(color: Colors.white70, fontSize: 12), + ), + ), + const SizedBox(height: 16), + FilledButton.icon( + onPressed: () => MessageActions.save(message), + icon: const Icon(Icons.download), + label: Text('saveAttachment'.tr()), + ), + const SizedBox(height: 24), + if (text != null) + Expanded( + child: SingleChildScrollView( + child: SelectableText( + text, + style: const TextStyle( + color: Colors.white, + fontFamily: 'monospace', + fontSize: 12, + ), + ), + ), + ) + else if (MediaUtils.isTextFile(message.fileName) && + (message.mediaSize ?? 0) > MediaUtils.maxTextPreviewBytes) + Text( + 'fileTooLargeToPreview'.tr(), + textAlign: TextAlign.center, + style: const TextStyle(color: Colors.white70, fontSize: 12), + ), + ], + ), + ); + } } diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index 3a78a7b..6724576 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -53,7 +53,11 @@ class ChatSender { /// Send [bytes] as a media attachment of [type] to [recipient]. The caller /// supplies the probed metadata so `null` there is meaningful. static Future sendMedia(User recipient, MediaType type, Uint8List bytes, - {String caption = '', int? width, int? height, int? durationMs}) async { + {String caption = '', + int? width, + int? height, + int? durationMs, + String? fileName}) async { try { await Utils.wsConnect(); if (!Singleton().wsClient.isConnected) { @@ -90,6 +94,7 @@ class ChatSender { width: width, height: height, durationMs: durationMs, + fileName: fileName, ); final envelope = MediaUtils.buildMediaEnvelope(reference, caption); @@ -120,6 +125,7 @@ class ChatSender { height: height, durationMs: durationMs, downloadStatus: MediaDownloadStatus.ready, + fileName: fileName, ) ]); return true; diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 9e483b7..d487da9 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -277,16 +277,21 @@ class MediaUtils { if (mime == 'image/gif' || lower.endsWith('.gif')) { return MediaType.gif; } + if (mime.startsWith('image/')) { + return MediaType.image; + } if (mime.startsWith('video/')) { return MediaType.video; } if (mime.startsWith('audio/')) { return MediaType.voice; } - return MediaType.image; + // Anything else is sent as a plain file. + return MediaType.file; } - /// Default file extension used when materializing a temp file for playback. + /// Default file extension used when materializing a temp file for playback, + /// or as a last resort when a real name is not known. static String extensionForType(MediaType type) { switch (type) { case MediaType.image: @@ -297,7 +302,59 @@ class MediaUtils { return '.mp4'; case MediaType.voice: return '.m4a'; + case MediaType.file: + return ''; + } + } + + /// Largest upload the server accepts (mirrors MEDIA_MAX_UPLOAD_SIZE). + static const int maxUploadBytes = 25 * 1024 * 1024; + + /// Largest text file the viewer renders as a preview. + static const int maxTextPreviewBytes = 256 * 1024; + + /// Last path segment of [path], i.e. the file name with its extension. + static String baseName(String path) => path.split(RegExp(r'[\\/]')).last; + + /// Extensions whose content can be shown as text in the viewer. + static const Set textExtensions = { + 'txt', + 'md', + 'log', + 'csv', + 'json', + 'xml', + 'yaml', + 'yml', + 'ini', + 'html', + }; + + /// Whether [fileName] is a text file we can preview. + static bool isTextFile(String? fileName) { + if (fileName == null) { + return false; + } + final dot = fileName.lastIndexOf('.'); + if (dot < 0 || dot == fileName.length - 1) { + return false; + } + return textExtensions.contains(fileName.substring(dot + 1).toLowerCase()); + } + + /// Human readable size, e.g. `1.4 MB`. + static String formatBytes(int bytes) { + if (bytes < 1024) { + return '$bytes B'; + } + const units = ['KB', 'MB', 'GB']; + double value = bytes / 1024; + var unit = 0; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit++; } + return '${value.toStringAsFixed(value >= 10 ? 0 : 1)} ${units[unit]}'; } /// Translation key for a short human label of a media type (used in previews @@ -312,6 +369,8 @@ class MediaUtils { return 'mediaVideo'; case MediaType.voice: return 'mediaVoice'; + case MediaType.file: + return 'mediaFile'; } } @@ -414,9 +473,9 @@ class MediaUtils { return picked == null ? null : File(picked.path); } - /// Pick an arbitrary media (image/video) file. + /// Pick an arbitrary file (images, videos, documents, ...). static Future pickFile() async { - final picked = await FilePicker.pickFile(type: FileType.media); + final picked = await FilePicker.pickFile(type: FileType.any); final path = picked?.path; return path == null ? null : File(path); } diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index c6e2420..393bea3 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -96,7 +96,7 @@ class MessageActions { final bytes = await MediaUtils.decryptAtRest(path); final saved = await FilePicker.saveFile( dialogTitle: 'saveAttachment'.tr(), - fileName: + fileName: message.fileName ?? 'whisper_${message.sentAt.millisecondsSinceEpoch}${MediaUtils.extensionForType(type)}', bytes: bytes, ); diff --git a/lib/utils/theme_notifier.dart b/lib/utils/theme_notifier.dart index e9d92be..6d715ce 100644 --- a/lib/utils/theme_notifier.dart +++ b/lib/utils/theme_notifier.dart @@ -3,7 +3,6 @@ import '../models/app_theme.dart'; // https://stackoverflow.com/a/65517149/19371130 class ThemeNotifier extends ChangeNotifier { - ThemeNotifier(this.appTheme); AppTheme appTheme; @@ -12,4 +11,4 @@ class ThemeNotifier extends ChangeNotifier { appTheme = theme; return notifyListeners(); } -} \ No newline at end of file +} diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 2342882..fc87f27 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -181,6 +181,7 @@ class Utils { width: ref.width, height: ref.height, durationMs: ref.durationMs, + fileName: ref.fileName, downloadStatus: pm.MediaDownloadStatus.pending, ); return (mediaMsg, ref); @@ -206,8 +207,9 @@ class Utils { final results = await Future.wait(decryptionTasks); // Filter out failed decryptions (null values) - final valid = - results.whereType<(pm.PrivateMessage, MediaReference?)>().toList(); + final valid = results + .whereType<(pm.PrivateMessage, MediaReference?)>() + .toList(); decryptedMessages = valid.map((e) => e.$1).toList(); pendingMediaRefs = valid.map((e) => e.$2).whereType().toList(); diff --git a/lib/utils/websocket_manager.dart b/lib/utils/websocket_manager.dart index 311cab5..18b5090 100644 --- a/lib/utils/websocket_manager.dart +++ b/lib/utils/websocket_manager.dart @@ -24,4 +24,4 @@ class WebSocketManager { void stopConnectionCheck() { _timer?.cancel(); } -} \ No newline at end of file +} diff --git a/lib/widgets/chat_list_item.dart b/lib/widgets/chat_list_item.dart index a28944a..b4cc8f0 100644 --- a/lib/widgets/chat_list_item.dart +++ b/lib/widgets/chat_list_item.dart @@ -67,11 +67,15 @@ class _ChatListItemState extends State { case MediaType.voice: preview = '🎤 $preview'; break; + case MediaType.file: + preview = '📄 $preview'; + break; case null: break; } } - String msg = preview.length <= 14 ? preview : '${preview.substring(0, 14)}...'; + String msg = + preview.length <= 14 ? preview : '${preview.substring(0, 14)}...'; return meText + msg; } diff --git a/lib/widgets/invite_list_item.dart b/lib/widgets/invite_list_item.dart index 8b8acc0..7d05485 100644 --- a/lib/widgets/invite_list_item.dart +++ b/lib/widgets/invite_list_item.dart @@ -45,7 +45,7 @@ class _UserListItemState extends State { displayDuration.toString().split('.').first.padLeft(8, '0'); return ListTile( - onTap: () {}, // Empty method so that the visual effect works + onTap: () {}, // Empty method so that the visual effect works tileColor: Colors.transparent, selectedTileColor: Theme.of(context).colorScheme.primaryContainer, shape: RoundedRectangleBorder( diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index c611d78..f87a6ee 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -129,14 +129,17 @@ class _MediaBubbleState extends State { case MediaType.voice: media = _voiceWidget(); break; + case MediaType.file: + media = _fileWidget(); + break; case null: media = _placeholder(child: const Icon(Icons.broken_image)); } } - final isVoice = type == MediaType.voice; - if (isVoice) { - // Voice messages live inside the coloured bubble. + // Voice and file messages live inside the coloured bubble. + final insideBubble = type == MediaType.voice || type == MediaType.file; + if (insideBubble) { return Container( decoration: BoxDecoration( color: widget.bubbleColor, @@ -294,6 +297,47 @@ class _MediaBubbleState extends State { ); } + /// Document bubble: icon, file name and size; opens the viewer's file page. + Widget _fileWidget() { + final name = widget.message.fileName ?? 'mediaFile'.tr(); + return GestureDetector( + onTap: _openViewer, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.insert_drive_file, color: widget.textColor, size: 32), + const SizedBox(width: 8), + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 180), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + name, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: widget.textColor), + ), + if (widget.message.mediaSize != null) + Text( + MediaUtils.formatBytes(widget.message.mediaSize!), + style: TextStyle( + color: widget.textColor.withValues(alpha: 0.7), + fontSize: 11, + ), + ), + ], + ), + ), + ], + ), + ), + ); + } + String _formatDuration(int ms) { final d = Duration(milliseconds: ms); final minutes = d.inMinutes.remainder(60).toString().padLeft(2, '0'); diff --git a/lib/widgets/select_user_list_item.dart b/lib/widgets/select_user_list_item.dart index 17e5291..e47aa1f 100644 --- a/lib/widgets/select_user_list_item.dart +++ b/lib/widgets/select_user_list_item.dart @@ -17,7 +17,7 @@ class _SelectUserListItemState extends State { @override Widget build(BuildContext context) { return ListTile( - onTap: () {}, // Empty method so that the visual effect works + onTap: () {}, // Empty method so that the visual effect works tileColor: Colors.transparent, selectedTileColor: Theme.of(context).colorScheme.primaryContainer, shape: RoundedRectangleBorder( diff --git a/lib/widgets/voice_player.dart b/lib/widgets/voice_player.dart index 56093e0..099e26f 100644 --- a/lib/widgets/voice_player.dart +++ b/lib/widgets/voice_player.dart @@ -40,7 +40,8 @@ class _VoicePlayerState extends State { Future _prepare() async { try { - _tempFile = await MediaUtils.materializeTempFile(widget.localPath, '.m4a'); + _tempFile = + await MediaUtils.materializeTempFile(widget.localPath, '.m4a'); await _player.setFilePath(_tempFile!.path); if (mounted) { setState(() { @@ -145,10 +146,10 @@ class _VoicePlayerState extends State { SliderTheme( data: SliderTheme.of(context).copyWith( trackHeight: 2, - thumbShape: const RoundSliderThumbShape( - enabledThumbRadius: 6), - overlayShape: const RoundSliderOverlayShape( - overlayRadius: 12), + thumbShape: + const RoundSliderThumbShape(enabledThumbRadius: 6), + overlayShape: + const RoundSliderOverlayShape(overlayRadius: 12), activeTrackColor: widget.color, thumbColor: widget.color, inactiveTrackColor: widget.color.withValues(alpha: 0.3), @@ -159,8 +160,8 @@ class _VoicePlayerState extends State { value: value, onChanged: _loading ? null - : (v) => _player - .seek(Duration(milliseconds: v.toInt())), + : (v) => + _player.seek(Duration(milliseconds: v.toInt())), ), ), Align( diff --git a/test/crypto_test.dart b/test/crypto_test.dart index 87fe904..f15c974 100644 --- a/test/crypto_test.dart +++ b/test/crypto_test.dart @@ -5,14 +5,17 @@ import 'package:whisper/utils/crypto_utils.dart'; void main() async { test('generate RSA keypair asynchronously', () async { - var keyPair = await CryptoUtils.getRSAKeyPair(); - debugPrint('${bu.CryptoUtils.encodeRSAPublicKeyToPem(keyPair.publicKey as bu.RSAPublicKey)}\n'); - debugPrint('${bu.CryptoUtils.encodeRSAPrivateKeyToPem(keyPair.privateKey as bu.RSAPrivateKey)}\n'); + var keyPair = await CryptoUtils.getRSAKeyPair(); + debugPrint( + '${bu.CryptoUtils.encodeRSAPublicKeyToPem(keyPair.publicKey as bu.RSAPublicKey)}\n'); + debugPrint( + '${bu.CryptoUtils.encodeRSAPrivateKeyToPem(keyPair.privateKey as bu.RSAPrivateKey)}\n'); }); test('generate JWT token', () async { var keyPair = await CryptoUtils.getRSAKeyPair(); - final token = await CryptoUtils.generateRsaJwt(1, keyPair.privateKey as bu.RSAPrivateKey); + final token = await CryptoUtils.generateRsaJwt( + 1, keyPair.privateKey as bu.RSAPrivateKey); debugPrint(token); }); } diff --git a/test/date_format_test.dart b/test/date_format_test.dart index 0adc25f..aec57c5 100644 --- a/test/date_format_test.dart +++ b/test/date_format_test.dart @@ -17,4 +17,4 @@ void main() { // Friday debugPrint(DateFormat.EEEE().format(DateTime.now().toLocal())); }); -} \ No newline at end of file +} diff --git a/test/file_media_test.dart b/test/file_media_test.dart new file mode 100644 index 0000000..c8a01bf --- /dev/null +++ b/test/file_media_test.dart @@ -0,0 +1,88 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper/utils/media_utils.dart'; +import 'package:whisper/utils/message_notifier.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +PrivateMessage media(String type, String? path, DateTime sentAt, + {String? fileName, int size = 1024}) { + return PrivateMessage(1, '', sentAt, sentAt, false, + mediaTypeStr: type, + localPath: path, + mediaSize: size, + fileName: fileName, + downloadStatus: MediaDownloadStatus.ready); +} + +void main() { + group('detectType', () { + test('documents become files', () { + expect(MediaUtils.detectType('/tmp/invoice.pdf'), MediaType.file); + expect(MediaUtils.detectType('/tmp/archive.zip'), MediaType.file); + }); + + test('known media keeps its own type', () { + expect(MediaUtils.detectType('/tmp/photo.png'), MediaType.image); + expect(MediaUtils.detectType('/tmp/anim.gif'), MediaType.gif); + expect(MediaUtils.detectType('/tmp/clip.mp4'), MediaType.video); + expect(MediaUtils.detectType('/tmp/song.mp3'), MediaType.voice); + }); + }); + + test('baseName keeps the name with its extension', () { + expect( + MediaUtils.baseName('/data/user/0/files/invoice.pdf'), 'invoice.pdf'); + expect(MediaUtils.baseName('no-slash.txt'), 'no-slash.txt'); + }); + + test('text previews are limited to text extensions', () { + expect(MediaUtils.isTextFile('notes.txt'), isTrue); + expect(MediaUtils.isTextFile('DATA.CSV'), isTrue); + expect(MediaUtils.isTextFile('invoice.pdf'), isFalse); + expect(MediaUtils.isTextFile('README'), isFalse); + expect(MediaUtils.isTextFile(null), isFalse); + }); + + test('sizes are formatted for the bubble', () { + expect(MediaUtils.formatBytes(512), '512 B'); + expect(MediaUtils.formatBytes(2048), '2.0 KB'); + expect(MediaUtils.formatBytes(3 * 1024 * 1024), '3.0 MB'); + }); + + test('a document without a caption previews its name', () { + final message = media('file', '/tmp/invoice.pdf', DateTime(2026, 11, 13), + fileName: 'invoice.pdf'); + expect(message.preview, 'invoice.pdf'); + expect(message.mediaType, MediaType.file); + }); + + test('shared media keeps documents, still drops voice', () { + final now = DateTime(2026, 11, 13, 12); + final viewable = MessageNotifier.viewableMedia([ + media('file', '/tmp/a.pdf', now, fileName: 'a.pdf'), + media('voice', '/tmp/b.m4a', now.subtract(const Duration(minutes: 1))), + ]); + expect(viewable.map((m) => m.fileName), ['a.pdf']); + }); + + test('the file name survives a Hive round trip', () async { + final dir = Directory.systemTemp.createTempSync('whisper_file_media_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + + final message = + media('file', null, DateTime(2026, 11, 13), fileName: 'a.pdf'); + await CacheUtils.addPrivateMessages(7, [message]); + final stored = await CacheUtils.getPrivateMessages(7); + + expect(stored.single.fileName, 'a.pdf'); + expect(stored.single.mediaTypeStr, 'file'); + + await Hive.close(); + dir.deleteSync(recursive: true); + }); +} From 3c9252437e932ea9a72548780d93ad4e24418beb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 02:46:02 +0100 Subject: [PATCH 037/181] test(chat): document bubble rendering --- test/file_media_test.dart | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/test/file_media_test.dart b/test/file_media_test.dart index c8a01bf..5214c94 100644 --- a/test/file_media_test.dart +++ b/test/file_media_test.dart @@ -1,11 +1,13 @@ import 'dart:io'; +import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; import 'package:whisper/models/private_message.dart'; import 'package:whisper/utils/cache_utils.dart'; import 'package:whisper/utils/media_utils.dart'; import 'package:whisper/utils/message_notifier.dart'; +import 'package:whisper/widgets/media_bubble.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; PrivateMessage media(String type, String? path, DateTime sentAt, @@ -85,4 +87,28 @@ void main() { await Hive.close(); dir.deleteSync(recursive: true); }); + + testWidgets('the document bubble shows the name and the size', + (tester) async { + final message = media('file', '/tmp/invoice.pdf', DateTime(2026, 11, 13), + fileName: 'invoice.pdf', size: 2048); + + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: MediaBubble( + message: message, + bubbleColor: Colors.blue, + textColor: Colors.white, + onRetry: () {}, + canRetry: false, + conversationUserId: 1, + ), + ), + )); + await tester.pump(); + + expect(find.text('invoice.pdf'), findsOneWidget); + expect(find.text('2.0 KB'), findsOneWidget); + expect(find.byIcon(Icons.insert_drive_file), findsOneWidget); + }); } From 01aff95401ab771677097c4c239c32eb7d82d52a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 02:58:41 +0100 Subject: [PATCH 038/181] fix(media): show the real file size on received attachments The reference carries the encrypted size, so a received file looked 28 bytes bigger than the original. A finished download now stores the plaintext length. --- lib/utils/cache_utils.dart | 6 +++++- lib/utils/message_notifier.dart | 2 ++ test/file_media_test.dart | 7 +++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 7d075e5..98e7036 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -332,8 +332,9 @@ class CacheUtils { } /// Update the local media state of a stored message (download progress). + /// [mediaSize] replaces the reference's encrypted size with the real one. static Future updatePrivateMessageMedia(int userId, String mediaId, - {String? localPath, int? downloadStatus}) async { + {String? localPath, int? downloadStatus, int? mediaSize}) async { Box box = await _openPrivateMessagesBox(); List? messages = box.get(userId); if (messages == null) { @@ -349,6 +350,9 @@ class CacheUtils { if (downloadStatus != null) { msg.downloadStatus = downloadStatus; } + if (mediaSize != null) { + msg.mediaSize = mediaSize; + } changed = true; } } diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index 312211e..4e039c8 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -64,6 +64,8 @@ class MessageNotifier extends ChangeNotifier { reference.mediaId, localPath: localPath, downloadStatus: MediaDownloadStatus.ready, + // The reference carries the encrypted size; show the real one. + mediaSize: plaintext.length, ); _pendingMediaRefs.remove(reference.mediaId); notifyListeners(); diff --git a/test/file_media_test.dart b/test/file_media_test.dart index 5214c94..acfe3ea 100644 --- a/test/file_media_test.dart +++ b/test/file_media_test.dart @@ -78,12 +78,19 @@ void main() { final message = media('file', null, DateTime(2026, 11, 13), fileName: 'a.pdf'); + message.mediaId = 'media-1'; await CacheUtils.addPrivateMessages(7, [message]); final stored = await CacheUtils.getPrivateMessages(7); expect(stored.single.fileName, 'a.pdf'); expect(stored.single.mediaTypeStr, 'file'); + // A finished download replaces the encrypted size with the real one + await CacheUtils.updatePrivateMessageMedia(7, stored.single.mediaId!, + downloadStatus: MediaDownloadStatus.ready, mediaSize: 4096); + final updated = await CacheUtils.getPrivateMessages(7); + expect(updated.single.mediaSize, 4096); + await Hive.close(); dir.deleteSync(recursive: true); }); From 8b48787c63ec7efeed049e97c3c99f904de6e1a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 03:05:35 +0100 Subject: [PATCH 039/181] feat(media): icons by document type, no text preview Documents are shown by their icon, name and size everywhere (bubble, viewer, gallery) instead of rendering text content; the icon follows the extension (pdf, doc, xls, ppt, archive, code, text and a plain file fallback). --- assets/translations/cs.json | 3 +- assets/translations/en.json | 3 +- lib/pages/chat_info_page.dart | 2 +- lib/pages/media_viewer_page.dart | 39 ++---------------- lib/utils/media_utils.dart | 69 ++++++++++++++++++++------------ lib/widgets/media_bubble.dart | 3 +- test/file_media_test.dart | 17 ++++---- 7 files changed, 62 insertions(+), 74 deletions(-) diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 6ba893d..12f3adc 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -130,6 +130,5 @@ "forwarded": "Přeposláno", "noChatsToForward": "Zatím žádné chaty, vyhledej uživatele", "mediaFile": "Soubor", - "fileTooLarge": "Soubor je příliš velký, maximum je", - "fileTooLargeToPreview": "Soubor je pro náhled příliš velký, ulož si ho." + "fileTooLarge": "Soubor je příliš velký, maximum je" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 0aefe93..b8f8150 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -130,6 +130,5 @@ "forwarded": "Forwarded", "noChatsToForward": "No chats yet, search for a user", "mediaFile": "File", - "fileTooLarge": "File is too large, the maximum is", - "fileTooLargeToPreview": "The file is too large to preview, save it instead." + "fileTooLarge": "File is too large, the maximum is" } diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index eff8b85..eea5d0e 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -309,7 +309,7 @@ class _MediaTileState extends State<_MediaTile> { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Icon(Icons.insert_drive_file, size: 24), + Icon(MediaUtils.iconForFileName(widget.message.fileName), size: 24), if (extension.isNotEmpty) Text( extension.toUpperCase(), diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index 0fa87ae..f53ee83 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -1,4 +1,3 @@ -import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; @@ -173,9 +172,6 @@ class _MediaPageState extends State<_MediaPage> { bool _loading = true; bool _error = false; - /// Decrypted text preview of a text file, null when there is none. - String? _text; - MediaType get _type => widget.message.mediaType ?? MediaType.image; bool get _isVideo => _type == MediaType.video; @@ -195,13 +191,7 @@ class _MediaPageState extends State<_MediaPage> { throw Exception('no local media'); } if (_isFile) { - // Only text files get a preview, everything else just shows its name. - final size = widget.message.mediaSize ?? 0; - if (MediaUtils.isTextFile(widget.message.fileName) && - size <= MediaUtils.maxTextPreviewBytes) { - final bytes = await MediaUtils.decryptAtRest(localPath); - _text = utf8.decode(bytes, allowMalformed: true); - } + // A file shows its icon and metadata, never its content. } else if (_isVideo) { _tempFile = await MediaUtils.materializeTempFile( localPath, MediaUtils.extensionForType(_type)); @@ -270,17 +260,17 @@ class _MediaPageState extends State<_MediaPage> { return Text('mediaError'.tr(), style: const TextStyle(color: Colors.white)); } - /// File page: name, size, save button and a text preview when we have one. + /// File page: icon, name, size and a save button. Widget _filePage() { final message = widget.message; final name = message.fileName ?? 'mediaFile'.tr(); - final text = _text; return Padding( padding: const EdgeInsets.all(24), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Icon(Icons.insert_drive_file, color: Colors.white, size: 64), + Icon(MediaUtils.iconForFileName(message.fileName), + color: Colors.white, size: 64), const SizedBox(height: 12), Text( name, @@ -301,27 +291,6 @@ class _MediaPageState extends State<_MediaPage> { icon: const Icon(Icons.download), label: Text('saveAttachment'.tr()), ), - const SizedBox(height: 24), - if (text != null) - Expanded( - child: SingleChildScrollView( - child: SelectableText( - text, - style: const TextStyle( - color: Colors.white, - fontFamily: 'monospace', - fontSize: 12, - ), - ), - ), - ) - else if (MediaUtils.isTextFile(message.fileName) && - (message.mediaSize ?? 0) > MediaUtils.maxTextPreviewBytes) - Text( - 'fileTooLargeToPreview'.tr(), - textAlign: TextAlign.center, - style: const TextStyle(color: Colors.white70, fontSize: 12), - ), ], ), ); diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index d487da9..0a264c0 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -5,6 +5,7 @@ import 'dart:ui' as ui; import 'package:cryptography/cryptography.dart' as cryptography; import 'package:file_picker/file_picker.dart'; import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart' show IconData, Icons; import 'package:image_picker/image_picker.dart'; import 'package:mime/mime.dart'; import 'package:path_provider/path_provider.dart'; @@ -310,36 +311,52 @@ class MediaUtils { /// Largest upload the server accepts (mirrors MEDIA_MAX_UPLOAD_SIZE). static const int maxUploadBytes = 25 * 1024 * 1024; - /// Largest text file the viewer renders as a preview. - static const int maxTextPreviewBytes = 256 * 1024; - /// Last path segment of [path], i.e. the file name with its extension. static String baseName(String path) => path.split(RegExp(r'[\\/]')).last; - /// Extensions whose content can be shown as text in the viewer. - static const Set textExtensions = { - 'txt', - 'md', - 'log', - 'csv', - 'json', - 'xml', - 'yaml', - 'yml', - 'ini', - 'html', - }; - - /// Whether [fileName] is a text file we can preview. - static bool isTextFile(String? fileName) { - if (fileName == null) { - return false; - } - final dot = fileName.lastIndexOf('.'); - if (dot < 0 || dot == fileName.length - 1) { - return false; + /// Icon for a document, picked from its extension. Everything unknown falls + /// back to a plain file. + static IconData iconForFileName(String? fileName) { + final dot = fileName?.lastIndexOf('.') ?? -1; + final extension = dot >= 0 && dot < (fileName!.length - 1) + ? fileName.substring(dot + 1).toLowerCase() + : ''; + switch (extension) { + case 'pdf': + return Icons.picture_as_pdf; + case 'doc': + case 'docx': + case 'odt': + case 'rtf': + return Icons.description; + case 'xls': + case 'xlsx': + case 'ods': + case 'csv': + return Icons.table_chart; + case 'ppt': + case 'pptx': + case 'odp': + return Icons.slideshow; + case 'zip': + case 'rar': + case '7z': + case 'tar': + case 'gz': + return Icons.folder_zip; + case 'json': + case 'xml': + case 'yaml': + case 'yml': + case 'html': + return Icons.code; + case 'txt': + case 'md': + case 'log': + return Icons.article; + default: + return Icons.insert_drive_file; } - return textExtensions.contains(fileName.substring(dot + 1).toLowerCase()); } /// Human readable size, e.g. `1.4 MB`. diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index f87a6ee..d4c0fb6 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -307,7 +307,8 @@ class _MediaBubbleState extends State { child: Row( mainAxisSize: MainAxisSize.min, children: [ - Icon(Icons.insert_drive_file, color: widget.textColor, size: 32), + Icon(MediaUtils.iconForFileName(widget.message.fileName), + color: widget.textColor, size: 32), const SizedBox(width: 8), ConstrainedBox( constraints: const BoxConstraints(maxWidth: 180), diff --git a/test/file_media_test.dart b/test/file_media_test.dart index acfe3ea..6d84cd0 100644 --- a/test/file_media_test.dart +++ b/test/file_media_test.dart @@ -41,12 +41,15 @@ void main() { expect(MediaUtils.baseName('no-slash.txt'), 'no-slash.txt'); }); - test('text previews are limited to text extensions', () { - expect(MediaUtils.isTextFile('notes.txt'), isTrue); - expect(MediaUtils.isTextFile('DATA.CSV'), isTrue); - expect(MediaUtils.isTextFile('invoice.pdf'), isFalse); - expect(MediaUtils.isTextFile('README'), isFalse); - expect(MediaUtils.isTextFile(null), isFalse); + test('documents get an icon per type', () { + expect(MediaUtils.iconForFileName('invoice.pdf'), Icons.picture_as_pdf); + expect(MediaUtils.iconForFileName('report.docx'), Icons.description); + expect(MediaUtils.iconForFileName('budget.xlsx'), Icons.table_chart); + expect(MediaUtils.iconForFileName('slides.pptx'), Icons.slideshow); + expect(MediaUtils.iconForFileName('pack.zip'), Icons.folder_zip); + expect(MediaUtils.iconForFileName('notes.txt'), Icons.article); + expect(MediaUtils.iconForFileName('blob'), Icons.insert_drive_file); + expect(MediaUtils.iconForFileName(null), Icons.insert_drive_file); }); test('sizes are formatted for the bubble', () { @@ -116,6 +119,6 @@ void main() { expect(find.text('invoice.pdf'), findsOneWidget); expect(find.text('2.0 KB'), findsOneWidget); - expect(find.byIcon(Icons.insert_drive_file), findsOneWidget); + expect(find.byIcon(Icons.picture_as_pdf), findsOneWidget); }); } From c3d7e32013da0cf8d385a10d016d6d85f8bf5865 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 03:28:24 +0100 Subject: [PATCH 040/181] feat(media): theme the attachment viewer The viewer no longer forces a black background with white text: the scaffold, caption bar, file page and error text use the color scheme, and the app bar keeps the default styling, so light and dark follow the system theme. --- lib/pages/media_viewer_page.dart | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index f53ee83..242a6de 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -117,12 +117,10 @@ class _MediaViewerPageState extends State { Widget build(BuildContext context) { final controller = _controller; final caption = controller == null ? '' : _current.message; + final colors = Theme.of(context).colorScheme; return Scaffold( - backgroundColor: Colors.black, + backgroundColor: colors.surface, appBar: AppBar( - backgroundColor: Colors.black, - foregroundColor: Colors.white, - iconTheme: const IconThemeData(color: Colors.white), actions: controller == null ? null : [_buildActions()], ), body: controller == null @@ -139,13 +137,13 @@ class _MediaViewerPageState extends State { ), bottomNavigationBar: caption.isNotEmpty ? Container( - color: Colors.black, + color: colors.surface, padding: const EdgeInsets.all(16), child: SafeArea( top: false, child: Text( caption, - style: const TextStyle(color: Colors.white), + style: TextStyle(color: colors.onSurface), ), ), ) @@ -237,7 +235,7 @@ class _MediaPageState extends State<_MediaPage> { } if (_error) { return Text('mediaError'.tr(), - style: const TextStyle(color: Colors.white)); + style: TextStyle(color: Theme.of(context).colorScheme.onSurface)); } if (_isFile) { return _filePage(); @@ -257,32 +255,34 @@ class _MediaPageState extends State<_MediaPage> { ), ); } - return Text('mediaError'.tr(), style: const TextStyle(color: Colors.white)); + return Text('mediaError'.tr(), + style: TextStyle(color: Theme.of(context).colorScheme.onSurface)); } /// File page: icon, name, size and a save button. Widget _filePage() { final message = widget.message; final name = message.fileName ?? 'mediaFile'.tr(); + final colors = Theme.of(context).colorScheme; return Padding( padding: const EdgeInsets.all(24), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(MediaUtils.iconForFileName(message.fileName), - color: Colors.white, size: 64), + color: colors.onSurface, size: 64), const SizedBox(height: 12), Text( name, textAlign: TextAlign.center, - style: const TextStyle(color: Colors.white, fontSize: 16), + style: TextStyle(color: colors.onSurface, fontSize: 16), ), if (message.mediaSize != null) Padding( padding: const EdgeInsets.only(top: 4), child: Text( MediaUtils.formatBytes(message.mediaSize!), - style: const TextStyle(color: Colors.white70, fontSize: 12), + style: TextStyle(color: colors.onSurfaceVariant, fontSize: 12), ), ), const SizedBox(height: 16), From 3cec03e1bafa996717374c38b9a2ef545055f2b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 03:35:16 +0100 Subject: [PATCH 041/181] feat(chat): chat color in the chat color picker and the attachment viewer Both live on separate routes/layers that only see the global theme, so the colour picker dialog and the viewer route now carry the per-chat ThemeData with them. --- lib/pages/chat_info_page.dart | 22 ++++++++++++++++------ lib/widgets/media_bubble.dart | 10 +++++++--- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index eea5d0e..9866686 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -51,12 +51,18 @@ class _ChatInfoPageState extends State { } } - /// Pick a per-chat theme color + /// Pick a per-chat theme color. The dialog uses the chat color too. Future _pickChatTheme() async { Color? color = await showDialog( context: context, - builder: (context) => DialogUtils.colorPickerDialog( - context, _chatThemeColor ?? Singleton().appTheme.color)); + builder: (dialogContext) => Theme( + data: ThemeUtils.chatTheme(context, _chatThemeColor), + child: Builder( + builder: (themedContext) => DialogUtils.colorPickerDialog( + themedContext, + _chatThemeColor ?? Singleton().appTheme.color), + ), + )); if (color == null || !mounted) { return; } @@ -80,9 +86,13 @@ class _ChatInfoPageState extends State { PageTransition( type: PageTransitionType.fade, duration: const Duration(milliseconds: 200), - child: MediaViewerPage( - message: message, - conversationUserId: widget.userId, + // The viewer is a separate route, so it needs the chat theme passed in + child: Theme( + data: ThemeUtils.chatTheme(context, _chatThemeColor), + child: MediaViewerPage( + message: message, + conversationUserId: widget.userId, + ), ), ), ); diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index d4c0fb6..103b81e 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -97,9 +97,13 @@ class _MediaBubbleState extends State { PageTransition( type: PageTransitionType.fade, duration: const Duration(milliseconds: 200), - child: MediaViewerPage( - message: widget.message, - conversationUserId: widget.conversationUserId, + // The viewer is a separate route; carry the chat theme over to it + child: Theme( + data: Theme.of(context), + child: MediaViewerPage( + message: widget.message, + conversationUserId: widget.conversationUserId, + ), ), ), ); From 774e71f2d2a81241190d55c3a2daa9cd1f92e73b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 04:01:47 +0100 Subject: [PATCH 042/181] feat: user ids are UUID strings Follows the server contract: User.id and PrivateMessage.senderId are strings, box keys and pending-chat ids follow, and notification payloads carry the UUID directly. Existing local data (numeric keys, int id in the Hive adapters) is unreadable after this change: log out to clear the cache and register again with a fresh invite. --- integration_test/app_e2e_test.dart | 10 ++++----- integration_test/fake_server.dart | 18 ++++++++-------- lib/models/private_message.dart | 2 +- lib/models/private_message.g.dart | 2 +- lib/models/user.dart | 2 +- lib/models/user.g.dart | 2 +- lib/pages/chat_info_page.dart | 2 +- lib/pages/home_page.dart | 4 ++-- lib/pages/media_viewer_page.dart | 2 +- lib/utils/cache_utils.dart | 32 ++++++++++++++--------------- lib/utils/crypto_utils.dart | 2 +- lib/utils/message_actions.dart | 4 ++-- lib/utils/message_notifier.dart | 10 ++++----- lib/utils/notification_service.dart | 8 ++++---- lib/utils/singleton.dart | 2 +- lib/widgets/media_bubble.dart | 2 +- test/chat_info_media_test.dart | 2 +- test/chat_theme_test.dart | 12 +++++------ test/crypto_test.dart | 2 +- test/delete_message_test.dart | 12 +++++------ test/file_media_test.dart | 12 +++++------ test/message_actions_test.dart | 6 +++--- 22 files changed, 75 insertions(+), 75 deletions(-) diff --git a/integration_test/app_e2e_test.dart b/integration_test/app_e2e_test.dart index 2cc3030..4b027ac 100644 --- a/integration_test/app_e2e_test.dart +++ b/integration_test/app_e2e_test.dart @@ -64,13 +64,13 @@ void main() { expect(user, isNotNull); expect(user!.username, 'e2euser'); - expect(user.id, greaterThan(0)); + expect(user.id, isNotEmpty); }); testWidgets('login with RSA JWT and refresh', (tester) async { final apiClient = client(null); final jwt = await CryptoUtils.generateRsaJwt( - 1, keys.privateKey as bu.RSAPrivateKey); + '1', keys.privateKey as bu.RSAPrivateKey); final auth = await AuthenticationApi(apiClient).authUser( authUserInput: AuthUserInput(token: jwt), ); @@ -103,7 +103,7 @@ void main() { Uint8List.fromList(utf8.encode('hello over websocket')), keys.publicKey as RSAPublicKey); sender.sendMessage(WsMessage.privateMessage(NewPrivateMessage( - 1, + '1', encrypted['encryptedData']!, encrypted['encryptedKey']!, encrypted['nonce']!, @@ -112,7 +112,7 @@ void main() { final response = await received.future.timeout(const Duration(seconds: 5)); final message = (response.payload as List).single; - expect(message.senderId, 2); + expect(message.senderId, '2'); final plaintext = await CryptoUtils.decryptMessageData( message.content, @@ -134,7 +134,7 @@ void main() { final upload = await MediaApi(client('access-1')).uploadMedia( http.MultipartFile.fromBytes('file', encrypted.blob, filename: 'blob.bin'), - 2, + '2', ); expect(upload!.id, isNotEmpty); diff --git a/integration_test/fake_server.dart b/integration_test/fake_server.dart index 2454421..d5c0ae2 100644 --- a/integration_test/fake_server.dart +++ b/integration_test/fake_server.dart @@ -12,10 +12,10 @@ class FakeServer { FakeServer._(this._server); final HttpServer _server; - final Map _wsTokens = {}; - final Map _sockets = {}; + final Map _wsTokens = {}; + final Map _sockets = {}; final Map _media = {}; - final Map _mediaReceivers = {}; + final Map _mediaReceivers = {}; int _nextUserId = 1; int _nextMediaId = 1; @@ -47,7 +47,7 @@ class FakeServer { if (path == '/api/auth/register') { final body = await _readJson(request); _json(request.response, { - 'id': _nextUserId++, + 'id': 'user-${_nextUserId++}', 'username': body['username'], 'publicKey': body['publicKey'], 'admin': false, @@ -95,13 +95,13 @@ class FakeServer { return; } Uint8List? file; - var receiverId = 0; + var receiverId = ''; await for (final part in MimeMultipartTransformer(boundary).bind(request)) { final disposition = part.headers['content-disposition'] ?? ''; final bytes = await part .fold>([], (buffer, chunk) => buffer..addAll(chunk)); if (disposition.contains('name="receiverId"')) { - receiverId = int.parse(utf8.decode(bytes)); + receiverId = utf8.decode(bytes); } else if (disposition.contains('name="file"') && disposition.contains('filename=')) { file = Uint8List.fromList(bytes); @@ -147,7 +147,7 @@ class FakeServer { return; } final payload = message['payload'] as Map; - final receiverId = payload['receiverId'] as int; + final receiverId = payload['receiverId'] as String; final response = jsonEncode({ 'type': 'messages', 'payload': [ @@ -174,10 +174,10 @@ class FakeServer { return jsonDecode(body) as Map; } - int _userId(HttpRequest request) { + String _userId(HttpRequest request) { final header = request.headers.value(HttpHeaders.authorizationHeader) ?? ''; final token = header.replaceFirst('Bearer ', ''); - return int.tryParse(token.replaceFirst('access-', '')) ?? 0; + return token.replaceFirst('access-', ''); } void _json(HttpResponse response, Object body) { diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index 3ac2bfa..856682b 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -21,7 +21,7 @@ class MediaDownloadStatus { @HiveType(typeId: 3) class PrivateMessage extends HiveObject { @HiveField(0) - int senderId; + String senderId; @HiveField(1) String message; @HiveField(2) diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index 3e96378..3fc488d 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -17,7 +17,7 @@ class PrivateMessageAdapter extends TypeAdapter { for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return PrivateMessage( - fields[0] as int, + fields[0] as String, fields[1] as String, fields[2] as DateTime, fields[3] as DateTime, diff --git a/lib/models/user.dart b/lib/models/user.dart index f590509..76edb3b 100644 --- a/lib/models/user.dart +++ b/lib/models/user.dart @@ -15,7 +15,7 @@ class User extends HiveObject { } @HiveField(0) - int id; + String id; @HiveField(1) String username; @HiveField(2) diff --git a/lib/models/user.g.dart b/lib/models/user.g.dart index 5eb6eb4..a25cbe9 100644 --- a/lib/models/user.g.dart +++ b/lib/models/user.g.dart @@ -17,7 +17,7 @@ class UserAdapter extends TypeAdapter { for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return User( - fields[0] as int, + fields[0] as String, fields[1] as String, fields[2] as String, fields[3] as bool, diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 9866686..6a3e093 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -15,7 +15,7 @@ import 'media_viewer_page.dart'; class ChatInfoPage extends StatefulWidget { const ChatInfoPage(this.userId, {super.key}); - final int userId; + final String userId; @override State createState() => _ChatInfoPageState(); diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 8f6c775..95991f3 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -34,7 +34,7 @@ class HomePage extends StatefulWidget { class _HomePageState extends State { final WebSocketManager _webSocketManager = WebSocketManager(); List _serverUsers = []; - List _selectedUsers = []; + List _selectedUsers = []; int _currentPageIndex = 0; List _serverInvites = []; Map _chats = {}; @@ -204,7 +204,7 @@ class _HomePageState extends State { } /// Open the chat of [userId] on top of Home. - Future _openChat(int userId) async { + Future _openChat(String userId) async { final user = await CacheUtils.getUserById(userId); if (user == null || !mounted) { return; diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index 242a6de..693a048 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -20,7 +20,7 @@ class MediaViewerPage extends StatefulWidget { /// The other side of the conversation: the source of the other attachments /// and what the delete action needs. - final int conversationUserId; + final String conversationUserId; const MediaViewerPage({ required this.message, diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 98e7036..f95e09b 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -227,20 +227,20 @@ class CacheUtils { } /// Returns per-chat theme color, null means the global theme is used - static Future getChatTheme(int userId) async { + static Future getChatTheme(String userId) async { Box box = await _openThemeBox(); String? hex = box.get('$_chatThemeKeyPrefix$userId'); return hex == null ? null : ColorUtils.colorFromHex(hex); } /// Sets per-chat theme color - static Future setChatTheme(int userId, Color color) async { + static Future setChatTheme(String userId, Color color) async { Box box = await _openThemeBox(); await box.put('$_chatThemeKeyPrefix$userId', ColorUtils.colorToHex(color)); } /// Clears per-chat theme color, the chat falls back to the global theme - static Future clearChatTheme(int userId) async { + static Future clearChatTheme(String userId) async { Box box = await _openThemeBox(); await box.delete('$_chatThemeKeyPrefix$userId'); } @@ -269,7 +269,7 @@ class CacheUtils { /// Add user message to cache static Future addPrivateMessages( - int userId, List messages) async { + String userId, List messages) async { Box box = await _openPrivateMessagesBox(); List chatMessages = await getPrivateMessages(userId); chatMessages.addAll(messages); @@ -277,7 +277,7 @@ class CacheUtils { } /// Get user messages and mark them as read - static Future> getPrivateMessages(int userId, + static Future> getPrivateMessages(String userId, {bool markAsRead = false}) async { Box box = await _openPrivateMessagesBox(); List? messages = box.get(userId); @@ -296,7 +296,7 @@ class CacheUtils { /// Delete a single message locally (and its media file). Nothing is sent to /// the server, so the other side keeps the message. static Future deletePrivateMessage( - int userId, PrivateMessage message) async { + String userId, PrivateMessage message) async { Box box = await _openPrivateMessagesBox(); List? messages = box.get(userId); if (messages == null) { @@ -311,7 +311,7 @@ class CacheUtils { } /// Delete user messages - static Future deletePrivateMessagesWithUser(int userId) async { + static Future deletePrivateMessagesWithUser(String userId) async { Box messageBox = await _openPrivateMessagesBox(); // Delete on-disk media files for this conversation first. await _deleteMediaFilesForUser(userId); @@ -322,7 +322,7 @@ class CacheUtils { } /// Delete the encrypted-at-rest media files of all messages with [userId]. - static Future _deleteMediaFilesForUser(int userId) async { + static Future _deleteMediaFilesForUser(String userId) async { final messages = await getPrivateMessages(userId); for (final msg in messages) { if (msg.localPath != null) { @@ -333,7 +333,7 @@ class CacheUtils { /// Update the local media state of a stored message (download progress). /// [mediaSize] replaces the reference's encrypted size with the real one. - static Future updatePrivateMessageMedia(int userId, String mediaId, + static Future updatePrivateMessageMedia(String userId, String mediaId, {String? localPath, int? downloadStatus, int? mediaSize}) async { Box box = await _openPrivateMessagesBox(); List? messages = box.get(userId); @@ -367,13 +367,13 @@ class CacheUtils { } /// Gets user by ID - static Future getUserById(int userId) async { + static Future getUserById(String userId) async { Box box = await _openUserBox(); return box.get(userId); } // Check if user with ID exists - static Future userExists(int userId) async { + static Future userExists(String userId) async { Box box = await _openUserBox(); return box.containsKey(userId); } @@ -389,9 +389,9 @@ class CacheUtils { Box box = await _openPrivateMessagesBox(); Map conversations = {}; for (var entry in box.toMap().entries) { - User? user = await getUserById(entry.key as int); + User? user = await getUserById(entry.key as String); List messages = entry.value; - conversations[user ?? User(entry.key as int, '', '', false)] = + conversations[user ?? User(entry.key as String, '', '', false)] = messages.last as PrivateMessage; } // Sort conversations by last message date @@ -418,20 +418,20 @@ class CacheUtils { } /// Sets message concept for user - static Future setMessageConcept(int userId, String message) async { + static Future setMessageConcept(String userId, String message) async { Box box = await _openMessageConceptBox(); await box.put(userId, message); } /// Return message concept for user - static Future getMessageConcept(int userId) async { + static Future getMessageConcept(String userId) async { Box box = await _openMessageConceptBox(); String? value = await box.get(userId); return value; } /// Delete message concept if it exists - static Future deleteMessageConcept(int userId) async { + static Future deleteMessageConcept(String userId) async { Box box = await _openMessageConceptBox(); await box.delete(userId); } diff --git a/lib/utils/crypto_utils.dart b/lib/utils/crypto_utils.dart index c8a0619..5890a38 100644 --- a/lib/utils/crypto_utils.dart +++ b/lib/utils/crypto_utils.dart @@ -89,7 +89,7 @@ class CryptoUtils { /// Generates JWT token valid for 5 seconds asynchronously. static Future generateRsaJwt( - int userId, RSAPrivateKey privateKey) async { + String userId, RSAPrivateKey privateKey) async { return await compute( _generateRsaJwt, {'userId': userId, 'privateKey': privateKey}); } diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 393bea3..c5302aa 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -28,7 +28,7 @@ class MessageActions { /// Bubble long-press sheet with all actions that apply to [message]. /// [conversationUserId] is the other side of the conversation. static Future showSheet( - BuildContext context, PrivateMessage message, int conversationUserId, + BuildContext context, PrivateMessage message, String conversationUserId, {VoidCallback? onDeleted}) { return showModalBottomSheet( context: context, @@ -119,7 +119,7 @@ class MessageActions { /// Delete the message only on this device, after a confirmation. static void delete( - BuildContext context, PrivateMessage message, int conversationUserId, + BuildContext context, PrivateMessage message, String conversationUserId, {VoidCallback? onDeleted}) { DialogUtils.yesNoDialog( context, 'deleteMessageConfirm'.tr(), 'deleteMessageConfirmText'.tr(), diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index 4e039c8..45ce0d0 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -47,7 +47,7 @@ class MessageNotifier extends ChangeNotifier { /// owning message is updated. On success the server copy is confirmed (and /// thus deleted); on failure the message is marked as failed for retry. Future downloadMediaMessage( - int conversationUserId, MediaReference reference) async { + String conversationUserId, MediaReference reference) async { _pendingMediaRefs[reference.mediaId] = reference; try { final blob = await Utils.callApi( @@ -84,7 +84,7 @@ class MessageNotifier extends ChangeNotifier { /// Retry a previously failed media download (current session only). Future retryMediaDownload( - int conversationUserId, String mediaId) async { + String conversationUserId, String mediaId) async { final reference = _pendingMediaRefs[mediaId]; if (reference == null) { return; @@ -102,7 +102,7 @@ class MessageNotifier extends ChangeNotifier { bool canRetryMedia(String mediaId) => _pendingMediaRefs.containsKey(mediaId); /// Add messages to cache - Future addMessages(int userId, List messages) async { + Future addMessages(String userId, List messages) async { // Check if users exist for (var msg in messages) { if (!await CacheUtils.userExists(msg.senderId)) { @@ -120,7 +120,7 @@ class MessageNotifier extends ChangeNotifier { } /// Get all messages by user ID - Future> getMessages(int userId) async { + Future> getMessages(String userId) async { var messages = await CacheUtils.getPrivateMessages(userId, markAsRead: true); await NotificationService().removeNotificationsById( @@ -163,7 +163,7 @@ class MessageNotifier extends ChangeNotifier { } /// Delete chat by user ID - Future deleteChat(int userId) async { + Future deleteChat(String userId) async { await CacheUtils.deletePrivateMessagesWithUser(userId); notifyListeners(); } diff --git a/lib/utils/notification_service.dart b/lib/utils/notification_service.dart index f1c85bd..1f6e181 100644 --- a/lib/utils/notification_service.dart +++ b/lib/utils/notification_service.dart @@ -11,7 +11,7 @@ import 'singleton.dart'; class NotificationService { /// Set by HomePage while it is alive, so a tap on a single message /// notification can open the chat immediately instead of being queued. - static void Function(int userId)? onChatSelected; + static void Function(String userId)? onChatSelected; final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); @@ -74,8 +74,8 @@ class NotificationService { /// The payload of a single message notification is the sender id; grouped /// notifications carry none and just open HomePage. void _setPendingChat(String? payload) { - final userId = int.tryParse(payload ?? ''); - if (userId == null) { + final userId = payload ?? ''; + if (userId.isEmpty) { return; } final onChatSelected = NotificationService.onChatSelected; @@ -88,7 +88,7 @@ class NotificationService { /// Show notifications. Future showMessagesNotification(List messages) async { - final Map> groupedMessagesById = {}; + final Map> groupedMessagesById = {}; for (var message in messages) { if (!groupedMessagesById.containsKey(message.senderId)) { groupedMessagesById[message.senderId] = []; diff --git a/lib/utils/singleton.dart b/lib/utils/singleton.dart index 46560dd..e6d6efd 100644 --- a/lib/utils/singleton.dart +++ b/lib/utils/singleton.dart @@ -24,7 +24,7 @@ class Singleton { // Current route late Route currentRoute; // Chat a notification tap asked for, opened by HomePage once it is shown - int? pendingChatUserId; + String? pendingChatUserId; // Offline mode bool _offlineMode = false; diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 103b81e..1f09991 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -19,7 +19,7 @@ class MediaBubble extends StatefulWidget { final Color textColor; final VoidCallback onRetry; final bool canRetry; - final int conversationUserId; + final String conversationUserId; const MediaBubble({ required this.message, diff --git a/test/chat_info_media_test.dart b/test/chat_info_media_test.dart index 6d20131..e888c2c 100644 --- a/test/chat_info_media_test.dart +++ b/test/chat_info_media_test.dart @@ -4,7 +4,7 @@ import 'package:whisper/utils/message_notifier.dart'; PrivateMessage message(String? type, String? path, DateTime sentAt, {int? downloadStatus}) { - return PrivateMessage(1, '', sentAt, sentAt, false, + return PrivateMessage('1', '', sentAt, sentAt, false, mediaTypeStr: type, localPath: path, downloadStatus: downloadStatus ?? MediaDownloadStatus.ready); diff --git a/test/chat_theme_test.dart b/test/chat_theme_test.dart index 5d3eab7..e7a7e3e 100644 --- a/test/chat_theme_test.dart +++ b/test/chat_theme_test.dart @@ -19,15 +19,15 @@ void main() { }); test('per-chat theme is stored, read and cleared', () async { - expect(await CacheUtils.getChatTheme(7), isNull); + expect(await CacheUtils.getChatTheme('7'), isNull); - await CacheUtils.setChatTheme(7, const Color(0xFF3366CC)); - expect(await CacheUtils.getChatTheme(7), const Color(0xFF3366CC)); + await CacheUtils.setChatTheme('7', const Color(0xFF3366CC)); + expect(await CacheUtils.getChatTheme('7'), const Color(0xFF3366CC)); // Another chat is not affected - expect(await CacheUtils.getChatTheme(8), isNull); + expect(await CacheUtils.getChatTheme('8'), isNull); - await CacheUtils.clearChatTheme(7); - expect(await CacheUtils.getChatTheme(7), isNull); + await CacheUtils.clearChatTheme('7'); + expect(await CacheUtils.getChatTheme('7'), isNull); }); } diff --git a/test/crypto_test.dart b/test/crypto_test.dart index f15c974..5fc1982 100644 --- a/test/crypto_test.dart +++ b/test/crypto_test.dart @@ -15,7 +15,7 @@ void main() async { test('generate JWT token', () async { var keyPair = await CryptoUtils.getRSAKeyPair(); final token = await CryptoUtils.generateRsaJwt( - 1, keyPair.privateKey as bu.RSAPrivateKey); + '1', keyPair.privateKey as bu.RSAPrivateKey); debugPrint(token); }); } diff --git a/test/delete_message_test.dart b/test/delete_message_test.dart index 451eca5..c9de429 100644 --- a/test/delete_message_test.dart +++ b/test/delete_message_test.dart @@ -20,10 +20,10 @@ void main() { await Hive.openBox('privateMessages'); await Hive.box('privateMessages').clear(); keep = PrivateMessage( - 2, 'keep me', DateTime(2026, 1, 1), DateTime(2026, 1, 1), true); + '2', 'keep me', DateTime(2026, 1, 1), DateTime(2026, 1, 1), true); drop = PrivateMessage( - 1, 'drop me', DateTime(2026, 1, 2), DateTime(2026, 1, 2), true); - await CacheUtils.addPrivateMessages(1, [keep, drop]); + '1', 'drop me', DateTime(2026, 1, 2), DateTime(2026, 1, 2), true); + await CacheUtils.addPrivateMessages('1', [keep, drop]); }); tearDownAll(() async { @@ -32,12 +32,12 @@ void main() { }); test('deletePrivateMessage removes only the matching message', () async { - await CacheUtils.deletePrivateMessage(1, drop); + await CacheUtils.deletePrivateMessage('1', drop); - final messages = await CacheUtils.getPrivateMessages(1); + final messages = await CacheUtils.getPrivateMessages('1'); expect(messages.length, 1); expect(messages.single.message, 'keep me'); // The other conversation is untouched - expect(await CacheUtils.getPrivateMessages(2), isEmpty); + expect(await CacheUtils.getPrivateMessages('2'), isEmpty); }); } diff --git a/test/file_media_test.dart b/test/file_media_test.dart index 6d84cd0..c3564fb 100644 --- a/test/file_media_test.dart +++ b/test/file_media_test.dart @@ -12,7 +12,7 @@ import 'package:whisper_websocket_client_dart/models/media_type.dart'; PrivateMessage media(String type, String? path, DateTime sentAt, {String? fileName, int size = 1024}) { - return PrivateMessage(1, '', sentAt, sentAt, false, + return PrivateMessage('1', '', sentAt, sentAt, false, mediaTypeStr: type, localPath: path, mediaSize: size, @@ -82,16 +82,16 @@ void main() { final message = media('file', null, DateTime(2026, 11, 13), fileName: 'a.pdf'); message.mediaId = 'media-1'; - await CacheUtils.addPrivateMessages(7, [message]); - final stored = await CacheUtils.getPrivateMessages(7); + await CacheUtils.addPrivateMessages('7', [message]); + final stored = await CacheUtils.getPrivateMessages('7'); expect(stored.single.fileName, 'a.pdf'); expect(stored.single.mediaTypeStr, 'file'); // A finished download replaces the encrypted size with the real one - await CacheUtils.updatePrivateMessageMedia(7, stored.single.mediaId!, + await CacheUtils.updatePrivateMessageMedia('7', stored.single.mediaId!, downloadStatus: MediaDownloadStatus.ready, mediaSize: 4096); - final updated = await CacheUtils.getPrivateMessages(7); + final updated = await CacheUtils.getPrivateMessages('7'); expect(updated.single.mediaSize, 4096); await Hive.close(); @@ -111,7 +111,7 @@ void main() { textColor: Colors.white, onRetry: () {}, canRetry: false, - conversationUserId: 1, + conversationUserId: '1', ), ), )); diff --git a/test/message_actions_test.dart b/test/message_actions_test.dart index 5baec80..195d8fc 100644 --- a/test/message_actions_test.dart +++ b/test/message_actions_test.dart @@ -18,7 +18,7 @@ void main() { // Swapped between the two steps; the app is built once so the localization // asset is loaded only once. var message = - PrivateMessage(2, 'hello', DateTime(2026), DateTime(2026), true); + PrivateMessage('2', 'hello', DateTime(2026), DateTime(2026), true); await tester.pumpWidget(EasyLocalization( path: 'assets/translations', @@ -33,7 +33,7 @@ void main() { return Scaffold( body: Center( child: ElevatedButton( - onPressed: () => MessageActions.showSheet(inner, message, 5), + onPressed: () => MessageActions.showSheet(inner, message, '5'), child: const Text('open'), ), ), @@ -57,7 +57,7 @@ void main() { await tester.pumpAndSettle(); // Attachment on disk without a caption: save, forward, delete, no copy. - message = PrivateMessage(2, '', DateTime(2026), DateTime(2026), true, + message = PrivateMessage('2', '', DateTime(2026), DateTime(2026), true, localPath: '/tmp/whisper_media_test', mediaTypeStr: 'image'); await tester.tap(find.text('open')); await tester.pumpAndSettle(); From d52bf158b7db401dafd14c9e2b3256e99cfd8be8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 16:57:33 +0100 Subject: [PATCH 043/181] feat(android,ios): release signing hook, permission parity, version policy Release builds read android/key.properties when it exists and fall back to the debug key otherwise (the file and keystores stay gitignored), with key.properties.example and a README section on generating one. iOS gets the missing NSFaceIDUsageDescription, LSApplicationQueriesSchemes, remote-notification background mode and a push entitlement file wired into the project; local notifications now initialise the Darwin settings instead of doing nothing on iOS/macOS. Android's main manifest declares INTERNET itself (until now only firebase_messaging did) and resolves https links for url_launcher. The version moves to 0.1.0+2 and the release workflow fails fast when the tag for the current version already exists, so a release without a bump cannot publish silently. --- .github/workflows/build_and_release.yml | 11 +++++++- README.md | 21 +++++++++++++++ android/app/build.gradle.kts | 33 +++++++++++++++++++++--- android/app/src/main/AndroidManifest.xml | 12 ++++++--- android/key.properties.example | 12 +++++++++ ios/Runner.xcodeproj/project.pbxproj | 6 +++++ ios/Runner/Info.plist | 11 ++++++++ ios/Runner/Runner.entitlements | 8 ++++++ lib/utils/notification_service.dart | 13 ++++------ pubspec.yaml | 5 ++-- 10 files changed, 114 insertions(+), 18 deletions(-) create mode 100644 android/key.properties.example create mode 100644 ios/Runner/Runner.entitlements diff --git a/.github/workflows/build_and_release.yml b/.github/workflows/build_and_release.yml index ff21b92..324a4da 100644 --- a/.github/workflows/build_and_release.yml +++ b/.github/workflows/build_and_release.yml @@ -65,6 +65,15 @@ jobs: # exit 1 #fi + # Fail fast when the version was not bumped for this release + - name: Check version bump + run: | + VERSION=$(grep 'version:' pubspec.yaml | sed 's/version: //' | cut -d+ -f1 | tr -d '[:space:]') + if git rev-parse -q --verify "refs/tags/v$VERSION" >/dev/null; then + echo "::error::v$VERSION is already released, bump version in pubspec.yaml" + exit 1 + fi + # Building Android APK - name: Build Android APK run: flutter build apk --release @@ -73,7 +82,7 @@ jobs: - name: Get version id: version run: | - VERSION=$(grep 'version:' pubspec.yaml | sed 's/version: //' | tr -d '[:space:]') + VERSION=$(grep 'version:' pubspec.yaml | sed 's/version: //' | cut -d+ -f1 | tr -d '[:space:]') echo "version=$VERSION" >> $GITHUB_OUTPUT # Rename APK file diff --git a/README.md b/README.md index ed4ce8c..db5bff5 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,27 @@ Required repository secrets (Settings > Secrets and variables > Actions): | `GOOGLE_SERVICE_INFO_PLIST_BASE64` | not wired yet | base64 of `ios/Runner/GoogleService-Info.plist`. Add it to the build before shipping iOS releases. | | `GITHUB_TOKEN` | both | Provided automatically by GitHub. Used by the secret scan. | +### Release signing + +Release builds are signed with the debug key unless `android/key.properties` +exists (copy `android/key.properties.example`). A keystore is never committed: + +```bash +keytool -genkeypair -v -keystore whisper-release.jks -keyalg RSA -keysize 4096 \ + -validity 10000 -alias whisper +cp android/key.properties.example android/key.properties # then fill it in +``` + +CI has no keystore, so the APK it publishes is debug-signed; add the keystore as +a secret and decode it in the workflow before shipping real releases. The +release workflow fails when the `v` tag for the current +`pubspec.yaml` version already exists, which is the reminder to bump `version` +(and the build number after `+`) before every release. + +iOS push notifications need the *Push Notifications* capability on the +`cz.josefraz.whisper` App ID; `ios/Runner/Runner.entitlements` is already wired +into the project. + Pull requests from forks cannot read repository secrets, so CI is skipped for them. These files are not included in the repository for security reasons. The base64 encoding ensures safe transmission and prevents issues with special characters. diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index e51247f..8dc7282 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -1,3 +1,6 @@ +import java.io.FileInputStream +import java.util.Properties + plugins { id("com.android.application") // START: FlutterFire Configuration @@ -8,6 +11,16 @@ plugins { id("dev.flutter.flutter-gradle-plugin") } +// Release signing: create android/key.properties (gitignored) with storeFile, +// storePassword, keyAlias and keyPassword. Without it the release build falls +// back to the debug keystore so `flutter run --release` keeps working locally. +val keystoreProperties = Properties() +val keystorePropertiesFile = rootProject.file("key.properties") +val hasReleaseKeystore = keystorePropertiesFile.exists() +if (hasReleaseKeystore) { + keystoreProperties.load(FileInputStream(keystorePropertiesFile)) +} + android { namespace = "cz.josefraz.whisper" // flutter_local_notifications 23 requires compiling against API 37. @@ -33,6 +46,17 @@ android { versionName = flutter.versionName } + signingConfigs { + if (hasReleaseKeystore) { + create("release") { + keyAlias = keystoreProperties["keyAlias"] as String + keyPassword = keystoreProperties["keyPassword"] as String + storeFile = file(keystoreProperties["storeFile"] as String) + storePassword = keystoreProperties["storePassword"] as String + } + } + } + buildTypes { debug { // Different applicationId for debug version @@ -41,9 +65,12 @@ android { resValue("string", "app_name", "Whisper Debug") } release { - // TODO: Add your own signing config for the release build. - // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig = signingConfigs.getByName("debug") + signingConfig = if (hasReleaseKeystore) { + signingConfigs.getByName("release") + } else { + logger.warn("key.properties not found, the release APK is signed with the debug key") + signingConfigs.getByName("debug") + } resValue("string", "app_name", "Whisper") } } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 4f57a39..44c496c 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,5 +1,6 @@ + @@ -76,10 +77,13 @@ - - + - - + + + + + + \ No newline at end of file diff --git a/android/key.properties.example b/android/key.properties.example new file mode 100644 index 0000000..ce65bec --- /dev/null +++ b/android/key.properties.example @@ -0,0 +1,12 @@ +# Copy to key.properties and fill in before building a release APK. +# key.properties is gitignored; never commit the keystore or these values. +# +# Generate a keystore once: +# keytool -genkeypair -v -keystore whisper-release.jks -keyalg RSA \ +# -keysize 4096 -validity 10000 -alias whisper +# +# storeFile is relative to android/. +storeFile=../whisper-release.jks +storePassword=CHANGE_ME +keyAlias=whisper +keyPassword=CHANGE_ME diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 4de624b..5832e62 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -55,6 +55,8 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A1B2C3D41CF9000F007C117D /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; + /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -113,6 +115,7 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */, 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, 97C147021CF9000F007C117D /* Info.plist */, + A1B2C3D41CF9000F007C117D /* Runner.entitlements */, 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, @@ -364,6 +367,7 @@ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -543,6 +547,7 @@ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -565,6 +570,7 @@ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index fa44478..e43d49d 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -47,6 +47,17 @@ Whisper needs microphone access to record voice messages. NSPhotoLibraryUsageDescription Whisper needs photo library access to attach images and videos to your messages. + NSFaceIDUsageDescription + Whisper uses Face ID to unlock your encrypted messages. + LSApplicationQueriesSchemes + + https + http + + UIBackgroundModes + + remote-notification + CADisableMinimumFrameDurationOnPhone UIApplicationSupportsIndirectInputEvents diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements new file mode 100644 index 0000000..903def2 --- /dev/null +++ b/ios/Runner/Runner.entitlements @@ -0,0 +1,8 @@ + + + + + aps-environment + development + + diff --git a/lib/utils/notification_service.dart b/lib/utils/notification_service.dart index 1f6e181..daba4dc 100644 --- a/lib/utils/notification_service.dart +++ b/lib/utils/notification_service.dart @@ -18,14 +18,6 @@ class NotificationService { /// Init notification settings Future init() async { - // Local notifications are only set up for the platforms that have their - // settings below. iOS/macOS need the Darwin settings tracked in the - // "Android / iOS permissions" backlog item. - if (defaultTargetPlatform != TargetPlatform.android && - defaultTargetPlatform != TargetPlatform.linux) { - return; - } - const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('ic_stat_whisper'); final LinuxInitializationSettings initializationSettingsLinux = @@ -33,10 +25,15 @@ class NotificationService { defaultActionName: 'whisper_message', defaultIcon: ThemeLinuxIcon('mail-unread'), ); + // Asks for alert/badge/sound permission on iOS and macOS. + const DarwinInitializationSettings initializationSettingsDarwin = + DarwinInitializationSettings(); final InitializationSettings initializationSettings = InitializationSettings( android: initializationSettingsAndroid, + iOS: initializationSettingsDarwin, + macOS: initializationSettingsDarwin, linux: initializationSettingsLinux); await _flutterLocalNotificationsPlugin.initialize( diff --git a/pubspec.yaml b/pubspec.yaml index ba8c891..ba16e83 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,8 +1,9 @@ name: whisper description: "Secure private self-hosted end-to-end encryption messaging app." publish_to: 'none' # Remove this line if you wish to publish to pub.dev -# TODO change version when relasing new version -version: 0.0.1 +# Bump before every release; the release workflow tags v and fails if +# that tag already exists. The build number after + must only ever grow. +version: 0.1.0+2 environment: sdk: '>=3.4.3 <4.0.0' From 484ce203325d5ed7150d1a0fb3acf13e8d85494c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 17:20:58 +0100 Subject: [PATCH 044/181] feat(media): album messages, video thumbnails, upload size guard Multi-select now sends one album message: several files are uploaded one by one (single-file endpoint) and travel in one envelope v2 (media is a list of references) inside one WebSocket message. The bubble renders a grid, each attachment keeps its own download status, and the viewer pages through the album. The caption sheet asks before sending, the File picker rejects photos and videos, and the 25 MiB server limit is checked before reading a file into memory and again in ChatSender, including the AES-GCM overhead (the old check was 28 bytes off and Forward bypassed it). Incoming batches are now stored per sender instead of under the first sender's conversation id, which used to drop other senders' messages into the wrong chat. The image preview no longer spins forever: MediaBubble compared widget objects while the cache mutates the same instance, so the future was never prepared; it now keys the prepared future on the local path. Videos show their first frame (VideoPlayerController over a temporary plaintext file) instead of a grey block, and the voice player keeps the progress bar centred by putting the time next to the slider. PrivateMessage gains sendStatus and albumJson (Hive fields 14/15); the adapter is regenerated and old records default to sent. --- assets/translations/cs.json | 11 +- assets/translations/en.json | 11 +- lib/models/private_message.dart | 146 +++++++++++- lib/models/private_message.g.dart | 10 +- lib/pages/media_viewer_page.dart | 30 ++- lib/utils/cache_utils.dart | 79 ++++++- lib/utils/chat_sender.dart | 302 ++++++++++++++++++------ lib/utils/media_utils.dart | 86 ++++++- lib/utils/message_notifier.dart | 54 ++++- lib/utils/utils.dart | 66 ++++-- lib/widgets/chat_bubble.dart | 23 ++ lib/widgets/media_bubble.dart | 380 ++++++++++++++++++++++++++---- lib/widgets/voice_player.dart | 57 ++--- test/media_album_test.dart | 204 ++++++++++++++++ 14 files changed, 1253 insertions(+), 206 deletions(-) create mode 100644 test/media_album_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 12f3adc..7d850c8 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -130,5 +130,14 @@ "forwarded": "Přeposláno", "noChatsToForward": "Zatím žádné chaty, vyhledej uživatele", "mediaFile": "Soubor", - "fileTooLarge": "Soubor je příliš velký, maximum je" + "fileTooLarge": "Soubor je příliš velký, maximum je", + "send": "Odeslat", + "cancel": "Zrušit", + "sendAttachment": "Odeslat přílohu", + "sendAlbum": "Odeslat album", + "addCaption": "Přidat popisek", + "fileTypeNotAllowed": "Fotky a videa posílej přes Galerii nebo Fotoaparát", + "mediaAlbum": "Album", + "messageSending": "Odesílá se", + "messageSendFailed": "Odeslání se nezdařilo" } diff --git a/assets/translations/en.json b/assets/translations/en.json index b8f8150..c279b95 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -130,5 +130,14 @@ "forwarded": "Forwarded", "noChatsToForward": "No chats yet, search for a user", "mediaFile": "File", - "fileTooLarge": "File is too large, the maximum is" + "fileTooLarge": "File is too large, the maximum is", + "send": "Send", + "cancel": "Cancel", + "sendAttachment": "Send attachment", + "sendAlbum": "Send album", + "addCaption": "Add a caption", + "fileTypeNotAllowed": "Photos and videos go through Gallery or Camera", + "mediaAlbum": "Album", + "messageSending": "Sending", + "messageSendFailed": "Sending failed" } diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index 856682b..3f8b238 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -1,3 +1,5 @@ +import 'dart:convert'; + import 'package:easy_localization/easy_localization.dart'; import 'package:hive/hive.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; @@ -18,6 +20,84 @@ class MediaDownloadStatus { static const int failed = 2; } +/// Outbound send state, shown as an icon in the bubble. +class SendStatus { + /// Written to the cache, not yet handed to the WebSocket. + static const int sending = 0; + + /// Handed to the WebSocket (there is no delivery receipt). + static const int sent = 1; + + /// The send failed; the message stays local with a failed marker. + static const int failed = 2; +} + +/// One attachment of an album message. Albums are stored as a JSON list on +/// [PrivateMessage.albumJson], so a new attachment type does not need a Hive +/// schema for every field. +class AlbumItem { + AlbumItem({ + required this.mediaId, + required this.type, + required this.size, + this.width, + this.height, + this.durationMs, + this.fileName, + this.localPath, + this.status = MediaDownloadStatus.ready, + }); + + String mediaId; + + /// [MediaType.name] of this item. + String type; + int size; + int? width; + int? height; + int? durationMs; + String? fileName; + + /// Encrypted-at-rest file on this device, null until downloaded/sent. + String? localPath; + int status; + + MediaType? get mediaType { + try { + return MediaType.values.byName(type); + } catch (_) { + return null; + } + } + + bool get isReady => + status == MediaDownloadStatus.ready && localPath != null; + + Map toJson() => { + 'mediaId': mediaId, + 'type': type, + 'size': size, + if (width != null) 'width': width, + if (height != null) 'height': height, + if (durationMs != null) 'durationMs': durationMs, + if (fileName != null) 'fileName': fileName, + if (localPath != null) 'localPath': localPath, + 'status': status, + }; + + static AlbumItem fromJson(Map json) => AlbumItem( + mediaId: json['mediaId'] as String, + type: json['type'] as String, + size: (json['size'] as num).toInt(), + width: (json['width'] as num?)?.toInt(), + height: (json['height'] as num?)?.toInt(), + durationMs: (json['durationMs'] as num?)?.toInt(), + fileName: json['fileName'] as String?, + localPath: json['localPath'] as String?, + status: (json['status'] as num?)?.toInt() ?? MediaDownloadStatus.ready, + ); +} + @HiveType(typeId: 3) class PrivateMessage extends HiveObject { @HiveField(0) @@ -38,7 +118,7 @@ class PrivateMessage extends HiveObject { @HiveField(5) String? mediaId; - /// [MediaType.name] of the attachment, or null for text messages. + /// [MediaType.name] of the attachment, or null for text messages and albums. @HiveField(6) String? mediaTypeStr; @@ -70,6 +150,15 @@ class PrivateMessage extends HiveObject { @HiveField(13) String? fileName; + /// Send state, see [SendStatus]. Old records default to sent. + @HiveField(14, defaultValue: SendStatus.sent) + int sendStatus; + + /// JSON list of [AlbumItem]s when this message carries more than one + /// attachment. Null for text and single-media messages. + @HiveField(15) + String? albumJson; + PrivateMessage( this.senderId, this.message, @@ -85,18 +174,62 @@ class PrivateMessage extends HiveObject { this.durationMs, this.downloadStatus = MediaDownloadStatus.ready, this.fileName, + this.sendStatus = SendStatus.sent, + this.albumJson, }); bool get isMe => senderId == Singleton().profile.user.id; int get notificationId => receivedAt.microsecondsSinceEpoch % 0x7FFFFFFF; - /// Whether this message carries a media attachment. - bool get isMedia => mediaTypeStr != null; + /// Whether this message carries a media attachment (single or album). + bool get isMedia => mediaTypeStr != null || isAlbum; + + /// Whether this message is an album (more than one attachment). + bool get isAlbum => albumJson != null; + + /// Decoded album items, empty for non-album messages. + List get album { + final raw = albumJson; + if (raw == null) { + return const []; + } + try { + final decoded = jsonDecode(raw); + if (decoded is List) { + return decoded + .whereType() + .map((item) => AlbumItem.fromJson(Map.from(item))) + .toList(); + } + } catch (_) { + // Corrupted entry: behave like a message without attachments. + } + return const []; + } + + /// Replaces the album items and serializes them back into [albumJson]. + void setAlbum(List items) { + albumJson = jsonEncode(items.map((item) => item.toJson()).toList()); + } + + /// Local (encrypted-at-rest) files of this message, for deletion. + List get localPaths { + final paths = []; + if (localPath != null) { + paths.add(localPath!); + } + for (final item in album) { + if (item.localPath != null) { + paths.add(item.localPath!); + } + } + return paths; + } - /// The decoded [MediaType] of the attachment, or null for text messages. + /// The decoded [MediaType] of the attachment, or null for text and albums. MediaType? get mediaType { - if (mediaTypeStr == null) { + if (albumJson != null || mediaTypeStr == null) { return null; } try { @@ -112,6 +245,9 @@ class PrivateMessage extends HiveObject { if (!isMedia || message.isNotEmpty) { return message; } + if (isAlbum) { + return '${'mediaAlbum'.tr()} (${album.length})'; + } switch (mediaType) { case MediaType.image: return 'mediaPhoto'.tr(); diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index 3fc488d..6585502 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -31,13 +31,15 @@ class PrivateMessageAdapter extends TypeAdapter { durationMs: fields[11] as int?, downloadStatus: fields[12] == null ? 1 : fields[12] as int, fileName: fields[13] as String?, + sendStatus: fields[14] == null ? 1 : fields[14] as int, + albumJson: fields[15] as String?, ); } @override void write(BinaryWriter writer, PrivateMessage obj) { writer - ..writeByte(14) + ..writeByte(16) ..writeByte(0) ..write(obj.senderId) ..writeByte(1) @@ -65,7 +67,11 @@ class PrivateMessageAdapter extends TypeAdapter { ..writeByte(12) ..write(obj.downloadStatus) ..writeByte(13) - ..write(obj.fileName); + ..write(obj.fileName) + ..writeByte(14) + ..write(obj.sendStatus) + ..writeByte(15) + ..write(obj.albumJson); } @override diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index 693a048..b90a726 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -22,9 +22,13 @@ class MediaViewerPage extends StatefulWidget { /// and what the delete action needs. final String conversationUserId; + /// Index of the tapped attachment when [message] is an album. + final int albumIndex; + const MediaViewerPage({ required this.message, required this.conversationUserId, + this.albumIndex = 0, super.key, }); @@ -48,12 +52,32 @@ class _MediaViewerPageState extends State { /// The viewer pages through the same attachments the gallery shows, starting /// at the one that was tapped. Future _loadMedia() async { + if (widget.message.isAlbum) { + // Album attachments are pages of their own; keep the album order so the + // tapped tile maps to the same index. + final media = MessageNotifier.albumMedia(widget.message); + if (!mounted) { + return; + } + setState(() { + _media = media.isEmpty ? [widget.message] : media; + _index = widget.albumIndex.clamp(0, _media.length - 1); + _controller = PageController(initialPage: _index); + }); + return; + } final messages = await CacheUtils.getPrivateMessages(widget.conversationUserId); final media = MessageNotifier.viewableMedia(messages); - final index = media.indexWhere((m) => - m.senderId == widget.message.senderId && - m.sentAt == widget.message.sentAt); + var index = -1; + if (widget.message.mediaId != null) { + index = media.indexWhere((m) => m.mediaId == widget.message.mediaId); + } + if (index < 0) { + index = media.indexWhere((m) => + m.senderId == widget.message.senderId && + m.sentAt == widget.message.sentAt); + } if (!mounted) { return; } diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index f95e09b..bfc115a 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -281,12 +281,19 @@ class CacheUtils { {bool markAsRead = false}) async { Box box = await _openPrivateMessagesBox(); List? messages = box.get(userId); - // Mark as read + // Mark as read, but only write when something actually changed: this runs + // on every chat rebuild. if (markAsRead && messages != null) { + var changed = false; for (PrivateMessage msg in messages) { - msg.read = true; + if (!msg.read) { + msg.read = true; + changed = true; + } + } + if (changed) { + await box.put(userId, messages); } - await box.put(userId, messages); } return messages == null ? [] @@ -307,7 +314,9 @@ class CacheUtils { m.senderId == message.senderId && m.sentAt == message.sentAt); await box.put(userId, messages); - await MediaUtils.deleteLocalFile(message.localPath); + for (final path in message.localPaths) { + await MediaUtils.deleteLocalFile(path); + } } /// Delete user messages @@ -325,8 +334,8 @@ class CacheUtils { static Future _deleteMediaFilesForUser(String userId) async { final messages = await getPrivateMessages(userId); for (final msg in messages) { - if (msg.localPath != null) { - await MediaUtils.deleteLocalFile(msg.localPath); + for (final path in msg.localPaths) { + await MediaUtils.deleteLocalFile(path); } } } @@ -355,12 +364,70 @@ class CacheUtils { } changed = true; } + // Album attachment: update the matching item. + if (msg.isAlbum) { + final items = msg.album; + var itemChanged = false; + for (final item in items) { + if (item.mediaId != mediaId) { + continue; + } + if (localPath != null) { + item.localPath = localPath; + } + if (downloadStatus != null) { + item.status = downloadStatus; + } + if (mediaSize != null) { + item.size = mediaSize; + } + itemChanged = true; + } + if (itemChanged) { + msg.setAlbum(items); + // The message-level flag follows the album, so the bubble can show a + // single state for "still downloading" vs "done". + if (downloadStatus != null) { + final allReady = items + .every((item) => item.status == MediaDownloadStatus.ready); + final anyFailed = items + .any((item) => item.status == MediaDownloadStatus.failed); + msg.downloadStatus = allReady + ? MediaDownloadStatus.ready + : (anyFailed + ? MediaDownloadStatus.failed + : MediaDownloadStatus.pending); + } + changed = true; + } + } } if (changed) { await box.put(userId, messages); } } + /// Apply [update] to the stored copy of [message] and persist the list. + /// The message is matched by sender and timestamp, the same identity the + /// delete path uses. + static Future updateStoredMessage(String userId, + PrivateMessage message, void Function(PrivateMessage stored) update) async { + Box box = await _openPrivateMessagesBox(); + List? messages = box.get(userId); + if (messages == null) { + return; + } + for (final dynamic m in messages) { + final stored = m as PrivateMessage; + if (stored.senderId == message.senderId && + stored.sentAt == message.sentAt) { + update(stored); + await box.put(userId, messages); + return; + } + } + } + /// Opens box with users static Future _openUserBox() async { return Hive.openBox(_userKey); diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index 6724576..a396cb5 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -20,33 +20,53 @@ import 'message_notifier.dart'; import 'singleton.dart'; import 'utils.dart'; +/// One attachment of an outgoing album (or a single media message). +class OutgoingAttachment { + final MediaType type; + final Uint8List bytes; + final int? width; + final int? height; + final int? durationMs; + final String? fileName; + + const OutgoingAttachment({ + required this.type, + required this.bytes, + this.width, + this.height, + this.durationMs, + this.fileName, + }); +} + /// Sends messages to an arbitrary recipient. Shared by the chat page and the /// forward page so both use one encrypted, persisted send path. /// -/// Each method reports its own errors with a toast and returns whether the -/// message was sent. +/// The bubble is stored as `sending` before anything goes out and flipped to +/// `sent` afterwards, so the message is visible immediately and a failure leaves +/// a visible failed state instead of a silent loss. class ChatSender { /// Send a text message to [recipient]. static Future sendText(User recipient, String text) async { + final now = DateTime.now(); + final message = PrivateMessage( + Singleton().profile.user.id, text, now, now, true, + sendStatus: SendStatus.sending); try { - await Utils.wsConnect(); - if (!Singleton().wsClient.isConnected) { - Fluttertoast.showToast( - msg: 'wsOffline'.tr(), backgroundColor: Colors.red); - return false; + await _persist(recipient, [message]); + if (!await _ensureConnected()) { + return await _fail(recipient.id, message); } final data = await CryptoUtils.encryptMessageData(utf8.encode(text), bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); - final sentAt = Singleton().wsClient.sendMessage(WsMessage.privateMessage( + Singleton().wsClient.sendMessage(WsMessage.privateMessage( NewPrivateMessage(recipient.id, data['encryptedData']!, data['encryptedKey']!, data['nonce']!, data['mac']!))); - await _persist(recipient, [ - PrivateMessage(Singleton().profile.user.id, text, sentAt, sentAt, true) - ]); + await _markSent(recipient.id, message); return true; } catch (e) { Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); - return false; + return await _fail(recipient.id, message); } } @@ -58,81 +78,215 @@ class ChatSender { int? height, int? durationMs, String? fileName}) async { + if (!MediaUtils.uploadFits(bytes.length)) { + _toastTooLarge(); + return false; + } + // Store the original media encrypted-at-rest first, so the bubble can show + // the content while the upload is still running. + final localPath = await MediaUtils.encryptAtRest(bytes); + final now = DateTime.now(); + final message = PrivateMessage( + Singleton().profile.user.id, + caption, + now, + now, + true, + mediaTypeStr: type.name, + localPath: localPath, + mediaSize: bytes.length, + width: width, + height: height, + durationMs: durationMs, + downloadStatus: MediaDownloadStatus.ready, + fileName: fileName, + sendStatus: SendStatus.sending, + ); try { - await Utils.wsConnect(); - if (!Singleton().wsClient.isConnected) { - Fluttertoast.showToast( - msg: 'wsOffline'.tr(), backgroundColor: Colors.red); - return false; + await _persist(recipient, [message]); + if (!await _ensureConnected()) { + return await _fail(recipient.id, message); } - - // Transport encryption with an ephemeral per-file key. final transport = await MediaUtils.encryptForTransport(bytes); + final reference = await _uploadReference( + recipient, type, transport.key, transport.blob, + width: width, + height: height, + durationMs: durationMs, + fileName: fileName); + if (reference == null) { + return await _fail(recipient.id, message); + } + final envelope = MediaUtils.buildMediaEnvelope(reference, caption); + await _sendEnvelope(recipient, envelope); + await CacheUtils.updateStoredMessage(recipient.id, message, (stored) { + stored.mediaId = reference.mediaId; + stored.sendStatus = SendStatus.sent; + }); + return true; + } catch (e) { + Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); + return await _fail(recipient.id, message); + } + } - // Upload the ciphertext over HTTP. - final uploadResponse = await Utils.callApi( - () => Singleton().mediaApi.uploadMedia( - http.MultipartFile.fromBytes('file', transport.blob, - filename: 'media.bin'), - recipient.id, - ), - rethrowErr: true, - ); - if (uploadResponse == null) { - Fluttertoast.showToast( - msg: 'mediaUploadFailed'.tr(), backgroundColor: Colors.red); + /// Send several attachments as one album message: one bubble, one encrypted + /// envelope carrying all references, one WebSocket message. + static Future sendAlbum( + User recipient, List attachments, + {String caption = ''}) async { + if (attachments.isEmpty) { + return false; + } + for (final attachment in attachments) { + if (!MediaUtils.uploadFits(attachment.bytes.length)) { + _toastTooLarge(); return false; } - final mediaId = uploadResponse.id; - - // Build the encrypted reference and wrap it in the message envelope. - final reference = MediaReference( - mediaId, - transport.key, - type, - transport.blob.length, - width: width, - height: height, - durationMs: durationMs, - fileName: fileName, - ); - final envelope = MediaUtils.buildMediaEnvelope(reference, caption); + } - // E2E-encrypt the envelope for the recipient. - final data = await CryptoUtils.encryptMessageData( - envelope, bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); + // Local copies first: the album bubble is visible while uploading. + final localPaths = []; + for (final attachment in attachments) { + localPaths.add(await MediaUtils.encryptAtRest(attachment.bytes)); + } + final now = DateTime.now(); + final message = PrivateMessage( + Singleton().profile.user.id, + caption, + now, + now, + true, + downloadStatus: MediaDownloadStatus.ready, + sendStatus: SendStatus.sending, + ); + message.setAlbum([ + for (var i = 0; i < attachments.length; i++) + AlbumItem( + mediaId: '', + type: attachments[i].type.name, + size: attachments[i].bytes.length, + width: attachments[i].width, + height: attachments[i].height, + durationMs: attachments[i].durationMs, + fileName: attachments[i].fileName, + localPath: localPaths[i], + status: MediaDownloadStatus.ready, + ) + ]); - // Send over the WebSocket. - final sentAt = Singleton().wsClient.sendMessage(WsMessage.privateMessage( - NewPrivateMessage(recipient.id, data['encryptedData']!, - data['encryptedKey']!, data['nonce']!, data['mac']!))); + try { + await _persist(recipient, [message]); + if (!await _ensureConnected()) { + return await _fail(recipient.id, message); + } - // Store the original media encrypted-at-rest for our own bubble. - final localPath = await MediaUtils.encryptAtRest(bytes); - - await _persist(recipient, [ - PrivateMessage( - Singleton().profile.user.id, - caption, - sentAt, - sentAt, - true, - mediaId: mediaId, - mediaTypeStr: type.name, - localPath: localPath, - mediaSize: bytes.length, - width: width, - height: height, - durationMs: durationMs, - downloadStatus: MediaDownloadStatus.ready, - fileName: fileName, - ) - ]); + // The server takes one file per request, so the album is N uploads. + final references = []; + for (final attachment in attachments) { + final transport = + await MediaUtils.encryptForTransport(attachment.bytes); + final reference = await _uploadReference( + recipient, attachment.type, transport.key, transport.blob, + width: attachment.width, + height: attachment.height, + durationMs: attachment.durationMs, + fileName: attachment.fileName); + if (reference == null) { + return await _fail(recipient.id, message); + } + references.add(reference); + } + + final envelope = MediaUtils.buildAlbumEnvelope(references, caption); + await _sendEnvelope(recipient, envelope); + await CacheUtils.updateStoredMessage(recipient.id, message, (stored) { + final items = stored.album; + for (var i = 0; i < items.length && i < references.length; i++) { + items[i].mediaId = references[i].mediaId; + } + stored.setAlbum(items); + stored.sendStatus = SendStatus.sent; + }); return true; } catch (e) { Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); - return false; + return await _fail(recipient.id, message); + } + } + + /// Upload one already transport-encrypted attachment and build its reference. + static Future _uploadReference( + User recipient, + MediaType type, + Uint8List key, + Uint8List blob, + {int? width, + int? height, + int? durationMs, + String? fileName}) async { + final uploadResponse = await Utils.callApi( + () => Singleton().mediaApi.uploadMedia( + http.MultipartFile.fromBytes('file', blob, filename: 'media.bin'), + recipient.id, + ), + rethrowErr: true, + ); + if (uploadResponse == null) { + Fluttertoast.showToast( + msg: 'mediaUploadFailed'.tr(), backgroundColor: Colors.red); + return null; } + return MediaReference( + uploadResponse.id, + key, + type, + blob.length, + width: width, + height: height, + durationMs: durationMs, + fileName: fileName, + ); + } + + /// E2E-encrypt [envelope] for [recipient] and hand it to the WebSocket. + static Future _sendEnvelope( + User recipient, Uint8List envelope) async { + final data = await CryptoUtils.encryptMessageData( + envelope, bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); + Singleton().wsClient.sendMessage(WsMessage.privateMessage( + NewPrivateMessage(recipient.id, data['encryptedData']!, + data['encryptedKey']!, data['nonce']!, data['mac']!))); + } + + /// Connect the WebSocket if needed; toasts and reports false when offline. + static Future _ensureConnected() async { + await Utils.wsConnect(); + if (Singleton().wsClient.isConnected) { + return true; + } + Fluttertoast.showToast(msg: 'wsOffline'.tr(), backgroundColor: Colors.red); + return false; + } + + static void _toastTooLarge() { + Fluttertoast.showToast( + msg: + '${'fileTooLarge'.tr()} ${MediaUtils.formatBytes(MediaUtils.maxUploadBytes)}', + backgroundColor: Colors.red); + } + + static Future _markSent(String userId, PrivateMessage message) => + CacheUtils.updateStoredMessage(userId, message, (stored) { + stored.sendStatus = SendStatus.sent; + }); + + /// Mark a persisted message as failed and report the failure. + static Future _fail(String userId, PrivateMessage message) async { + await CacheUtils.updateStoredMessage(userId, message, (stored) { + stored.sendStatus = SendStatus.failed; + }); + return false; } /// Store the recipient and the sent message in the local cache. diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 0a264c0..2a0e5b4 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -99,9 +99,12 @@ class MediaUtils { static const Uuid _uuid = Uuid(); static final ImagePicker _imagePicker = ImagePicker(); - /// Version marker used by the media message envelope. + /// Version marker used by a single-media message envelope. static const int envelopeVersion = 1; + /// Version marker used by an album envelope (media is a list of references). + static const int envelopeVersionAlbum = 2; + // --------------------------------------------------------------------------- // Transport encryption // --------------------------------------------------------------------------- @@ -311,6 +314,14 @@ class MediaUtils { /// Largest upload the server accepts (mirrors MEDIA_MAX_UPLOAD_SIZE). static const int maxUploadBytes = 25 * 1024 * 1024; + /// AES-GCM overhead added to every uploaded file (nonce + mac). + static const int transportOverheadBytes = _nonceLength + _macLength; + + /// Whether a plaintext file of [plaintextBytes] fits the server limit once + /// it is encrypted for transport. + static bool uploadFits(int plaintextBytes) => + plaintextBytes + transportOverheadBytes <= maxUploadBytes; + /// Last path segment of [path], i.e. the file name with its extension. static String baseName(String path) => path.split(RegExp(r'[\\/]')).last; @@ -446,19 +457,43 @@ class MediaUtils { return Uint8List.fromList(utf8.encode(jsonEncode(map))); } - /// Try to parse decrypted [plaintext] as a media envelope. Returns null when - /// the bytes are not a media envelope (i.e. a plain text message). + /// Build the plaintext (pre-encryption) bytes for an album message: a JSON + /// envelope wrapping [references] and an optional [caption]. + static Uint8List buildAlbumEnvelope( + List references, String caption) { + final map = { + 'whisperMsg': envelopeVersionAlbum, + 'kind': 'media', + 'caption': caption, + 'media': references.map((reference) => reference.toJson()).toList(), + }; + return Uint8List.fromList(utf8.encode(jsonEncode(map))); + } + + /// Try to parse decrypted [plaintext] as a media envelope (single or album). + /// Returns null when the bytes are not a media envelope (i.e. plain text). static ParsedMediaEnvelope? tryParseMediaEnvelope(Uint8List plaintext) { try { final decoded = jsonDecode(utf8.decode(plaintext)); - if (decoded is Map && - decoded['whisperMsg'] == envelopeVersion && - decoded['kind'] == 'media' && - decoded['media'] is Map) { - final reference = MediaReference.fromJson( - Map.from(decoded['media'] as Map)); + if (decoded is Map && decoded['kind'] == 'media') { final caption = (decoded['caption'] as String?) ?? ''; - return ParsedMediaEnvelope(reference, caption); + if (decoded['whisperMsg'] == envelopeVersion && + decoded['media'] is Map) { + final reference = MediaReference.fromJson( + Map.from(decoded['media'] as Map)); + return ParsedMediaEnvelope([reference], caption); + } + if (decoded['whisperMsg'] == envelopeVersionAlbum && + decoded['media'] is List) { + final references = (decoded['media'] as List) + .whereType() + .map((item) => + MediaReference.fromJson(Map.from(item))) + .toList(); + if (references.isNotEmpty) { + return ParsedMediaEnvelope(references, caption); + } + } } } catch (_) { // Not JSON / not a media envelope -> treat as plain text. @@ -496,14 +531,39 @@ class MediaUtils { final path = picked?.path; return path == null ? null : File(path); } + + /// Pick several images/videos from the gallery at once (album). + static Future> pickMultipleMediaFromGallery() async { + final picked = await _imagePicker.pickMultipleMedia(); + return picked.map((x) => File(x.path)).toList(); + } + + /// Pick several arbitrary files at once (album). + static Future> pickMultipleFiles() async { + final picked = await FilePicker.pickFiles(type: FileType.any); + return picked + .map((file) => file.path) + .whereType() + .map((path) => File(path)) + .toList(); + } + + /// Whether [file] is a photo, gif or video (the "File" attachment must not + /// send those; the gallery and camera entries are for them). + static bool isVisualMedia(File file) { + final type = detectType(file.path); + return type == MediaType.image || + type == MediaType.gif || + type == MediaType.video; + } } -/// Parsed media envelope: a [MediaReference] plus its caption. +/// Parsed media envelope: one or more [MediaReference]s plus the caption. class ParsedMediaEnvelope { - final MediaReference reference; + final List references; final String caption; - const ParsedMediaEnvelope(this.reference, this.caption); + const ParsedMediaEnvelope(this.references, this.caption); } /// Thin wrapper around the [AudioRecorder] for hold-to-record voice messages. diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index 45ce0d0..17d10bc 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -22,19 +22,57 @@ class MessageNotifier extends ChangeNotifier { MessageNotifier._internal(); /// The media messages of a conversation that the viewer can open, newest - /// first: a local file, a known type, fully downloaded, not voice. + /// first: a local file, a known type, fully downloaded, not voice. Album + /// items are expanded into one entry per attachment. static List viewableMedia(List messages) { - final media = messages - .where((m) => - m.localPath != null && - m.mediaType != null && - m.mediaType != MediaType.voice && - m.downloadStatus == MediaDownloadStatus.ready) - .toList(); + final media = []; + for (final message in messages) { + if (message.isAlbum) { + for (final item in albumMedia(message)) { + if (item.localPath != null && + item.mediaType != null && + item.mediaType != MediaType.voice && + item.downloadStatus == MediaDownloadStatus.ready) { + media.add(item); + } + } + continue; + } + if (message.localPath != null && + message.mediaType != null && + message.mediaType != MediaType.voice && + message.downloadStatus == MediaDownloadStatus.ready) { + media.add(message); + } + } media.sort((a, b) => b.sentAt.compareTo(a.sentAt)); return media; } + /// One [PrivateMessage] per album attachment, in album order, so the viewer + /// and the gallery can treat them like single media messages. + static List albumMedia(PrivateMessage message) { + return [ + for (final item in message.album) + PrivateMessage( + message.senderId, + message.message, + message.sentAt, + message.receivedAt, + message.read, + mediaId: item.mediaId, + mediaTypeStr: item.type, + localPath: item.localPath, + mediaSize: item.size, + width: item.width, + height: item.height, + durationMs: item.durationMs, + fileName: item.fileName, + downloadStatus: item.status, + ) + ]; + } + /// In-memory map of media references awaiting (or having failed) download, /// keyed by media id. The transport key is intentionally never persisted to /// disk, so tap-to-retry only works within the current session. diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index fc87f27..9c002a5 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -150,8 +150,8 @@ class Utils { var messages = wsResponse.payload as List; messages.sort((a, b) => a.sentAt.compareTo(b.sentAt)); List decryptedMessages = []; - // Media references that still need to be downloaded after persisting. - List pendingMediaRefs = []; + // Media references of each conversation that still need a download. + final pendingMediaRefs = >{}; // Parallel decrypt all messages try { @@ -168,7 +168,31 @@ class Utils { final envelope = MediaUtils.tryParseMediaEnvelope(decryptedMessage); if (envelope != null) { - final ref = envelope.reference; + if (envelope.references.length > 1) { + // Album: one bubble, one download per attachment. + final albumMsg = pm.PrivateMessage( + message.senderId, + envelope.caption, + message.sentAt, + DateTime.now(), + false, + downloadStatus: pm.MediaDownloadStatus.pending, + ); + albumMsg.setAlbum(envelope.references + .map((ref) => pm.AlbumItem( + mediaId: ref.mediaId, + type: ref.type.name, + size: ref.size, + width: ref.width, + height: ref.height, + durationMs: ref.durationMs, + fileName: ref.fileName, + status: pm.MediaDownloadStatus.pending, + )) + .toList()); + return (albumMsg, envelope.references); + } + final ref = envelope.references.single; final mediaMsg = pm.PrivateMessage( message.senderId, envelope.caption, @@ -184,7 +208,7 @@ class Utils { fileName: ref.fileName, downloadStatus: pm.MediaDownloadStatus.pending, ); - return (mediaMsg, ref); + return (mediaMsg, [ref]); } // Plain text message (legacy/unchanged path). final textMsg = pm.PrivateMessage( @@ -193,7 +217,7 @@ class Utils { message.sentAt, DateTime.now(), false); - return (textMsg, null); + return (textMsg, const []); } catch (e) { // Log individual message decryption errors if (kDebugMode) { @@ -208,11 +232,16 @@ class Utils { // Filter out failed decryptions (null values) final valid = results - .whereType<(pm.PrivateMessage, MediaReference?)>() + .whereType<(pm.PrivateMessage, List)>() .toList(); decryptedMessages = valid.map((e) => e.$1).toList(); - pendingMediaRefs = - valid.map((e) => e.$2).whereType().toList(); + for (final (message, refs) in valid) { + if (refs.isNotEmpty) { + pendingMediaRefs + .putIfAbsent(message.senderId, () => []) + .addAll(refs); + } + } // Show toast only if all messages failed to decrypt if (decryptedMessages.isEmpty && messages.isNotEmpty) { @@ -224,14 +253,19 @@ class Utils { msg: 'decryptionFailed'.tr(), backgroundColor: Colors.red); } if (decryptedMessages.isNotEmpty) { - final conversationUserId = decryptedMessages.first.senderId; - await MessageNotifier() - .addMessages(conversationUserId, decryptedMessages); - - // Kick off media downloads now that placeholders are persisted. - for (final ref in pendingMediaRefs) { - // Fire-and-forget; updates the message + notifies on completion. - MessageNotifier().downloadMediaMessage(conversationUserId, ref); + // A batch can hold messages from several senders: store each + // conversation under its own key. + final bySender = >{}; + for (final message in decryptedMessages) { + bySender.putIfAbsent(message.senderId, () => []).add(message); + } + for (final entry in bySender.entries) { + await MessageNotifier().addMessages(entry.key, entry.value); + // Kick off media downloads now that placeholders are persisted. + for (final ref in pendingMediaRefs[entry.key] ?? const []) { + // Fire-and-forget; updates the message + notifies on completion. + MessageNotifier().downloadMediaMessage(entry.key, ref); + } } // Remove messages from notifications if user was not online when they were sent diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 87a9bcc..baaa328 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -261,6 +261,29 @@ class _ChatBubbleState extends State { softWrap: true, ), ), + // Outgoing messages show a clock while they are being + // sent and an error when the send failed. + if (widget.message.isMe && + widget.message.sendStatus != SendStatus.sent) + Padding( + padding: const EdgeInsets.only(top: 2), + child: Tooltip( + message: widget.message.sendStatus == + SendStatus.failed + ? 'messageSendFailed'.tr() + : 'messageSending'.tr(), + child: Icon( + widget.message.sendStatus == SendStatus.failed + ? Icons.error_outline + : Icons.schedule, + size: 13, + color: widget.message.sendStatus == + SendStatus.failed + ? Colors.red + : Colors.grey, + ), + ), + ), ], ), ), diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 1f09991..4f9a588 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -1,8 +1,10 @@ +import 'dart:io'; import 'dart:typed_data'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:page_transition/page_transition.dart'; +import 'package:video_player/video_player.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; @@ -11,8 +13,8 @@ import '../utils/media_utils.dart'; import 'voice_player.dart'; /// Renders a media attachment inside a chat bubble: image/gif thumbnail, video -/// preview with a play overlay, or an inline voice player. Handles the -/// download/loading/failed states for incoming media. +/// preview with a play overlay, an inline voice player, or an album grid. +/// Handles the download/loading/failed states for incoming media. class MediaBubble extends StatefulWidget { final PrivateMessage message; final Color bubbleColor; @@ -38,31 +40,33 @@ class MediaBubble extends StatefulWidget { class _MediaBubbleState extends State { Future? _imageFuture; + /// Path the current [_imageFuture] belongs to. The cache mutates the same + /// message instance in place, so comparing widget objects cannot detect a + /// finished download; the path can. + String? _imagePath; + @override void initState() { super.initState(); - _prepareFutures(); + _prepareImage(); } @override void didUpdateWidget(covariant MediaBubble oldWidget) { super.didUpdateWidget(oldWidget); - if (oldWidget.message.localPath != widget.message.localPath || - oldWidget.message.downloadStatus != widget.message.downloadStatus) { - _prepareFutures(); - } + _prepareImage(); } - void _prepareFutures() { - _imageFuture = null; + void _prepareImage() { final path = widget.message.localPath; - if (path == null) { + if (path == _imagePath) { return; } + _imagePath = path; final type = widget.message.mediaType; - if (type == MediaType.image || type == MediaType.gif) { - _imageFuture = MediaUtils.decryptAtRest(path); - } + final isImage = type == MediaType.image || type == MediaType.gif; + _imageFuture = + path != null && isImage ? MediaUtils.decryptAtRest(path) : null; } /// Constrained display size derived from the original media dimensions. @@ -87,10 +91,10 @@ class _MediaBubbleState extends State { return Size(dw, dh); } - void _openViewer() { + void _openViewer({int albumIndex = 0}) { final path = widget.message.localPath; final type = widget.message.mediaType; - if (path == null || type == null) { + if (!widget.message.isAlbum && (path == null || type == null)) { return; } Navigator.of(context).push( @@ -103,6 +107,7 @@ class _MediaBubbleState extends State { child: MediaViewerPage( message: widget.message, conversationUserId: widget.conversationUserId, + albumIndex: albumIndex, ), ), ), @@ -114,6 +119,10 @@ class _MediaBubbleState extends State { final type = widget.message.mediaType; final hasCaption = widget.message.message.isNotEmpty; + if (widget.message.isAlbum) { + return _albumWidget(hasCaption); + } + Widget media; if (widget.message.downloadStatus == MediaDownloadStatus.pending) { media = _placeholder(child: const CircularProgressIndicator()); @@ -155,6 +164,46 @@ class _MediaBubbleState extends State { } // Visual media: rounded thumbnail with optional caption underneath. + return _withCaption(media, hasCaption); + } + + /// Album: two-column grid of thumbnails (four tiles max, the last one shows + /// how many are hidden) plus the shared caption. + Widget _albumWidget(bool hasCaption) { + final items = widget.message.album; + const tile = 110.0; + const gap = 4.0; + final shown = items.length > 4 ? 4 : items.length; + return _withCaption( + SizedBox( + width: tile * 2 + gap, + child: GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + padding: EdgeInsets.zero, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + mainAxisSpacing: gap, + crossAxisSpacing: gap, + ), + itemCount: shown, + itemBuilder: (context, index) { + final hidden = items.length > 4 && index == 3 + ? items.length - 3 + : null; + return AlbumTile( + item: items[index], + hiddenCount: hidden, + onTap: () => _openViewer(albumIndex: index), + ); + }, + ), + ), + hasCaption, + ); + } + + Widget _withCaption(Widget media, bool hasCaption) { return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, @@ -249,46 +298,48 @@ class _MediaBubbleState extends State { final size = _displaySize(); return GestureDetector( onTap: _openViewer, - child: Stack( - alignment: Alignment.center, - children: [ - Container( - width: size.width, - height: size.height, - decoration: BoxDecoration( - gradient: const LinearGradient( - begin: Alignment.topLeft, - end: Alignment.bottomRight, - colors: [Color(0xFF2B2B2B), Color(0xFF000000)], + child: SizedBox( + width: size.width, + height: size.height, + child: Stack( + alignment: Alignment.center, + fit: StackFit.expand, + children: [ + VideoThumbnail(path: widget.message.localPath), + Container( + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.25), + borderRadius: BorderRadius.circular(16), ), - borderRadius: BorderRadius.circular(16), ), - ), - Container( - decoration: BoxDecoration( - color: Colors.black.withValues(alpha: 0.45), - shape: BoxShape.circle, + Container( + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.45), + shape: BoxShape.circle, + ), + padding: const EdgeInsets.all(8), + child: + const Icon(Icons.play_arrow, color: Colors.white, size: 36), ), - padding: const EdgeInsets.all(8), - child: const Icon(Icons.play_arrow, color: Colors.white, size: 36), - ), - if (widget.message.durationMs != null) - Positioned( - right: 8, - bottom: 8, - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), - decoration: BoxDecoration( - color: Colors.black.withValues(alpha: 0.6), - borderRadius: BorderRadius.circular(8), - ), - child: Text( - _formatDuration(widget.message.durationMs!), - style: const TextStyle(color: Colors.white, fontSize: 11), + if (widget.message.durationMs != null) + Positioned( + right: 8, + bottom: 8, + child: Container( + padding: + const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(8), + ), + child: Text( + _formatDuration(widget.message.durationMs!), + style: const TextStyle(color: Colors.white, fontSize: 11), + ), ), ), - ), - ], + ], + ), ), ); } @@ -350,3 +401,232 @@ class _MediaBubbleState extends State { return '$minutes:$seconds'; } } + +/// One tile of an album bubble: image/gif thumbnail, first video frame, or a +/// type icon, with its own download state. +class AlbumTile extends StatefulWidget { + final AlbumItem item; + + /// When set, this tile stands in for all remaining attachments. + final int? hiddenCount; + final VoidCallback onTap; + + const AlbumTile({ + required this.item, + required this.onTap, + this.hiddenCount, + super.key, + }); + + @override + State createState() => _AlbumTileState(); +} + +class _AlbumTileState extends State { + Future? _imageFuture; + String? _imagePath; + + @override + void initState() { + super.initState(); + _prepare(); + } + + @override + void didUpdateWidget(covariant AlbumTile oldWidget) { + super.didUpdateWidget(oldWidget); + _prepare(); + } + + void _prepare() { + final path = widget.item.localPath; + if (path == _imagePath) { + return; + } + _imagePath = path; + final type = widget.item.mediaType; + final isImage = type == MediaType.image || type == MediaType.gif; + _imageFuture = + path != null && isImage ? MediaUtils.decryptAtRest(path) : null; + } + + @override + Widget build(BuildContext context) { + final item = widget.item; + final type = item.mediaType; + Widget content; + if (widget.hiddenCount != null && + widget.hiddenCount! > 0 && + item.isReady) { + content = Stack( + fit: StackFit.expand, + children: [ + _thumbnail(type), + Container( + color: Colors.black.withValues(alpha: 0.5), + alignment: Alignment.center, + child: Text( + '+${widget.hiddenCount}', + style: const TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.bold), + ), + ), + ], + ); + } else if (item.status == MediaDownloadStatus.failed) { + content = const Center(child: Icon(Icons.error_outline)); + } else if (!item.isReady) { + content = + const Center(child: CircularProgressIndicator(strokeWidth: 2)); + } else { + content = _thumbnail(type); + } + + return GestureDetector( + onTap: widget.onTap, + child: ClipRRect( + borderRadius: BorderRadius.circular(8), + child: Container( + color: Colors.black.withValues(alpha: 0.1), + child: content, + ), + ), + ); + } + + Widget _thumbnail(MediaType? type) { + switch (type) { + case MediaType.image: + case MediaType.gif: + return FutureBuilder( + future: _imageFuture, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { + return const Center( + child: CircularProgressIndicator(strokeWidth: 2)); + } + if (!snapshot.hasData) { + return const Center(child: Icon(Icons.broken_image)); + } + return Image.memory(snapshot.data!, fit: BoxFit.cover); + }, + ); + case MediaType.video: + return Stack( + fit: StackFit.expand, + children: [ + VideoThumbnail(path: widget.item.localPath), + const Center( + child: Icon(Icons.play_circle_outline, + color: Colors.white, size: 28)), + ], + ); + case MediaType.voice: + return const Center(child: Icon(Icons.mic)); + case MediaType.file: + return Center( + child: Icon(MediaUtils.iconForFileName(widget.item.fileName))); + case null: + return const Center(child: Icon(Icons.broken_image)); + } + } +} + +/// First frame of an encrypted-at-rest video, used as a bubble thumbnail. +/// Materializes a temporary plaintext file for the platform player and +/// releases both when the bubble is disposed. +class VideoThumbnail extends StatefulWidget { + final String? path; + + const VideoThumbnail({this.path, super.key}); + + @override + State createState() => _VideoThumbnailState(); +} + +class _VideoThumbnailState extends State { + VideoPlayerController? _controller; + File? _tempFile; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void didUpdateWidget(covariant VideoThumbnail oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.path != widget.path) { + _disposeController(); + _load(); + } + } + + Future _load() async { + final path = widget.path; + if (path == null) { + return; + } + try { + final temp = await MediaUtils.materializeTempFile( + path, MediaUtils.extensionForType(MediaType.video)); + final controller = VideoPlayerController.file(temp); + await controller.initialize(); + await controller.setVolume(0); + if (!mounted) { + await controller.dispose(); + MediaUtils.deleteLocalFile(temp.path); + return; + } + setState(() { + _tempFile = temp; + _controller = controller; + }); + } catch (_) { + // The gradient fallback stays visible. + } + } + + void _disposeController() { + _controller?.dispose(); + _controller = null; + final temp = _tempFile; + _tempFile = null; + if (temp != null) { + MediaUtils.deleteLocalFile(temp.path); + } + } + + @override + void dispose() { + _disposeController(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final controller = _controller; + if (controller == null || !controller.value.isInitialized) { + return DecoratedBox( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [Color(0xFF2B2B2B), Color(0xFF000000)], + ), + ), + ); + } + return FittedBox( + fit: BoxFit.cover, + child: SizedBox( + width: controller.value.size.width, + height: controller.value.size.height, + child: VideoPlayer(controller), + ), + ); + } +} diff --git a/lib/widgets/voice_player.dart b/lib/widgets/voice_player.dart index 099e26f..c9552b9 100644 --- a/lib/widgets/voice_player.dart +++ b/lib/widgets/voice_player.dart @@ -140,36 +140,39 @@ class _VoicePlayerState extends State { : total.inMilliseconds.toDouble(); final value = position.inMilliseconds.clamp(0, max.toInt()).toDouble(); - return Column( - mainAxisSize: MainAxisSize.min, + // Slider and the time label sit on one line, so the track is + // vertically centred in the row instead of being pushed up by + // a stacked label. + return Row( children: [ - SliderTheme( - data: SliderTheme.of(context).copyWith( - trackHeight: 2, - thumbShape: - const RoundSliderThumbShape(enabledThumbRadius: 6), - overlayShape: - const RoundSliderOverlayShape(overlayRadius: 12), - activeTrackColor: widget.color, - thumbColor: widget.color, - inactiveTrackColor: widget.color.withValues(alpha: 0.3), - ), - child: Slider( - min: 0, - max: max, - value: value, - onChanged: _loading - ? null - : (v) => - _player.seek(Duration(milliseconds: v.toInt())), + Expanded( + child: SliderTheme( + data: SliderTheme.of(context).copyWith( + trackHeight: 2, + thumbShape: const RoundSliderThumbShape( + enabledThumbRadius: 6), + overlayShape: const RoundSliderOverlayShape( + overlayRadius: 12), + activeTrackColor: widget.color, + thumbColor: widget.color, + inactiveTrackColor: + widget.color.withValues(alpha: 0.3), + ), + child: Slider( + min: 0, + max: max, + value: value, + onChanged: _loading + ? null + : (v) => _player + .seek(Duration(milliseconds: v.toInt())), + ), ), ), - Align( - alignment: Alignment.centerRight, - child: Text( - _format(position.inMilliseconds > 0 ? position : total), - style: TextStyle(fontSize: 11, color: widget.color), - ), + const SizedBox(width: 4), + Text( + _format(position.inMilliseconds > 0 ? position : total), + style: TextStyle(fontSize: 11, color: widget.color), ), ], ); diff --git a/test/media_album_test.dart b/test/media_album_test.dart new file mode 100644 index 0000000..db6f823 --- /dev/null +++ b/test/media_album_test.dart @@ -0,0 +1,204 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper/utils/media_utils.dart'; +import 'package:whisper/utils/message_notifier.dart'; +import 'package:whisper_websocket_client_dart/models/media_reference.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +MediaReference _reference(String id, {MediaType type = MediaType.image}) => + MediaReference( + id, + Uint8List.fromList(List.generate(32, (i) => i)), + type, + 1024, + width: 800, + height: 600, + fileName: 'photo.jpg', + ); + +void main() { + group('media envelope', () { + test('single media keeps the v1 envelope', () { + final envelope = MediaUtils.buildMediaEnvelope(_reference('m1'), 'hi'); + final parsed = MediaUtils.tryParseMediaEnvelope(envelope); + expect(parsed, isNotNull); + expect(parsed!.references.single.mediaId, 'm1'); + expect(parsed.caption, 'hi'); + }); + + test('album round trips every reference in order', () { + final envelope = MediaUtils.buildAlbumEnvelope( + [_reference('a'), _reference('b'), _reference('c')], + 'album caption', + ); + final decoded = jsonDecode(utf8.decode(envelope)) as Map; + expect(decoded['whisperMsg'], MediaUtils.envelopeVersionAlbum); + + final parsed = MediaUtils.tryParseMediaEnvelope(envelope); + expect(parsed, isNotNull); + expect(parsed!.references.map((r) => r.mediaId), ['a', 'b', 'c']); + expect(parsed.caption, 'album caption'); + }); + + test('plain text is not an envelope', () { + final parsed = MediaUtils.tryParseMediaEnvelope( + Uint8List.fromList(utf8.encode('just text'))); + expect(parsed, isNull); + }); + + test('an unknown envelope version is not parsed', () { + final parsed = MediaUtils.tryParseMediaEnvelope(Uint8List.fromList( + utf8.encode('{"whisperMsg":99,"kind":"media","media":[]}'))); + expect(parsed, isNull); + }); + }); + + group('upload limit', () { + test('accounts for the transport overhead', () { + expect(MediaUtils.uploadFits(MediaUtils.maxUploadBytes), isFalse); + expect( + MediaUtils.uploadFits( + MediaUtils.maxUploadBytes - MediaUtils.transportOverheadBytes), + isTrue); + expect( + MediaUtils.uploadFits(MediaUtils.maxUploadBytes - + MediaUtils.transportOverheadBytes + + 1), + isFalse); + }); + }); + + group('album items', () { + test('serialize and deserialize', () { + final message = PrivateMessage('1', 'cap', DateTime(2026), DateTime(2026), + true); + message.setAlbum([ + AlbumItem( + mediaId: 'a', + type: MediaType.image.name, + size: 10, + width: 100, + height: 50, + fileName: 'a.jpg', + localPath: '/tmp/a', + ), + AlbumItem( + mediaId: 'b', + type: MediaType.video.name, + size: 20, + durationMs: 1500, + status: MediaDownloadStatus.pending, + ), + ]); + + expect(message.isAlbum, isTrue); + expect(message.isMedia, isTrue); + expect(message.mediaType, isNull); + final items = message.album; + expect(items.length, 2); + expect(items.first.isReady, isTrue); + expect(items.first.fileName, 'a.jpg'); + expect(items.last.isReady, isFalse); + expect(items.last.durationMs, 1500); + expect(message.localPaths, ['/tmp/a']); + }); + + test('expands into one entry per attachment for the viewer', () { + final message = PrivateMessage('1', 'cap', DateTime(2026), DateTime(2026), + true); + message.setAlbum([ + AlbumItem( + mediaId: 'a', + type: MediaType.image.name, + size: 1, + localPath: '/tmp/a'), + AlbumItem( + mediaId: 'b', + type: MediaType.image.name, + size: 1, + localPath: '/tmp/b'), + ]); + + final expanded = MessageNotifier.albumMedia(message); + expect(expanded.map((m) => m.mediaId), ['a', 'b']); + expect(expanded.every((m) => m.localPath != null), isTrue); + expect(MessageNotifier.viewableMedia([message]).length, 2); + }); + }); + + group('cache', () { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_album_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + }); + + tearDown(() async { + await Hive.box('privateMessages').clear(); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('updating one album attachment keeps the others untouched', () async { + final message = PrivateMessage('1', 'cap', DateTime(2026, 1, 1), + DateTime(2026, 1, 1), true, + downloadStatus: MediaDownloadStatus.pending); + message.setAlbum([ + AlbumItem( + mediaId: 'a', + type: MediaType.image.name, + size: 1, + status: MediaDownloadStatus.pending), + AlbumItem( + mediaId: 'b', + type: MediaType.image.name, + size: 1, + status: MediaDownloadStatus.pending), + ]); + await CacheUtils.addPrivateMessages('1', [message]); + + await CacheUtils.updatePrivateMessageMedia('1', 'b', + localPath: '/tmp/b', downloadStatus: MediaDownloadStatus.ready); + + final stored = (await CacheUtils.getPrivateMessages('1')).single; + final items = stored.album; + expect(items[0].status, MediaDownloadStatus.pending); + expect(items[0].localPath, isNull); + expect(items[1].status, MediaDownloadStatus.ready); + expect(items[1].localPath, '/tmp/b'); + // Not everything is ready yet, so the message stays pending. + expect(stored.downloadStatus, MediaDownloadStatus.pending); + + await CacheUtils.updatePrivateMessageMedia('1', 'a', + localPath: '/tmp/a', downloadStatus: MediaDownloadStatus.ready); + final done = (await CacheUtils.getPrivateMessages('1')).single; + expect(done.downloadStatus, MediaDownloadStatus.ready); + }); + + test('send status is stored on the message', () async { + final message = PrivateMessage('1', 'hi', DateTime(2026, 2, 1), + DateTime(2026, 2, 1), true, + sendStatus: SendStatus.sending); + await CacheUtils.addPrivateMessages('1', [message]); + await CacheUtils.updateStoredMessage('1', message, (stored) { + stored.sendStatus = SendStatus.sent; + }); + final stored = (await CacheUtils.getPrivateMessages('1')).single; + expect(stored.sendStatus, SendStatus.sent); + await CacheUtils.deletePrivateMessagesWithUser('1'); + }); + }); +} From fdac3b9f0cee445462953be465d7197a3169cfeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 17:21:05 +0100 Subject: [PATCH 045/181] feat(chat): sending state, bottom-anchored paged list, stoppable voice The bubble is stored before anything is sent (sendStatus sending, clock icon in the bubble, error icon when the send fails), so a message no longer appears only after the socket write and the UI never looks like it dropped the input. The message list is reversed: offset 0 is the newest message, so the chat opens at the bottom and growing bubbles or the keyboard cannot strand it mid-list. Only the newest 30 messages are rendered and 30 more are added when the user scrolls towards the top, without touching the Hive layout. Loading moved out of build (one read per change instead of a new Future and a full-box read-modify-write per rebuild). Hold-to-record works again: the recording bar is now overlaid on the input bar instead of replacing it, so the long-press recognizer is not disposed mid gesture and onLongPressEnd fires. A finger lifted while the recorder was still starting is handled, and the bar has explicit send and cancel buttons. --- lib/pages/chat_page.dart | 547 ++++++++++++++++++++++++++++----------- 1 file changed, 391 insertions(+), 156 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index d386b60..9b5e6eb 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1,11 +1,11 @@ import 'dart:async'; import 'dart:io'; +import 'dart:typed_data'; import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:page_transition/page_transition.dart'; -import 'package:provider/provider.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../models/user.dart'; @@ -28,18 +28,27 @@ class ChatPage extends StatefulWidget { // Transaprent AppBar: https://ckreymborg.medium.com/how-to-create-a-glassmorphism-frosted-glass-appbar-in-flutter-fb217ce1b4ca class _ChatPageState extends State { + /// Messages added per scroll-up step (incremental loading). + static const int _pageSize = 30; + // Add controller for text input final TextEditingController _controllerMessage = TextEditingController(); // Add list for messages List _messages = []; + // How many of the newest messages are rendered + int _visibleCount = _pageSize; // Buttons bool _isSending = false; - // ScrollController for content + // ScrollController for content (list is reversed: offset 0 is the newest) final ScrollController _scrollController = ScrollController(); // Indicates whether messages are being load for the first time bool _firstLoad = true; + // Guards against overlapping cache reads + bool _loading = false; // Voice recording state bool _isRecording = false; + bool _recordingStarting = false; + bool _stopRequested = false; bool _cancelRecording = false; MediaRecorderController? _recorderController; Duration _recordDuration = Duration.zero; @@ -50,6 +59,8 @@ class _ChatPageState extends State { @override void initState() { super.initState(); + MessageNotifier().addListener(_onMessagesChanged); + _scrollController.addListener(_onScroll); // Load messages from cache _loadMessages(); // Load concept message @@ -58,42 +69,77 @@ class _ChatPageState extends State { _loadChatTheme(); } - Future _loadChatTheme() async { - Color? color = await CacheUtils.getChatTheme(widget.user.id); - if (mounted) { + /// Reload the conversation from the cache when messages or media state change. + void _onMessagesChanged() { + _loadMessages(); + } + + /// Load the conversation once per change instead of once per build. + Future _loadMessages() async { + if (_loading || !mounted) { + return; + } + _loading = true; + try { + final messages = await MessageNotifier().getMessages(widget.user.id); + if (!mounted) { + return; + } + setState(() { + _messages = messages; + _firstLoad = false; + }); + } finally { + _loading = false; + } + } + + /// Extend the rendered window when the user scrolls towards older messages. + void _onScroll() { + if (!_scrollController.hasClients) { + return; + } + if (_scrollController.position.extentAfter < 200 && + _visibleCount < _messages.length) { setState(() { - _chatThemeColor = color; + _visibleCount += _pageSize; }); } } + /// Load the draft message saved when leaving the chat. Future getConceptMessage() async { String? conceptMsg = await CacheUtils.getMessageConcept(widget.user.id); - if (conceptMsg != null) { - _controllerMessage.text = conceptMsg; + if (!mounted) { + return; } + setState(() { + _controllerMessage.text = conceptMsg ?? ''; + }); } - Future _loadMessages() async { - _messages = await MessageNotifier().getMessages(widget.user.id); - MessageNotifier().notify(); - setState(() {}); + /// Load the per-chat theme override. + Future _loadChatTheme() async { + Color? color = await CacheUtils.getChatTheme(widget.user.id); + if (!mounted) { + return; + } + setState(() { + _chatThemeColor = color; + }); } - /// Open the chat info page (avatar and name in the header, info button). Future _openChatInfo() async { await Navigator.of(context).push(PageTransition( - duration: const Duration(milliseconds: 300), - reverseDuration: const Duration(milliseconds: 300), - curve: Curves.easeInOut, - type: PageTransitionType.rightToLeftJoined, - child: ChatInfoPage(widget.user.id), - childCurrent: widget)); - // The theme may have changed while the info page was open + type: PageTransitionType.rightToLeft, + child: ChatInfoPage(widget.user.id), + )); + // The theme (and possibly the user) may have changed while it was open. await _loadChatTheme(); + await _loadMessages(); } - /// Send message + /// Send the typed text. Future _sendMessage() async { final text = _controllerMessage.text; if (text.isEmpty) { @@ -104,7 +150,6 @@ class _ChatPageState extends State { }); if (await ChatSender.sendText(widget.user, text)) { _controllerMessage.text = ''; - // Delete concept await CacheUtils.deleteMessageConcept(widget.user.id); } if (mounted) { @@ -114,9 +159,8 @@ class _ChatPageState extends State { } } - /// Send a media attachment: encrypt for transport, upload, embed an encrypted - /// reference in the message, store the file encrypted-at-rest and add an - /// optimistic bubble. + /// Send a media attachment: probe what the type needs, then the shared send + /// path (encrypt, upload, persist a bubble, send). Future _sendMedia(MediaType type, File file, {String caption = '', int? durationMs}) async { setState(() { @@ -124,43 +168,49 @@ class _ChatPageState extends State { }); try { final bytes = await file.readAsBytes(); - - // Refuse what the server would reject anyway, before uploading it. - if (bytes.length > MediaUtils.maxUploadBytes) { - await Fluttertoast.showToast( - msg: - '${'fileTooLarge'.tr()} ${MediaUtils.formatBytes(MediaUtils.maxUploadBytes)}', - backgroundColor: Colors.red); - return; - } - - // Probe metadata depending on the media type. - int? width; - int? height; - int? duration = durationMs; - if (type == MediaType.image || type == MediaType.gif) { - final probe = await MediaUtils.imageDimensions(bytes); - width = probe.width; - height = probe.height; - } else if (type == MediaType.video) { - final probe = await MediaUtils.videoMetadata(file.path); - width = probe.width; - height = probe.height; - duration ??= probe.durationMs; - } - + final probe = await _probe(type, bytes, file.path, durationMs); final sent = await ChatSender.sendMedia(widget.user, type, bytes, caption: caption, - width: width, - height: height, - durationMs: duration, + width: probe.width, + height: probe.height, + durationMs: probe.durationMs, fileName: MediaUtils.baseName(file.path)); + _afterSend(sent, caption); + } catch (e) { + await Fluttertoast.showToast( + msg: e.toString(), backgroundColor: Colors.red); + } finally { + if (mounted) { + setState(() { + _isSending = false; + }); + } + } + } - // The caption (taken from the text field) was consumed -> clear it. - if (sent && caption.isNotEmpty && _controllerMessage.text == caption) { - _controllerMessage.text = ''; - await CacheUtils.deleteMessageConcept(widget.user.id); + /// Send several attachments as one album message. + Future _sendAlbum(List files, {String caption = ''}) async { + setState(() { + _isSending = true; + }); + try { + final attachments = []; + for (final file in files) { + final bytes = await file.readAsBytes(); + final type = MediaUtils.detectType(file.path); + final probe = await _probe(type, bytes, file.path, null); + attachments.add(OutgoingAttachment( + type: type, + bytes: bytes, + width: probe.width, + height: probe.height, + durationMs: probe.durationMs, + fileName: MediaUtils.baseName(file.path), + )); } + final sent = await ChatSender.sendAlbum(widget.user, attachments, + caption: caption); + _afterSend(sent, caption); } catch (e) { await Fluttertoast.showToast( msg: e.toString(), backgroundColor: Colors.red); @@ -173,24 +223,140 @@ class _ChatPageState extends State { } } - /// Pick media using [picker], detect its type (unless [forcedType] is set) - /// and send it, using any typed text as the caption. + /// Clear the composer when the caption was consumed by a successful send. + void _afterSend(bool sent, String caption) { + if (sent && caption.isNotEmpty && _controllerMessage.text == caption) { + _controllerMessage.text = ''; + CacheUtils.deleteMessageConcept(widget.user.id); + } + } + + /// Width/height/duration for the types that need them. + Future _probe( + MediaType type, Uint8List bytes, String path, int? durationMs) async { + if (type == MediaType.image || type == MediaType.gif) { + return MediaUtils.imageDimensions(bytes); + } + if (type == MediaType.video) { + final probe = await MediaUtils.videoMetadata(path); + return MediaProbe( + width: probe.width, + height: probe.height, + durationMs: probe.durationMs ?? durationMs, + ); + } + return MediaProbe(durationMs: durationMs); + } + + /// Pick one or more files, then confirm with an optional caption. + /// + /// [forcedType] fixes the type for camera picks; [filesOnly] rejects photos + /// and videos (the "File" entry must stay a document picker). Future _pickAndSend( - Future Function() picker, MediaType? forcedType) async { + Future> Function() picker, + {MediaType? forcedType, + bool filesOnly = false}) async { try { - final file = await picker(); - if (file == null) { + final picked = await picker(); + if (picked.isEmpty) { return; } - final type = forcedType ?? MediaUtils.detectType(file.path); - final caption = _controllerMessage.text.trim(); - await _sendMedia(type, file, caption: caption); + var files = picked; + if (filesOnly) { + files = picked.where((file) => !MediaUtils.isVisualMedia(file)).toList(); + if (files.length != picked.length) { + await Fluttertoast.showToast( + msg: 'fileTypeNotAllowed'.tr(), + backgroundColor: Colors.orange); + } + if (files.isEmpty) { + return; + } + } + + // Cheap size check before reading anything into memory. + for (final file in files) { + if (!MediaUtils.uploadFits(await file.length())) { + await Fluttertoast.showToast( + msg: + '${'fileTooLarge'.tr()} ${MediaUtils.formatBytes(MediaUtils.maxUploadBytes)}', + backgroundColor: Colors.red); + return; + } + } + + final caption = await _confirmAttachment(files.length); + if (caption == null) { + return; + } + if (files.length == 1) { + final type = forcedType ?? MediaUtils.detectType(files.first.path); + await _sendMedia(type, files.first, caption: caption); + } else { + await _sendAlbum(files, caption: caption); + } } catch (e) { await Fluttertoast.showToast( msg: e.toString(), backgroundColor: Colors.red); } } + /// Bottom sheet with a caption field; returns the caption, or null to cancel. + Future _confirmAttachment(int count) async { + final controller = TextEditingController(text: _controllerMessage.text.trim()); + final result = await showModalBottomSheet( + context: context, + showDragHandle: true, + isScrollControlled: true, + builder: (ctx) { + return Padding( + padding: EdgeInsets.only( + left: 16, + right: 16, + bottom: MediaQuery.of(ctx).viewInsets.bottom + 16, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + count > 1 + ? '${'sendAlbum'.tr()} ($count)' + : 'sendAttachment'.tr(), + style: Theme.of(ctx).textTheme.titleMedium, + ), + const SizedBox(height: 12), + TextField( + controller: controller, + minLines: 1, + maxLines: 4, + autofocus: true, + decoration: InputDecoration(hintText: 'addCaption'.tr()), + ), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + onPressed: () => Navigator.pop(ctx), + child: Text('cancel'.tr()), + ), + const SizedBox(width: 8), + FilledButton( + onPressed: () => Navigator.pop(ctx, controller.text.trim()), + child: Text('send'.tr()), + ), + ], + ), + ], + ), + ); + }, + ); + controller.dispose(); + return result; + } + /// GIF/WebP inserted straight from the keyboard (Gboard image keyboard). Future _onKeyboardContentInserted( KeyboardInsertedContent content) async { @@ -219,7 +385,10 @@ class _ChatPageState extends State { title: Text('attachCamera'.tr()), onTap: () { Navigator.pop(ctx); - _pickAndSend(MediaUtils.pickImageFromCamera, MediaType.image); + _pickAndSend(() async { + final file = await MediaUtils.pickImageFromCamera(); + return file == null ? [] : [file]; + }, forcedType: MediaType.image); }, ), ListTile( @@ -227,7 +396,10 @@ class _ChatPageState extends State { title: Text('attachVideoCamera'.tr()), onTap: () { Navigator.pop(ctx); - _pickAndSend(MediaUtils.pickVideoFromCamera, MediaType.video); + _pickAndSend(() async { + final file = await MediaUtils.pickVideoFromCamera(); + return file == null ? [] : [file]; + }, forcedType: MediaType.video); }, ), ListTile( @@ -235,7 +407,7 @@ class _ChatPageState extends State { title: Text('attachGallery'.tr()), onTap: () { Navigator.pop(ctx); - _pickAndSend(MediaUtils.pickMediaFromGallery, null); + _pickAndSend(MediaUtils.pickMultipleMediaFromGallery); }, ), ListTile( @@ -243,7 +415,7 @@ class _ChatPageState extends State { title: Text('attachFile'.tr()), onTap: () { Navigator.pop(ctx); - _pickAndSend(MediaUtils.pickFile, null); + _pickAndSend(MediaUtils.pickMultipleFiles, filesOnly: true); }, ), ], @@ -255,23 +427,30 @@ class _ChatPageState extends State { /// Start recording a voice message (hold-to-record). Future _startRecording() async { - if (_isRecording || _isSending) { + if (_isRecording || _recordingStarting || _isSending) { return; } + _recordingStarting = true; final controller = MediaRecorderController(); - if (!await controller.hasPermission()) { - await controller.dispose(); - await Fluttertoast.showToast( - msg: 'micPermissionDenied'.tr(), backgroundColor: Colors.red); - return; - } try { + if (!await controller.hasPermission()) { + await Fluttertoast.showToast( + msg: 'micPermissionDenied'.tr(), backgroundColor: Colors.red); + await controller.dispose(); + return; + } await controller.start(); } catch (e) { await controller.dispose(); await Fluttertoast.showToast( msg: e.toString(), backgroundColor: Colors.red); return; + } finally { + _recordingStarting = false; + } + if (!mounted) { + await controller.dispose(); + return; } setState(() { _recorderController = controller; @@ -286,6 +465,11 @@ class _ChatPageState extends State { }); } }); + // The finger was lifted while the recorder was still starting. + if (_stopRequested) { + _stopRequested = false; + await _stopRecording(); + } } /// Finish recording and send (unless the gesture was cancelled). @@ -295,9 +479,12 @@ class _ChatPageState extends State { final controller = _recorderController; _recorderController = null; final cancelled = _cancelRecording; - setState(() { - _isRecording = false; - }); + _cancelRecording = false; + if (mounted) { + setState(() { + _isRecording = false; + }); + } if (controller == null) { return; } @@ -322,6 +509,17 @@ class _ChatPageState extends State { durationMs: recorded.durationMs); } + /// Stop and drop the recording (bar button). + Future _cancelRecordingGesture() async { + if (!_isRecording) { + return; + } + setState(() { + _cancelRecording = true; + }); + await _stopRecording(); + } + String _formatRecordDuration(Duration d) { final minutes = d.inMinutes.remainder(60).toString().padLeft(2, '0'); final seconds = d.inSeconds.remainder(60).toString().padLeft(2, '0'); @@ -366,10 +564,19 @@ class _ChatPageState extends State { if (hasText) { return IconButton( onPressed: _isSending ? null : _sendMessage, - icon: const Icon(Icons.send), + icon: _isSending + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2), + ) + : const Icon(Icons.send), ); } - // Hold-to-record voice message. + // Hold-to-record voice message. The bar is overlaid while + // recording, so this detector stays mounted and its + // long-press end still fires. return GestureDetector( onLongPressStart: (_) { if (!_isSending) { @@ -388,6 +595,8 @@ class _ChatPageState extends State { onLongPressEnd: (_) { if (_isRecording) { _stopRecording(); + } else { + _stopRequested = true; } }, child: IconButton( @@ -415,7 +624,7 @@ class _ChatPageState extends State { final color = _cancelRecording ? Colors.red : Theme.of(context).colorScheme.primary; return Container( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), decoration: BoxDecoration( color: Theme.of(context).brightness == Brightness.dark ? Theme.of(context).colorScheme.surfaceBright @@ -435,8 +644,16 @@ class _ChatPageState extends State { overflow: TextOverflow.ellipsis, ), ), - Icon( - _cancelRecording ? Icons.delete : Icons.arrow_back, + IconButton( + tooltip: 'cancel'.tr(), + onPressed: _cancelRecordingGesture, + icon: const Icon(Icons.delete), + color: Colors.red, + ), + IconButton( + tooltip: 'send'.tr(), + onPressed: _stopRecording, + icon: const Icon(Icons.send), color: color, ), ], @@ -444,66 +661,94 @@ class _ChatPageState extends State { ); } - /// Get ListView with content - ListView _getContent(List messages) { - _firstLoad = false; + /// Avatar + name header shown above the oldest message. + Widget _buildHeader() { + return Center( + child: Padding( + padding: const EdgeInsets.only(top: 20, bottom: 20), + child: Column( + children: [ + CircleAvatar( + radius: 50, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 40, + color: widget.user.avatarTextColor, + ), + ), + ), + const SizedBox(height: 12), + Text( + widget.user.username, + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 30), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 50), + child: Text('legendaryChat'.tr(), textAlign: TextAlign.center)), + ], + ), + ), + ); + } + + /// Reversed list: offset 0 is the newest message, so the chat opens at the + /// bottom and growing bubbles or the keyboard never strand it mid-list. + Widget _getContent(List messages) { + final start = messages.length > _visibleCount + ? messages.length - _visibleCount + : 0; + final visible = messages.sublist(start); + final hasOlder = start > 0; + final itemCount = visible.length + 1; + return ListView.builder( physics: const BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics(), ), controller: _scrollController, - reverse: false, - itemCount: messages.length + 1, + reverse: true, + itemCount: itemCount, itemBuilder: (context, index) { - if (index == 0) { - // Header with avatar (will appear at the top) - return Center( - child: Padding( - padding: const EdgeInsets.only(top: 20, bottom: 20), - child: Column( - children: [ - CircleAvatar( - radius: 50, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 40, - color: widget.user.avatarTextColor, - ), - ), - ), - const SizedBox(height: 12), - Text( - widget.user.username, - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), - ), - const SizedBox(height: 30), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 50), - child: Text('legendaryChat'.tr(), - textAlign: TextAlign.center)), - ], + // Last item is the conversation header (top of the screen). + if (index == visible.length) { + if (hasOlder) { + return const Padding( + padding: EdgeInsets.symmetric(vertical: 16), + child: Center( + child: SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ), ), - ), - ); + ); + } + return _buildHeader(); } - // Return chat bubble - final previousMessage = index > 1 ? messages[index - 2] : null; - final message = messages[index - 1]; - final nextMessage = index < messages.length ? messages[index] : null; - return ChatBubble(previousMessage, message, nextMessage, widget.user); + // index 0 is the newest message; older messages have higher indices. + final message = visible[visible.length - 1 - index]; + final position = visible.length - 1 - index; + final older = position > 0 ? visible[position - 1] : null; + final newer = position < visible.length - 1 + ? visible[position + 1] + : null; + return ChatBubble(older, message, newer, widget.user); }, ); } @override void dispose() { + MessageNotifier().removeListener(_onMessagesChanged); + _scrollController.removeListener(_onScroll); _recordTimer?.cancel(); _recorderController?.dispose(); _controllerMessage.dispose(); @@ -513,8 +758,6 @@ class _ChatPageState extends State { @override Widget build(BuildContext context) { - final notifier = context.watch(); - return PopScope( onPopInvokedWithResult: (didPop, _) async { if (didPop && _messages.isNotEmpty) { @@ -591,35 +834,27 @@ class _ChatPageState extends State { children: [ // Messages and avatar list Expanded( - child: FutureBuilder>( - future: notifier.getMessages(widget.user.id), - builder: (context, snapshot) { - if (snapshot.connectionState == ConnectionState.waiting && - _firstLoad) { - return Center( - child: Transform.scale( - scale: 1.5, - child: CircularProgressIndicator(), - ), - ); - } - // Set data - if (snapshot.hasData) { - WidgetsBinding.instance.addPostFrameCallback((_) { - _scrollController.jumpTo( - _scrollController.position.maxScrollExtent); - }); - _messages = snapshot.data!; - } - // Return messages - return _getContent(_messages); - }), + child: _firstLoad + ? Center( + child: Transform.scale( + scale: 1.5, + child: CircularProgressIndicator(), + ), + ) + : _getContent(_messages), ), SafeArea( top: false, child: Padding( padding: const EdgeInsets.all(8.0), - child: _isRecording ? _buildRecordingBar() : _buildInputBar(), + child: Stack( + alignment: Alignment.center, + children: [ + _buildInputBar(), + if (_isRecording) + Positioned.fill(child: _buildRecordingBar()), + ], + ), ), ), ], From db03ffc510cb1463dca9b0d04eebdb586d0f3f4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 17:41:03 +0100 Subject: [PATCH 046/181] fix(chat): let the caption sheet own its TextEditingController _confirmAttachment disposed the controller as soon as showModalBottomSheet returned, but the route keeps rebuilding its TextField while it animates out, so every send through the attachment sheet threw 'A TextEditingController was used after being disposed' (followed by a cascade of framework assertions). The sheet is a StatefulWidget now and disposes the controller itself. Verified on the emulator by sending a video with an empty caption, and covered by a widget test that taps Send and lets the exit animation finish. --- lib/pages/chat_page.dart | 58 ++------------- lib/widgets/attachment_confirm_sheet.dart | 91 +++++++++++++++++++++++ test/attachment_confirm_sheet_test.dart | 64 ++++++++++++++++ 3 files changed, 161 insertions(+), 52 deletions(-) create mode 100644 lib/widgets/attachment_confirm_sheet.dart create mode 100644 test/attachment_confirm_sheet_test.dart diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 9b5e6eb..905cac0 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -14,6 +14,7 @@ import '../utils/chat_sender.dart'; import '../utils/media_utils.dart'; import '../utils/message_notifier.dart'; import '../utils/theme_utils.dart'; +import '../widgets/attachment_confirm_sheet.dart'; import '../widgets/chat_bubble.dart'; import 'chat_info_page.dart'; @@ -302,59 +303,12 @@ class _ChatPageState extends State { } /// Bottom sheet with a caption field; returns the caption, or null to cancel. - Future _confirmAttachment(int count) async { - final controller = TextEditingController(text: _controllerMessage.text.trim()); - final result = await showModalBottomSheet( - context: context, - showDragHandle: true, - isScrollControlled: true, - builder: (ctx) { - return Padding( - padding: EdgeInsets.only( - left: 16, - right: 16, - bottom: MediaQuery.of(ctx).viewInsets.bottom + 16, - ), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Text( - count > 1 - ? '${'sendAlbum'.tr()} ($count)' - : 'sendAttachment'.tr(), - style: Theme.of(ctx).textTheme.titleMedium, - ), - const SizedBox(height: 12), - TextField( - controller: controller, - minLines: 1, - maxLines: 4, - autofocus: true, - decoration: InputDecoration(hintText: 'addCaption'.tr()), - ), - const SizedBox(height: 12), - Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - TextButton( - onPressed: () => Navigator.pop(ctx), - child: Text('cancel'.tr()), - ), - const SizedBox(width: 8), - FilledButton( - onPressed: () => Navigator.pop(ctx, controller.text.trim()), - child: Text('send'.tr()), - ), - ], - ), - ], - ), - ); - }, + Future _confirmAttachment(int count) { + return AttachmentConfirmSheet.show( + context, + count: count, + initialCaption: _controllerMessage.text.trim(), ); - controller.dispose(); - return result; } /// GIF/WebP inserted straight from the keyboard (Gboard image keyboard). diff --git a/lib/widgets/attachment_confirm_sheet.dart b/lib/widgets/attachment_confirm_sheet.dart new file mode 100644 index 0000000..7e2fe9c --- /dev/null +++ b/lib/widgets/attachment_confirm_sheet.dart @@ -0,0 +1,91 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +/// Sheet shown after picking an attachment: an optional caption and a +/// Send/Cancel decision. Owns its [TextEditingController], because the sheet +/// route keeps rebuilding while it animates out. +class AttachmentConfirmSheet extends StatefulWidget { + /// Number of picked attachments; more than one means an album. + final int count; + final String initialCaption; + + const AttachmentConfirmSheet({ + required this.count, + this.initialCaption = '', + super.key, + }); + + /// Shows the sheet and returns the caption, or null when cancelled. + static Future show(BuildContext context, + {required int count, String initialCaption = ''}) { + return showModalBottomSheet( + context: context, + showDragHandle: true, + isScrollControlled: true, + builder: (ctx) => AttachmentConfirmSheet( + count: count, + initialCaption: initialCaption, + ), + ); + } + + @override + State createState() => _AttachmentConfirmSheetState(); +} + +class _AttachmentConfirmSheetState extends State { + late final TextEditingController _controller = + TextEditingController(text: widget.initialCaption); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Padding( + padding: EdgeInsets.only( + left: 16, + right: 16, + bottom: MediaQuery.of(context).viewInsets.bottom + 16, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + widget.count > 1 + ? '${'sendAlbum'.tr()} (${widget.count})' + : 'sendAttachment'.tr(), + style: Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 12), + TextField( + controller: _controller, + minLines: 1, + maxLines: 4, + autofocus: true, + decoration: InputDecoration(hintText: 'addCaption'.tr()), + ), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text('cancel'.tr()), + ), + const SizedBox(width: 8), + FilledButton( + onPressed: () => Navigator.pop(context, _controller.text.trim()), + child: Text('send'.tr()), + ), + ], + ), + ], + ), + ); + } +} diff --git a/test/attachment_confirm_sheet_test.dart b/test/attachment_confirm_sheet_test.dart new file mode 100644 index 0000000..191bd01 --- /dev/null +++ b/test/attachment_confirm_sheet_test.dart @@ -0,0 +1,64 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/widgets/attachment_confirm_sheet.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + setUpAll(() async { + // easy_localization reads the locale from shared_preferences + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + }); + + testWidgets('cancel returns null and send returns the caption', (tester) async { + String? result = 'unset'; + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Builder( + builder: (inner) => Scaffold( + body: Center( + child: ElevatedButton( + onPressed: () async { + result = await AttachmentConfirmSheet.show(inner, + count: 2, initialCaption: 'draft'); + }, + child: const Text('open'), + ), + ), + ), + ), + ); + }), + )); + // Let easy_localization load the bundle before interacting. + await tester.pumpAndSettle(); + + // Cancel + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('draft'), findsOneWidget); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(result, isNull); + + // Send: the exit animation keeps rebuilding the sheet, which used to touch + // a controller that had already been disposed. + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + await tester.tap(find.byType(FilledButton)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(result, 'draft'); + }); +} From 5434bb25fc788adff18dc74fc1dc82858a9f9ff8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 17:53:34 +0100 Subject: [PATCH 047/181] fix(media): video thumbnails in Chat Info, smaller play badge, caption side The shared media grid showed only a play icon for videos; it now renders the first frame (VideoThumbnail) with a small badge on top, so a video is recognisable next to photos. The chat bubble's play circle was oversized for a 240px thumbnail: the icon is 26px in a 36px circle instead of 36px in a 52px one. The caption bubble under an attachment is aligned to the same side as the message, so own albums and files no longer have a left-aligned caption under a right-aligned bubble. Verified on the emulator: Chat Info shows video frames, the bubble badge is smaller, own captions sit on the right. --- lib/pages/chat_info_page.dart | 34 ++++++++++++++++++++++++---------- lib/widgets/media_bubble.dart | 11 +++++++---- 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 6a3e093..bf0fb66 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -10,6 +10,7 @@ import '../utils/dialog_utils.dart'; import '../utils/media_utils.dart'; import '../utils/singleton.dart'; import '../utils/theme_utils.dart'; +import '../widgets/media_bubble.dart'; import 'home_page.dart'; import 'media_viewer_page.dart'; @@ -257,7 +258,7 @@ class _MediaTileState extends State<_MediaTile> { } Future _loadImage() async { - // Videos and documents have no thumbnail, an icon is enough. + // Videos get a first-frame thumbnail; documents show an icon. if (widget.message.mediaType == MediaType.video || widget.message.mediaType == MediaType.file) { return; @@ -290,26 +291,39 @@ class _MediaTileState extends State<_MediaTile> { onTap: widget.onTap, child: Container( color: Theme.of(context).colorScheme.surfaceContainerHighest, - child: _bytes != null - ? Image.memory(_bytes!, fit: BoxFit.cover) - : Center( - child: _error - ? Icon(Icons.broken_image, size: 24) - : isVideo - ? Icon(Icons.play_arrow, size: 32) + child: isVideo + ? _videoTile() + : _bytes != null + ? Image.memory(_bytes!, fit: BoxFit.cover) + : Center( + child: _error + ? const Icon(Icons.broken_image, size: 24) : isFile ? _fileTile() - : SizedBox( + : const SizedBox( width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2), ), - ), + ), ), ); } + /// Video: first frame with a play badge. + Widget _videoTile() { + return Stack( + fit: StackFit.expand, + children: [ + VideoThumbnail(path: widget.message.localPath), + const Center( + child: Icon(Icons.play_arrow, color: Colors.white, size: 28), + ), + ], + ); + } + /// Documents: extension badge instead of a thumbnail. Widget _fileTile() { final name = widget.message.fileName ?? ''; diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 4f9a588..c3bd4e4 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -205,7 +205,10 @@ class _MediaBubbleState extends State { Widget _withCaption(Widget media, bool hasCaption) { return Column( - crossAxisAlignment: CrossAxisAlignment.start, + // Own messages sit on the right, so the caption does too. + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ ClipRRect( @@ -314,12 +317,12 @@ class _MediaBubbleState extends State { ), Container( decoration: BoxDecoration( - color: Colors.black.withValues(alpha: 0.45), + color: Colors.black.withValues(alpha: 0.4), shape: BoxShape.circle, ), - padding: const EdgeInsets.all(8), + padding: const EdgeInsets.all(5), child: - const Icon(Icons.play_arrow, color: Colors.white, size: 36), + const Icon(Icons.play_arrow, color: Colors.white, size: 26), ), if (widget.message.durationMs != null) Positioned( From d99ee4a5ea85fad9a70df1eefaa22838d4de5344 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 17:58:19 +0100 Subject: [PATCH 048/181] fix(media): shrink the play badge on video bubbles 18px icon in a 24px circle instead of 26/36, and 20px in the album grid, so the badge no longer covers the thumbnail. --- lib/widgets/media_bubble.dart | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index c3bd4e4..6d4a7a5 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -317,12 +317,12 @@ class _MediaBubbleState extends State { ), Container( decoration: BoxDecoration( - color: Colors.black.withValues(alpha: 0.4), + color: Colors.black.withValues(alpha: 0.35), shape: BoxShape.circle, ), - padding: const EdgeInsets.all(5), + padding: const EdgeInsets.all(3), child: - const Icon(Icons.play_arrow, color: Colors.white, size: 26), + const Icon(Icons.play_arrow, color: Colors.white, size: 18), ), if (widget.message.durationMs != null) Positioned( @@ -523,7 +523,7 @@ class _AlbumTileState extends State { VideoThumbnail(path: widget.item.localPath), const Center( child: Icon(Icons.play_circle_outline, - color: Colors.white, size: 28)), + color: Colors.white, size: 20)), ], ); case MediaType.voice: From 68fd9012feb695c65134457587b047b74c773af2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 18:07:39 +0100 Subject: [PATCH 049/181] fix(media): keep the video play badge at its intrinsic size The badge was a direct child of a StackFit.expand Stack, so its Container got the full bubble constraints and the circle was drawn as a huge ellipse over the thumbnail. Wrapping it in Center gives it its own 24px box. This is why shrinking the icon did not help: the visible 'icon' was the stretched circle, not the triangle. --- lib/widgets/media_bubble.dart | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 6d4a7a5..5d85694 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -315,14 +315,18 @@ class _MediaBubbleState extends State { borderRadius: BorderRadius.circular(16), ), ), - Container( - decoration: BoxDecoration( - color: Colors.black.withValues(alpha: 0.35), - shape: BoxShape.circle, + // Center gives the badge its intrinsic size; without it the + // StackFit.expand stack stretches the circle over the whole bubble. + Center( + child: Container( + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.35), + shape: BoxShape.circle, + ), + padding: const EdgeInsets.all(3), + child: + const Icon(Icons.play_arrow, color: Colors.white, size: 18), ), - padding: const EdgeInsets.all(3), - child: - const Icon(Icons.play_arrow, color: Colors.white, size: 18), ), if (widget.message.durationMs != null) Positioned( From b4f298a0066ac0ca09f44e76be83ad5ca99ff11c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 13 Nov 2026 18:39:36 +0100 Subject: [PATCH 050/181] fix(media): make the video play badge a bit larger 24px icon in a 32px circle (was 18/24), so it reads as a play button without looking oversized again. Verified on the emulator. --- lib/widgets/media_bubble.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 5d85694..70ac618 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -323,9 +323,9 @@ class _MediaBubbleState extends State { color: Colors.black.withValues(alpha: 0.35), shape: BoxShape.circle, ), - padding: const EdgeInsets.all(3), + padding: const EdgeInsets.all(4), child: - const Icon(Icons.play_arrow, color: Colors.white, size: 18), + const Icon(Icons.play_arrow, color: Colors.white, size: 24), ), ), if (widget.message.durationMs != null) From de9d86e2264022e3328a02ca97584b3b93be6d32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 17:05:15 +0100 Subject: [PATCH 051/181] feat(search): rework user search page Debounced search with inline loading, empty and error states, and a clear action. Adds the search page strings plus the admin card strings used by the upcoming users/invites rework. --- assets/translations/cs.json | 11 +- assets/translations/en.json | 11 +- lib/pages/search_user_page.dart | 209 ++++++++++++++++++++++---------- test/search_user_test.dart | 110 +++++++++++++++++ 4 files changed, 275 insertions(+), 66 deletions(-) create mode 100644 test/search_user_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 7d850c8..885c653 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -25,6 +25,13 @@ "deleteUserConfirm": "Potvrdit smazání uživatele", "deleteUserConfirmText": "Opravdu chcete smazat tohoto uživatele? Tato akce je nevratná.", "deleteUser": "Smazat uživatele", + "adminBadge": "ADMIN", + "noUsers": "Žádní uživatelé", + "noInvites": "Žádné pozvánky", + "loadError": "Nepodařilo se načíst data", + "userDeleted": "Uživatel smazán", + "deleteUserConfirmTextName": "Opravdu chcete smazat uživatele %s? Tato akce je nevratná.", + "inviteExpiresIn": "vyprší za %s %s", "chatInfoPage": "Informace o chatu", "deleteChatConfirm": "Potvrdit smazání chatu", "deleteChatConfirmText": "Opravdu chcete smazat tento chat?", @@ -47,6 +54,9 @@ "scanQr": "Naskenujte QR kód pozvánky", "searchUserPage": "Hledat uživatele", "enterUsername": "Uživatelské jméno vaší oběti", + "clearSearch": "Vymazat hledání", + "noUsersFound": "Uživatel nenalezen", + "userSearchFailed": "Hledání se nezdařilo", "settingsPage": "Nastavení", "themeSettings": "Motiv", "chatTheme": "Téma chatu", @@ -55,7 +65,6 @@ "biometrySettings": "Ověření otiskem prstu", "wikiLink": "Wiki", "repoLink": "Zdrojový kód", - "dangerZone": "Nebezpečná zóna", "deleteAllChatsConfirm": "Potvrdit smazání všech chatů", "deleteAllChatsConfirmText": "Opravdu chcete smazat všechny své chaty?", "deleteAllChats": "Smazat všechny chaty", diff --git a/assets/translations/en.json b/assets/translations/en.json index c279b95..d6a39d2 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -25,6 +25,13 @@ "deleteUserConfirm": "Confirm User Deletion", "deleteUserConfirmText": "Are you sure you want to delete this user? This action cannot be undone.", "deleteUser": "Delete User", + "adminBadge": "ADMIN", + "noUsers": "No users", + "noInvites": "No invites", + "loadError": "Failed to load data", + "userDeleted": "User deleted", + "deleteUserConfirmTextName": "Are you sure you want to delete %s? This action cannot be undone.", + "inviteExpiresIn": "expires in %s %s", "chatInfoPage": "Chat Info", "deleteChatConfirm": "Confirm Chat Deletion", "deleteChatConfirmText": "Are you sure you want to delete this chat?", @@ -47,6 +54,9 @@ "scanQr": "Scan the invitation QR code", "searchUserPage": "Search for users", "enterUsername": "Your victim's username", + "clearSearch": "Clear search", + "noUsersFound": "No users found", + "userSearchFailed": "Search failed", "settingsPage": "Settings", "themeSettings": "Theme", "chatTheme": "Chat theme", @@ -55,7 +65,6 @@ "biometrySettings": "Fingerprint authentication", "wikiLink": "Wiki", "repoLink": "Source code", - "dangerZone": "Danger zone", "deleteAllChatsConfirm": "Confirm deletion of all chats", "deleteAllChatsConfirmText": "Are you sure you want to delete all your chats?", "deleteAllChats": "Delete all chats", diff --git a/lib/pages/search_user_page.dart b/lib/pages/search_user_page.dart index 43e3e43..02dac5e 100644 --- a/lib/pages/search_user_page.dart +++ b/lib/pages/search_user_page.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import '../models/user.dart'; @@ -6,57 +8,112 @@ import '../utils/utils.dart'; import '../widgets/user_list_item.dart'; import 'chat_page.dart'; +typedef UserSearchCallback = Future?> Function(String query); + class SearchUserPage extends StatefulWidget { - const SearchUserPage({this.onUserSelected, super.key}); + const SearchUserPage({this.onUserSelected, this.search, super.key}); /// When set, a tapped user is passed here instead of opening the chat. final void Function(User)? onUserSelected; + /// Search implementation; defaults to the server API. + final UserSearchCallback? search; + @override State createState() => _SearchUserPageState(); } class _SearchUserPageState extends State { + static const _debounceDuration = Duration(milliseconds: 250); + final _controllerSearch = TextEditingController(); List _users = []; bool _loading = false; + bool _error = false; + bool _searched = false; + Timer? _debounce; - /// Search users - Future _searchUsers() async { - // Empty search - if (_controllerSearch.text.isEmpty) { - return; + /// Invalidates in-flight requests as soon as the query changes. + int _generation = 0; + + Future?> _performSearch(String query) async { + final search = widget.search; + if (search != null) { + return search(query); } + final users = + await Utils.callApi(() => Singleton().userApi.searchUsers(query)); + return users?.map(User.fromModel).toList(); + } - if (context.mounted) { + void _onQueryChanged(String value) { + _debounce?.cancel(); + final query = value.trim(); + final generation = ++_generation; + + if (query.isEmpty) { setState(() { - _loading = true; _users = []; + _loading = false; + _error = false; + _searched = false; }); + return; } - // Get users from server - var users = await Utils.callApi( - () => Singleton().userApi.searchUsers(_controllerSearch.text)); - if (context.mounted) { - setState(() { - if (users != null) { - for (var x in users) { - _users.add(User.fromModel(x)); - } - } - }); + setState(() { + _error = false; + }); + _debounce = Timer(_debounceDuration, () => _search(query, generation)); + } + + Future _search(String query, int generation) async { + if (!mounted || generation != _generation) { + return; } + setState(() { + _loading = true; + _error = false; + }); - if (context.mounted) { - setState(() { - _loading = false; - }); + final users = await _performSearch(query); + if (!mounted || generation != _generation) { + return; + } + setState(() { + _loading = false; + _searched = true; + if (users == null) { + _error = true; + } else { + _users = users; + _error = false; + } + }); + } + + void _submitQuery(String value) { + _debounce?.cancel(); + final query = value.trim(); + if (query.isEmpty) { + return; } + final generation = ++_generation; + _search(query, generation); + } + + void _retry() { + _submitQuery(_controllerSearch.text); + } + + void _clearQuery() { + _controllerSearch.clear(); + _onQueryChanged(''); } @override void dispose() { + _debounce?.cancel(); _controllerSearch.dispose(); super.dispose(); } @@ -67,7 +124,6 @@ class _SearchUserPageState extends State { appBar: AppBar( title: Text('searchUserPage'.tr()), ), - resizeToAvoidBottomInset: false, body: SafeArea( child: Padding( padding: const EdgeInsets.all(16.0), @@ -78,6 +134,9 @@ class _SearchUserPageState extends State { padding: const EdgeInsets.only(bottom: 15), child: TextField( controller: _controllerSearch, + onChanged: _onQueryChanged, + onSubmitted: _submitQuery, + textInputAction: TextInputAction.search, decoration: InputDecoration( hintText: 'enterUsername'.tr(), filled: true, @@ -88,51 +147,73 @@ class _SearchUserPageState extends State { borderRadius: BorderRadius.circular(30), borderSide: BorderSide.none, ), - suffixIcon: IconButton( - onPressed: _loading ? null : _searchUsers, - icon: const Icon(Icons.search), - ), + suffixIcon: _loading + ? const Padding( + padding: EdgeInsets.all(14), + child: SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ) + : _controllerSearch.text.isNotEmpty + ? IconButton( + tooltip: 'clearSearch'.tr(), + onPressed: _clearQuery, + icon: const Icon(Icons.close), + ) + : null, ), ), ), - // Loading - Visibility( - visible: _loading, - child: const Padding( - padding: EdgeInsets.only(top: 20, left: 7, right: 7), - child: CircularProgressIndicator(), - ), - ), - // Users list - Visibility( - visible: !_loading, - child: Expanded( - child: ListView.builder( - physics: const BouncingScrollPhysics( - parent: AlwaysScrollableScrollPhysics(), - ), - itemCount: _users.length, - itemBuilder: (context, index) { - return Padding( - padding: const EdgeInsets.only(bottom: 10), - child: UserListItem(_users[index], () async { - final onUserSelected = widget.onUserSelected; - if (onUserSelected != null) { - onUserSelected(_users[index]); - return; - } - Navigator.pushAndRemoveUntil( - context, - MaterialPageRoute( - builder: (context) => ChatPage(_users[index])), - (route) => route - .isFirst, // Returns true only for Home page - ); - }), - ); - }, + if (_error) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + children: [ + const Icon(Icons.error_outline, size: 20), + const SizedBox(width: 8), + Expanded(child: Text('userSearchFailed'.tr())), + TextButton( + onPressed: _retry, + child: Text('retry'.tr()), + ), + ], ), ), + Expanded( + child: _users.isEmpty + ? Center( + child: !_loading && !_error && _searched + ? Text('noUsersFound'.tr()) + : const SizedBox.shrink(), + ) + : ListView.builder( + physics: const BouncingScrollPhysics( + parent: AlwaysScrollableScrollPhysics(), + ), + itemCount: _users.length, + itemBuilder: (context, index) { + return Padding( + padding: const EdgeInsets.only(bottom: 10), + child: UserListItem(_users[index], () async { + final onUserSelected = widget.onUserSelected; + if (onUserSelected != null) { + onUserSelected(_users[index]); + return; + } + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (context) => + ChatPage(_users[index])), + (route) => route + .isFirst, // Returns true only for Home page + ); + }), + ); + }, + ), ), ], ), diff --git a/test/search_user_test.dart b/test/search_user_test.dart new file mode 100644 index 0000000..00fdd89 --- /dev/null +++ b/test/search_user_test.dart @@ -0,0 +1,110 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/pages/search_user_page.dart'; + +User user(String name) => User(name, name, 'public-key', false); + +Widget app(SearchUserPage page) => MaterialApp(home: page); + +void main() { + testWidgets('searches after the debounce and clears the results', + (tester) async { + final calls = []; + Future?> search(String query) async { + calls.add(query); + return [user('result-$query')]; + } + + await tester.pumpWidget(app(SearchUserPage(search: search))); + await tester.pumpAndSettle(); + final field = find.byType(TextField); + + await tester.enterText(field, 'a'); + await tester.pump(const Duration(milliseconds: 200)); + expect(calls, isEmpty); + + await tester.enterText(field, 'ab'); + await tester.pump(const Duration(milliseconds: 249)); + expect(calls, isEmpty); + + await tester.pump(const Duration(milliseconds: 1)); + await tester.pumpAndSettle(); + expect(calls, ['ab']); + expect(find.text('result-ab'), findsOneWidget); + + await tester.tap(find.byTooltip('clearSearch')); + await tester.pumpAndSettle(); + expect(find.text('result-ab'), findsNothing); + expect(calls, ['ab']); + }); + + testWidgets('ignores a stale response', (tester) async { + final first = Completer?>(); + final second = Completer?>(); + final calls = []; + Future?> search(String query) { + calls.add(query); + return query == 'a' ? first.future : second.future; + } + + await tester.pumpWidget(app(SearchUserPage(search: search))); + await tester.pumpAndSettle(); + final field = find.byType(TextField); + + await tester.enterText(field, 'a'); + await tester.pump(const Duration(milliseconds: 250)); + await tester.enterText(field, 'ab'); + await tester.pump(const Duration(milliseconds: 250)); + expect(calls, ['a', 'ab']); + + second.complete([user('new')]); + await tester.pumpAndSettle(); + expect(find.text('new'), findsOneWidget); + + first.complete([user('old')]); + await tester.pumpAndSettle(); + expect(find.text('new'), findsOneWidget); + expect(find.text('old'), findsNothing); + }); + + testWidgets('keeps results on error and retries', (tester) async { + var fail = false; + Future?> search(String query) async => + fail ? null : [user('alice')]; + + await tester.pumpWidget(app(SearchUserPage(search: search))); + await tester.pumpAndSettle(); + final field = find.byType(TextField); + + await tester.enterText(field, 'a'); + await tester.pump(const Duration(milliseconds: 250)); + await tester.pumpAndSettle(); + expect(find.text('alice'), findsOneWidget); + + fail = true; + await tester.enterText(field, 'ab'); + await tester.pump(const Duration(milliseconds: 250)); + await tester.pumpAndSettle(); + expect(find.text('userSearchFailed'), findsOneWidget); + expect(find.text('alice'), findsOneWidget); + + fail = false; + await tester.tap(find.text('retry')); + await tester.pumpAndSettle(); + expect(find.text('userSearchFailed'), findsNothing); + expect(find.text('alice'), findsOneWidget); + }); + + testWidgets('shows the empty result state', (tester) async { + await tester.pumpWidget(app(SearchUserPage(search: (_) async => []))); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), 'nobody'); + await tester.pump(const Duration(milliseconds: 250)); + await tester.pumpAndSettle(); + + expect(find.text('noUsersFound'), findsOneWidget); + }); +} From d770053d6687a5d8ee2c23b8e015eb5c2a0d8134 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 17:05:19 +0100 Subject: [PATCH 052/181] fix(media): own caption controller, smaller play badge, chat info thumbnails --- lib/pages/chat_info_page.dart | 3 +++ lib/pages/chat_page.dart | 28 ++++++++++------------- lib/widgets/media_bubble.dart | 43 +++++++++++++++++++++++++---------- test/file_media_test.dart | 31 +++++++++++++++++++++++++ 4 files changed, 77 insertions(+), 28 deletions(-) diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index bf0fb66..29a773b 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -166,6 +166,8 @@ class _ChatInfoPageState extends State { ), ), + Divider(thickness: 1, indent: 10, endIndent: 10), + // Shared media if (_media.isNotEmpty) ...[ Padding( @@ -190,6 +192,7 @@ class _ChatInfoPageState extends State { onTap: () => _openMedia(_media[index]), ), ), + Divider(thickness: 1, indent: 10, endIndent: 10), ], // Delete chat diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 905cac0..c451623 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -253,10 +253,8 @@ class _ChatPageState extends State { /// /// [forcedType] fixes the type for camera picks; [filesOnly] rejects photos /// and videos (the "File" entry must stay a document picker). - Future _pickAndSend( - Future> Function() picker, - {MediaType? forcedType, - bool filesOnly = false}) async { + Future _pickAndSend(Future> Function() picker, + {MediaType? forcedType, bool filesOnly = false}) async { try { final picked = await picker(); if (picked.isEmpty) { @@ -264,11 +262,11 @@ class _ChatPageState extends State { } var files = picked; if (filesOnly) { - files = picked.where((file) => !MediaUtils.isVisualMedia(file)).toList(); + files = + picked.where((file) => !MediaUtils.isVisualMedia(file)).toList(); if (files.length != picked.length) { await Fluttertoast.showToast( - msg: 'fileTypeNotAllowed'.tr(), - backgroundColor: Colors.orange); + msg: 'fileTypeNotAllowed'.tr(), backgroundColor: Colors.orange); } if (files.isEmpty) { return; @@ -522,8 +520,8 @@ class _ChatPageState extends State { ? const SizedBox( width: 18, height: 18, - child: CircularProgressIndicator( - strokeWidth: 2), + child: + CircularProgressIndicator(strokeWidth: 2), ) : const Icon(Icons.send), ); @@ -656,9 +654,8 @@ class _ChatPageState extends State { /// Reversed list: offset 0 is the newest message, so the chat opens at the /// bottom and growing bubbles or the keyboard never strand it mid-list. Widget _getContent(List messages) { - final start = messages.length > _visibleCount - ? messages.length - _visibleCount - : 0; + final start = + messages.length > _visibleCount ? messages.length - _visibleCount : 0; final visible = messages.sublist(start); final hasOlder = start > 0; final itemCount = visible.length + 1; @@ -691,9 +688,8 @@ class _ChatPageState extends State { final message = visible[visible.length - 1 - index]; final position = visible.length - 1 - index; final older = position > 0 ? visible[position - 1] : null; - final newer = position < visible.length - 1 - ? visible[position + 1] - : null; + final newer = + position < visible.length - 1 ? visible[position + 1] : null; return ChatBubble(older, message, newer, widget.user); }, ); @@ -740,7 +736,7 @@ class _ChatPageState extends State { backgroundColor: Theme.of(context) .colorScheme .surface - .withValues(alpha: 0.2), + .withValues(alpha: 0.5), leading: Row( children: [ IconButton( diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 70ac618..d32a9f4 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -123,8 +123,21 @@ class _MediaBubbleState extends State { return _albumWidget(hasCaption); } + final insideBubble = type == MediaType.voice || type == MediaType.file; + Widget media; - if (widget.message.downloadStatus == MediaDownloadStatus.pending) { + if (insideBubble && + widget.message.downloadStatus == MediaDownloadStatus.pending) { + media = type == MediaType.voice + ? SizedBox( + width: 220, + height: 48, + child: Center( + child: CircularProgressIndicator(color: widget.textColor), + ), + ) + : _fileWidget(); + } else if (widget.message.downloadStatus == MediaDownloadStatus.pending) { media = _placeholder(child: const CircularProgressIndicator()); } else if (widget.message.downloadStatus == MediaDownloadStatus.failed) { media = _failed(); @@ -151,7 +164,6 @@ class _MediaBubbleState extends State { } // Voice and file messages live inside the coloured bubble. - final insideBubble = type == MediaType.voice || type == MediaType.file; if (insideBubble) { return Container( decoration: BoxDecoration( @@ -188,9 +200,8 @@ class _MediaBubbleState extends State { ), itemCount: shown, itemBuilder: (context, index) { - final hidden = items.length > 4 && index == 3 - ? items.length - 3 - : null; + final hidden = + items.length > 4 && index == 3 ? items.length - 3 : null; return AlbumTile( item: items[index], hiddenCount: hidden, @@ -369,8 +380,18 @@ class _MediaBubbleState extends State { child: Row( mainAxisSize: MainAxisSize.min, children: [ - Icon(MediaUtils.iconForFileName(widget.message.fileName), - color: widget.textColor, size: 32), + if (widget.message.downloadStatus == MediaDownloadStatus.pending) + SizedBox( + width: 32, + height: 32, + child: CircularProgressIndicator( + strokeWidth: 2, + color: widget.textColor, + ), + ) + else + Icon(MediaUtils.iconForFileName(widget.message.fileName), + color: widget.textColor, size: 32), const SizedBox(width: 8), ConstrainedBox( constraints: const BoxConstraints(maxWidth: 180), @@ -462,9 +483,7 @@ class _AlbumTileState extends State { final item = widget.item; final type = item.mediaType; Widget content; - if (widget.hiddenCount != null && - widget.hiddenCount! > 0 && - item.isReady) { + if (widget.hiddenCount != null && widget.hiddenCount! > 0 && item.isReady) { content = Stack( fit: StackFit.expand, children: [ @@ -485,8 +504,7 @@ class _AlbumTileState extends State { } else if (item.status == MediaDownloadStatus.failed) { content = const Center(child: Icon(Icons.error_outline)); } else if (!item.isReady) { - content = - const Center(child: CircularProgressIndicator(strokeWidth: 2)); + content = const Center(child: CircularProgressIndicator(strokeWidth: 2)); } else { content = _thumbnail(type); } @@ -629,6 +647,7 @@ class _VideoThumbnailState extends State { } return FittedBox( fit: BoxFit.cover, + clipBehavior: Clip.hardEdge, child: SizedBox( width: controller.value.size.width, height: controller.value.size.height, diff --git a/test/file_media_test.dart b/test/file_media_test.dart index c3564fb..e1faf62 100644 --- a/test/file_media_test.dart +++ b/test/file_media_test.dart @@ -121,4 +121,35 @@ void main() { expect(find.text('2.0 KB'), findsOneWidget); expect(find.byIcon(Icons.picture_as_pdf), findsOneWidget); }); + + testWidgets('pending voice and file bubbles are not square', (tester) async { + PrivateMessage pending(String type, {String? fileName}) => PrivateMessage( + '1', '', DateTime(2026, 11, 13), DateTime(2026, 11, 13), false, + mediaTypeStr: type, + mediaSize: 2048, + fileName: fileName, + downloadStatus: MediaDownloadStatus.pending); + + Widget bubble(PrivateMessage message) => MaterialApp( + home: Scaffold( + body: MediaBubble( + message: message, + bubbleColor: Colors.blue, + textColor: Colors.white, + onRetry: () {}, + canRetry: false, + conversationUserId: '1', + ), + ), + ); + + await tester.pumpWidget(bubble(pending('voice'))); + expect(tester.getSize(find.byType(MediaBubble)), const Size(236, 56)); + + await tester.pumpWidget(bubble(pending('file', fileName: 'invoice.pdf'))); + expect(find.text('invoice.pdf'), findsOneWidget); + final fileSize = tester.getSize(find.byType(MediaBubble)); + expect(fileSize.width, greaterThan(fileSize.height)); + expect(fileSize.height, lessThan(100)); + }); } From 9d9377a559164f6eb3c46d6e9bbaf98a70778ee8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 17:05:19 +0100 Subject: [PATCH 053/181] fix(settings): drop the danger zone heading --- lib/pages/settings_page.dart | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 9116d3b..5817690 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -271,18 +271,6 @@ class _SettingsPageState extends State { Divider(thickness: 1, indent: 10, endIndent: 10), - // Danger zone title - Padding( - padding: EdgeInsets.only(bottom: 5), - child: Text( - 'dangerZone'.tr(), - style: TextStyle( - color: Colors.red, - fontWeight: FontWeight.bold, - fontSize: 16), - ), - ), - // Delete all chats TextButton( onPressed: () async { From 20fdb5dde4233f38654eeea47fa143fe952642d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 17:05:20 +0100 Subject: [PATCH 054/181] fix(chat): drop the server echo of self-sent messages --- lib/utils/utils.dart | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 9c002a5..e5a2388 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -252,6 +252,11 @@ class Utils { await Fluttertoast.showToast( msg: 'decryptionFailed'.tr(), backgroundColor: Colors.red); } + // Self-sent messages are stored locally before sending; dropping the + // server echo prevents a duplicate bubble in the debug self-chat. + decryptedMessages.removeWhere( + (message) => message.senderId == Singleton().profile.user.id); + if (decryptedMessages.isNotEmpty) { // A batch can hold messages from several senders: store each // conversation under its own key. From 9f748d561587347ba1065798c251ffa249d8749b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 17:05:25 +0100 Subject: [PATCH 055/181] feat(admin): rework the server users and invites card Per-row delete via an overflow menu with a named confirmation dialog, an ADMIN badge, alphabetical ordering and a grouped card that matches the rest of the app. Adds loading, empty and retryable error states, keeps the selected sub-tab across bottom navigation switches and moves the invite FAB onto the invites tab only. Invites now show "expires in 14 min" instead of a raw countdown, and their timer is cancelled on dispose. --- lib/pages/home_page.dart | 403 +++++++++++++++---------- lib/utils/admin_format.dart | 27 ++ lib/widgets/admin_user_list_item.dart | 73 +++++ lib/widgets/invite_list_item.dart | 60 ++-- lib/widgets/select_user_list_item.dart | 51 ---- test/admin_format_test.dart | 33 ++ test/admin_user_list_item_test.dart | 45 +++ 7 files changed, 450 insertions(+), 242 deletions(-) create mode 100644 lib/utils/admin_format.dart create mode 100644 lib/widgets/admin_user_list_item.dart delete mode 100644 lib/widgets/select_user_list_item.dart create mode 100644 test/admin_format_test.dart create mode 100644 test/admin_user_list_item_test.dart diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 95991f3..8d299ea 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -5,8 +5,10 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; import 'package:page_transition/page_transition.dart'; import 'package:provider/provider.dart'; +import 'package:sprintf/sprintf.dart'; import '../pages/chat_page.dart'; import '../utils/websocket_manager.dart'; import '../widgets/chat_list_item.dart'; @@ -20,9 +22,10 @@ import '../utils/dialog_utils.dart'; import '../widgets/invite_list_item.dart'; import 'package:whisper_openapi_client_dart/api.dart'; import '../models/user.dart'; +import '../utils/admin_format.dart'; import '../utils/singleton.dart'; import '../utils/utils.dart'; -import '../widgets/select_user_list_item.dart'; +import '../widgets/admin_user_list_item.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @@ -31,16 +34,25 @@ class HomePage extends StatefulWidget { State createState() => _HomePageState(); } -class _HomePageState extends State { +class _HomePageState extends State + with SingleTickerProviderStateMixin { final WebSocketManager _webSocketManager = WebSocketManager(); List _serverUsers = []; - List _selectedUsers = []; int _currentPageIndex = 0; List _serverInvites = []; Map _chats = {}; bool _firstLoad = true; String? _pendingFid; // Store pending FID + // Kept in state so switching the bottom navigation back to the admin panel + // does not drop the selected sub-tab. + late final TabController _adminTabController = + TabController(length: 2, vsync: this); + bool _usersLoading = true; + bool _usersError = false; + bool _invitesLoading = true; + bool _invitesError = false; + @override void initState() { super.initState(); @@ -83,6 +95,7 @@ class _HomePageState extends State { @override void dispose() { + _adminTabController.dispose(); if (NotificationService.onChatSelected == _openChat) { NotificationService.onChatSelected = null; } @@ -151,56 +164,69 @@ class _HomePageState extends State { /// Get server users Future _getServerUsers() async { - if (mounted) { - setState(() { - _serverUsers = []; - _selectedUsers = []; - }); - var users = await Utils.callApi(() => Singleton().userApi.getAllUsers()); - if (users != null) { - for (var x in users) { - _serverUsers.add(User.fromModel(x)); - } - if (mounted) { - setState(() {}); - } - } + if (!mounted) { + return; } - } - - /// Delete selected users - Future _deleteSelectedUsers() async { setState(() { - _serverUsers = - []; // I am unable to deactivate the user checkbox, so I will make all the users vanish so it will reset itself :) + _usersError = false; + _usersLoading = true; }); - // Delete selected users - await Utils.callApi(() => Singleton() - .userApi - .deleteUsers(deleteUsersInput: DeleteUsersInput(ids: _selectedUsers))); + final users = await Utils.callApi(() => Singleton().userApi.getAllUsers()); + if (!mounted) { + return; + } setState(() { - _selectedUsers = []; + // A failed refresh keeps the rows that are already on screen. + _usersError = users == null; + if (users != null) { + _serverUsers = sortedByUsername(users.map(User.fromModel).toList()); + } + _usersLoading = false; }); - // Refresh users + } + + /// Delete one user after the confirmation dialog confirmed it. + Future _deleteUser(User user) async { + try { + await Utils.callApi( + () => Singleton() + .userApi + .deleteUsers(deleteUsersInput: DeleteUsersInput(ids: [user.id])), + rethrowErr: true, + ); + } catch (_) { + // Utils.callApi already surfaced the error as a red toast. + return; + } + if (!mounted) { + return; + } + Fluttertoast.showToast( + msg: 'userDeleted'.tr(), backgroundColor: Colors.grey); await _getServerUsers(); } /// Get server invites Future _getServerInvites() async { - if (mounted) { - setState(() { - _serverInvites = []; - }); - var invites = - await Utils.callApi(() => Singleton().inviteApi.getAllInvites()); - if (mounted) { - setState(() { - if (invites != null) { - _serverInvites = invites; - } - }); - } + if (!mounted) { + return; } + setState(() { + _invitesError = false; + _invitesLoading = true; + }); + final invites = + await Utils.callApi(() => Singleton().inviteApi.getAllInvites()); + if (!mounted) { + return; + } + setState(() { + _invitesError = invites == null; + if (invites != null) { + _serverInvites = invites; + } + _invitesLoading = false; + }); } /// Open the chat of [userId] on top of Home. @@ -235,12 +261,11 @@ class _HomePageState extends State { await _openChat(userId); } - /// Shows new invite dialog. + /// Shows new invite dialog. It has no cancel path, so closing it always + /// means an invite was created. Future _createNewInvite(BuildContext context) async { - await showDialog(context: context, builder: DialogUtils.inviteDialog) - .then((_) async { - await _getServerInvites(); - }); + await showDialog(context: context, builder: DialogUtils.inviteDialog); + await _getServerInvites(); } /// Get ListView with content @@ -289,7 +314,7 @@ class _HomePageState extends State { backgroundColor: Theme.of(context) .colorScheme .surface - .withValues(alpha: 0.2), + .withValues(alpha: 0.5), // User icon with first letter leading: Transform.scale( scale: 0.65, @@ -337,10 +362,10 @@ class _HomePageState extends State { ) : null, resizeToAvoidBottomInset: false, - // Floating button - floatingActionButton: FloatingActionButton( - onPressed: _currentPageIndex == 0 - ? () { + // Floating button, only on the messages tab; the invites tab has its own + floatingActionButton: _currentPageIndex == 0 + ? FloatingActionButton( + onPressed: () { Navigator.of(context).push(PageTransition( duration: const Duration(milliseconds: 300), reverseDuration: const Duration(milliseconds: 300), @@ -348,20 +373,14 @@ class _HomePageState extends State { type: PageTransitionType.bottomToTopJoined, child: SearchUserPage(), childCurrent: widget)); - } - : () async { - await _createNewInvite(context); }, - shape: const CircleBorder(), - foregroundColor: Theme.of(context).colorScheme.surface, - backgroundColor: Theme.of(context).colorScheme.primary, - tooltip: _currentPageIndex == 0 - ? 'addChat'.tr() - : 'newInvite'.tr(), // Change tooltip according to page index - child: Icon(_currentPageIndex == 0 - ? Icons.add_comment - : Icons.person_add), // Change icon according to page index - ), + shape: const CircleBorder(), + foregroundColor: Theme.of(context).colorScheme.surface, + backgroundColor: Theme.of(context).colorScheme.primary, + tooltip: 'addChat'.tr(), + child: const Icon(Icons.add_comment), + ) + : null, // Bottom navigation bar for admin only bottomNavigationBar: Singleton().profile.user.admin ? SafeArea( @@ -420,104 +439,172 @@ class _HomePageState extends State { ], ), // Admin panel - DefaultTabController( - initialIndex: 0, - length: 2, - child: Scaffold( - appBar: AppBar( - title: Text('adminPage'.tr()), - bottom: TabBar( - tabs: [ - Tab( - child: Text( - 'serverUsersPage'.tr(), - style: TextStyle(fontSize: 18), - ), - ), - Tab( - child: Text( - 'serverInvitesPage'.tr(), - style: TextStyle(fontSize: 18), - ), - ), - ], - ), - ), - body: TabBarView( - children: [ - // Server users - Column( - children: [ - Visibility( - visible: _serverUsers.isNotEmpty, - child: Align( - alignment: Alignment.topRight, - child: Padding( - padding: EdgeInsets.all(5), - child: ElevatedButton( - onPressed: _selectedUsers.isEmpty - ? null - : () async { - await DialogUtils.yesNoDialog( - context, - 'deleteUserConfirm'.tr(), - 'deleteUserConfirmText'.tr(), - _deleteSelectedUsers); - }, - child: Text('deleteUser'.tr()), - ), - ), - ), - ), - Expanded( - child: RefreshIndicator( - onRefresh: _getServerUsers, - child: ListView.builder( - physics: const BouncingScrollPhysics( - parent: AlwaysScrollableScrollPhysics(), - ), - itemCount: _serverUsers.length, - itemBuilder: (context, index) { - return Padding( - padding: const EdgeInsets.only(bottom: 10), - child: SelectUserListItem(_serverUsers[index], - (isSelected) { - // Add/remove selected users from list - setState(() { - if (isSelected) { - isSelected = isSelected; - _selectedUsers.add(_serverUsers[index].id); - } else { - _selectedUsers - .remove(_serverUsers[index].id); - } - }); - }), - ); - }, - ), - ), - ) - ], - ), - // Invites - RefreshIndicator( - onRefresh: _getServerInvites, - child: ListView.builder( - physics: const BouncingScrollPhysics( - parent: AlwaysScrollableScrollPhysics(), - ), - itemCount: _serverInvites.length, - itemBuilder: (context, index) { - return InviteListItem(_serverInvites[index]); - }, - ), - ) + Scaffold( + appBar: AppBar( + title: Text('adminPage'.tr()), + bottom: TabBar( + controller: _adminTabController, + tabs: [ + Tab(child: Text('serverUsersPage'.tr())), + Tab(child: Text('serverInvitesPage'.tr())), ], ), ), + body: TabBarView( + controller: _adminTabController, + children: [ + _usersTab(), + _invitesTab(), + ], + ), ) ][_currentPageIndex], // Pick widget by current index ); } + + /// Rounded surface the admin rows sit in. + Widget _adminCard(List children) { + final colors = Theme.of(context).colorScheme; + return ClipRRect( + borderRadius: BorderRadius.circular(16), + child: Material( + color: colors.surfaceContainerHigh, + child: Column( + children: [ + for (var i = 0; i < children.length; i++) ...[ + if (i > 0) + Divider( + height: 1, + indent: 16, + endIndent: 16, + color: colors.outlineVariant, + ), + children[i], + ], + ], + ), + ), + ); + } + + /// Centred icon + message used for the empty admin lists. + Widget _adminEmpty(IconData icon, String message) { + final colors = Theme.of(context).colorScheme; + return SizedBox( + height: 220, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, size: 40, color: colors.secondary), + const SizedBox(height: 12), + Text(message, style: TextStyle(color: colors.secondary)), + ], + ), + ); + } + + /// Error row with a retry button, replacing the blank tab of the old UI. + Widget _adminError(VoidCallback retry) { + final colors = Theme.of(context).colorScheme; + return Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + Icon(Icons.error_outline, size: 20, color: colors.error), + const SizedBox(width: 8), + Expanded(child: Text('loadError'.tr())), + TextButton(onPressed: retry, child: Text('retry'.tr())), + ], + ), + ); + } + + Widget _adminSpinner() { + return Center( + child: Transform.scale( + scale: 1.5, + child: const CircularProgressIndicator(), + ), + ); + } + + Widget _usersTab() { + if (_usersLoading && _serverUsers.isEmpty) { + return _adminSpinner(); + } + if (_usersError && _serverUsers.isEmpty) { + return _adminError(_getServerUsers); + } + return RefreshIndicator( + onRefresh: _getServerUsers, + child: ListView( + physics: const BouncingScrollPhysics( + parent: AlwaysScrollableScrollPhysics(), + ), + padding: const EdgeInsets.fromLTRB(10, 10, 10, 24), + children: [ + if (_serverUsers.isEmpty) + _adminEmpty(Icons.people_outline, 'noUsers'.tr()) + else + _adminCard([ + for (final user in _serverUsers) + AdminUserListItem( + user, + onDelete: () async { + await DialogUtils.yesNoDialog( + context, + 'deleteUserConfirm'.tr(), + sprintf( + 'deleteUserConfirmTextName'.tr(), [user.username]), + () => _deleteUser(user), + ); + }, + ), + ]), + ], + ), + ); + } + + Widget _invitesTab() { + if (_invitesLoading && _serverInvites.isEmpty) { + return _adminSpinner(); + } + if (_invitesError && _serverInvites.isEmpty) { + return _adminError(_getServerInvites); + } + return Stack( + children: [ + RefreshIndicator( + onRefresh: _getServerInvites, + child: ListView( + physics: const BouncingScrollPhysics( + parent: AlwaysScrollableScrollPhysics(), + ), + padding: const EdgeInsets.fromLTRB(10, 10, 10, 96), + children: [ + if (_serverInvites.isEmpty) + _adminEmpty(Icons.mail_outline, 'noInvites'.tr()) + else + _adminCard([ + for (final invite in _serverInvites) InviteListItem(invite), + ]), + ], + ), + ), + Positioned( + right: 16, + bottom: 16, + child: FloatingActionButton( + onPressed: () => _createNewInvite(context), + shape: const CircleBorder(), + foregroundColor: Theme.of(context).colorScheme.surface, + backgroundColor: Theme.of(context).colorScheme.primary, + tooltip: 'newInvite'.tr(), + child: const Icon(Icons.person_add), + ), + ), + ], + ); + } } diff --git a/lib/utils/admin_format.dart b/lib/utils/admin_format.dart new file mode 100644 index 0000000..c61b3c1 --- /dev/null +++ b/lib/utils/admin_format.dart @@ -0,0 +1,27 @@ +import '../models/user.dart'; + +/// Remaining lifetime of an invite, bucketed for a list row. +/// +/// Returns the largest sensible unit and its value, or `null` once the +/// invite expired. `min` is clamped to at least 1 so a fresh invite never +/// reads "in 0 min". +({int value, String unit})? inviteRemaining(Duration remaining) { + if (remaining.isNegative) { + return null; + } + if (remaining.inMinutes < 60) { + return (value: remaining.inMinutes.clamp(1, 59), unit: 'min'); + } + if (remaining.inHours < 24) { + return (value: remaining.inHours, unit: 'h'); + } + return (value: remaining.inDays, unit: 'd'); +} + +/// Users sorted by name, the way the admin list shows them. +List sortedByUsername(List users) { + final sorted = [...users]; + sorted.sort( + (a, b) => a.username.toLowerCase().compareTo(b.username.toLowerCase())); + return sorted; +} diff --git a/lib/widgets/admin_user_list_item.dart b/lib/widgets/admin_user_list_item.dart new file mode 100644 index 0000000..1695db4 --- /dev/null +++ b/lib/widgets/admin_user_list_item.dart @@ -0,0 +1,73 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +import '../models/user.dart'; + +/// One row of the admin user list: avatar, name, admin badge and the +/// destructive action in an overflow menu. +class AdminUserListItem extends StatelessWidget { + const AdminUserListItem(this.user, {required this.onDelete, super.key}); + + final User user; + final VoidCallback onDelete; + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + return ListTile( + tileColor: Colors.transparent, + leading: CircleAvatar( + radius: 22, + backgroundColor: user.avatarColor, + child: Text( + user.username.isNotEmpty ? user.username[0].toUpperCase() : '?', + style: TextStyle(fontSize: 20, color: user.avatarTextColor), + ), + ), + title: Row( + children: [ + Flexible( + child: Text(user.username, overflow: TextOverflow.ellipsis), + ), + if (user.admin) + Padding( + padding: const EdgeInsets.only(left: 8), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: colors.primaryContainer, + borderRadius: BorderRadius.circular(6), + ), + child: Text( + 'adminBadge'.tr(), + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + letterSpacing: 0.5, + color: colors.onPrimaryContainer, + ), + ), + ), + ), + ], + ), + trailing: PopupMenuButton( + icon: const Icon(Icons.more_vert), + onSelected: (_) => onDelete(), + itemBuilder: (context) => [ + PopupMenuItem( + value: 'delete', + child: Row( + children: [ + const Icon(Icons.delete_forever, color: Colors.red), + const SizedBox(width: 8), + Text('deleteUser'.tr(), + style: const TextStyle(color: Colors.red)), + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/invite_list_item.dart b/lib/widgets/invite_list_item.dart index 7d05485..7f7b77f 100644 --- a/lib/widgets/invite_list_item.dart +++ b/lib/widgets/invite_list_item.dart @@ -2,28 +2,31 @@ import 'dart:async'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:sprintf/sprintf.dart'; import 'package:whisper_openapi_client_dart/api.dart'; +import '../utils/admin_format.dart'; + +/// One row of the admin invite list: the invited address and how long the +/// invitation is still valid. Mostly static, so it only rebuilds per minute. class InviteListItem extends StatefulWidget { const InviteListItem(this.invite, {super.key}); final ModelsInvite invite; @override - State createState() => _UserListItemState(); + State createState() => _InviteListItemState(); } -class _UserListItemState extends State { - late Timer _timer; +class _InviteListItemState extends State { + Timer? _timer; late Duration _remainingTime; @override void initState() { super.initState(); _remainingTime = widget.invite.validUntil.difference(DateTime.now()); - - // Start the timer to update every second - _timer = Timer.periodic(const Duration(seconds: 1), (timer) { + _timer = Timer.periodic(const Duration(minutes: 1), (_) { if (mounted) { setState(() { _remainingTime = widget.invite.validUntil.difference(DateTime.now()); @@ -33,36 +36,27 @@ class _UserListItemState extends State { } @override - Widget build(BuildContext context) { - // Stop when remaining time is negative - if (_remainingTime.isNegative) { - _timer.cancel(); - } - // Calculate absolute remaining time - Duration displayDuration = _remainingTime; - // Format display time - String displayTime = - displayDuration.toString().split('.').first.padLeft(8, '0'); + void dispose() { + _timer?.cancel(); + super.dispose(); + } + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + final remaining = inviteRemaining(_remainingTime); return ListTile( - onTap: () {}, // Empty method so that the visual effect works tileColor: Colors.transparent, - selectedTileColor: Theme.of(context).colorScheme.primaryContainer, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - ), - title: Text(widget.invite.mail), - trailing: Transform.scale( - scale: 1.3, - child: Text( - _remainingTime.isNegative ? 'inviteExpired'.tr() : displayTime, - style: TextStyle( - color: _remainingTime.isNegative - ? Colors.red - : Theme.of(context).colorScheme.secondary, - fontWeight: - _remainingTime.isNegative ? FontWeight.bold : FontWeight.normal, - ), + title: Text(widget.invite.mail, overflow: TextOverflow.ellipsis), + trailing: Text( + remaining == null + ? 'inviteExpired'.tr() + : sprintf( + 'inviteExpiresIn'.tr(), ['${remaining.value}', remaining.unit]), + style: TextStyle( + fontSize: 12, + color: remaining == null ? Colors.red : colors.secondary, + fontWeight: remaining == null ? FontWeight.bold : FontWeight.normal, ), ), ); diff --git a/lib/widgets/select_user_list_item.dart b/lib/widgets/select_user_list_item.dart deleted file mode 100644 index e47aa1f..0000000 --- a/lib/widgets/select_user_list_item.dart +++ /dev/null @@ -1,51 +0,0 @@ -import 'package:flutter/material.dart'; -import '../models/user.dart'; - -class SelectUserListItem extends StatefulWidget { - const SelectUserListItem(this.user, this.valueChanged, {super.key}); - - final User user; - final Function(bool) valueChanged; - - @override - State createState() => _SelectUserListItemState(); -} - -class _SelectUserListItemState extends State { - bool _isSelected = false; - - @override - Widget build(BuildContext context) { - return ListTile( - onTap: () {}, // Empty method so that the visual effect works - tileColor: Colors.transparent, - selectedTileColor: Theme.of(context).colorScheme.primaryContainer, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - ), - leading: CircleAvatar( - radius: 22, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 20, - color: widget.user.avatarTextColor, - ), - ), - ), - title: Text(widget.user.username), - trailing: Checkbox( - value: _isSelected, - onChanged: (_) { - setState(() { - _isSelected = !_isSelected; - widget.valueChanged(_isSelected); - }); - }, - ), - ); - } -} diff --git a/test/admin_format_test.dart b/test/admin_format_test.dart new file mode 100644 index 0000000..ae7b561 --- /dev/null +++ b/test/admin_format_test.dart @@ -0,0 +1,33 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/admin_format.dart'; + +User user(String name) => User(name, name, 'public-key', false); + +void main() { + test('invite lifetime is bucketed into minutes, hours and days', () { + expect( + inviteRemaining(const Duration(seconds: 20)), (value: 1, unit: 'min')); + expect( + inviteRemaining(const Duration(minutes: 14)), (value: 14, unit: 'min')); + expect(inviteRemaining(const Duration(minutes: 90)), (value: 1, unit: 'h')); + expect(inviteRemaining(const Duration(days: 3, hours: 5)), + (value: 3, unit: 'd')); + }); + + test('expired invites have no remaining lifetime', () { + expect(inviteRemaining(const Duration(seconds: -1)), isNull); + }); + + test('users are sorted by name, case insensitive', () { + final sorted = + sortedByUsername([user('zdeněk'), user('Adam'), user('bob')]); + expect(sorted.map((u) => u.username), ['Adam', 'bob', 'zdeněk']); + }); + + test('sorting keeps the input list untouched', () { + final users = [user('b'), user('a')]; + sortedByUsername(users); + expect(users.map((u) => u.username), ['b', 'a']); + }); +} diff --git a/test/admin_user_list_item_test.dart b/test/admin_user_list_item_test.dart new file mode 100644 index 0000000..e8967ca --- /dev/null +++ b/test/admin_user_list_item_test.dart @@ -0,0 +1,45 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/widgets/admin_user_list_item.dart'; + +Widget app(User user, VoidCallback onDelete) { + return MaterialApp( + home: Scaffold(body: AdminUserListItem(user, onDelete: onDelete)), + ); +} + +void main() { + testWidgets('shows the initial, the name and no badge for a normal user', + (tester) async { + await tester.pumpWidget(app(User('1', 'test', 'key', false), () {})); + + expect(find.text('T'), findsOneWidget); + expect(find.text('test'), findsOneWidget); + expect(find.text('adminBadge'), findsNothing); + }); + + testWidgets('marks admins with a badge', (tester) async { + await tester.pumpWidget(app(User('1', 'root', 'key', true), () {})); + + expect(find.text('adminBadge'), findsOneWidget); + }); + + testWidgets('the overflow menu offers the delete action', (tester) async { + var deleted = 0; + await tester.pumpWidget(app(User('1', 'test', 'key', false), () { + deleted++; + })); + + await tester.tap(find.byIcon(Icons.more_vert)); + await tester.pumpAndSettle(); + + expect(find.text('deleteUser'), findsOneWidget); + expect(deleted, 0); + + await tester.tap(find.text('deleteUser')); + await tester.pumpAndSettle(); + + expect(deleted, 1); + }); +} From 38b2b7e82b3c67a024ca387ee1e5b0b610225d85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 17:05:30 +0100 Subject: [PATCH 056/181] feat(media): playback speed and a single-player lock for voice messages A 1x/1.5x/2x cycle button appears under the elapsed time once playback starts and disappears again when the message finishes. The chosen speed is stored and applied to every later voice message. Starting voice or video playback now pauses whatever else was playing, and the app pauses both when it goes to the background. --- lib/pages/media_viewer_page.dart | 53 ++++++++++- lib/utils/cache_utils.dart | 30 +++++-- lib/utils/playback_lock.dart | 19 ++++ lib/utils/playback_speed.dart | 13 +++ lib/widgets/voice_player.dart | 146 ++++++++++++++++++++++++------- test/playback_lock_test.dart | 23 +++++ test/playback_speed_test.dart | 20 +++++ 7 files changed, 263 insertions(+), 41 deletions(-) create mode 100644 lib/utils/playback_lock.dart create mode 100644 lib/utils/playback_speed.dart create mode 100644 test/playback_lock_test.dart create mode 100644 test/playback_speed_test.dart diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index b90a726..99a7894 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -12,6 +12,7 @@ import '../utils/cache_utils.dart'; import '../utils/media_utils.dart'; import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; +import '../utils/playback_lock.dart'; /// Fullscreen viewer for the media of one conversation, stored /// encrypted-at-rest. Swiping moves between the attachments. @@ -156,7 +157,7 @@ class _MediaViewerPageState extends State { _index = index; }), itemBuilder: (context, index) => Center( - child: _MediaPage(_media[index]), + child: _MediaPage(_media[index], current: index == _index), ), ), bottomNavigationBar: caption.isNotEmpty @@ -179,20 +180,24 @@ class _MediaViewerPageState extends State { /// One attachment of the viewer: decodes its own file and releases it again /// when the page is swiped away. class _MediaPage extends StatefulWidget { - const _MediaPage(this.message); + const _MediaPage(this.message, {required this.current}); final PrivateMessage message; + /// Whether this page is the one on screen; a swiped-away page pauses. + final bool current; + @override State<_MediaPage> createState() => _MediaPageState(); } -class _MediaPageState extends State<_MediaPage> { +class _MediaPageState extends State<_MediaPage> with WidgetsBindingObserver { Uint8List? _imageBytes; VideoPlayerController? _videoController; ChewieController? _chewieController; File? _tempFile; bool _loading = true; bool _error = false; + bool _lockHeld = false; MediaType get _type => widget.message.mediaType ?? MediaType.image; @@ -203,9 +208,46 @@ class _MediaPageState extends State<_MediaPage> { @override void initState() { super.initState(); + WidgetsBinding.instance.addObserver(this); + PlaybackLock.owner.addListener(_onLockChanged); _load(); } + /// A video claims the lock while it plays and gives it back when it stops, + /// so a voice message can never be heard underneath it. + void _onVideoStateChanged() { + final playing = _videoController?.value.isPlaying ?? false; + if (playing) { + _lockHeld = true; + PlaybackLock.claim(this); + } else if (_lockHeld) { + _lockHeld = false; + PlaybackLock.release(this); + } + } + + /// Pauses when a voice message starts playing. + void _onLockChanged() { + if (!identical(PlaybackLock.owner.value, this)) { + _videoController?.pause(); + } + } + + @override + void didUpdateWidget(covariant _MediaPage oldWidget) { + super.didUpdateWidget(oldWidget); + if (!widget.current) { + _videoController?.pause(); + } + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state != AppLifecycleState.resumed) { + _videoController?.pause(); + } + } + Future _load() async { try { final localPath = widget.message.localPath; @@ -219,6 +261,7 @@ class _MediaPageState extends State<_MediaPage> { localPath, MediaUtils.extensionForType(_type)); final controller = VideoPlayerController.file(_tempFile!); await controller.initialize(); + controller.addListener(_onVideoStateChanged); _videoController = controller; _chewieController = ChewieController( videoPlayerController: controller, @@ -246,6 +289,10 @@ class _MediaPageState extends State<_MediaPage> { @override void dispose() { + WidgetsBinding.instance.removeObserver(this); + PlaybackLock.owner.removeListener(_onLockChanged); + PlaybackLock.release(this); + _videoController?.removeListener(_onVideoStateChanged); _chewieController?.dispose(); _videoController?.dispose(); MediaUtils.deleteLocalFile(_tempFile?.path); diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index bfc115a..012b047 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -24,6 +24,7 @@ class CacheUtils { static const _userKey = 'user'; static const _messageConceptKey = 'messageConcept'; static const _biometry = 'biometry'; + static const _playbackSpeed = 'playbackSpeed'; static const String _saltStorageKey = 'whisper_pbkdf2_salt'; static const FlutterSecureStorage _secureStorage = FlutterSecureStorage(); static const _chatThemeKeyPrefix = 'chatTheme:'; @@ -262,6 +263,23 @@ class CacheUtils { await box.put(_biometry, enabled); } + /// Opens box with playback preferences + static Future _openPlaybackBox() async { + return Hive.openBox(_playbackSpeed); + } + + /// Returns the voice message playback speed, 1x until changed + static Future getPlaybackSpeed() async { + Box box = await _openPlaybackBox(); + return (box.get(_playbackSpeed) as num?)?.toDouble() ?? 1.0; + } + + /// Sets the voice message playback speed + static Future setPlaybackSpeed(double speed) async { + Box box = await _openPlaybackBox(); + await box.put(_playbackSpeed, speed); + } + /// Opens box with private messages static Future _openPrivateMessagesBox() async { return Hive.openBox(_privateMessagesKey); @@ -388,10 +406,10 @@ class CacheUtils { // The message-level flag follows the album, so the bubble can show a // single state for "still downloading" vs "done". if (downloadStatus != null) { - final allReady = items - .every((item) => item.status == MediaDownloadStatus.ready); - final anyFailed = items - .any((item) => item.status == MediaDownloadStatus.failed); + final allReady = + items.every((item) => item.status == MediaDownloadStatus.ready); + final anyFailed = + items.any((item) => item.status == MediaDownloadStatus.failed); msg.downloadStatus = allReady ? MediaDownloadStatus.ready : (anyFailed @@ -410,8 +428,8 @@ class CacheUtils { /// Apply [update] to the stored copy of [message] and persist the list. /// The message is matched by sender and timestamp, the same identity the /// delete path uses. - static Future updateStoredMessage(String userId, - PrivateMessage message, void Function(PrivateMessage stored) update) async { + static Future updateStoredMessage(String userId, PrivateMessage message, + void Function(PrivateMessage stored) update) async { Box box = await _openPrivateMessagesBox(); List? messages = box.get(userId); if (messages == null) { diff --git a/lib/utils/playback_lock.dart b/lib/utils/playback_lock.dart new file mode 100644 index 0000000..2635e2d --- /dev/null +++ b/lib/utils/playback_lock.dart @@ -0,0 +1,19 @@ +import 'package:flutter/foundation.dart'; + +/// Only one source may play at a time (voice messages and the video viewer). +/// +/// Whoever starts playing claims the lock; every other player pauses itself +/// when the owner changes. +class PlaybackLock { + PlaybackLock._(); + + static final ValueNotifier owner = ValueNotifier(null); + + static void claim(Object source) => owner.value = source; + + static void release(Object source) { + if (identical(owner.value, source)) { + owner.value = null; + } + } +} diff --git a/lib/utils/playback_speed.dart b/lib/utils/playback_speed.dart new file mode 100644 index 0000000..703b0f7 --- /dev/null +++ b/lib/utils/playback_speed.dart @@ -0,0 +1,13 @@ +/// Playback speeds the voice player cycles through. +const List playbackSpeeds = [1.0, 1.5, 2.0]; + +/// Next speed in the cycle; an unknown value falls back to the first one. +double nextSpeed(double current) { + final index = playbackSpeeds.indexOf(current); + return playbackSpeeds[(index + 1) % playbackSpeeds.length]; +} + +/// Label of the cycle button: `1x`, `1.5x`, `2x`. +String speedLabel(double speed) { + return speed == speed.roundToDouble() ? '${speed.toInt()}x' : '${speed}x'; +} diff --git a/lib/widgets/voice_player.dart b/lib/widgets/voice_player.dart index c9552b9..b979352 100644 --- a/lib/widgets/voice_player.dart +++ b/lib/widgets/voice_player.dart @@ -4,7 +4,10 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:just_audio/just_audio.dart'; +import '../utils/cache_utils.dart'; import '../utils/media_utils.dart'; +import '../utils/playback_lock.dart'; +import '../utils/playback_speed.dart'; /// Inline player for a voice message stored encrypted-at-rest. /// @@ -26,23 +29,48 @@ class VoicePlayer extends StatefulWidget { State createState() => _VoicePlayerState(); } -class _VoicePlayerState extends State { +class _VoicePlayerState extends State with WidgetsBindingObserver { final AudioPlayer _player = AudioPlayer(); File? _tempFile; bool _loading = true; bool _error = false; + double _speed = playbackSpeeds.first; @override void initState() { super.initState(); + WidgetsBinding.instance.addObserver(this); + _player.playerStateStream.listen((state) { + if (!state.playing || + state.processingState == ProcessingState.completed) { + PlaybackLock.release(this); + } + }); + PlaybackLock.owner.addListener(_onLockChanged); _prepare(); } + /// Pauses when another voice message or a video starts playing. + void _onLockChanged() { + if (!identical(PlaybackLock.owner.value, this) && _player.playing) { + _player.pause(); + } + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state != AppLifecycleState.resumed) { + _player.pause(); + } + } + Future _prepare() async { try { _tempFile = await MediaUtils.materializeTempFile(widget.localPath, '.m4a'); await _player.setFilePath(_tempFile!.path); + _speed = await CacheUtils.getPlaybackSpeed(); + await _player.setSpeed(_speed); if (mounted) { setState(() { _loading = false; @@ -60,11 +88,24 @@ class _VoicePlayerState extends State { @override void dispose() { + WidgetsBinding.instance.removeObserver(this); + PlaybackLock.owner.removeListener(_onLockChanged); + PlaybackLock.release(this); _player.dispose(); MediaUtils.deleteLocalFile(_tempFile?.path); super.dispose(); } + /// Steps to the next speed and stores it for every other message. + Future _cycleSpeed() async { + final speed = nextSpeed(_speed); + setState(() { + _speed = speed; + }); + await _player.setSpeed(speed); + await CacheUtils.setPlaybackSpeed(speed); + } + String _format(Duration d) { final minutes = d.inMinutes.remainder(60).toString().padLeft(2, '0'); final seconds = d.inSeconds.remainder(60).toString().padLeft(2, '0'); @@ -121,6 +162,7 @@ class _VoicePlayerState extends State { if (playing && !completed) { await _player.pause(); } else { + PlaybackLock.claim(this); if (completed) { await _player.seek(Duration.zero); } @@ -143,38 +185,78 @@ class _VoicePlayerState extends State { // Slider and the time label sit on one line, so the track is // vertically centred in the row instead of being pushed up by // a stacked label. - return Row( - children: [ - Expanded( - child: SliderTheme( - data: SliderTheme.of(context).copyWith( - trackHeight: 2, - thumbShape: const RoundSliderThumbShape( - enabledThumbRadius: 6), - overlayShape: const RoundSliderOverlayShape( - overlayRadius: 12), - activeTrackColor: widget.color, - thumbColor: widget.color, - inactiveTrackColor: - widget.color.withValues(alpha: 0.3), - ), - child: Slider( - min: 0, - max: max, - value: value, - onChanged: _loading - ? null - : (v) => _player - .seek(Duration(milliseconds: v.toInt())), + return StreamBuilder( + stream: _player.playerStateStream, + builder: (context, stateSnapshot) { + final completed = stateSnapshot.data?.processingState == + ProcessingState.completed; + // The speed control appears with playback and is gone + // again once the message finished. + final started = position > Duration.zero && !completed; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded( + child: SliderTheme( + data: SliderTheme.of(context).copyWith( + trackHeight: 2, + thumbShape: const RoundSliderThumbShape( + enabledThumbRadius: 6), + overlayShape: const RoundSliderOverlayShape( + overlayRadius: 12), + activeTrackColor: widget.color, + thumbColor: widget.color, + inactiveTrackColor: + widget.color.withValues(alpha: 0.3), + ), + child: Slider( + min: 0, + max: max, + value: value, + onChanged: _loading + ? null + : (v) => _player.seek( + Duration(milliseconds: v.toInt())), + ), + ), + ), + const SizedBox(width: 4), + Text( + _format(position.inMilliseconds > 0 + ? position + : total), + style: + TextStyle(fontSize: 11, color: widget.color), + ), + ], ), - ), - ), - const SizedBox(width: 4), - Text( - _format(position.inMilliseconds > 0 ? position : total), - style: TextStyle(fontSize: 11, color: widget.color), - ), - ], + if (started) + Align( + alignment: Alignment.centerRight, + child: Semantics( + button: true, + child: InkWell( + onTap: _cycleSpeed, + child: Padding( + padding: const EdgeInsets.only(right: 4), + child: Text( + speedLabel(_speed), + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: widget.color, + ), + ), + ), + ), + ), + ), + ], + ); + }, ); }, ), diff --git a/test/playback_lock_test.dart b/test/playback_lock_test.dart new file mode 100644 index 0000000..384bf06 --- /dev/null +++ b/test/playback_lock_test.dart @@ -0,0 +1,23 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/playback_lock.dart'; + +void main() { + test('claim hands the lock to the newest source', () { + final first = Object(); + final second = Object(); + PlaybackLock.claim(first); + expect(PlaybackLock.owner.value, same(first)); + PlaybackLock.claim(second); + expect(PlaybackLock.owner.value, same(second)); + }); + + test('release only clears an owned lock', () { + final owner = Object(); + final stranger = Object(); + PlaybackLock.claim(owner); + PlaybackLock.release(stranger); + expect(PlaybackLock.owner.value, same(owner)); + PlaybackLock.release(owner); + expect(PlaybackLock.owner.value, isNull); + }); +} diff --git a/test/playback_speed_test.dart b/test/playback_speed_test.dart new file mode 100644 index 0000000..e70bfd9 --- /dev/null +++ b/test/playback_speed_test.dart @@ -0,0 +1,20 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/playback_speed.dart'; + +void main() { + test('cycles through 1x, 1.5x, 2x and back', () { + expect(nextSpeed(1.0), 1.5); + expect(nextSpeed(1.5), 2.0); + expect(nextSpeed(2.0), 1.0); + }); + + test('unknown speed falls back to 1x', () { + expect(nextSpeed(0.5), 1.0); + }); + + test('labels drop the decimal for whole speeds', () { + expect(speedLabel(1.0), '1x'); + expect(speedLabel(1.5), '1.5x'); + expect(speedLabel(2.0), '2x'); + }); +} From 26f7795956110ef2ffb2ea4bb9105286f6eb37d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 17:05:30 +0100 Subject: [PATCH 057/181] feat(chat): linkify URLs in message text --- lib/utils/link_utils.dart | 43 +++++++++++++++++++++++ lib/widgets/chat_bubble.dart | 12 +++---- lib/widgets/linkified_text.dart | 60 +++++++++++++++++++++++++++++++++ test/link_utils_test.dart | 35 +++++++++++++++++++ 4 files changed, 144 insertions(+), 6 deletions(-) create mode 100644 lib/utils/link_utils.dart create mode 100644 lib/widgets/linkified_text.dart create mode 100644 test/link_utils_test.dart diff --git a/lib/utils/link_utils.dart b/lib/utils/link_utils.dart new file mode 100644 index 0000000..8c9ab68 --- /dev/null +++ b/lib/utils/link_utils.dart @@ -0,0 +1,43 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:sprintf/sprintf.dart'; +import 'package:url_launcher/url_launcher.dart'; + +/// Absolute http(s) addresses in a message text. +final RegExp _urlPattern = RegExp(r'https?://[^\s<>"]+', caseSensitive: false); + +/// Splits [text] into plain pieces and links, in order. +/// +/// `url` is null for plain text. A sentence-final dot, comma, semicolon or +/// colon is not treated as part of the address. +List<({String text, String? url})> splitLinks(String text) { + final parts = <({String text, String? url})>[]; + var index = 0; + for (final match in _urlPattern.allMatches(text)) { + var end = match.end; + while (end > match.start && '.,;:'.contains(text[end - 1])) { + end--; + } + if (match.start > index) { + parts.add((text: text.substring(index, match.start), url: null)); + } + final url = text.substring(match.start, end); + parts.add((text: url, url: url)); + index = end; + } + if (index < text.length) { + parts.add((text: text.substring(index), url: null)); + } + return parts; +} + +/// Opens [url] in the browser and reports a failure the way the app does. +Future openLink(String url) async { + if (!await launchUrl(Uri.parse(url))) { + await Fluttertoast.showToast( + msg: sprintf('urlError'.tr(), [url]), + backgroundColor: Colors.red, + ); + } +} diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index baaa328..f15212c 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -4,6 +4,7 @@ import '../models/user.dart'; import '../models/private_message.dart'; import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; +import 'linkified_text.dart'; import 'media_bubble.dart'; // Long-press opens the message actions sheet (copy, forward, save, delete). @@ -253,12 +254,11 @@ class _ChatBubbleState extends State { ), padding: const EdgeInsets.symmetric( horizontal: 16, vertical: 10), - child: Text( + child: LinkifiedText( widget.message.message, style: TextStyle( color: bubbleTextColor(), ), - softWrap: true, ), ), // Outgoing messages show a clock while they are being @@ -268,10 +268,10 @@ class _ChatBubbleState extends State { Padding( padding: const EdgeInsets.only(top: 2), child: Tooltip( - message: widget.message.sendStatus == - SendStatus.failed - ? 'messageSendFailed'.tr() - : 'messageSending'.tr(), + message: + widget.message.sendStatus == SendStatus.failed + ? 'messageSendFailed'.tr() + : 'messageSending'.tr(), child: Icon( widget.message.sendStatus == SendStatus.failed ? Icons.error_outline diff --git a/lib/widgets/linkified_text.dart b/lib/widgets/linkified_text.dart new file mode 100644 index 0000000..3e4b493 --- /dev/null +++ b/lib/widgets/linkified_text.dart @@ -0,0 +1,60 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +import '../utils/link_utils.dart'; + +/// Message text where http(s) addresses are underlined and open in the +/// browser when tapped. +class LinkifiedText extends StatefulWidget { + const LinkifiedText(this.text, {this.style, super.key}); + + final String text; + final TextStyle? style; + + @override + State createState() => _LinkifiedTextState(); +} + +class _LinkifiedTextState extends State { + // Kept per address so a rebuild does not leak recognizers. + final Map _recognizers = {}; + + @override + void dispose() { + for (final recognizer in _recognizers.values) { + recognizer.dispose(); + } + super.dispose(); + } + + TapGestureRecognizer _recognizer(String url) { + return _recognizers.putIfAbsent( + url, + () => TapGestureRecognizer()..onTap = () => openLink(url), + ); + } + + @override + Widget build(BuildContext context) { + final color = + widget.style?.color ?? DefaultTextStyle.of(context).style.color; + return Text.rich( + TextSpan( + children: [ + for (final part in splitLinks(widget.text)) + part.url == null + ? TextSpan(text: part.text) + : TextSpan( + text: part.text, + recognizer: _recognizer(part.url!), + style: TextStyle( + decoration: TextDecoration.underline, + decorationColor: color, + ), + ), + ], + ), + style: widget.style, + ); + } +} diff --git a/test/link_utils_test.dart b/test/link_utils_test.dart new file mode 100644 index 0000000..0744aa9 --- /dev/null +++ b/test/link_utils_test.dart @@ -0,0 +1,35 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/link_utils.dart'; + +void main() { + test('text without a link stays plain', () { + final parts = splitLinks('ahoj, jak je?'); + expect(parts, [(text: 'ahoj, jak je?', url: null)]); + }); + + test('a link in the middle is split out', () { + final parts = splitLinks('mrkni na https://example.com/a?b=1 a dej vědět'); + expect(parts.map((p) => p.url), [null, 'https://example.com/a?b=1', null]); + expect(parts.first.text, 'mrkni na '); + expect(parts.last.text, ' a dej vědět'); + }); + + test('a sentence-final dot is not part of the link', () { + final parts = splitLinks('viz https://example.com.'); + final link = parts.firstWhere((p) => p.url != null); + expect(link.url, 'https://example.com'); + expect(parts.last, (text: '.', url: null)); + }); + + test('several links and http scheme are handled', () { + final parts = splitLinks('http://a.cz a https://b.cz/x'); + expect(parts.where((p) => p.url != null).map((p) => p.url), + ['http://a.cz', 'https://b.cz/x']); + }); + + test('text starting with a link produces no empty plain piece', () { + final parts = splitLinks('https://example.com'); + expect(parts, hasLength(1)); + expect(parts.single.url, 'https://example.com'); + }); +} From 0b964f5ab611604b1ca32281a3adbb48164704f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 17:05:30 +0100 Subject: [PATCH 058/181] fix(chat): drop emoji prefixes from attachment previews --- lib/widgets/chat_list_item.dart | 23 ----------------------- 1 file changed, 23 deletions(-) diff --git a/lib/widgets/chat_list_item.dart b/lib/widgets/chat_list_item.dart index b4cc8f0..4328e9d 100644 --- a/lib/widgets/chat_list_item.dart +++ b/lib/widgets/chat_list_item.dart @@ -1,6 +1,5 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../models/user.dart'; @@ -52,28 +51,6 @@ class _ChatListItemState extends State { String meText = widget.lastMessage.isMe ? '${'meText'.tr()}: ' : ''; // Use preview text (caption, or a localized label for media). String preview = widget.lastMessage.preview; - // Prefix media messages with a small icon hint. - if (widget.lastMessage.isMedia) { - switch (widget.lastMessage.mediaType) { - case MediaType.image: - preview = '🖼 $preview'; - break; - case MediaType.gif: - preview = '🖼 $preview'; - break; - case MediaType.video: - preview = '🎬 $preview'; - break; - case MediaType.voice: - preview = '🎤 $preview'; - break; - case MediaType.file: - preview = '📄 $preview'; - break; - case null: - break; - } - } String msg = preview.length <= 14 ? preview : '${preview.substring(0, 14)}...'; return meText + msg; From b3cdc395edc4a8e633b8d101a4fa2fdd296f429d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 19:56:33 +0100 Subject: [PATCH 059/181] perf(nav): snappy, consistent view transitions Opening a view no longer rebuilds the page underneath: the *Joined transition variants were handed childCurrent: widget, which mounted a second HomePage (full Hive scan, user and invite fetches, FCM and WebSocket setup) for the duration of every push, and showed a spinner instead of the chat list while sliding away. All navigation now shares one timing (200 ms, easeOutCubic) and a transition that fits the step: conversation from the bottom, secondary pages from the side, root swaps (login, registration, account deletion) as a fade. Material page routes are covered by a pageTransitionsTheme so no route falls back to the platform default. The chat defers its first content frame until the push animation finished, so attachment decryption no longer lands inside the transition, and the per-chat theme is memoized instead of recomputing ColorScheme.fromSeed on every rebuild. --- lib/pages/chat_info_page.dart | 10 +++--- lib/pages/chat_page.dart | 35 +++++++++++++++++--- lib/pages/forward_page.dart | 13 ++++---- lib/pages/home_page.dart | 35 +++----------------- lib/pages/password_page.dart | 7 ++-- lib/pages/register_page.dart | 7 ++-- lib/pages/scan_invite_button_page.dart | 6 ++-- lib/pages/scan_invite_page.dart | 6 ++-- lib/pages/search_user_page.dart | 5 ++- lib/pages/settings_page.dart | 5 ++- lib/pages/whisper_page.dart | 35 ++++++++++++++------ lib/utils/message_actions.dart | 4 +-- lib/utils/nav_transitions.dart | 44 ++++++++++++++++++++++++++ lib/utils/theme_utils.dart | 11 +++++-- lib/widgets/media_bubble.dart | 8 ++--- 15 files changed, 143 insertions(+), 88 deletions(-) create mode 100644 lib/utils/nav_transitions.dart diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 29a773b..e39ad9a 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -1,7 +1,7 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; -import 'package:page_transition/page_transition.dart'; +import '../utils/nav_transitions.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../utils/cache_utils.dart'; @@ -84,11 +84,9 @@ class _ChatInfoPageState extends State { return; } Navigator.of(context).push( - PageTransition( - type: PageTransitionType.fade, - duration: const Duration(milliseconds: 200), + fadeRoute( // The viewer is a separate route, so it needs the chat theme passed in - child: Theme( + Theme( data: ThemeUtils.chatTheme(context, _chatThemeColor), child: MediaViewerPage( message: message, @@ -206,7 +204,7 @@ class _ChatInfoPageState extends State { // Redirect to home page and clear navigation stack Navigator.pushAndRemoveUntil( context, - MaterialPageRoute(builder: (context) => const HomePage()), + fadeRoute(const HomePage()), (route) => false, ); }); diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index c451623..83c7663 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -5,7 +5,7 @@ import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:page_transition/page_transition.dart'; +import '../utils/nav_transitions.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../models/user.dart'; @@ -86,6 +86,14 @@ class _ChatPageState extends State { if (!mounted) { return; } + // The first content frame decrypts every visible attachment, so keep it + // out of the push animation and let the spinner ride along instead. + if (_firstLoad) { + await _waitForRouteAnimation(); + } + if (!mounted) { + return; + } setState(() { _messages = messages; _firstLoad = false; @@ -95,6 +103,26 @@ class _ChatPageState extends State { } } + /// Completes once the page transition that opened this page has finished. + Future _waitForRouteAnimation() async { + final animation = ModalRoute.of(context)?.animation; + if (animation == null || animation.status == AnimationStatus.completed) { + return; + } + final done = Completer(); + void onStatus(AnimationStatus status) { + if (status == AnimationStatus.completed) { + animation.removeStatusListener(onStatus); + if (!done.isCompleted) { + done.complete(); + } + } + } + + animation.addStatusListener(onStatus); + await done.future; + } + /// Extend the rendered window when the user scrolls towards older messages. void _onScroll() { if (!_scrollController.hasClients) { @@ -131,10 +159,7 @@ class _ChatPageState extends State { } Future _openChatInfo() async { - await Navigator.of(context).push(PageTransition( - type: PageTransitionType.rightToLeft, - child: ChatInfoPage(widget.user.id), - )); + await Navigator.of(context).push(stepRoute(ChatInfoPage(widget.user.id))); // The theme (and possibly the user) may have changed while it was open. await _loadChatTheme(); await _loadMessages(); diff --git a/lib/pages/forward_page.dart b/lib/pages/forward_page.dart index 49b08c1..90e857e 100644 --- a/lib/pages/forward_page.dart +++ b/lib/pages/forward_page.dart @@ -9,6 +9,7 @@ import '../utils/media_utils.dart'; import '../utils/message_notifier.dart'; import '../widgets/user_list_item.dart'; import 'search_user_page.dart'; +import '../utils/nav_transitions.dart'; /// Picks the destination of a forwarded message: an existing conversation or a /// user found by search. Sends the message and closes itself. @@ -94,12 +95,12 @@ class _ForwardPageState extends State { icon: const Icon(Icons.search), tooltip: 'searchUserPage'.tr(), onPressed: () { - Navigator.of(context).push(MaterialPageRoute( - builder: (_) => SearchUserPage(onUserSelected: (user) { - // Close the search page, _forward closes this one - Navigator.pop(context); - _forward(user); - }))); + Navigator.of(context) + .push(stepRoute(SearchUserPage(onUserSelected: (user) { + // Close the search page, _forward closes this one + Navigator.pop(context); + _forward(user); + }))); }, ), ], diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 8d299ea..7a3f019 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -6,7 +6,7 @@ import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:page_transition/page_transition.dart'; +import '../utils/nav_transitions.dart'; import 'package:provider/provider.dart'; import 'package:sprintf/sprintf.dart'; import '../pages/chat_page.dart'; @@ -239,13 +239,7 @@ class _HomePageState extends State if (!mounted) { return; } - Navigator.of(context).push(PageTransition( - duration: const Duration(milliseconds: 300), - reverseDuration: const Duration(milliseconds: 300), - curve: Curves.easeInOut, - type: PageTransitionType.bottomToTopJoined, - child: ChatPage(user), - childCurrent: widget)); + Navigator.of(context).push(slideUpRoute(ChatPage(user))); }); } @@ -282,13 +276,7 @@ class _HomePageState extends State padding: EdgeInsets.only(right: 5, left: 5, bottom: 3), child: ChatListItem(chat.key, chat.value, () { // Push to chat - Navigator.of(context).push(PageTransition( - duration: const Duration(milliseconds: 300), - reverseDuration: const Duration(milliseconds: 300), - curve: Curves.easeInOut, - type: PageTransitionType.bottomToTopJoined, - child: ChatPage(chat.key), - childCurrent: widget)); + Navigator.of(context).push(slideUpRoute(ChatPage(chat.key))); }), ); }, @@ -345,14 +333,7 @@ class _HomePageState extends State icon: const Icon(Icons.settings), tooltip: 'settingsButton'.tr(), onPressed: () { - Navigator.of(context).push(PageTransition( - duration: const Duration(milliseconds: 300), - reverseDuration: const Duration(milliseconds: 300), - curve: Curves.easeInOut, - type: PageTransitionType.rightToLeftJoined, - child: SettingsPage(), - childCurrent: widget, - )); + Navigator.of(context).push(stepRoute(SettingsPage())); }, ), ], @@ -366,13 +347,7 @@ class _HomePageState extends State floatingActionButton: _currentPageIndex == 0 ? FloatingActionButton( onPressed: () { - Navigator.of(context).push(PageTransition( - duration: const Duration(milliseconds: 300), - reverseDuration: const Duration(milliseconds: 300), - curve: Curves.easeInOut, - type: PageTransitionType.bottomToTopJoined, - child: SearchUserPage(), - childCurrent: widget)); + Navigator.of(context).push(stepRoute(SearchUserPage())); }, shape: const CircleBorder(), foregroundColor: Theme.of(context).colorScheme.surface, diff --git a/lib/pages/password_page.dart b/lib/pages/password_page.dart index 524660b..ec6c754 100644 --- a/lib/pages/password_page.dart +++ b/lib/pages/password_page.dart @@ -9,6 +9,7 @@ import '../utils/crypto_utils.dart'; import '../utils/singleton.dart'; import '../utils/utils.dart'; import 'home_page.dart'; +import '../utils/nav_transitions.dart'; class PasswordPage extends StatefulWidget { const PasswordPage({super.key}); @@ -69,8 +70,7 @@ class _PasswordPageState extends State { // Redirect to home page if (mounted) { - Navigator.pushReplacement(context, - MaterialPageRoute(builder: (context) => const HomePage())); + Navigator.pushReplacement(context, fadeRoute(const HomePage())); } } catch (e) { setState(() { @@ -158,8 +158,7 @@ class _PasswordPageState extends State { await Utils.wsConnect(firstConnect: true); if (mounted) { - Navigator.pushReplacement(context, - MaterialPageRoute(builder: (context) => const HomePage())); + Navigator.pushReplacement(context, fadeRoute(const HomePage())); } } else { await Fluttertoast.showToast( diff --git a/lib/pages/register_page.dart b/lib/pages/register_page.dart index c7b7338..0b1e431 100644 --- a/lib/pages/register_page.dart +++ b/lib/pages/register_page.dart @@ -15,6 +15,7 @@ import '../utils/singleton.dart'; import '../utils/utils.dart'; import 'package:basic_utils/basic_utils.dart' as bu; import 'home_page.dart'; +import '../utils/nav_transitions.dart'; class RegisterPage extends StatefulWidget { const RegisterPage(this.invite, {super.key}); @@ -170,7 +171,7 @@ class _RegisterPageState extends State { // Redirect to home page and clear navigation history Navigator.of(context).pushAndRemoveUntil( - MaterialPageRoute(builder: (context) => const HomePage()), + fadeRoute(const HomePage()), (Route route) => false, ); } else { @@ -180,7 +181,7 @@ class _RegisterPageState extends State { // Redirect to home page and clear navigation history Navigator.of(context).pushAndRemoveUntil( - MaterialPageRoute(builder: (context) => const HomePage()), + fadeRoute(const HomePage()), (Route route) => false, ); } @@ -189,7 +190,7 @@ class _RegisterPageState extends State { } else { // Redirect to home page and clear navigation history Navigator.of(context).pushAndRemoveUntil( - MaterialPageRoute(builder: (context) => const HomePage()), + fadeRoute(const HomePage()), (Route route) => false, ); } diff --git a/lib/pages/scan_invite_button_page.dart b/lib/pages/scan_invite_button_page.dart index caa9af7..719c2ad 100644 --- a/lib/pages/scan_invite_button_page.dart +++ b/lib/pages/scan_invite_button_page.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:easy_localization/easy_localization.dart'; import 'scan_invite_page.dart'; +import '../utils/nav_transitions.dart'; class ScanInviteButtonPage extends StatefulWidget { const ScanInviteButtonPage({super.key}); @@ -30,10 +31,7 @@ class _ScanInviteButtonPageState extends State { ), onPressed: () { // Navigate to scanning invite - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => const ScanInvitePage())); + Navigator.push(context, stepRoute(const ScanInvitePage())); }, child: Padding( padding: const EdgeInsets.all(7), diff --git a/lib/pages/scan_invite_page.dart b/lib/pages/scan_invite_page.dart index dd8db36..ac5c79e 100644 --- a/lib/pages/scan_invite_page.dart +++ b/lib/pages/scan_invite_page.dart @@ -8,6 +8,7 @@ import 'package:qr_code_scanner_plus/qr_code_scanner_plus.dart'; import '../models/invite_data.dart'; import 'register_page.dart'; +import '../utils/nav_transitions.dart'; class ScanInvitePage extends StatefulWidget { const ScanInvitePage({super.key}); @@ -59,10 +60,7 @@ class _ScanInvitePageState extends State { await _qrController?.pauseCamera(); if (!mounted) return; - await Navigator.push( - context, - MaterialPageRoute(builder: (context) => RegisterPage(invite)), - ); + await Navigator.push(context, stepRoute(RegisterPage(invite))); } catch (_) { if (_showScanToastOnce(scanCode, 'invalidQr')) { Fluttertoast.showToast( diff --git a/lib/pages/search_user_page.dart b/lib/pages/search_user_page.dart index 02dac5e..12a0578 100644 --- a/lib/pages/search_user_page.dart +++ b/lib/pages/search_user_page.dart @@ -7,6 +7,7 @@ import '../utils/singleton.dart'; import '../utils/utils.dart'; import '../widgets/user_list_item.dart'; import 'chat_page.dart'; +import '../utils/nav_transitions.dart'; typedef UserSearchCallback = Future?> Function(String query); @@ -204,9 +205,7 @@ class _SearchUserPageState extends State { } Navigator.pushAndRemoveUntil( context, - MaterialPageRoute( - builder: (context) => - ChatPage(_users[index])), + slideUpRoute(ChatPage(_users[index])), (route) => route .isFirst, // Returns true only for Home page ); diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 5817690..800f29a 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -14,6 +14,7 @@ import '../utils/message_notifier.dart'; import '../utils/utils.dart'; import 'scan_invite_button_page.dart'; import '../widgets/change_password_dialog.dart'; +import '../utils/nav_transitions.dart'; class SettingsPage extends StatefulWidget { const SettingsPage({super.key}); @@ -319,9 +320,7 @@ class _SettingsPageState extends State { if (Platform.isIOS) { // Apple (https://stackoverflow.com/a/57534684/19371130) Navigator.pushReplacement( - context, - MaterialPageRoute( - builder: (context) => ScanInviteButtonPage())); + context, fadeRoute(ScanInviteButtonPage())); } else if (Platform.isAndroid) { // Android SystemNavigator.pop(); diff --git a/lib/pages/whisper_page.dart b/lib/pages/whisper_page.dart index ec588e9..443e658 100644 --- a/lib/pages/whisper_page.dart +++ b/lib/pages/whisper_page.dart @@ -1,4 +1,5 @@ import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../utils/page_navigator_observer.dart'; @@ -10,6 +11,18 @@ import '../utils/cache_utils.dart'; class WhisperPage extends StatelessWidget { const WhisperPage({super.key}); + /// Fade-through everywhere so `MaterialPageRoute` pushes (forward, search, + /// registration) use the same timing as the rest of the app. + static const PageTransitionsTheme _pageTransitionsTheme = + PageTransitionsTheme(builders: { + TargetPlatform.android: FadeForwardsPageTransitionsBuilder(), + TargetPlatform.iOS: CupertinoPageTransitionsBuilder(), + TargetPlatform.linux: FadeForwardsPageTransitionsBuilder(), + TargetPlatform.macOS: CupertinoPageTransitionsBuilder(), + TargetPlatform.windows: FadeForwardsPageTransitionsBuilder(), + TargetPlatform.fuchsia: FadeForwardsPageTransitionsBuilder(), + }); + /// Returns default page based on user in cache. Future _getDefaultPage() async { // Set default page @@ -43,18 +56,20 @@ class WhisperPage extends StatelessWidget { debugShowCheckedModeBanner: true, // Light theme theme: ThemeData.from( - colorScheme: ColorScheme.fromSeed( - seedColor: Provider.of(context).appTheme.color, - brightness: Brightness.light), - useMaterial3: - Provider.of(context).appTheme.useMaterial3), + colorScheme: ColorScheme.fromSeed( + seedColor: Provider.of(context).appTheme.color, + brightness: Brightness.light), + useMaterial3: + Provider.of(context).appTheme.useMaterial3) + .copyWith(pageTransitionsTheme: _pageTransitionsTheme), // Dark theme darkTheme: ThemeData.from( - colorScheme: ColorScheme.fromSeed( - seedColor: Provider.of(context).appTheme.color, - brightness: Brightness.dark), - useMaterial3: - Provider.of(context).appTheme.useMaterial3), + colorScheme: ColorScheme.fromSeed( + seedColor: Provider.of(context).appTheme.color, + brightness: Brightness.dark), + useMaterial3: + Provider.of(context).appTheme.useMaterial3) + .copyWith(pageTransitionsTheme: _pageTransitionsTheme), // Light / Dark / System themeMode: Provider.of(context).appTheme.themeMode, localizationsDelegates: context.localizationDelegates, diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index c5302aa..67c085d 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -10,6 +10,7 @@ import 'cache_utils.dart'; import 'dialog_utils.dart'; import 'media_utils.dart'; import 'message_notifier.dart'; +import '../utils/nav_transitions.dart'; /// Actions for a single message, offered by the bubble long-press sheet and by /// the attachment viewer's overflow menu. @@ -113,8 +114,7 @@ class MessageActions { /// Pick a chat (or a user) and send the message there. static Future forward( BuildContext context, PrivateMessage message) async { - await Navigator.of(context) - .push(MaterialPageRoute(builder: (_) => ForwardPage(message))); + await Navigator.of(context).push(stepRoute(ForwardPage(message))); } /// Delete the message only on this device, after a confirmation. diff --git a/lib/utils/nav_transitions.dart b/lib/utils/nav_transitions.dart new file mode 100644 index 0000000..e0c7e59 --- /dev/null +++ b/lib/utils/nav_transitions.dart @@ -0,0 +1,44 @@ +import 'package:flutter/material.dart'; +import 'package:page_transition/page_transition.dart'; + +/// Shared navigation timing: fast start, soft landing. +const Duration navDuration = Duration(milliseconds: 200); +const Curve navCurve = Curves.easeOutCubic; + +/// Opens a conversation: the new page rises from the bottom. +/// +/// Deliberately not `bottomToTopJoined` — the joined variants need the +/// previous page as a widget and mount it a second time, which restarts its +/// `initState` (cache scans, network calls) while the transition animates. +Route slideUpRoute(Widget child) { + return PageTransition( + type: PageTransitionType.bottomToTop, + child: child, + duration: navDuration, + reverseDuration: navDuration, + curve: navCurve, + ); +} + +/// Opens a secondary page: the content cross-fades, nothing large slides. +Route fadeRoute(Widget child) { + return PageTransition( + type: PageTransitionType.fade, + child: child, + duration: navDuration, + reverseDuration: navDuration, + curve: navCurve, + ); +} + +/// Opens the next step of a flow (forwarding, onboarding): it comes in from +/// the side, the way a form usually does. +Route stepRoute(Widget child) { + return PageTransition( + type: PageTransitionType.rightToLeft, + child: child, + duration: navDuration, + reverseDuration: navDuration, + curve: navCurve, + ); +} diff --git a/lib/utils/theme_utils.dart b/lib/utils/theme_utils.dart index d5bba93..117ca38 100644 --- a/lib/utils/theme_utils.dart +++ b/lib/utils/theme_utils.dart @@ -10,9 +10,14 @@ class ThemeUtils { if (seed == null) { return Theme.of(context); } - return ThemeData.from( - colorScheme: ColorScheme.fromSeed( - seedColor: seed, brightness: Theme.of(context).brightness), + final brightness = Theme.of(context).brightness; + // Recomputing the tonal palette on every rebuild lands mid-transition. + final key = Object.hash(seed, brightness); + return _chatThemes[key] ??= ThemeData.from( + colorScheme: + ColorScheme.fromSeed(seedColor: seed, brightness: brightness), useMaterial3: Singleton().appTheme.useMaterial3); } + + static final Map _chatThemes = {}; } diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index d32a9f4..cb096b2 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -3,7 +3,7 @@ import 'dart:typed_data'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; -import 'package:page_transition/page_transition.dart'; +import '../utils/nav_transitions.dart'; import 'package:video_player/video_player.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; @@ -98,11 +98,9 @@ class _MediaBubbleState extends State { return; } Navigator.of(context).push( - PageTransition( - type: PageTransitionType.fade, - duration: const Duration(milliseconds: 200), + fadeRoute( // The viewer is a separate route; carry the chat theme over to it - child: Theme( + Theme( data: Theme.of(context), child: MediaViewerPage( message: widget.message, From 25bed6b9a95c065aa90b7bc6faa7539bf366f988 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 20:46:28 +0100 Subject: [PATCH 060/181] perf(media): batch decryption, throttled decrypts, lazy chat info grid - Incoming WebSocket batches decrypt in a single isolate with one RSA key parse instead of one spawn and one parse per message. - Media decrypts share a two-slot limiter and each bubble waits for the first frame, so a chat full of attachments no longer spawns a burst of isolates during the push or a scroll. - The Chat Info gallery is a sliver grid, so only visible tiles decrypt. - PrivateMessage.album caches its decoded items per stored JSON instead of re-decoding on every preview, deletion or album widget access. --- lib/models/private_message.dart | 22 +++- lib/pages/chat_info_page.dart | 219 +++++++++++++++++--------------- lib/utils/crypto_utils.dart | 41 ++++++ lib/utils/media_utils.dart | 34 ++++- lib/utils/utils.dart | 29 +++-- lib/widgets/media_bubble.dart | 17 ++- test/batch_decrypt_test.dart | 55 ++++++++ 7 files changed, 300 insertions(+), 117 deletions(-) create mode 100644 test/batch_decrypt_test.dart diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index 3f8b238..721aa90 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -70,8 +70,7 @@ class AlbumItem { } } - bool get isReady => - status == MediaDownloadStatus.ready && localPath != null; + bool get isReady => status == MediaDownloadStatus.ready && localPath != null; Map toJson() => { 'mediaId': mediaId, @@ -159,6 +158,10 @@ class PrivateMessage extends HiveObject { @HiveField(15) String? albumJson; + /// Cache for [album], keyed by the [albumJson] it was decoded from. + String? _albumCacheJson; + List? _albumCache; + PrivateMessage( this.senderId, this.message, @@ -189,11 +192,24 @@ class PrivateMessage extends HiveObject { bool get isAlbum => albumJson != null; /// Decoded album items, empty for non-album messages. + /// + /// Cached per [albumJson]: the getter is hit from previews, deletion paths + /// and album widgets, and decoding the JSON on every access is wasteful. List get album { final raw = albumJson; if (raw == null) { return const []; } + if (raw == _albumCacheJson) { + return _albumCache ?? const []; + } + final decodedItems = _decodeAlbum(raw); + _albumCacheJson = raw; + _albumCache = decodedItems; + return decodedItems; + } + + List _decodeAlbum(String raw) { try { final decoded = jsonDecode(raw); if (decoded is List) { @@ -211,6 +227,8 @@ class PrivateMessage extends HiveObject { /// Replaces the album items and serializes them back into [albumJson]. void setAlbum(List items) { albumJson = jsonEncode(items.map((item) => item.toJson()).toList()); + _albumCacheJson = null; + _albumCache = null; } /// Local (encrypted-at-rest) files of this message, for deletion. diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index e39ad9a..aa86b7a 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -106,126 +106,143 @@ class _ChatInfoPageState extends State { title: Text('chatInfoPage'.tr()), ), body: SafeArea( - child: ListView( - children: [ - // Chat theme - TextButton( - onPressed: _pickChatTheme, - child: Row( + child: CustomScrollView( + slivers: [ + SliverToBoxAdapter( + child: Column( children: [ - Icon( - Icons.palette, - size: 24, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'chatTheme'.tr(), + // Chat theme + TextButton( + onPressed: _pickChatTheme, + child: Row( + children: [ + Icon( + Icons.palette, + size: 24, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'chatTheme'.tr(), + ), + ), + if (_chatThemeColor != null) + Padding( + padding: EdgeInsets.only(left: 10), + child: Container( + width: 16, + height: 16, + decoration: BoxDecoration( + color: _chatThemeColor, + shape: BoxShape.circle, + ), + ), + ), + SizedBox( + width: 24, + ), + ], ), ), + // Drop the override if (_chatThemeColor != null) - Padding( - padding: EdgeInsets.only(left: 10), - child: Container( - width: 16, - height: 16, - decoration: BoxDecoration( - color: _chatThemeColor, - shape: BoxShape.circle, - ), + TextButton( + onPressed: _clearChatTheme, + child: Row( + children: [ + Icon( + Icons.restart_alt, + size: 24, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'useGlobalTheme'.tr(), + ), + ), + SizedBox( + width: 24, + ), + ], ), ), - SizedBox( - width: 24, - ), + + Divider(thickness: 1, indent: 10, endIndent: 10), ], ), ), - // Drop the override - if (_chatThemeColor != null) - TextButton( - onPressed: _clearChatTheme, - child: Row( - children: [ - Icon( - Icons.restart_alt, - size: 24, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'useGlobalTheme'.tr(), - ), - ), - SizedBox( - width: 24, - ), - ], - ), - ), - Divider(thickness: 1, indent: 10, endIndent: 10), - - // Shared media - if (_media.isNotEmpty) ...[ - Padding( - padding: EdgeInsets.fromLTRB(16, 12, 16, 8), - child: Text( - 'mediaTitle'.tr(), - style: TextStyle(fontSize: 16), + // Shared media title + if (_media.isNotEmpty) + SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.fromLTRB(16, 12, 16, 8), + child: Text( + 'mediaTitle'.tr(), + style: TextStyle(fontSize: 16), + ), ), ), - GridView.builder( - shrinkWrap: true, - physics: NeverScrollableScrollPhysics(), + // Grid as a sliver, so only the visible tiles decrypt + if (_media.isNotEmpty) + SliverPadding( padding: EdgeInsets.symmetric(horizontal: 8), - gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 3, - mainAxisSpacing: 4, - crossAxisSpacing: 4, - ), - itemCount: _media.length, - itemBuilder: (context, index) => _MediaTile( - message: _media[index], - onTap: () => _openMedia(_media[index]), + sliver: SliverGrid.builder( + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 3, + mainAxisSpacing: 4, + crossAxisSpacing: 4, + ), + itemCount: _media.length, + itemBuilder: (context, index) => _MediaTile( + message: _media[index], + onTap: () => _openMedia(_media[index]), + ), ), ), - Divider(thickness: 1, indent: 10, endIndent: 10), - ], - // Delete chat - TextButton( - onPressed: () async { - await DialogUtils.yesNoDialog( - context, - 'deleteChatConfirm'.tr(), - 'deleteChatConfirmText'.tr(), () async { - MessageNotifier().deleteChat(widget.userId); - // Redirect to home page and clear navigation stack - Navigator.pushAndRemoveUntil( - context, - fadeRoute(const HomePage()), - (route) => false, - ); - }); - }, - child: Row( + SliverToBoxAdapter( + child: Column( children: [ - Icon( - Icons.delete_forever, - size: 24, - color: Colors.red, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'deleteChat'.tr(), - style: TextStyle(color: Colors.red), + if (_media.isNotEmpty) + Divider(thickness: 1, indent: 10, endIndent: 10), + + // Delete chat + TextButton( + onPressed: () async { + await DialogUtils.yesNoDialog( + context, + 'deleteChatConfirm'.tr(), + 'deleteChatConfirmText'.tr(), () async { + MessageNotifier().deleteChat(widget.userId); + // Redirect to home page and clear navigation stack + Navigator.pushAndRemoveUntil( + context, + fadeRoute(const HomePage()), + (route) => false, + ); + }); + }, + child: Row( + children: [ + Icon( + Icons.delete_forever, + size: 24, + color: Colors.red, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'deleteChat'.tr(), + style: TextStyle(color: Colors.red), + ), + ), + SizedBox( + width: 24, + ), + ], ), ), - SizedBox( - width: 24, - ), ], ), ), diff --git a/lib/utils/crypto_utils.dart b/lib/utils/crypto_utils.dart index 5890a38..2468914 100644 --- a/lib/utils/crypto_utils.dart +++ b/lib/utils/crypto_utils.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:math'; +import 'package:basic_utils/basic_utils.dart' as bu; import 'package:crypto/crypto.dart'; import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart' as djwt; import 'package:flutter/foundation.dart'; @@ -87,6 +88,46 @@ class CryptoUtils { return cipher.process(data['message']); } + /// Decrypts a batch of hybrid-encrypted messages inside one isolate. + /// + /// A burst of incoming messages used to cost one RSA key parse and one + /// isolate spawn per message; here it costs one of each per batch. + /// Messages that fail to decrypt come back as null. + static Future> decryptMessageBatch( + List> messages, String privateKeyPem) async { + return compute( + _decryptMessageBatch, {'messages': messages, 'pem': privateKeyPem}); + } + + static Future> _decryptMessageBatch( + Map data) async { + final privateKey = + bu.CryptoUtils.rsaPrivateKeyFromPem(data['pem'] as String); + final messages = data['messages'] as List; + final aesAlgorithm = cryptography.AesGcm.with256bits(); + final decrypted = []; + for (final entry in messages) { + final message = (entry as Map).cast(); + try { + final cipher = PKCS1Encoding(RSAEngine()) + ..init(false, PrivateKeyParameter(privateKey)); + final aesKeyBytes = cipher.process(message['key'] as Uint8List); + final plainText = await aesAlgorithm.decrypt( + cryptography.SecretBox( + message['data'] as Uint8List, + nonce: message['nonce'] as Uint8List, + mac: cryptography.Mac(message['mac'] as Uint8List), + ), + secretKey: cryptography.SecretKey(aesKeyBytes), + ); + decrypted.add(Uint8List.fromList(plainText)); + } catch (_) { + decrypted.add(null); + } + } + return decrypted; + } + /// Generates JWT token valid for 5 seconds asynchronously. static Future generateRsaJwt( String userId, RSAPrivateKey privateKey) async { diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 2a0e5b4..fd2a6d0 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:ui' as ui; @@ -140,10 +141,37 @@ class MediaUtils { } /// Decrypt an at-rest file written by [encryptAtRest]. + /// + /// Throttled: decrypting spawns an isolate per call, so a chat full of + /// attachments would otherwise spawn one burst per scroll. static Future decryptAtRest(String path) async { - final blob = await File(path).readAsBytes(); - final key = Uint8List.fromList(Singleton().boxCollectionKey); - return compute(_gcmDecrypt, _GcmArgs(blob, key)); + return _withDecryptSlot(() async { + final blob = await File(path).readAsBytes(); + final key = Uint8List.fromList(Singleton().boxCollectionKey); + return compute(_gcmDecrypt, _GcmArgs(blob, key)); + }); + } + + static const int _maxConcurrentDecrypts = 2; + static int _activeDecrypts = 0; + static final List> _decryptWaiters = []; + + /// Runs [task] while at most [_maxConcurrentDecrypts] decrypts are alive. + static Future _withDecryptSlot(Future Function() task) async { + while (_activeDecrypts >= _maxConcurrentDecrypts) { + final waiter = Completer(); + _decryptWaiters.add(waiter); + await waiter.future; + } + _activeDecrypts++; + try { + return await task(); + } finally { + _activeDecrypts--; + if (_decryptWaiters.isNotEmpty) { + _decryptWaiters.removeAt(0).complete(); + } + } } /// Encrypt bytes with an explicit AES-GCM key (no singleton lookup). diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index e5a2388..e3268a1 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -153,17 +153,28 @@ class Utils { // Media references of each conversation that still need a download. final pendingMediaRefs = >{}; - // Parallel decrypt all messages try { - final decryptionTasks = messages.map((message) async { + // One isolate for the whole batch: a per-message decrypt used to + // cost an RSA key parse and an isolate spawn each. + final decryptedBatch = await CryptoUtils.decryptMessageBatch( + messages + .map((message) => { + 'data': message.content, + 'key': message.key, + 'nonce': message.nonce, + 'mac': message.mac, + }) + .toList(), + Singleton().profile.privateKey); + + final decryptionTasks = messages.asMap().entries.map((entry) async { + final index = entry.key; + final message = entry.value; try { - var decryptedMessage = await CryptoUtils.decryptMessageData( - message.content, - message.key, - message.nonce, - message.mac, - bu.CryptoUtils.rsaPrivateKeyFromPem( - Singleton().profile.privateKey)); + final decryptedMessage = decryptedBatch[index]; + if (decryptedMessage == null) { + throw const FormatException('message decryption failed'); + } // Media message: decode the envelope and create a placeholder. final envelope = MediaUtils.tryParseMediaEnvelope(decryptedMessage); diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index cb096b2..4436dac 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; @@ -65,8 +66,20 @@ class _MediaBubbleState extends State { _imagePath = path; final type = widget.message.mediaType; final isImage = type == MediaType.image || type == MediaType.gif; - _imageFuture = - path != null && isImage ? MediaUtils.decryptAtRest(path) : null; + _imageFuture = path != null && isImage ? _decryptAfterFrame(path) : null; + } + + /// Lets the first frame land before paying for the decryption, so a chat + /// full of images does not stall the push animation. + Future _decryptAfterFrame(String path) async { + final firstFrame = Completer(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!firstFrame.isCompleted) { + firstFrame.complete(); + } + }); + await firstFrame.future; + return MediaUtils.decryptAtRest(path); } /// Constrained display size derived from the original media dimensions. diff --git a/test/batch_decrypt_test.dart b/test/batch_decrypt_test.dart new file mode 100644 index 0000000..7b732fb --- /dev/null +++ b/test/batch_decrypt_test.dart @@ -0,0 +1,55 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:basic_utils/basic_utils.dart' as bu; +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/crypto_utils.dart'; + +void main() { + test('album is decoded once per stored json', () { + final message = + PrivateMessage('1', '', DateTime.now(), DateTime.now(), false); + + message.setAlbum([ + AlbumItem(mediaId: 'a', type: 'image', size: 1), + ]); + final first = message.album; + expect(first.single.mediaId, 'a'); + // Cached: the same list instance comes back. + expect(identical(message.album, first), isTrue); + + message.setAlbum([ + AlbumItem(mediaId: 'b', type: 'image', size: 1), + ]); + expect(message.album.single.mediaId, 'b'); + }); + + test('batch decryption round-trips and keeps failures as null', () async { + final keyPair = await CryptoUtils.getRSAKeyPair(); + final publicKey = keyPair.publicKey as bu.RSAPublicKey; + final privateKeyPem = bu.CryptoUtils.encodeRSAPrivateKeyToPem( + keyPair.privateKey as bu.RSAPrivateKey); + + final payload = Uint8List.fromList(utf8.encode('ahoj')); + final encrypted = await CryptoUtils.encryptMessageData(payload, publicKey); + final valid = { + 'data': encrypted['encryptedData']!, + 'key': encrypted['encryptedKey']!, + 'nonce': encrypted['nonce']!, + 'mac': encrypted['mac']!, + }; + // Same ciphertext with a wrong MAC must fail on its own. + final broken = { + ...valid, + 'mac': Uint8List.fromList(List.filled(16, 7)), + }; + + final result = + await CryptoUtils.decryptMessageBatch([valid, broken], privateKeyPem); + + expect(result, hasLength(2)); + expect(result.first, payload); + expect(result.last, isNull); + }); +} From 1becd38f3ebb24552e5d38d3988d504991c8f98d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 22:37:47 +0100 Subject: [PATCH 061/181] fix: acknowledged delivery, per-message cache and auth recovery - delivery: messages stay 'sending' until the server acks, unacked ones are resent on reconnect; received messages are acked after being stored - cache: one Hive key per message instead of a list per chat, so a new message no longer rewrites the conversation; legacy lists migrate on read - auth: a refused refresh falls back to the RSA login, the login JWT carries the server challenge and its nbf tolerates clock skew - media: an attachment the server no longer has shows a terminal state - messages that cannot be decrypted leave a visible placeholder - home: conversation list is state, not a future per build; no O(n^2) lookup - reconnect: exponential backoff instead of a 5s token request - deps: drop mobile_scanner and jwt_decoder --- AGENTS.md | 10 + README.md | 13 +- assets/translations/cs.json | 302 ++++++++++++++------------- assets/translations/en.json | 302 ++++++++++++++------------- integration_test/app_e2e_test.dart | 10 +- integration_test/fake_server.dart | 2 + lib/models/private_message.dart | 15 ++ lib/pages/home_page.dart | 101 +++++---- lib/utils/cache_utils.dart | 286 ++++++++++++++++++++----- lib/utils/chat_sender.dart | 122 ++++++++--- lib/utils/crypto_utils.dart | 19 +- lib/utils/message_notifier.dart | 13 +- lib/utils/utils.dart | 224 +++++++++++++++----- lib/utils/websocket_manager.dart | 46 +++- lib/widgets/chat_bubble.dart | 20 +- lib/widgets/media_bubble.dart | 6 +- pubspec.lock | 16 -- pubspec.yaml | 2 - test/auth_refresh_fallback_test.dart | 165 +++++++++++++++ test/crypto_test.dart | 23 +- test/message_store_test.dart | 144 +++++++++++++ test/reconnect_backoff_test.dart | 16 ++ test/token_expiry_test.dart | 41 ++++ test/undecryptable_message_test.dart | 28 +++ 24 files changed, 1394 insertions(+), 532 deletions(-) create mode 100644 test/auth_refresh_fallback_test.dart create mode 100644 test/message_store_test.dart create mode 100644 test/reconnect_backoff_test.dart create mode 100644 test/token_expiry_test.dart create mode 100644 test/undecryptable_message_test.dart diff --git a/AGENTS.md b/AGENTS.md index 1fe8569..b09d666 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,6 +45,16 @@ not in this repository). Use them for the fast loop, but the shell gates below s - **Media upload**: `uploadMedia(file, receiverId)` — the argument order comes from the generator, not from logic. Verify call sites after regenerating the client. - **Path dependencies**: `pubspec.yaml` pulls both clients via `path:`, so CI cannot see which client version the app actually uses. Pinning to a tag is phase 2 debt. - **Firebase**: analysis fails without `lib/firebase_options.dart`. CI decodes it from a secret. +- **Login needs a challenge**: `CryptoUtils.generateRsaJwt` requires a `nonce` + fetched from `AuthenticationApi.authChallenge()`; the server spends it on use. + A login without it is refused. +- **Delivery ack**: `ChatSender` keeps a message `sending` until the server acks it + (`WsResponseType.ack`), and `Utils.onWsMessageReceived` acks what it stored. Do + not mark a message `sent` on the socket write; that hides lost messages. +- **Message storage**: one Hive key per message (`|`), + so a new message never rewrites a chat. Do not go back to a list per chat. +- **Media is single-delivery**: the server deletes the file on confirm, so a + second device or a reinstall shows `MediaDownloadStatus.expired`. ## Definition of done diff --git a/README.md b/README.md index db5bff5..36d1a30 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,15 @@ Also see [Wiki](https://github.com/jsfraz/whisper/wiki)! |---|---|---| |![Screenshot 1](screenshots/1.png)|![Screenshot 2](screenshots/2.png)|![Screenshot 3](screenshots/3.png)| +## Delivery model + +One account is one device, and the server keeps an encrypted copy of a message +only until the receiver acknowledges that it stored it. A message that was sent +but never acknowledged is re-sent on the next connect; the server drops the +duplicates. Media is deleted from the server when the receiver confirms the +download, so an attachment that was never fetched before its TTL (or before a +reinstall) shows as expired rather than being re-downloadable. + ## Download You can download the app [here in the releases](https://github.com/jsfraz/whisper/releases). @@ -85,12 +94,8 @@ Known limitations (Linux desktop, verified): - used for HTTP requests - [json_annotation](https://pub.dev/packages/json_annotation) - used for JSON serialization annotations -- [jwt_decoder](https://pub.dev/packages/jwt_decoder) - - used for JWT token decoding - [local_auth](https://pub.dev/packages/local_auth) - used for biometric authentication -- [mobile_scanner](https://pub.dev/packages/mobile_scanner) - - used for QR code scanning - [page_transition](https://pub.dev/packages/page_transition) - used for custom page transitions - [path_provider](https://pub.dev/packages/path_provider) diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 885c653..d72d3ef 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -1,152 +1,154 @@ { - "xMessagesFromYChats": "%d nových zpráv z %d chatů", - "urlError": "Chyba při otevířání URL %s", - "passwordPlsWait": "Ověřování hesla, čekejte prosím...", - "useBiometrics": "Použít otisk prstu", - "biometricAuthReason": "Prosím, ověřte svou identitu otiskem prstu", - "biometricAuthPrompt": "Přiložte prst k senzoru", - "biometricSetupReason": "Nastavení ověřování otiskem prstu", - "biometricSetupAuth": "Přiložte prst k senzoru pro aktivaci", - "biometricAuthFailed": "Ověření otiskem prstu selhalo", - "biometricSetupFailed": "Nastavení otisku prstu selhalo", - "enableBiometrics": "Povolit přihlašování otiskem prstu", - "biometricsEnabled": "Přihlašování otiskem prstu povoleno", - "biometricsDisabled": "Přihlašování otiskem prstu vypnuto", - "yesText": "Ano", - "noText": "Ne", - "okText": "Budiž", - "msgPage": "Zprávy", - "settingsButton": "Nastavení", - "addChat": "Nový chat", - "newInvite": "Nová pozvánka", - "adminPage": "Správa", - "serverUsersPage": "Uživatelé serveru", - "serverInvitesPage": "Pozvánky na server", - "deleteUserConfirm": "Potvrdit smazání uživatele", - "deleteUserConfirmText": "Opravdu chcete smazat tohoto uživatele? Tato akce je nevratná.", - "deleteUser": "Smazat uživatele", - "adminBadge": "ADMIN", - "noUsers": "Žádní uživatelé", - "noInvites": "Žádné pozvánky", - "loadError": "Nepodařilo se načíst data", - "userDeleted": "Uživatel smazán", - "deleteUserConfirmTextName": "Opravdu chcete smazat uživatele %s? Tato akce je nevratná.", - "inviteExpiresIn": "vyprší za %s %s", - "chatInfoPage": "Informace o chatu", - "deleteChatConfirm": "Potvrdit smazání chatu", - "deleteChatConfirmText": "Opravdu chcete smazat tento chat?", - "deleteChat": "Smazat chat", - "legendaryChat": "Toto je začátek vaší legendární konverzace. Nebo něco na ten způsob, těžko říct.", - "infoButton": "Informace o chatu", - "yourMessage": "Vaše úžasná zpráva...", - "invalidPassword": "Neplatné heslo", - "invalidLocalPassword": "Neplatné heslo", - "localPasswordPlaceholder": "Vaše tajné heslo", - "localPasswordButton": "Přihlásit", - "invalidUsername": "Neplatné uživatelské jméno", - "waitPls": "Vyčkejte...", - "usernamePlaceholder": "Vaše magické uživatelské jméno", - "inviteExpired": "Pozvánka vypršela", - "inviteValidFor": "Platnost pozvánky", - "registerButton": "Zaregistrovat", - "scanQrButton": "Naskenovat QR kód", - "invalidQr": "Neplatný QR kód", - "scanQr": "Naskenujte QR kód pozvánky", - "searchUserPage": "Hledat uživatele", - "enterUsername": "Uživatelské jméno vaší oběti", - "clearSearch": "Vymazat hledání", - "noUsersFound": "Uživatel nenalezen", - "userSearchFailed": "Hledání se nezdařilo", - "settingsPage": "Nastavení", - "themeSettings": "Motiv", - "chatTheme": "Téma chatu", - "useGlobalTheme": "Použít globální motiv", - "notificationSettings": "Oznámení", - "biometrySettings": "Ověření otiskem prstu", - "wikiLink": "Wiki", - "repoLink": "Zdrojový kód", - "deleteAllChatsConfirm": "Potvrdit smazání všech chatů", - "deleteAllChatsConfirmText": "Opravdu chcete smazat všechny své chaty?", - "deleteAllChats": "Smazat všechny chaty", - "logoutConfirm": "Potvrdit odhlášení", - "logoutConfirmText": "Opravdu se chcete odhlásit? Všechna vaše data budou smazána a váš účet bude odstraněn i ze serveru.", - "logout": "Odhlásit se", - "accountDeleted1": "Byli jste odhlášeni a váš účet byl smazán", - "logoutAndDelete": "Odhlásit se a smazat účet", - "invalidMail": "Neplatný e-mail", - "userMail": "E-mail uživatele", - "themeMode": "Režim motivu", - "systemText": "Systémový", - "lightText": "Světlý", - "darkText": "Tmavý", - "themeColor": "Barva motivu", - "chooseColor": "Vybrat barvu", - "useMat3": "Material Design 3", - "pickColor": "Vyberte barvu", - "newMessagesTitle": "Nové zprávy", - "newMessagesBody": "Máte nové zprávy v chatu", - "notificationChannelDesc": "Oznámení pro nové zprávy v chatu", - "tickerLocalNotifications": "Nové zprávy v chatu", - "whisperLocalNotificationSingleMessage": "Máte novou zprávu v chatu", - "offlineTrue": "Jste offline :(", - "offlineFalse": "Jste zpět online :)", - "decryptionFailed": "Dešifrování selhalo", - "yesterdayText": "Včera", - "todayText": "Dnes", - "meText": "Já", - "accountDeleted2": "Váš účet byl smazán :P", - "wsOffline": "WebSocket je offline", - "attachButton": "Přiložit", - "attachCamera": "Vyfotit", - "attachVideoCamera": "Natočit video", - "attachGallery": "Galerie fotek a videí", - "gifFromKeyboardFailed": "GIF z klávesnice se nepodařilo načíst", - "attachFile": "Soubor", - "holdToRecord": "Podržením nahrajete hlasovou zprávu", - "slideToCancel": "Posunutím zrušíte", - "releaseToCancel": "Uvolněním zrušíte", - "voiceTooShort": "Nahrávka je příliš krátká", - "micPermissionDenied": "Přístup k mikrofonu byl odepřen", - "mediaUploadFailed": "Nahrání přílohy selhalo", - "mediaDownloadFailed": "Stažení selhalo", - "mediaError": "Médium se nepodařilo otevřít", - "retry": "Zkusit znovu", - "mediaPhoto": "Fotka", - "mediaGif": "GIF", - "mediaVideo": "Video", - "mediaTitle": "Média", - "mediaVoice": "Hlasová zpráva", - "changePassword": "Změnit heslo", - "currentPassword": "Současné heslo", - "newPassword": "Nové heslo", - "confirmPassword": "Potvrďte nové heslo", - "passwordMismatch": "Hesla se neshodují", - "wrongCurrentPassword": "Současné heslo není správné", - "passwordChanged": "Heslo změněno", - "passwordChangeFailed": "Heslo se nepodařilo změnit", - "biometricsDisabledAfterMigration": "Biometrika byla vypnuta. Odemkni heslem a znovu ji zapni v nastavení.", - "passwordMigrationFailed": "Lokální data se nepodařilo otevřít. Heslo neodpovídá uloženým datům.", - "copyMessage": "Kopírovat", - "forwardMessage": "Přeposlat", - "saveAttachment": "Uložit přílohu", - "deleteMessageForMe": "Smazat pro mě", - "deleteMessageConfirm": "Smazat zprávu", - "deleteMessageConfirmText": "Zpráva se smaže jen z tohoto zařízení. Druhá strana si ji nechá.", - "copiedText": "Zkopírováno", - "attachmentSaved": "Příloha uložena", - "attachmentSaveFailed": "Uložení přílohy se nepovedlo", - "forwardTo": "Přeposlat komu", - "forwarded": "Přeposláno", - "noChatsToForward": "Zatím žádné chaty, vyhledej uživatele", - "mediaFile": "Soubor", - "fileTooLarge": "Soubor je příliš velký, maximum je", - "send": "Odeslat", - "cancel": "Zrušit", - "sendAttachment": "Odeslat přílohu", - "sendAlbum": "Odeslat album", - "addCaption": "Přidat popisek", - "fileTypeNotAllowed": "Fotky a videa posílej přes Galerii nebo Fotoaparát", - "mediaAlbum": "Album", - "messageSending": "Odesílá se", - "messageSendFailed": "Odeslání se nezdařilo" + "xMessagesFromYChats": "%d nových zpráv z %d chatů", + "urlError": "Chyba při otevířání URL %s", + "passwordPlsWait": "Ověřování hesla, čekejte prosím...", + "useBiometrics": "Použít otisk prstu", + "biometricAuthReason": "Prosím, ověřte svou identitu otiskem prstu", + "biometricAuthPrompt": "Přiložte prst k senzoru", + "biometricSetupReason": "Nastavení ověřování otiskem prstu", + "biometricSetupAuth": "Přiložte prst k senzoru pro aktivaci", + "biometricAuthFailed": "Ověření otiskem prstu selhalo", + "biometricSetupFailed": "Nastavení otisku prstu selhalo", + "enableBiometrics": "Povolit přihlašování otiskem prstu", + "biometricsEnabled": "Přihlašování otiskem prstu povoleno", + "biometricsDisabled": "Přihlašování otiskem prstu vypnuto", + "yesText": "Ano", + "noText": "Ne", + "okText": "Budiž", + "msgPage": "Zprávy", + "settingsButton": "Nastavení", + "addChat": "Nový chat", + "newInvite": "Nová pozvánka", + "adminPage": "Správa", + "serverUsersPage": "Uživatelé serveru", + "serverInvitesPage": "Pozvánky na server", + "deleteUserConfirm": "Potvrdit smazání uživatele", + "deleteUserConfirmText": "Opravdu chcete smazat tohoto uživatele? Tato akce je nevratná.", + "deleteUser": "Smazat uživatele", + "adminBadge": "ADMIN", + "noUsers": "Žádní uživatelé", + "noInvites": "Žádné pozvánky", + "loadError": "Nepodařilo se načíst data", + "userDeleted": "Uživatel smazán", + "deleteUserConfirmTextName": "Opravdu chcete smazat uživatele %s? Tato akce je nevratná.", + "inviteExpiresIn": "vyprší za %s %s", + "chatInfoPage": "Informace o chatu", + "deleteChatConfirm": "Potvrdit smazání chatu", + "deleteChatConfirmText": "Opravdu chcete smazat tento chat?", + "deleteChat": "Smazat chat", + "legendaryChat": "Toto je začátek vaší legendární konverzace. Nebo něco na ten způsob, těžko říct.", + "infoButton": "Informace o chatu", + "yourMessage": "Vaše úžasná zpráva...", + "invalidPassword": "Neplatné heslo", + "invalidLocalPassword": "Neplatné heslo", + "localPasswordPlaceholder": "Vaše tajné heslo", + "localPasswordButton": "Přihlásit", + "invalidUsername": "Neplatné uživatelské jméno", + "waitPls": "Vyčkejte...", + "usernamePlaceholder": "Vaše magické uživatelské jméno", + "inviteExpired": "Pozvánka vypršela", + "inviteValidFor": "Platnost pozvánky", + "registerButton": "Zaregistrovat", + "scanQrButton": "Naskenovat QR kód", + "invalidQr": "Neplatný QR kód", + "scanQr": "Naskenujte QR kód pozvánky", + "searchUserPage": "Hledat uživatele", + "enterUsername": "Uživatelské jméno vaší oběti", + "clearSearch": "Vymazat hledání", + "noUsersFound": "Uživatel nenalezen", + "userSearchFailed": "Hledání se nezdařilo", + "settingsPage": "Nastavení", + "themeSettings": "Motiv", + "chatTheme": "Téma chatu", + "useGlobalTheme": "Použít globální motiv", + "notificationSettings": "Oznámení", + "biometrySettings": "Ověření otiskem prstu", + "wikiLink": "Wiki", + "repoLink": "Zdrojový kód", + "deleteAllChatsConfirm": "Potvrdit smazání všech chatů", + "deleteAllChatsConfirmText": "Opravdu chcete smazat všechny své chaty?", + "deleteAllChats": "Smazat všechny chaty", + "logoutConfirm": "Potvrdit odhlášení", + "logoutConfirmText": "Opravdu se chcete odhlásit? Všechna vaše data budou smazána a váš účet bude odstraněn i ze serveru.", + "logout": "Odhlásit se", + "accountDeleted1": "Byli jste odhlášeni a váš účet byl smazán", + "logoutAndDelete": "Odhlásit se a smazat účet", + "invalidMail": "Neplatný e-mail", + "userMail": "E-mail uživatele", + "themeMode": "Režim motivu", + "systemText": "Systémový", + "lightText": "Světlý", + "darkText": "Tmavý", + "themeColor": "Barva motivu", + "chooseColor": "Vybrat barvu", + "useMat3": "Material Design 3", + "pickColor": "Vyberte barvu", + "newMessagesTitle": "Nové zprávy", + "newMessagesBody": "Máte nové zprávy v chatu", + "notificationChannelDesc": "Oznámení pro nové zprávy v chatu", + "tickerLocalNotifications": "Nové zprávy v chatu", + "whisperLocalNotificationSingleMessage": "Máte novou zprávu v chatu", + "offlineTrue": "Jste offline :(", + "offlineFalse": "Jste zpět online :)", + "decryptionFailed": "Dešifrování selhalo", + "yesterdayText": "Včera", + "todayText": "Dnes", + "meText": "Já", + "accountDeleted2": "Váš účet byl smazán :P", + "wsOffline": "WebSocket je offline", + "attachButton": "Přiložit", + "attachCamera": "Vyfotit", + "attachVideoCamera": "Natočit video", + "attachGallery": "Galerie fotek a videí", + "gifFromKeyboardFailed": "GIF z klávesnice se nepodařilo načíst", + "attachFile": "Soubor", + "holdToRecord": "Podržením nahrajete hlasovou zprávu", + "slideToCancel": "Posunutím zrušíte", + "releaseToCancel": "Uvolněním zrušíte", + "voiceTooShort": "Nahrávka je příliš krátká", + "micPermissionDenied": "Přístup k mikrofonu byl odepřen", + "mediaUploadFailed": "Nahrání přílohy selhalo", + "mediaDownloadFailed": "Stažení selhalo", + "mediaError": "Médium se nepodařilo otevřít", + "retry": "Zkusit znovu", + "mediaPhoto": "Fotka", + "mediaGif": "GIF", + "mediaVideo": "Video", + "mediaTitle": "Média", + "mediaVoice": "Hlasová zpráva", + "changePassword": "Změnit heslo", + "currentPassword": "Současné heslo", + "newPassword": "Nové heslo", + "confirmPassword": "Potvrďte nové heslo", + "passwordMismatch": "Hesla se neshodují", + "wrongCurrentPassword": "Současné heslo není správné", + "passwordChanged": "Heslo změněno", + "passwordChangeFailed": "Heslo se nepodařilo změnit", + "biometricsDisabledAfterMigration": "Biometrika byla vypnuta. Odemkni heslem a znovu ji zapni v nastavení.", + "passwordMigrationFailed": "Lokální data se nepodařilo otevřít. Heslo neodpovídá uloženým datům.", + "copyMessage": "Kopírovat", + "forwardMessage": "Přeposlat", + "saveAttachment": "Uložit přílohu", + "deleteMessageForMe": "Smazat pro mě", + "deleteMessageConfirm": "Smazat zprávu", + "deleteMessageConfirmText": "Zpráva se smaže jen z tohoto zařízení. Druhá strana si ji nechá.", + "copiedText": "Zkopírováno", + "attachmentSaved": "Příloha uložena", + "attachmentSaveFailed": "Uložení přílohy se nepovedlo", + "forwardTo": "Přeposlat komu", + "forwarded": "Přeposláno", + "noChatsToForward": "Zatím žádné chaty, vyhledej uživatele", + "mediaFile": "Soubor", + "fileTooLarge": "Soubor je příliš velký, maximum je", + "send": "Odeslat", + "cancel": "Zrušit", + "sendAttachment": "Odeslat přílohu", + "sendAlbum": "Odeslat album", + "addCaption": "Přidat popisek", + "fileTypeNotAllowed": "Fotky a videa posílej přes Galerii nebo Fotoaparát", + "mediaAlbum": "Album", + "messageSending": "Odesílá se", + "messageSendFailed": "Odeslání se nezdařilo", + "messageUndecryptable": "Tuto zprávu se nepodařilo dešifrovat", + "mediaExpired": "Příloha už není na serveru dostupná" } diff --git a/assets/translations/en.json b/assets/translations/en.json index d6a39d2..c2aa173 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -1,152 +1,154 @@ { - "xMessagesFromYChats": "%d new messages from %d chats", - "urlError": "Error opening URL %s", - "passwordPlsWait": "Verifying password, please wait...", - "useBiometrics": "Use fingerprint", - "biometricAuthReason": "Please verify your identity with fingerprint", - "biometricAuthPrompt": "Place your finger on the sensor", - "biometricSetupReason": "Setting up fingerprint authentication", - "biometricSetupAuth": "Place your finger on the sensor to activate", - "biometricAuthFailed": "Fingerprint authentication failed", - "biometricSetupFailed": "Fingerprint setup failed", - "enableBiometrics": "Enable fingerprint login", - "biometricsEnabled": "Fingerprint login enabled", - "biometricsDisabled": "Fingerprint login disabled", - "yesText": "Yes", - "noText": "No", - "okText": "So be it", - "msgPage": "Messages", - "settingsButton": "Settings", - "addChat": "New chat", - "newInvite": "New Invite", - "adminPage": "Administration", - "serverUsersPage": "Server Users", - "serverInvitesPage": "Server Invites", - "deleteUserConfirm": "Confirm User Deletion", - "deleteUserConfirmText": "Are you sure you want to delete this user? This action cannot be undone.", - "deleteUser": "Delete User", - "adminBadge": "ADMIN", - "noUsers": "No users", - "noInvites": "No invites", - "loadError": "Failed to load data", - "userDeleted": "User deleted", - "deleteUserConfirmTextName": "Are you sure you want to delete %s? This action cannot be undone.", - "inviteExpiresIn": "expires in %s %s", - "chatInfoPage": "Chat Info", - "deleteChatConfirm": "Confirm Chat Deletion", - "deleteChatConfirmText": "Are you sure you want to delete this chat?", - "deleteChat": "Delete chat", - "legendaryChat": "This is the beginning of your legendary conversation. Or something like that, hard to say.", - "infoButton": "Chat info", - "yourMessage": "Your awesome message...", - "invalidPassword": "Invalid password", - "invalidLocalPassword": "Invalid password", - "localPasswordPlaceholder": "Your secret password", - "localPasswordButton": "Sign in", - "invalidUsername": "Invalid username", - "waitPls": "Please wait...", - "usernamePlaceholder": "Your magical username", - "inviteExpired": "Invitation expired", - "inviteValidFor": "Invitation validity", - "registerButton": "Register", - "scanQrButton": "Scan QR code", - "invalidQr": "Invalid QR code", - "scanQr": "Scan the invitation QR code", - "searchUserPage": "Search for users", - "enterUsername": "Your victim's username", - "clearSearch": "Clear search", - "noUsersFound": "No users found", - "userSearchFailed": "Search failed", - "settingsPage": "Settings", - "themeSettings": "Theme", - "chatTheme": "Chat theme", - "useGlobalTheme": "Use global theme", - "notificationSettings": "Notifications", - "biometrySettings": "Fingerprint authentication", - "wikiLink": "Wiki", - "repoLink": "Source code", - "deleteAllChatsConfirm": "Confirm deletion of all chats", - "deleteAllChatsConfirmText": "Are you sure you want to delete all your chats?", - "deleteAllChats": "Delete all chats", - "logoutConfirm": "Confirm logout", - "logoutConfirmText": "Are you sure you want to log out? All your data will be deleted and your account will be removed from the server.", - "logout": "Log out", - "accountDeleted1": "You have been logged out and your account has been deleted", - "logoutAndDelete": "Log out and delete account", - "invalidMail": "Invalid email", - "userMail": "User email", - "themeMode": "Theme mode", - "systemText": "System", - "lightText": "Light", - "darkText": "Dark", - "themeColor": "Theme color", - "chooseColor": "Choose color", - "useMat3": "Material Design 3", - "pickColor": "Pick color", - "newMessagesTitle": "New messages", - "newMessagesBody": "You have new messages in chat", - "notificationChannelDesc": "Notifications for new messages in chat", - "tickerLocalNotifications": "New messages in chat", - "whisperLocalNotificationSingleMessage": "You have a new message in chat", - "offlineTrue": "You are offline :(", - "offlineFalse": "You are back online :)", - "decryptionFailed": "Decryption failed", - "yesterdayText": "Yesterday", - "todayText": "Today", - "meText": "Me", - "accountDeleted2": "Your account has been deleted :P", - "wsOffline": "WebSocket is offline", - "attachButton": "Attach", - "attachCamera": "Take a photo", - "attachVideoCamera": "Record a video", - "attachGallery": "Photo & video gallery", - "gifFromKeyboardFailed": "This keyboard GIF could not be read", - "attachFile": "File", - "holdToRecord": "Hold to record a voice message", - "slideToCancel": "Slide to cancel", - "releaseToCancel": "Release to cancel", - "voiceTooShort": "Recording too short", - "micPermissionDenied": "Microphone permission denied", - "mediaUploadFailed": "Failed to upload attachment", - "mediaDownloadFailed": "Download failed", - "mediaError": "Could not open media", - "retry": "Retry", - "mediaPhoto": "Photo", - "mediaGif": "GIF", - "mediaVideo": "Video", - "mediaTitle": "Media", - "mediaVoice": "Voice message", - "changePassword": "Change password", - "currentPassword": "Current password", - "newPassword": "New password", - "confirmPassword": "Confirm new password", - "passwordMismatch": "Passwords do not match", - "wrongCurrentPassword": "Current password is incorrect", - "passwordChanged": "Password changed", - "passwordChangeFailed": "Password could not be changed", - "biometricsDisabledAfterMigration": "Biometrics were turned off. Unlock with your password and enable them again in settings.", - "passwordMigrationFailed": "Local data could not be opened. The password does not match the stored data.", - "copyMessage": "Copy", - "forwardMessage": "Forward", - "saveAttachment": "Save attachment", - "deleteMessageForMe": "Delete for me", - "deleteMessageConfirm": "Delete message", - "deleteMessageConfirmText": "The message will be deleted only from this device. The other side keeps it.", - "copiedText": "Copied", - "attachmentSaved": "Attachment saved", - "attachmentSaveFailed": "Saving the attachment failed", - "forwardTo": "Forward to", - "forwarded": "Forwarded", - "noChatsToForward": "No chats yet, search for a user", - "mediaFile": "File", - "fileTooLarge": "File is too large, the maximum is", - "send": "Send", - "cancel": "Cancel", - "sendAttachment": "Send attachment", - "sendAlbum": "Send album", - "addCaption": "Add a caption", - "fileTypeNotAllowed": "Photos and videos go through Gallery or Camera", - "mediaAlbum": "Album", - "messageSending": "Sending", - "messageSendFailed": "Sending failed" + "xMessagesFromYChats": "%d new messages from %d chats", + "urlError": "Error opening URL %s", + "passwordPlsWait": "Verifying password, please wait...", + "useBiometrics": "Use fingerprint", + "biometricAuthReason": "Please verify your identity with fingerprint", + "biometricAuthPrompt": "Place your finger on the sensor", + "biometricSetupReason": "Setting up fingerprint authentication", + "biometricSetupAuth": "Place your finger on the sensor to activate", + "biometricAuthFailed": "Fingerprint authentication failed", + "biometricSetupFailed": "Fingerprint setup failed", + "enableBiometrics": "Enable fingerprint login", + "biometricsEnabled": "Fingerprint login enabled", + "biometricsDisabled": "Fingerprint login disabled", + "yesText": "Yes", + "noText": "No", + "okText": "So be it", + "msgPage": "Messages", + "settingsButton": "Settings", + "addChat": "New chat", + "newInvite": "New Invite", + "adminPage": "Administration", + "serverUsersPage": "Server Users", + "serverInvitesPage": "Server Invites", + "deleteUserConfirm": "Confirm User Deletion", + "deleteUserConfirmText": "Are you sure you want to delete this user? This action cannot be undone.", + "deleteUser": "Delete User", + "adminBadge": "ADMIN", + "noUsers": "No users", + "noInvites": "No invites", + "loadError": "Failed to load data", + "userDeleted": "User deleted", + "deleteUserConfirmTextName": "Are you sure you want to delete %s? This action cannot be undone.", + "inviteExpiresIn": "expires in %s %s", + "chatInfoPage": "Chat Info", + "deleteChatConfirm": "Confirm Chat Deletion", + "deleteChatConfirmText": "Are you sure you want to delete this chat?", + "deleteChat": "Delete chat", + "legendaryChat": "This is the beginning of your legendary conversation. Or something like that, hard to say.", + "infoButton": "Chat info", + "yourMessage": "Your awesome message...", + "invalidPassword": "Invalid password", + "invalidLocalPassword": "Invalid password", + "localPasswordPlaceholder": "Your secret password", + "localPasswordButton": "Sign in", + "invalidUsername": "Invalid username", + "waitPls": "Please wait...", + "usernamePlaceholder": "Your magical username", + "inviteExpired": "Invitation expired", + "inviteValidFor": "Invitation validity", + "registerButton": "Register", + "scanQrButton": "Scan QR code", + "invalidQr": "Invalid QR code", + "scanQr": "Scan the invitation QR code", + "searchUserPage": "Search for users", + "enterUsername": "Your victim's username", + "clearSearch": "Clear search", + "noUsersFound": "No users found", + "userSearchFailed": "Search failed", + "settingsPage": "Settings", + "themeSettings": "Theme", + "chatTheme": "Chat theme", + "useGlobalTheme": "Use global theme", + "notificationSettings": "Notifications", + "biometrySettings": "Fingerprint authentication", + "wikiLink": "Wiki", + "repoLink": "Source code", + "deleteAllChatsConfirm": "Confirm deletion of all chats", + "deleteAllChatsConfirmText": "Are you sure you want to delete all your chats?", + "deleteAllChats": "Delete all chats", + "logoutConfirm": "Confirm logout", + "logoutConfirmText": "Are you sure you want to log out? All your data will be deleted and your account will be removed from the server.", + "logout": "Log out", + "accountDeleted1": "You have been logged out and your account has been deleted", + "logoutAndDelete": "Log out and delete account", + "invalidMail": "Invalid email", + "userMail": "User email", + "themeMode": "Theme mode", + "systemText": "System", + "lightText": "Light", + "darkText": "Dark", + "themeColor": "Theme color", + "chooseColor": "Choose color", + "useMat3": "Material Design 3", + "pickColor": "Pick color", + "newMessagesTitle": "New messages", + "newMessagesBody": "You have new messages in chat", + "notificationChannelDesc": "Notifications for new messages in chat", + "tickerLocalNotifications": "New messages in chat", + "whisperLocalNotificationSingleMessage": "You have a new message in chat", + "offlineTrue": "You are offline :(", + "offlineFalse": "You are back online :)", + "decryptionFailed": "Decryption failed", + "yesterdayText": "Yesterday", + "todayText": "Today", + "meText": "Me", + "accountDeleted2": "Your account has been deleted :P", + "wsOffline": "WebSocket is offline", + "attachButton": "Attach", + "attachCamera": "Take a photo", + "attachVideoCamera": "Record a video", + "attachGallery": "Photo & video gallery", + "gifFromKeyboardFailed": "This keyboard GIF could not be read", + "attachFile": "File", + "holdToRecord": "Hold to record a voice message", + "slideToCancel": "Slide to cancel", + "releaseToCancel": "Release to cancel", + "voiceTooShort": "Recording too short", + "micPermissionDenied": "Microphone permission denied", + "mediaUploadFailed": "Failed to upload attachment", + "mediaDownloadFailed": "Download failed", + "mediaError": "Could not open media", + "retry": "Retry", + "mediaPhoto": "Photo", + "mediaGif": "GIF", + "mediaVideo": "Video", + "mediaTitle": "Media", + "mediaVoice": "Voice message", + "changePassword": "Change password", + "currentPassword": "Current password", + "newPassword": "New password", + "confirmPassword": "Confirm new password", + "passwordMismatch": "Passwords do not match", + "wrongCurrentPassword": "Current password is incorrect", + "passwordChanged": "Password changed", + "passwordChangeFailed": "Password could not be changed", + "biometricsDisabledAfterMigration": "Biometrics were turned off. Unlock with your password and enable them again in settings.", + "passwordMigrationFailed": "Local data could not be opened. The password does not match the stored data.", + "copyMessage": "Copy", + "forwardMessage": "Forward", + "saveAttachment": "Save attachment", + "deleteMessageForMe": "Delete for me", + "deleteMessageConfirm": "Delete message", + "deleteMessageConfirmText": "The message will be deleted only from this device. The other side keeps it.", + "copiedText": "Copied", + "attachmentSaved": "Attachment saved", + "attachmentSaveFailed": "Saving the attachment failed", + "forwardTo": "Forward to", + "forwarded": "Forwarded", + "noChatsToForward": "No chats yet, search for a user", + "mediaFile": "File", + "fileTooLarge": "File is too large, the maximum is", + "send": "Send", + "cancel": "Cancel", + "sendAttachment": "Send attachment", + "sendAlbum": "Send album", + "addCaption": "Add a caption", + "fileTypeNotAllowed": "Photos and videos go through Gallery or Camera", + "mediaAlbum": "Album", + "messageSending": "Sending", + "messageSendFailed": "Sending failed", + "messageUndecryptable": "This message could not be decrypted", + "mediaExpired": "The attachment is no longer available on the server" } diff --git a/integration_test/app_e2e_test.dart b/integration_test/app_e2e_test.dart index 4b027ac..876e514 100644 --- a/integration_test/app_e2e_test.dart +++ b/integration_test/app_e2e_test.dart @@ -69,16 +69,20 @@ void main() { testWidgets('login with RSA JWT and refresh', (tester) async { final apiClient = client(null); + final authApi = AuthenticationApi(apiClient); + // The login token must carry the one-time challenge. + final challenge = await authApi.authChallenge(); final jwt = await CryptoUtils.generateRsaJwt( - '1', keys.privateKey as bu.RSAPrivateKey); - final auth = await AuthenticationApi(apiClient).authUser( + '1', keys.privateKey as bu.RSAPrivateKey, + nonce: challenge!.challenge); + final auth = await authApi.authUser( authUserInput: AuthUserInput(token: jwt), ); expect(auth!.accessToken, isNotEmpty); expect(auth.refreshToken, isNotEmpty); - final refreshed = await AuthenticationApi(apiClient).refreshUserAccessToken( + final refreshed = await authApi.refreshUserAccessToken( refreshUserAccessTokenInput: RefreshUserAccessTokenInput(refreshToken: auth.refreshToken), ); diff --git a/integration_test/fake_server.dart b/integration_test/fake_server.dart index d5c0ae2..588de0d 100644 --- a/integration_test/fake_server.dart +++ b/integration_test/fake_server.dart @@ -52,6 +52,8 @@ class FakeServer { 'publicKey': body['publicKey'], 'admin': false, }); + } else if (path == '/api/auth/challenge') { + _json(request.response, {'challenge': 'challenge-1', 'expiresIn': 30}); } else if (path == '/api/auth') { _json(request.response, { 'accessToken': 'access-1', diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index 721aa90..a4aa1df 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -18,6 +18,10 @@ class MediaDownloadStatus { /// Download or decryption failed; can be retried. static const int failed = 2; + + /// The server no longer has the file: it was confirmed on another device, + /// expired, or the sender's account was cleaned up. Retrying cannot help. + static const int expired = 3; } /// Outbound send state, shown as an icon in the bubble. @@ -181,8 +185,16 @@ class PrivateMessage extends HiveObject { this.albumJson, }); + /// Stored instead of the text when a message cannot be decrypted. It keeps a + /// visible gap in the chat, and the receiver only acks what it stored, so the + /// server still has the ciphertext. + static const String undecryptableMarker = '\uE000whisper-undecryptable'; + bool get isMe => senderId == Singleton().profile.user.id; + /// Whether the stored text is the placeholder of an undecryptable message. + bool get isUndecryptable => message == undecryptableMarker; + int get notificationId => receivedAt.microsecondsSinceEpoch % 0x7FFFFFFF; /// Whether this message carries a media attachment (single or album). @@ -260,6 +272,9 @@ class PrivateMessage extends HiveObject { /// Short text used in chat list previews and notifications. Falls back to a /// localized media label when a media message has no caption. String get preview { + if (isUndecryptable) { + return 'messageUndecryptable'.tr(); + } if (!isMedia || message.isNotEmpty) { return message; } diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 7a3f019..ba2d9e9 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -7,7 +7,6 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import '../utils/nav_transitions.dart'; -import 'package:provider/provider.dart'; import 'package:sprintf/sprintf.dart'; import '../pages/chat_page.dart'; import '../utils/websocket_manager.dart'; @@ -40,7 +39,7 @@ class _HomePageState extends State List _serverUsers = []; int _currentPageIndex = 0; List _serverInvites = []; - Map _chats = {}; + List> _chatEntries = []; bool _firstLoad = true; String? _pendingFid; // Store pending FID @@ -63,6 +62,11 @@ class _HomePageState extends State } // Get all conversations with their last messages _getConversations(); + // Refresh the list when a message arrives or its state changes; the build + // method must not create a new future on every rebuild. + MessageNotifier().addListener(_onMessagesChanged); + // A pending FCM id is retried when the socket comes up instead of polling. + Utils.onConnected = _sendPendingFid; // Open the chat a notification tap pointed at (after unlocking) _openPendingChat(); // Taps arriving while Home is alive open the chat right away @@ -89,29 +93,36 @@ class _HomePageState extends State // Register with FCM, the FID arrives via onRegistered _registerForPush(); - // Listen to offline mode changes to send the pending FID - _listenToConnectivityChanges(); } @override void dispose() { _adminTabController.dispose(); + MessageNotifier().removeListener(_onMessagesChanged); if (NotificationService.onChatSelected == _openChat) { NotificationService.onChatSelected = null; } + if (Utils.onConnected == _sendPendingFid) { + Utils.onConnected = null; + } super.dispose(); // Stop checking WebSocket connection _webSocketManager.stopConnectionCheck(); } - /// Listen to connectivity changes and send the pending FID - void _listenToConnectivityChanges() { - // Check periodically if we came back online and have a pending FID - Timer.periodic(Duration(seconds: 30), (timer) { - if (!Singleton().offlineMode && _pendingFid != null) { - _sendPushTargetWhenOnline(_pendingFid!); - } - }); + /// Reload the conversation list after a message or its send/media state + /// changed. + void _onMessagesChanged() { + _getConversations(); + } + + /// Push a pending Firebase installation id once the socket is up. + Future _sendPendingFid() async { + final fid = _pendingFid; + if (fid == null) { + return; + } + await _sendPushTargetWhenOnline(fid); } /// Register with FCM, the FID arrives via onRegistered @@ -156,10 +167,14 @@ class _HomePageState extends State /// Get all conversations with their last messages Future _getConversations() async { - _chats = await CacheUtils.getLatestPrivateMessages(); - if (context.mounted) { - setState(() {}); + final chats = await CacheUtils.getLatestPrivateMessages(); + if (!mounted) { + return; } + setState(() { + _chatEntries = chats.entries.toList(); + _firstLoad = false; + }); } /// Get server users @@ -263,7 +278,7 @@ class _HomePageState extends State } /// Get ListView with content - ListView _getContent(Map chats) { + ListView _getContent(List> chats) { _firstLoad = false; return ListView.builder( physics: const BouncingScrollPhysics( @@ -271,7 +286,9 @@ class _HomePageState extends State ), itemCount: chats.length, itemBuilder: (context, index) { - final chat = chats.entries.elementAt(index); + // Indexed access: `Map.entries.elementAt` is O(n) and made the list + // build O(n^2). + final chat = chats[index]; return Padding( padding: EdgeInsets.only(right: 5, left: 5, bottom: 3), child: ChatListItem(chat.key, chat.value, () { @@ -285,8 +302,6 @@ class _HomePageState extends State @override Widget build(BuildContext context) { - final notifier = context.watch(); - return Scaffold( extendBodyBehindAppBar: true, appBar: _currentPageIndex == 0 @@ -391,25 +406,14 @@ class _HomePageState extends State SizedBox(height: 10), // Messages and avatar list Expanded( - child: FutureBuilder>( - future: notifier.getLatestPrivateMessages(), - builder: (context, snapshot) { - if (snapshot.connectionState == ConnectionState.waiting && - _firstLoad) { - return Center( - child: Transform.scale( - scale: 1.5, - child: CircularProgressIndicator(), - ), - ); - } - // Set data - if (snapshot.hasData) { - _chats = snapshot.data!; - } - // Return chats - return _getContent(_chats); - }), + child: _firstLoad + ? Center( + child: Transform.scale( + scale: 1.5, + child: CircularProgressIndicator(), + ), + ) + : _getContent(_chatEntries), ), ], ), @@ -478,17 +482,22 @@ class _HomePageState extends State ); } - /// Error row with a retry button, replacing the blank tab of the old UI. + /// Centred error message with a retry button, replacing the blank tab of the old UI. Widget _adminError(VoidCallback retry) { final colors = Theme.of(context).colorScheme; - return Padding( - padding: const EdgeInsets.all(16), - child: Row( + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, children: [ - Icon(Icons.error_outline, size: 20, color: colors.error), - const SizedBox(width: 8), - Expanded(child: Text('loadError'.tr())), - TextButton(onPressed: retry, child: Text('retry'.tr())), + Icon(Icons.error_outline, size: 40, color: colors.error), + const SizedBox(height: 12), + Text( + 'loadError'.tr(), + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 16), + FilledButton.tonal(onPressed: retry, child: Text('retry'.tr())), ], ), ); diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 012b047..496c801 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -23,6 +23,7 @@ class CacheUtils { static const _privateMessagesKey = 'privateMessages'; static const _userKey = 'user'; static const _messageConceptKey = 'messageConcept'; + static const _pendingSendsKey = 'pendingSends'; static const _biometry = 'biometry'; static const _playbackSpeed = 'playbackSpeed'; static const String _saltStorageKey = 'whisper_pbkdf2_salt'; @@ -116,6 +117,8 @@ class CacheUtils { userBox.deleteFromDisk(); Box messageConceptBox = await _openMessageConceptBox(); messageConceptBox.deleteFromDisk(); + Box pendingSendsBox = await _openPendingSendsBox(); + pendingSendsBox.deleteFromDisk(); if (await isBiometryEnabled()) { await BiometricAuth.clearEncryptionKey(); } @@ -280,42 +283,115 @@ class CacheUtils { await box.put(_playbackSpeed, speed); } - /// Opens box with private messages + /// Opens the message box. One key per message, so a write touches one entry + /// instead of rewriting a whole conversation. static Future _openPrivateMessagesBox() async { return Hive.openBox(_privateMessagesKey); } - /// Add user message to cache + /// Separates the conversation id from the timestamp in a message key. + static const String _messageKeySeparator = '|'; + + /// Key of one stored message: conversation id plus client timestamp. + /// + /// One key per message instead of one list per conversation: adding a message + /// writes a single entry instead of rewriting the whole chat. + static String messageKey(String userId, DateTime sentAt) => + '$userId$_messageKeySeparator${sentAt.microsecondsSinceEpoch}'; + + /// Conversation id of a stored message key, null for legacy keys. + static String? conversationOfKey(dynamic key) { + if (key is! String) { + return null; + } + final index = key.lastIndexOf(_messageKeySeparator); + if (index <= 0) { + return null; + } + return key.substring(0, index); + } + + static int _timestampOfKey(String key) { + final index = key.lastIndexOf(_messageKeySeparator); + return int.tryParse(key.substring(index + 1)) ?? 0; + } + + /// Keys of one conversation, in box order. + static Iterable _conversationKeys(Box box, String userId) { + return box.keys.whereType().where((key) { + final index = key.lastIndexOf(_messageKeySeparator); + return index > 0 && key.substring(0, index) == userId; + }); + } + + /// Older versions stored a whole conversation under the user id. Move those + /// messages into per-message keys once, then drop the old entry. + static Future _migrateLegacyConversation( + Box box, String userId) async { + if (!box.containsKey(userId)) { + return; + } + final legacy = box.get(userId); + if (legacy is List) { + for (final entry in legacy) { + if (entry is PrivateMessage) { + await box.put(messageKey(userId, entry.sentAt), entry); + } + } + } + await box.delete(userId); + } + + /// Migrates every legacy conversation entry in the box. + static Future _migrateLegacyMessages(Box box) async { + for (final key in box.keys.whereType().toList()) { + if (conversationOfKey(key) != null) { + continue; + } + await _migrateLegacyConversation(box, key); + } + } + + /// Add messages to a conversation. + /// + /// A message that is already stored is skipped: the server re-sends + /// unacknowledged messages, and the stored copy may already carry the read + /// flag. static Future addPrivateMessages( String userId, List messages) async { Box box = await _openPrivateMessagesBox(); - List chatMessages = await getPrivateMessages(userId); - chatMessages.addAll(messages); - await box.put(userId, chatMessages); + await _migrateLegacyConversation(box, userId); + for (final message in messages) { + final key = messageKey(userId, message.sentAt); + if (box.containsKey(key)) { + continue; + } + await box.put(key, message); + } } - /// Get user messages and mark them as read + /// Get user messages, oldest first, and mark them as read static Future> getPrivateMessages(String userId, {bool markAsRead = false}) async { Box box = await _openPrivateMessagesBox(); - List? messages = box.get(userId); - // Mark as read, but only write when something actually changed: this runs - // on every chat rebuild. - if (markAsRead && messages != null) { - var changed = false; - for (PrivateMessage msg in messages) { - if (!msg.read) { - msg.read = true; - changed = true; - } + await _migrateLegacyConversation(box, userId); + final entries = >[]; + for (final key in _conversationKeys(box, userId)) { + final value = box.get(key); + if (value is PrivateMessage) { + entries.add(MapEntry(key, value)); } - if (changed) { - await box.put(userId, messages); + } + entries.sort((a, b) => a.value.sentAt.compareTo(b.value.sentAt)); + // Mark as read, but only write the messages that actually changed: this + // runs on every chat rebuild. + for (final entry in entries) { + if (markAsRead && !entry.value.read) { + entry.value.read = true; + await box.put(entry.key, entry.value); } } - return messages == null - ? [] - : messages.map((e) => e as PrivateMessage).toList(); + return entries.map((entry) => entry.value).toList(); } /// Delete a single message locally (and its media file). Nothing is sent to @@ -323,15 +399,10 @@ class CacheUtils { static Future deletePrivateMessage( String userId, PrivateMessage message) async { Box box = await _openPrivateMessagesBox(); - List? messages = box.get(userId); - if (messages == null) { - return; - } - messages.removeWhere((m) => - m is PrivateMessage && - m.senderId == message.senderId && - m.sentAt == message.sentAt); - await box.put(userId, messages); + await _migrateLegacyConversation(box, userId); + // Removing the key also removes an emptied conversation from the list. + await box.delete(messageKey(userId, message.sentAt)); + await _deletePendingSend(userId, message.sentAt); for (final path in message.localPaths) { await MediaUtils.deleteLocalFile(path); } @@ -342,7 +413,12 @@ class CacheUtils { Box messageBox = await _openPrivateMessagesBox(); // Delete on-disk media files for this conversation first. await _deleteMediaFilesForUser(userId); - await messageBox.delete(userId); + for (final key in _conversationKeys(messageBox, userId).toList()) { + await messageBox.delete(key); + } + if (messageBox.containsKey(userId)) { + await messageBox.delete(userId); + } Box userBox = await _openUserBox(); await userBox.delete(userId); await deleteMessageConcept(userId); @@ -363,13 +439,19 @@ class CacheUtils { static Future updatePrivateMessageMedia(String userId, String mediaId, {String? localPath, int? downloadStatus, int? mediaSize}) async { Box box = await _openPrivateMessagesBox(); - List? messages = box.get(userId); - if (messages == null) { + await _migrateLegacyConversation(box, userId); + final keys = _conversationKeys(box, userId).toList(); + if (keys.isEmpty) { return; } - bool changed = false; - for (final dynamic m in messages) { - final msg = m as PrivateMessage; + final updated = []; + for (final key in keys) { + final dynamic m = box.get(key); + if (m is! PrivateMessage) { + continue; + } + bool changed = false; + final msg = m; if (msg.mediaId == mediaId) { if (localPath != null) { msg.localPath = localPath; @@ -408,8 +490,9 @@ class CacheUtils { if (downloadStatus != null) { final allReady = items.every((item) => item.status == MediaDownloadStatus.ready); - final anyFailed = - items.any((item) => item.status == MediaDownloadStatus.failed); + final anyFailed = items.any((item) => + item.status == MediaDownloadStatus.failed || + item.status == MediaDownloadStatus.expired); msg.downloadStatus = allReady ? MediaDownloadStatus.ready : (anyFailed @@ -419,31 +502,95 @@ class CacheUtils { changed = true; } } + if (changed) { + updated.add(key); + } } - if (changed) { - await box.put(userId, messages); + for (final key in updated) { + final message = box.get(key); + if (message is PrivateMessage) { + await box.put(key, message); + } } } - /// Apply [update] to the stored copy of [message] and persist the list. - /// The message is matched by sender and timestamp, the same identity the - /// delete path uses. + /// Apply [update] to the stored copy of [message] and persist it. + /// + /// The message is identified by conversation and client timestamp, the same + /// identity the delete path and the delivery ack use. static Future updateStoredMessage(String userId, PrivateMessage message, void Function(PrivateMessage stored) update) async { Box box = await _openPrivateMessagesBox(); - List? messages = box.get(userId); - if (messages == null) { + await _migrateLegacyConversation(box, userId); + final key = messageKey(userId, message.sentAt); + final stored = box.get(key); + if (stored is! PrivateMessage) { return; } - for (final dynamic m in messages) { - final stored = m as PrivateMessage; - if (stored.senderId == message.senderId && - stored.sentAt == message.sentAt) { - update(stored); - await box.put(userId, messages); - return; + update(stored); + await box.put(key, stored); + } + + /// Marks the message the server acknowledged as sent. + /// + /// [receiverId] and [sentAt] are the values the server echoes back; the pair + /// identifies the stored message without keeping a client message id. + static Future markMessageSent( + String receiverId, DateTime sentAt) async { + Box box = await _openPrivateMessagesBox(); + await _migrateLegacyConversation(box, receiverId); + final key = messageKey(receiverId, sentAt); + final stored = box.get(key); + if (stored is! PrivateMessage) { + return; + } + stored.sendStatus = SendStatus.sent; + await box.put(key, stored); + await _deletePendingSend(receiverId, sentAt); + } + + /// Remembers a message that is waiting for its delivery ack, so a reconnect + /// can resend exactly those. + static Future addPendingSend( + String receiverId, DateTime sentAt) async { + Box box = await _openPendingSendsBox(); + await box.put(messageKey(receiverId, sentAt), receiverId); + } + + static Future _deletePendingSend( + String receiverId, DateTime sentAt) async { + Box box = await _openPendingSendsBox(); + await box.delete(messageKey(receiverId, sentAt)); + } + + /// Messages still waiting for a delivery ack, grouped by conversation. + static Future>> getPendingSends() async { + Box pending = await _openPendingSendsBox(); + Box box = await _openPrivateMessagesBox(); + final byConversation = >{}; + for (final entry in pending.toMap().entries) { + final key = entry.key; + if (key is! String) { + continue; + } + final receiverId = entry.value as String; + final message = box.get(key); + if (message is! PrivateMessage || + message.sendStatus != SendStatus.sending) { + // Acked, deleted or already given up: forget the marker. + await pending.delete(key); + continue; } + byConversation.putIfAbsent(receiverId, () => []).add(message); } + for (final messages in byConversation.values) { + messages.sort((a, b) => a.sentAt.compareTo(b.sentAt)); + } + return byConversation; + } + + static Future _openPendingSendsBox() { + return Hive.openBox(_pendingSendsKey); } /// Opens box with users @@ -469,15 +616,36 @@ class CacheUtils { await box.put(user.id, user); } - /// Get Map of all conversations with their last messages + /// Get Map of all conversations with their last messages. + /// + /// Only the newest message of each conversation is deserialized, so the list + /// does not pay for the whole history. static Future> getLatestPrivateMessages() async { Box box = await _openPrivateMessagesBox(); + await _migrateLegacyMessages(box); + + final newestKey = {}; + final newestTimestamp = {}; + for (final key in box.keys.whereType()) { + final userId = conversationOfKey(key); + if (userId == null) { + continue; + } + final timestamp = _timestampOfKey(key); + if (timestamp > (newestTimestamp[userId] ?? -1)) { + newestTimestamp[userId] = timestamp; + newestKey[userId] = key; + } + } + Map conversations = {}; - for (var entry in box.toMap().entries) { - User? user = await getUserById(entry.key as String); - List messages = entry.value; - conversations[user ?? User(entry.key as String, '', '', false)] = - messages.last as PrivateMessage; + for (final entry in newestKey.entries) { + final message = box.get(entry.value); + if (message is! PrivateMessage) { + continue; + } + User? user = await getUserById(entry.key); + conversations[user ?? User(entry.key, '', '', false)] = message; } // Sort conversations by last message date var sortedEntries = conversations.entries.toList() @@ -490,9 +658,11 @@ class CacheUtils { Box messageBox = await _openPrivateMessagesBox(); Box userBox = await _openUserBox(); Box conceptBox = await _openMessageConceptBox(); + Box pendingBox = await _openPendingSendsBox(); await userBox.clear(); await messageBox.clear(); await conceptBox.clear(); + await pendingBox.clear(); // Remove every locally stored media file. await MediaUtils.clearMediaDir(); } diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index a396cb5..9bf6d37 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -1,8 +1,8 @@ import 'dart:convert'; -import 'dart:typed_data'; import 'package:basic_utils/basic_utils.dart' as bu; import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:http/http.dart' as http; @@ -43,9 +43,19 @@ class OutgoingAttachment { /// forward page so both use one encrypted, persisted send path. /// /// The bubble is stored as `sending` before anything goes out and flipped to -/// `sent` afterwards, so the message is visible immediately and a failure leaves -/// a visible failed state instead of a silent loss. +/// `sent` only when the server acknowledges the message. Without an ack the +/// message stays pending and is resent on the next connect, so a lost frame is +/// visible instead of silent. class ChatSender { + /// Transport references of media messages sent in this session, keyed by + /// [CacheUtils.messageKey]. Needed to resend a media message whose ack was + /// lost; the transport key is never persisted, so after a restart such a + /// message cannot be resent. + /// + /// shortcut: resending media only works in the session that uploaded it, + /// upgrade by persisting the transport key inside the encrypted profile box. + static final Map> _outgoingReferences = {}; + /// Send a text message to [recipient]. static Future sendText(User recipient, String text) async { final now = DateTime.now(); @@ -57,12 +67,8 @@ class ChatSender { if (!await _ensureConnected()) { return await _fail(recipient.id, message); } - final data = await CryptoUtils.encryptMessageData(utf8.encode(text), - bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); - Singleton().wsClient.sendMessage(WsMessage.privateMessage( - NewPrivateMessage(recipient.id, data['encryptedData']!, - data['encryptedKey']!, data['nonce']!, data['mac']!))); - await _markSent(recipient.id, message); + await _sendText(recipient, message); + // No ack yet: the message stays `sending` until the server confirms. return true; } catch (e) { Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); @@ -117,11 +123,12 @@ class ChatSender { if (reference == null) { return await _fail(recipient.id, message); } + _outgoingReferences[CacheUtils.messageKey(recipient.id, message.sentAt)] = + [reference]; final envelope = MediaUtils.buildMediaEnvelope(reference, caption); - await _sendEnvelope(recipient, envelope); + await _sendEnvelope(recipient, envelope, message.sentAt); await CacheUtils.updateStoredMessage(recipient.id, message, (stored) { stored.mediaId = reference.mediaId; - stored.sendStatus = SendStatus.sent; }); return true; } catch (e) { @@ -198,15 +205,16 @@ class ChatSender { references.add(reference); } + _outgoingReferences[CacheUtils.messageKey(recipient.id, message.sentAt)] = + references; final envelope = MediaUtils.buildAlbumEnvelope(references, caption); - await _sendEnvelope(recipient, envelope); + await _sendEnvelope(recipient, envelope, message.sentAt); await CacheUtils.updateStoredMessage(recipient.id, message, (stored) { final items = stored.album; for (var i = 0; i < items.length && i < references.length; i++) { items[i].mediaId = references[i].mediaId; } stored.setAlbum(items); - stored.sendStatus = SendStatus.sent; }); return true; } catch (e) { @@ -215,16 +223,75 @@ class ChatSender { } } + /// Resend every message that never received a delivery ack. + /// + /// Called after a WebSocket reconnect: the server deduplicates by + /// (receiver, sentAt), so a message that did arrive is not delivered twice. + static Future resendPending() async { + if (!Singleton().wsClient.isConnected) { + return; + } + final pending = await CacheUtils.getPendingSends(); + for (final entry in pending.entries) { + final recipient = await CacheUtils.getUserById(entry.key); + if (recipient == null || recipient.publicKey.isEmpty) { + continue; + } + for (final message in entry.value) { + try { + if (message.isMedia) { + final references = _outgoingReferences[ + CacheUtils.messageKey(entry.key, message.sentAt)]; + if (references == null || references.isEmpty) { + continue; + } + final envelope = message.isAlbum + ? MediaUtils.buildAlbumEnvelope(references, message.message) + : MediaUtils.buildMediaEnvelope(references.first, message.message); + await _sendEnvelope(recipient, envelope, message.sentAt); + } else { + await _sendText(recipient, message); + } + } catch (e) { + if (kDebugMode) { + debugPrint('resend failed: $e'); + } + } + } + } + } + + /// Mark a message as sent after the server acknowledged it. + static Future confirmSent(String receiverId, DateTime sentAt) async { + await CacheUtils.markMessageSent(receiverId, sentAt); + _outgoingReferences.remove(CacheUtils.messageKey(receiverId, sentAt)); + MessageNotifier().notify(); + } + + /// Encrypt [message] for [recipient] and hand it to the WebSocket. The + /// original timestamp is kept so a resend maps onto the same server entry. + static Future _sendText( + User recipient, PrivateMessage message) async { + final data = await CryptoUtils.encryptMessageData( + utf8.encode(message.message), + bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); + Singleton().wsClient.sendMessage(WsMessage.privateMessage( + NewPrivateMessage(recipient.id, data['encryptedData']!, + data['encryptedKey']!, data['nonce']!, data['mac']!, + sentAt: message.sentAt))); + } + /// Upload one already transport-encrypted attachment and build its reference. static Future _uploadReference( - User recipient, - MediaType type, - Uint8List key, - Uint8List blob, - {int? width, - int? height, - int? durationMs, - String? fileName}) async { + User recipient, + MediaType type, + Uint8List key, + Uint8List blob, { + int? width, + int? height, + int? durationMs, + String? fileName, + }) async { final uploadResponse = await Utils.callApi( () => Singleton().mediaApi.uploadMedia( http.MultipartFile.fromBytes('file', blob, filename: 'media.bin'), @@ -251,12 +318,13 @@ class ChatSender { /// E2E-encrypt [envelope] for [recipient] and hand it to the WebSocket. static Future _sendEnvelope( - User recipient, Uint8List envelope) async { + User recipient, Uint8List envelope, DateTime sentAt) async { final data = await CryptoUtils.encryptMessageData( envelope, bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); Singleton().wsClient.sendMessage(WsMessage.privateMessage( NewPrivateMessage(recipient.id, data['encryptedData']!, - data['encryptedKey']!, data['nonce']!, data['mac']!))); + data['encryptedKey']!, data['nonce']!, data['mac']!, + sentAt: sentAt))); } /// Connect the WebSocket if needed; toasts and reports false when offline. @@ -276,11 +344,6 @@ class ChatSender { backgroundColor: Colors.red); } - static Future _markSent(String userId, PrivateMessage message) => - CacheUtils.updateStoredMessage(userId, message, (stored) { - stored.sendStatus = SendStatus.sent; - }); - /// Mark a persisted message as failed and report the failure. static Future _fail(String userId, PrivateMessage message) async { await CacheUtils.updateStoredMessage(userId, message, (stored) { @@ -298,5 +361,8 @@ class ChatSender { await CacheUtils.addUser(recipient); } await MessageNotifier().addMessages(recipient.id, messages); + for (final message in messages) { + await CacheUtils.addPendingSend(recipient.id, message.sentAt); + } } } diff --git a/lib/utils/crypto_utils.dart b/lib/utils/crypto_utils.dart index 2468914..ac39f57 100644 --- a/lib/utils/crypto_utils.dart +++ b/lib/utils/crypto_utils.dart @@ -128,18 +128,25 @@ class CryptoUtils { return decrypted; } - /// Generates JWT token valid for 5 seconds asynchronously. + /// Generates the login JWT, valid for 5 seconds, asynchronously. + /// + /// [nonce] is the one-time challenge from the server: it is signed into the + /// token and spent on use, so a captured token cannot be replayed. static Future generateRsaJwt( - String userId, RSAPrivateKey privateKey) async { - return await compute( - _generateRsaJwt, {'userId': userId, 'privateKey': privateKey}); + String userId, RSAPrivateKey privateKey, + {required String nonce}) async { + return await compute(_generateRsaJwt, + {'userId': userId, 'privateKey': privateKey, 'nonce': nonce}); } /// Generate JWT token synchronously. static String _generateRsaJwt(Map data) { - final jwt = djwt.JWT({'sub': data['userId']}); + final jwt = djwt.JWT({'sub': data['userId'], 'nonce': data['nonce']}); Duration expiresIn = Duration(seconds: 5); - Duration notBefore = Duration.zero; + // dart_jsonwebtoken writes `nbf = now + notBefore`, so a negative value + // backdates the token and a server clock a few seconds behind the phone no + // longer rejects it as "not valid yet". + Duration notBefore = const Duration(seconds: -30); return jwt.sign(djwt.RSAPrivateKey.raw(data['privateKey']), algorithm: djwt.JWTAlgorithm.RS256, expiresIn: expiresIn, diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index 17d10bc..2586de5 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:whisper_openapi_client_dart/api.dart'; import 'package:whisper_openapi_client_dart/media_download.dart'; import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; @@ -110,11 +111,19 @@ class MessageNotifier extends ChangeNotifier { // Confirm receipt so the server can delete its copy. await Utils.callApi( () => Singleton().mediaApi.confirmMediaDownload(reference.mediaId)); - } catch (_) { + } catch (e) { + // A 404 means the server no longer has the file (confirmed on another + // device, expired, or the account was cleaned up): retrying cannot work, + // so the message shows a terminal state instead of a retry button. + final expired = e is ApiException && e.code == 404; + if (expired) { + _pendingMediaRefs.remove(reference.mediaId); + } await CacheUtils.updatePrivateMessageMedia( conversationUserId, reference.mediaId, - downloadStatus: MediaDownloadStatus.failed, + downloadStatus: + expired ? MediaDownloadStatus.expired : MediaDownloadStatus.failed, ); notifyListeners(); } diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index e3268a1..105519d 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -5,7 +5,6 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:jwt_decoder/jwt_decoder.dart'; import 'package:page_transition/page_transition.dart'; import 'package:path_provider/path_provider.dart'; import 'package:vibration/vibration.dart'; @@ -13,11 +12,14 @@ import '../utils/notification_service.dart'; import '../pages/chat_page.dart'; import 'package:whisper_openapi_client_dart/api.dart'; import 'package:basic_utils/basic_utils.dart' as bu; +import 'package:whisper_websocket_client_dart/models/delivery_ack.dart'; import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import 'package:whisper_websocket_client_dart/models/private_message.dart'; +import 'package:whisper_websocket_client_dart/models/ws_message.dart'; import 'package:whisper_websocket_client_dart/models/ws_response.dart'; import 'package:whisper_websocket_client_dart/models/ws_response_type.dart'; import 'cache_utils.dart'; +import 'chat_sender.dart'; import 'crypto_utils.dart'; import 'media_utils.dart'; import 'message_notifier.dart'; @@ -34,8 +36,13 @@ class Utils { } /// Call API, handle errors and return result. + /// + /// [showError] turns the red error toast off for internal calls (token + /// renewal) that have their own recovery path. static Future callApi(Future Function() call, - {bool useSecurity = true, bool rethrowErr = false}) async { + {bool useSecurity = true, + bool rethrowErr = false, + bool showError = true}) async { // Check tokens if (useSecurity) { await authCheck(); @@ -47,7 +54,11 @@ class Utils { return result; } catch (e) { // Handle error - if (e is ApiException) { + if (e is ApiException && !showError) { + if (e.innerException is SocketException) { + Singleton().offlineMode = true; + } + } else if (e is ApiException) { if (e.innerException == null) { if (e.message != '') { Map messageMap = @@ -85,53 +96,95 @@ class Utils { } /// Checks access and refresh tokens and renews them if necessary. + /// + /// A refresh can be refused (session revoked, or a token minted before + /// sessions were recorded). The RSA challenge always works with the stored + /// private key, so it is the fallback instead of leaving the app unauthorized. static Future authCheck() async { - bool toAuth = false; - // Initial auth - if (Singleton().profile.refreshToken == '' && - Singleton().profile.accessToken == '') { - toAuth = true; - } else { - // Auth when refresh token is expired - toAuth = JwtDecoder.isExpired(Singleton().profile.refreshToken); + final profile = Singleton().profile; + final hasTokens = profile.refreshToken != '' || profile.accessToken != ''; + bool toAuth = !hasTokens || isTokenExpired(profile.refreshToken); + + if (!toAuth && isTokenExpired(profile.accessToken)) { + var refreshed = false; + try { + final refreshResponse = await Utils.callApi( + () => Singleton().authApi.refreshUserAccessToken( + refreshUserAccessTokenInput: RefreshUserAccessTokenInput( + refreshToken: profile.refreshToken)), + useSecurity: false, + rethrowErr: true, + showError: false); + if (refreshResponse != null) { + profile.accessToken = refreshResponse.accessToken; + await CacheUtils.setProfile(profile); + refreshed = true; + } + } on ApiException catch (e) { + // 401: the server will not renew this session -> log in again. + if (e.code == 401) { + toAuth = true; + } + } catch (_) { + // Network problem: stay offline, the next call retries. + } + if (!refreshed && !toAuth) { + Singleton().apiToken = profile.accessToken; + return; + } } - // Auth if necessary if (toAuth) { - // Auth - final token = await CryptoUtils.generateRsaJwt( - Singleton().profile.user.id, - bu.CryptoUtils.rsaPrivateKeyFromPem(Singleton().profile.privateKey)); - var authResponse = await Utils.callApi( - () => Singleton() - .authApi - .authUser(authUserInput: AuthUserInput(token: token)), - useSecurity: false); - if (authResponse != null) { - // Set tokens to singleton - Singleton().profile.accessToken = authResponse.accessToken; - Singleton().profile.refreshToken = authResponse.refreshToken; - // Save profile to cache - await CacheUtils.setProfile(Singleton().profile); - } - } else if (JwtDecoder.isExpired(Singleton().profile.accessToken)) { - // Refresh access token if expired - var refreshResponse = await Utils.callApi( - () => Singleton().authApi.refreshUserAccessToken( - refreshUserAccessTokenInput: RefreshUserAccessTokenInput( - refreshToken: Singleton().profile.refreshToken)), - useSecurity: false); - - if (refreshResponse != null) { - // Set access token to singleton - Singleton().profile.accessToken = refreshResponse.accessToken; - // Save profile to cache - await CacheUtils.setProfile(Singleton().profile); + // The server only accepts a login JWT that carries a fresh challenge, so + // it can never be replayed and a revoked session stays revoked. + final challenge = await Utils.callApi( + () => Singleton().authApi.authChallenge(), + useSecurity: false, + showError: false); + if (challenge != null) { + final token = await CryptoUtils.generateRsaJwt( + profile.user.id, + bu.CryptoUtils.rsaPrivateKeyFromPem(profile.privateKey), + nonce: challenge.challenge); + final authResponse = await Utils.callApi( + () => Singleton().authApi.authUser( + authUserInput: AuthUserInput(token: token)), + useSecurity: false, + showError: false); + if (authResponse != null) { + profile.accessToken = authResponse.accessToken; + profile.refreshToken = authResponse.refreshToken; + await CacheUtils.setProfile(profile); + } } } // Set API token - Singleton().apiToken = Singleton().profile.accessToken; + Singleton().apiToken = profile.accessToken; + } + + /// Whether a JWT is expired or unreadable. + /// + /// A local convenience only: the server remains the authority. Replaces the + /// jwt_decoder dependency, which was used for this single check. + static bool isTokenExpired(String token) { + final parts = token.split('.'); + if (parts.length != 3) { + return true; + } + try { + final payload = jsonDecode( + utf8.decode(base64Url.decode(base64Url.normalize(parts[1])))) + as Map; + final exp = payload['exp']; + if (exp is! int) { + return false; + } + return DateTime.fromMillisecondsSinceEpoch(exp * 1000) + .isBefore(DateTime.now()); + } catch (_) { + return true; + } } /// Get WebSocket URL from APi URL @@ -156,16 +209,23 @@ class Utils { try { // One isolate for the whole batch: a per-message decrypt used to // cost an RSA key parse and an isolate spawn each. - final decryptedBatch = await CryptoUtils.decryptMessageBatch( - messages - .map((message) => { - 'data': message.content, - 'key': message.key, - 'nonce': message.nonce, - 'mac': message.mac, - }) - .toList(), - Singleton().profile.privateKey); + List decryptedBatch; + try { + decryptedBatch = await CryptoUtils.decryptMessageBatch( + messages + .map((message) => { + 'data': message.content, + 'key': message.key, + 'nonce': message.nonce, + 'mac': message.mac, + }) + .toList(), + Singleton().profile.privateKey); + } catch (_) { + // A batch failure must not drop the messages: they become visible + // placeholders below instead of disappearing. + decryptedBatch = List.filled(messages.length, null); + } final decryptionTasks = messages.asMap().entries.map((entry) async { final index = entry.key; @@ -235,7 +295,18 @@ class Utils { debugPrint( 'Failed to decrypt message from ${message.senderId}: $e'); } - return null; // Return null for failed decryptions + // Keep a visible placeholder: dropping the message hides the loss + // from the user and from the server (which still has the entry). + return ( + pm.PrivateMessage( + message.senderId, + pm.PrivateMessage.undecryptableMarker, + message.sentAt, + DateTime.now(), + false, + ), + const [] + ); } }); @@ -284,6 +355,10 @@ class Utils { } } + // Everything is stored (placeholders included): the server may drop + // these entries from the offline queue. + _ackReceived(messages); + // Remove messages from notifications if user was not online when they were sent decryptedMessages.removeWhere((x) => !messages .where((y) => y.sentAt == x.sentAt && y.senderId == x.senderId) @@ -324,6 +399,12 @@ class Utils { SystemNavigator.pop(); break; + // Delivery acknowledgement of one of our outgoing messages + case WsResponseType.ack: + final ack = wsResponse.payload as DeliveryAck; + await ChatSender.confirmSent(ack.receiverId, ack.sentAt); + break; + // Error case WsResponseType.error: var error = wsResponse.payload as String; @@ -332,6 +413,35 @@ class Utils { } } + /// Tells the server the received messages are stored, so it can drop them + /// from the offline queue. Batched, the server accepts at most 100 per ack. + static void _ackReceived(List messages) { + if (messages.isEmpty || !Singleton().wsClient.isConnected) { + return; + } + final acked = messages + .map((message) => AckedMessage(message.senderId, message.sentAt)) + .toList(); + const batchSize = 100; + for (var i = 0; i < acked.length; i += batchSize) { + final end = + i + batchSize < acked.length ? i + batchSize : acked.length; + try { + Singleton() + .wsClient + .sendMessage(WsMessage.ack(acked.sublist(i, end))); + } catch (e) { + if (kDebugMode) { + debugPrint('ack failed: $e'); + } + } + } + } + + /// Invoked after a successful connect, e.g. to push a pending Firebase id + /// without polling. + static Future Function()? onConnected; + /// Connect to WebSocket with improved connection handling static Future wsConnect({bool firstConnect = false}) async { // Skip if already connected @@ -385,6 +495,14 @@ class Utils { if (kDebugMode) { debugPrint('WebSocket connected successfully'); } + + // Messages that never got a delivery ack are retried now; the server + // deduplicates them by (receiver, sentAt). + await ChatSender.resendPending(); + final onConnected = Utils.onConnected; + if (onConnected != null) { + await onConnected(); + } } catch (e) { // WebSocket connection failed Singleton().offlineMode = true; diff --git a/lib/utils/websocket_manager.dart b/lib/utils/websocket_manager.dart index 18b5090..63ae312 100644 --- a/lib/utils/websocket_manager.dart +++ b/lib/utils/websocket_manager.dart @@ -1,9 +1,21 @@ import 'dart:async'; +import 'dart:math'; + import '../utils/utils.dart'; +/// Keeps the WebSocket connected with exponential backoff. +/// +/// A fixed short interval cost a token request every few seconds, on battery and +/// on the server, even when the device was offline for hours. class WebSocketManager { static final WebSocketManager _instance = WebSocketManager._internal(); Timer? _timer; + bool _running = false; + int _attempt = 0; + + /// First retry delay; doubles up to [maxDelay]. + static const Duration _initialDelay = Duration(seconds: 2); + static const Duration maxDelay = Duration(seconds: 60); /// Private constructor for singleton pattern WebSocketManager._internal(); @@ -13,15 +25,39 @@ class WebSocketManager { return _instance; } - /// Start periodic connection check + /// Delay before the next connection attempt. Exposed for tests. + static Duration delayForAttempt(int attempt) { + // Clamp the exponent before shifting: 2^attempt overflows an int long + // before the delay is capped. + final exponent = attempt < 0 ? 0 : min(attempt, 16); + final seconds = _initialDelay.inSeconds * pow(2, exponent).toInt(); + return Duration(seconds: min(seconds, maxDelay.inSeconds)); + } + + /// Start the reconnect loop. void startConnectionCheck() { - _timer = Timer.periodic(Duration(seconds: 5), (timer) async { - await Utils.wsConnect(); - }); + _timer?.cancel(); + _running = true; + _attempt = 0; + _scheduleNext(); } - /// Stop the periodic connection check + /// Stop the reconnect loop. void stopConnectionCheck() { + _running = false; _timer?.cancel(); + _timer = null; + } + + void _scheduleNext() { + if (!_running) { + return; + } + _timer = Timer(delayForAttempt(_attempt), () async { + await Utils.wsConnect(); + // A successful connection restarts the schedule from the short delay. + _attempt = Utils.isOnline ? 0 : _attempt + 1; + _scheduleNext(); + }); } } diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index f15212c..5b2b532 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -254,12 +254,20 @@ class _ChatBubbleState extends State { ), padding: const EdgeInsets.symmetric( horizontal: 16, vertical: 10), - child: LinkifiedText( - widget.message.message, - style: TextStyle( - color: bubbleTextColor(), - ), - ), + child: widget.message.isUndecryptable + ? Text( + 'messageUndecryptable'.tr(), + style: TextStyle( + color: bubbleTextColor(), + fontStyle: FontStyle.italic, + ), + ) + : LinkifiedText( + widget.message.message, + style: TextStyle( + color: bubbleTextColor(), + ), + ), ), // Outgoing messages show a clock while they are being // sent and an error when the send failed. diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 4436dac..42fe702 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -150,7 +150,8 @@ class _MediaBubbleState extends State { : _fileWidget(); } else if (widget.message.downloadStatus == MediaDownloadStatus.pending) { media = _placeholder(child: const CircularProgressIndicator()); - } else if (widget.message.downloadStatus == MediaDownloadStatus.failed) { + } else if (widget.message.downloadStatus == MediaDownloadStatus.failed || + widget.message.downloadStatus == MediaDownloadStatus.expired) { media = _failed(); } else if (widget.message.localPath == null) { media = _placeholder(child: const CircularProgressIndicator()); @@ -512,7 +513,8 @@ class _AlbumTileState extends State { ), ], ); - } else if (item.status == MediaDownloadStatus.failed) { + } else if (item.status == MediaDownloadStatus.failed || + item.status == MediaDownloadStatus.expired) { content = const Center(child: Icon(Icons.error_outline)); } else if (!item.isReady) { content = const Center(child: CircularProgressIndicator(strokeWidth: 2)); diff --git a/pubspec.lock b/pubspec.lock index 5d72b3b..bed3ea7 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -972,14 +972,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.4.16" - jwt_decoder: - dependency: "direct main" - description: - name: jwt_decoder - sha256: "54774aebf83f2923b99e6416b4ea915d47af3bde56884eb622de85feabbc559f" - url: "https://pub.dev" - source: hosted - version: "2.0.1" leak_tracker: dependency: transitive description: @@ -1100,14 +1092,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.0" - mobile_scanner: - dependency: "direct main" - description: - name: mobile_scanner - sha256: "175c62fc813c2bd762757359a2088f8cbdb72020cf85d4cd27fc4d3fe59be058" - url: "https://pub.dev" - source: hosted - version: "7.5.0" nested: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index ba16e83..e888af5 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -32,11 +32,9 @@ dependencies: image_picker: ^1.2.2 json_annotation: ^4.9.0 just_audio: ^0.10.5 - jwt_decoder: ^2.0.1 local_auth: ^3.0.1 mcp_toolkit: 7.0.1 mime: ^2.0.0 - mobile_scanner: ^7.0.0 page_transition: ^2.2.1 path_provider: ^2.1.3 pointycastle: ^4.0.0 diff --git a/test/auth_refresh_fallback_test.dart b/test/auth_refresh_fallback_test.dart new file mode 100644 index 0000000..5a6a187 --- /dev/null +++ b/test/auth_refresh_fallback_test.dart @@ -0,0 +1,165 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:basic_utils/basic_utils.dart' as bu; +import 'package:pointycastle/export.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/profile.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper/utils/singleton.dart'; +import 'package:whisper/utils/utils.dart'; +import 'package:whisper_openapi_client_dart/api.dart'; + +/// flutter_test replaces HttpClient with one that answers 400 and never touches +/// the network; this test serves its own backend on loopback. +class _RealHttpOverrides extends HttpOverrides {} + +/// An unsigned JWT that only has to be readable by the local expiry check. +String tokenExpiring({required Duration inFuture}) { + String encode(Map value) => + base64Url.encode(utf8.encode(jsonEncode(value))).replaceAll('=', ''); + final payload = { + 'sub': 'user', + 'exp': DateTime.now().add(inFuture).millisecondsSinceEpoch ~/ 1000, + }; + return '${encode({'alg': 'HS256', 'typ': 'JWT'})}.${encode(payload)}.sig'; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory dir; + late HttpServer server; + late AsymmetricKeyPair keys; + late List requestedPaths; + const challenge = 'test-challenge-1'; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_auth_fallback_test'); + Hive.init(dir.path); + Hive.registerAdapter(ProfileAdapter()); + Hive.registerAdapter(UserAdapter()); + // Not used here, but the box collection is shared with the message tests. + Hive.registerAdapter(PrivateMessageAdapter()); + // 2048 bits is enough here: the fake server never verifies the signature. + keys = bu.CryptoUtils.generateRSAKeyPair(); + + // path_provider is not registered in a unit test; CacheUtils needs a dir. + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => dir.path, + ); + }); + + setUp(() async { + HttpOverrides.global = _RealHttpOverrides(); + requestedPaths = []; + Singleton().boxCollectionKey = List.filled(32, 7); + Singleton().profile = Profile( + 'http://localhost', + User('user', 'tester', 'public-key', false), + 'public-key', + bu.CryptoUtils.encodeRSAPrivateKeyToPem( + keys.privateKey as RSAPrivateKey), + tokenExpiring(inFuture: const Duration(minutes: 10)), + tokenExpiring(inFuture: const Duration(days: 6)), + true, + ); + }); + + tearDown(() async { + await server.close(force: true); + }); + + Future startServer({required int refreshStatus}) async { + server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server.listen((request) async { + requestedPaths.add(request.uri.path); + final body = await utf8.decoder.bind(request).join(); + request.response.headers.contentType = ContentType.json; + if (request.uri.path == '/api/auth/challenge') { + request.response.statusCode = 200; + request.response + .write(jsonEncode({'challenge': challenge, 'expiresIn': 30})); + } else if (request.uri.path == '/api/auth/refresh') { + request.response.statusCode = refreshStatus; + request.response.write(refreshStatus == 200 + ? jsonEncode({'accessToken': 'refreshed-access'}) + : jsonEncode({'error': 'refresh session was revoked'})); + } else if (request.uri.path == '/api/auth') { + expect(body, contains('token')); + // The signed login token must carry the one-time challenge. + final token = (jsonDecode(body) as Map)['token'] + as String; + final payload = jsonDecode(utf8.decode( + base64Url.decode(base64Url.normalize(token.split('.')[1])))) + as Map; + expect(payload['nonce'], challenge); + request.response.statusCode = 200; + request.response.write(jsonEncode({ + 'accessToken': 'fresh-access', + 'refreshToken': 'fresh-refresh', + })); + } else { + request.response.statusCode = 404; + request.response.write(jsonEncode({'error': 'not found'})); + } + await request.response.close(); + }); + Singleton().api = + ApiClient(basePath: 'http://127.0.0.1:${server.port}'); + } + + test('a refused refresh falls back to the RSA login', () async { + // The token in the store predates revocable sessions: the server answers + // 401 and the app used to stay unauthorized forever. + await startServer(refreshStatus: 401); + Singleton().profile.accessToken = tokenExpiring(inFuture: Duration.zero); + + await Utils.authCheck(); + + expect(requestedPaths, contains('/api/auth/refresh')); + expect(requestedPaths, contains('/api/auth/challenge')); + expect(requestedPaths, contains('/api/auth')); + expect(Singleton().profile.accessToken, 'fresh-access'); + expect(Singleton().profile.refreshToken, 'fresh-refresh'); + expect(Singleton().profile.accessToken, isNot('old-access')); + expect(Singleton().profile.refreshToken, isNot('legacy-refresh')); + }); + + test('a working refresh does not trigger a full login', () async { + await startServer(refreshStatus: 200); + Singleton().profile.accessToken = tokenExpiring(inFuture: Duration.zero); + + await Utils.authCheck(); + + expect(requestedPaths, ['/api/auth/refresh']); + expect(Singleton().profile.accessToken, 'refreshed-access'); + }); + + test('a live access token skips the network entirely', () async { + await startServer(refreshStatus: 200); + final accessToken = Singleton().profile.accessToken; + + await Utils.authCheck(); + + expect(requestedPaths, isEmpty); + expect(Singleton().profile.accessToken, accessToken); + }); + + test('the profile survives a restart with the new tokens', () async { + await startServer(refreshStatus: 401); + Singleton().profile.accessToken = tokenExpiring(inFuture: Duration.zero); + + await Utils.authCheck(); + + final stored = await CacheUtils.getProfile(); + expect(stored.accessToken, 'fresh-access'); + expect(stored.refreshToken, 'fresh-refresh'); + }); +} diff --git a/test/crypto_test.dart b/test/crypto_test.dart index 5fc1982..da2c404 100644 --- a/test/crypto_test.dart +++ b/test/crypto_test.dart @@ -1,3 +1,5 @@ +import 'dart:convert'; + import 'package:basic_utils/basic_utils.dart' as bu; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/foundation.dart'; @@ -15,7 +17,26 @@ void main() async { test('generate JWT token', () async { var keyPair = await CryptoUtils.getRSAKeyPair(); final token = await CryptoUtils.generateRsaJwt( - '1', keyPair.privateKey as bu.RSAPrivateKey); + '1', keyPair.privateKey as bu.RSAPrivateKey, + nonce: 'test-challenge'); debugPrint(token); }); + + test('the login token tolerates a server clock behind the phone', () async { + var keyPair = await CryptoUtils.getRSAKeyPair(); + final token = await CryptoUtils.generateRsaJwt( + '1', keyPair.privateKey as bu.RSAPrivateKey, + nonce: 'test-challenge'); + + final payload = jsonDecode( + utf8.decode(base64Url.decode(base64Url.normalize(token.split('.')[1])))) + as Map; + final notBefore = DateTime.fromMillisecondsSinceEpoch( + (payload['nbf'] as int) * 1000); + // A token whose nbf is "now" is rejected by a server whose clock is a + // little behind; it must already be valid. + expect(notBefore.isBefore(DateTime.now()), isTrue); + expect(notBefore.isAfter(DateTime.now().subtract(const Duration(minutes: 1))), + isTrue); + }); } diff --git a/test/message_store_test.dart b/test/message_store_test.dart new file mode 100644 index 0000000..d3d69e6 --- /dev/null +++ b/test/message_store_test.dart @@ -0,0 +1,144 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +PrivateMessage message(String senderId, String text, DateTime sentAt, + {int sendStatus = SendStatus.sent}) { + return PrivateMessage(senderId, text, sentAt, sentAt, true, + mediaTypeStr: MediaType.image.name, + downloadStatus: MediaDownloadStatus.ready, + sendStatus: sendStatus); +} + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_message_store_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + await Hive.openBox('pendingSends'); + await Hive.box('pendingSends').clear(); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('one key per message: adding a message does not rewrite the chat', + () async { + final base = DateTime(2026, 1, 1); + for (var i = 0; i < 5; i++) { + await CacheUtils.addPrivateMessages( + 'conv', [message('peer', 'msg $i', base.add(Duration(minutes: i)))]); + } + + final box = Hive.box('privateMessages'); + expect(box.length, 5, reason: 'every message has its own entry'); + for (final key in box.keys) { + expect(CacheUtils.conversationOfKey(key), 'conv'); + } + final stored = await CacheUtils.getPrivateMessages('conv'); + expect(stored.map((m) => m.message), + ['msg 0', 'msg 1', 'msg 2', 'msg 3', 'msg 4']); + }); + + test('a redelivered message is stored once', () async { + final sentAt = DateTime(2026, 1, 1); + final first = message('peer', 'hello', sentAt); + await CacheUtils.addPrivateMessages('conv', [first]); + // The server re-sends what was not acknowledged yet. + await CacheUtils.addPrivateMessages( + 'conv', [message('peer', 'hello', sentAt)]); + + final stored = await CacheUtils.getPrivateMessages('conv'); + expect(stored.length, 1); + }); + + test('deleting the last message of a chat leaves no empty conversation', + () async { + final sentAt = DateTime(2026, 1, 2); + final only = message('peer', 'only one', sentAt); + await CacheUtils.addPrivateMessages('conv', [only]); + + await CacheUtils.deletePrivateMessage('conv', only); + + expect(await CacheUtils.getPrivateMessages('conv'), isEmpty); + // This used to throw on `messages.last` and blank the whole chat list. + expect(await CacheUtils.getLatestPrivateMessages(), isEmpty); + }); + + test('the conversation list shows the newest message per chat', () async { + final base = DateTime(2026, 2, 1); + await CacheUtils.addPrivateMessages('a', [ + message('a', 'old', base), + message('a', 'new', base.add(const Duration(minutes: 5))), + ]); + await CacheUtils.addPrivateMessages('b', [ + message('b', 'other', base.add(const Duration(minutes: 1))), + ]); + + final chats = await CacheUtils.getLatestPrivateMessages(); + final byId = { + for (final entry in chats.entries) entry.key.id: entry.value.message + }; + expect(byId['a'], 'new'); + expect(byId['b'], 'other'); + }); + + test('a legacy conversation list is migrated into per-message keys', () async { + // Format written by older versions: one list under the user id. + await Hive.box('privateMessages').put('legacy', [ + message('legacy', 'first', DateTime(2026, 3, 1)), + message('legacy', 'second', DateTime(2026, 3, 1, 1)), + ]); + + final chats = await CacheUtils.getLatestPrivateMessages(); + expect(chats.keys.single.id, 'legacy'); + expect(chats.values.single.message, 'second'); + + final box = Hive.box('privateMessages'); + expect(box.containsKey('legacy'), isFalse); + expect(box.keys.whereType().every( + (key) => CacheUtils.conversationOfKey(key) == 'legacy'), isTrue); + }); + + test('the delivery ack flips the message to sent and clears the marker', + () async { + final sentAt = DateTime(2026, 4, 1); + final outgoing = message('peer', 'pending', sentAt, + sendStatus: SendStatus.sending); + await CacheUtils.addPrivateMessages('peer', [outgoing]); + await CacheUtils.addPendingSend('peer', sentAt); + + expect((await CacheUtils.getPendingSends())['peer'], hasLength(1)); + + await CacheUtils.markMessageSent('peer', sentAt); + + final stored = await CacheUtils.getPrivateMessages('peer'); + expect(stored.single.sendStatus, SendStatus.sent); + expect(await CacheUtils.getPendingSends(), isEmpty); + expect(Hive.box('pendingSends').isEmpty, isTrue); + }); + + test('an unacknowledged message stays pending for a resend', () async { + final sentAt = DateTime(2026, 4, 2); + await CacheUtils.addPrivateMessages('peer', [ + message('peer', 'no ack', sentAt, sendStatus: SendStatus.sending) + ]); + await CacheUtils.addPendingSend('peer', sentAt); + + final pending = await CacheUtils.getPendingSends(); + expect(pending['peer']!.single.message, 'no ack'); + }); +} diff --git a/test/reconnect_backoff_test.dart b/test/reconnect_backoff_test.dart new file mode 100644 index 0000000..52ab7f7 --- /dev/null +++ b/test/reconnect_backoff_test.dart @@ -0,0 +1,16 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/websocket_manager.dart'; + +void main() { + test('reconnects back off instead of polling every few seconds', () { + expect(WebSocketManager.delayForAttempt(0), const Duration(seconds: 2)); + expect(WebSocketManager.delayForAttempt(1), const Duration(seconds: 4)); + expect(WebSocketManager.delayForAttempt(2), const Duration(seconds: 8)); + expect(WebSocketManager.delayForAttempt(3), const Duration(seconds: 16)); + }); + + test('the delay is capped so a long offline period stays cheap', () { + expect(WebSocketManager.delayForAttempt(10), WebSocketManager.maxDelay); + expect(WebSocketManager.delayForAttempt(100), WebSocketManager.maxDelay); + }); +} diff --git a/test/token_expiry_test.dart b/test/token_expiry_test.dart new file mode 100644 index 0000000..68775cc --- /dev/null +++ b/test/token_expiry_test.dart @@ -0,0 +1,41 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/utils.dart'; + +String _token(Map payload) { + String encode(Map value) => + base64Url.encode(utf8.encode(jsonEncode(value))).replaceAll('=', ''); + return '${encode({'alg': 'HS256', 'typ': 'JWT'})}.${encode(payload)}.signature'; +} + +void main() { + // Replaces the jwt_decoder dependency, which was only used for this check. + test('an expired token is detected without a package', () { + final expired = _token({ + 'sub': 'user', + 'exp': DateTime.now() + .subtract(const Duration(minutes: 1)) + .millisecondsSinceEpoch ~/ + 1000, + }); + expect(Utils.isTokenExpired(expired), isTrue); + }); + + test('a live token is not reported as expired', () { + final live = _token({ + 'sub': 'user', + 'exp': DateTime.now() + .add(const Duration(minutes: 5)) + .millisecondsSinceEpoch ~/ + 1000, + }); + expect(Utils.isTokenExpired(live), isFalse); + }); + + test('a malformed token counts as expired', () { + expect(Utils.isTokenExpired(''), isTrue); + expect(Utils.isTokenExpired('not-a-jwt'), isTrue); + expect(Utils.isTokenExpired('a.b.c'), isTrue); + }); +} diff --git a/test/undecryptable_message_test.dart b/test/undecryptable_message_test.dart new file mode 100644 index 0000000..d72322c --- /dev/null +++ b/test/undecryptable_message_test.dart @@ -0,0 +1,28 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/models/private_message.dart'; + +void main() { + final sentAt = DateTime(2026, 5, 1); + + test('an undecryptable message is kept as a visible placeholder', () { + final message = PrivateMessage('peer', PrivateMessage.undecryptableMarker, + sentAt, DateTime(2026, 5, 1, 0, 1), false); + + expect(message.isUndecryptable, isTrue); + // The chat list shows the placeholder instead of an empty preview. + expect(message.preview, isNotEmpty); + }); + + test('a normal message is not mistaken for the placeholder', () { + final message = PrivateMessage( + 'peer', 'hello', sentAt, DateTime(2026, 5, 1, 0, 1), false); + expect(message.isUndecryptable, isFalse); + expect(message.preview, 'hello'); + }); + + test('an expired attachment is a terminal state, not a failure', () { + // Download retries are pointless once the server dropped the file. + expect(MediaDownloadStatus.expired, isNot(MediaDownloadStatus.failed)); + expect(MediaDownloadStatus.expired, isNot(MediaDownloadStatus.pending)); + }); +} From 7846e6f1503f4fb1bd2352a00892b858a12633d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 22:55:26 +0100 Subject: [PATCH 062/181] fix(security): no plaintext temp media, HTTPS only, notification previews - privacy: plaintext temp files are swept on startup, notifications can hide the message text (setting, default on) - transport: release builds refuse a non-HTTPS server url - auth: one renewal at a time (the refresh token is single use now), the rotated token is stored; login JWT carries the challenge - remove a leftover literal password from the unlock screen --- AGENTS.md | 5 ++++ assets/translations/cs.json | 5 +++- assets/translations/en.json | 5 +++- lib/main.dart | 5 ++++ lib/pages/password_page.dart | 1 - lib/pages/scan_invite_page.dart | 12 +++++++++ lib/pages/settings_page.dart | 35 +++++++++++++++++++++++++ lib/utils/cache_utils.dart | 17 ++++++++++++ lib/utils/media_utils.dart | 27 +++++++++++++++++++ lib/utils/notification_service.dart | 12 ++++++--- lib/utils/utils.dart | 39 +++++++++++++++++++++++++++- test/auth_refresh_fallback_test.dart | 20 +++++++++++++- test/server_url_and_temp_test.dart | 34 ++++++++++++++++++++++++ 13 files changed, 209 insertions(+), 8 deletions(-) create mode 100644 test/server_url_and_temp_test.dart diff --git a/AGENTS.md b/AGENTS.md index b09d666..12a04f9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,6 +48,11 @@ not in this repository). Use them for the fast loop, but the shell gates below s - **Login needs a challenge**: `CryptoUtils.generateRsaJwt` requires a `nonce` fetched from `AuthenticationApi.authChallenge()`; the server spends it on use. A login without it is refused. +- **Privacy defaults**: notifications may show the decrypted text; the setting + lives in the `settings` box (`CacheUtils.getNotificationPreview`). Plaintext + temp media is swept on startup (`MediaUtils.clearTempFiles`) and must stay + that way — the temp dir may never hold readable media after a restart. +- **Server URL**: `Utils.isAllowedServerUrl` allows HTTP only in debug builds. - **Delivery ack**: `ChatSender` keeps a message `sending` until the server acks it (`WsResponseType.ack`), and `Utils.onWsMessageReceived` acks what it stored. Do not mark a message `sent` on the socket write; that hides lost messages. diff --git a/assets/translations/cs.json b/assets/translations/cs.json index d72d3ef..8105069 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -150,5 +150,8 @@ "messageSending": "Odesílá se", "messageSendFailed": "Odeslání se nezdařilo", "messageUndecryptable": "Tuto zprávu se nepodařilo dešifrovat", - "mediaExpired": "Příloha už není na serveru dostupná" + "mediaExpired": "Příloha už není na serveru dostupná", + "notificationPreview": "Zobrazovat text zpráv v notifikacích", + "newMessageBody": "Máte novou zprávu", + "insecureServerUrl": "Server musí používat HTTPS" } diff --git a/assets/translations/en.json b/assets/translations/en.json index c2aa173..2dfa2a5 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -150,5 +150,8 @@ "messageSending": "Sending", "messageSendFailed": "Sending failed", "messageUndecryptable": "This message could not be decrypted", - "mediaExpired": "The attachment is no longer available on the server" + "mediaExpired": "The attachment is no longer available on the server", + "notificationPreview": "Show message text in notifications", + "newMessageBody": "You have a new message", + "insecureServerUrl": "The server must use HTTPS" } diff --git a/lib/main.dart b/lib/main.dart index 96fca35..852b033 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -16,6 +16,7 @@ import 'models/private_message.dart'; import 'models/profile.dart'; import 'models/user.dart'; import 'pages/whisper_page.dart'; +import 'utils/media_utils.dart'; import 'utils/notification_service.dart'; import 'utils/singleton.dart'; import 'utils/theme_notifier.dart'; @@ -68,6 +69,10 @@ void main() async { ..registerAdapter(AppThemeAdapter()) ..registerAdapter(PrivateMessageAdapter()); + // Plaintext media from an interrupted playback or send must not survive a + // restart. + await MediaUtils.clearTempFiles(); + // Default theme Singleton().appTheme = await CacheUtils.getTheme() ?? AppTheme.fromValues(ThemeMode.system, Colors.blue, true); diff --git a/lib/pages/password_page.dart b/lib/pages/password_page.dart index ec6c754..539d0d8 100644 --- a/lib/pages/password_page.dart +++ b/lib/pages/password_page.dart @@ -50,7 +50,6 @@ class _PasswordPageState extends State { if (key != null) { setState(() { _isButtonDisabled = true; - _controllerLocalPassword.text = 'yourAmazingPasswordIsHereOhYesItIs'; }); // Set the decryption key diff --git a/lib/pages/scan_invite_page.dart b/lib/pages/scan_invite_page.dart index ac5c79e..a0555f4 100644 --- a/lib/pages/scan_invite_page.dart +++ b/lib/pages/scan_invite_page.dart @@ -9,6 +9,7 @@ import 'package:qr_code_scanner_plus/qr_code_scanner_plus.dart'; import '../models/invite_data.dart'; import 'register_page.dart'; import '../utils/nav_transitions.dart'; +import '../utils/utils.dart'; class ScanInvitePage extends StatefulWidget { const ScanInvitePage({super.key}); @@ -46,6 +47,17 @@ class _ScanInvitePageState extends State { try { final inviteMap = jsonDecode(scanCode) as Map; final invite = InviteData.fromJson(inviteMap); + // Release builds only talk to HTTPS: tokens and metadata would otherwise + // travel in clear text. + if (!Utils.isAllowedServerUrl(invite.url)) { + if (_showScanToastOnce(scanCode, 'insecureServerUrl')) { + Fluttertoast.showToast( + msg: 'insecureServerUrl'.tr(), + backgroundColor: Colors.red, + ); + } + return; + } if (invite.validUntil.difference(DateTime.now()).isNegative) { if (_showScanToastOnce(scanCode, 'inviteExpired')) { Fluttertoast.showToast( diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 800f29a..739a2b7 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -25,6 +25,7 @@ class SettingsPage extends StatefulWidget { class _SettingsPageState extends State { bool _isBiometryEnabled = false; + bool _notificationPreview = true; @override void initState() { @@ -34,6 +35,7 @@ class _SettingsPageState extends State { Future _loadSettings() async { _isBiometryEnabled = await CacheUtils.isBiometryEnabled(); + _notificationPreview = await CacheUtils.getNotificationPreview(); setState(() {}); } @@ -141,6 +143,39 @@ class _SettingsPageState extends State { ), ), + // Notification previews + TextButton( + onPressed: null, + child: Row( + children: [ + Icon( + Icons.visibility, + size: 24, + color: Theme.of(context).colorScheme.secondary, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'notificationPreview'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.secondary), + ), + ), + Spacer(), + Switch( + value: _notificationPreview, + onChanged: (value) async { + setState(() { + _notificationPreview = !_notificationPreview; + }); + await CacheUtils.setNotificationPreview( + _notificationPreview); + }, + ) + ], + ), + ), + Divider(thickness: 1, indent: 10, endIndent: 10), // Biometric authentication diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 496c801..94b9c8f 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -24,6 +24,8 @@ class CacheUtils { static const _userKey = 'user'; static const _messageConceptKey = 'messageConcept'; static const _pendingSendsKey = 'pendingSends'; + static const _settingsKey = 'settings'; + static const _notificationPreviewKey = 'notificationPreview'; static const _biometry = 'biometry'; static const _playbackSpeed = 'playbackSpeed'; static const String _saltStorageKey = 'whisper_pbkdf2_salt'; @@ -119,6 +121,8 @@ class CacheUtils { messageConceptBox.deleteFromDisk(); Box pendingSendsBox = await _openPendingSendsBox(); pendingSendsBox.deleteFromDisk(); + Box settingsBox = await Hive.openBox(_settingsKey); + settingsBox.deleteFromDisk(); if (await isBiometryEnabled()) { await BiometricAuth.clearEncryptionKey(); } @@ -266,6 +270,19 @@ class CacheUtils { await box.put(_biometry, enabled); } + /// Whether notifications may show the decrypted message text. Default on, + /// matching the previous behaviour; the user can hide it. + static Future getNotificationPreview() async { + Box box = await Hive.openBox(_settingsKey); + return box.get(_notificationPreviewKey) as bool? ?? true; + } + + /// Sets whether notifications may show the message text. + static Future setNotificationPreview(bool value) async { + Box box = await Hive.openBox(_settingsKey); + await box.put(_notificationPreviewKey, value); + } + /// Opens box with playback preferences static Future _openPlaybackBox() async { return Hive.openBox(_playbackSpeed); diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index fd2a6d0..23d9bd0 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -267,6 +267,33 @@ class MediaUtils { return file; } + /// Whether a file name belongs to the app's plaintext temp files. + static bool isTempMediaName(String name) => + name.startsWith('whisper_media_') || name.startsWith('whisper_send_'); + + /// Remove plaintext media left in the temp directory. + /// + /// Playback materializes decrypted files and the keyboard writes plaintext + /// GIFs; both are deleted on dispose, but a crash leaves them behind. At + /// rest they must not exist. + static Future clearTempFiles() async { + try { + final dir = await getTemporaryDirectory(); + await for (final entity in dir.list()) { + if (entity is! File) { + continue; + } + if (isTempMediaName(baseName(entity.path))) { + await entity.delete(); + } + } + } catch (e) { + if (kDebugMode) { + debugPrint('Failed to clear temp media: $e'); + } + } + } + /// Delete a single (encrypted) media file, ignoring errors. static Future deleteLocalFile(String? path) async { if (path == null) { diff --git a/lib/utils/notification_service.dart b/lib/utils/notification_service.dart index daba4dc..bb228a7 100644 --- a/lib/utils/notification_service.dart +++ b/lib/utils/notification_service.dart @@ -106,7 +106,10 @@ class NotificationService { } // More messages if (messages.length > 1) { - final lines = getGroupedNotificationLines(groupedMessagesByUser); + final preview = await CacheUtils.getNotificationPreview(); + final lines = preview + ? getGroupedNotificationLines(groupedMessagesByUser) + : ['newMessageBody'.tr()]; final groupedPlatformChannelSpecifics = await groupedNotificationDetails( lines, groupedMessagesByUser.keys.length, messages.length); await _flutterLocalNotificationsPlugin.show( @@ -167,6 +170,9 @@ class NotificationService { Future showMessageNotification(PrivateMessage message) async { var user = await CacheUtils.getUserById(message.senderId) ?? User(message.senderId, '', '', false); + // The text is decrypted; the user decides whether the lock screen shows it. + final preview = await CacheUtils.getNotificationPreview(); + final body = preview ? message.preview : 'newMessageBody'.tr(); AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails( @@ -181,14 +187,14 @@ class NotificationService { playSound: true, sound: RawResourceAndroidNotificationSound('notification'), // Message previews are long, don't let Android truncate them - styleInformation: BigTextStyleInformation(message.preview), + styleInformation: BigTextStyleInformation(body), ); NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics); await _flutterLocalNotificationsPlugin.show( id: message.notificationId, title: user.username, - body: message.preview, + body: body, notificationDetails: platformChannelSpecifics, payload: message.senderId.toString(), ); diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 105519d..05993de 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -95,12 +95,29 @@ class Utils { return '${dir.path}/whisper'; } + /// In-flight token renewal. Concurrent callers (a resume fires several API + /// calls at once) share one renewal: the refresh token is single use, so two + /// parallel refreshes would burn the session. + static Future? _authInFlight; + /// Checks access and refresh tokens and renews them if necessary. /// /// A refresh can be refused (session revoked, or a token minted before /// sessions were recorded). The RSA challenge always works with the stored /// private key, so it is the fallback instead of leaving the app unauthorized. - static Future authCheck() async { + static Future authCheck() { + final inFlight = _authInFlight; + if (inFlight != null) { + return inFlight; + } + final renewal = _doAuthCheck(); + _authInFlight = renewal; + return renewal.whenComplete(() { + _authInFlight = null; + }); + } + + static Future _doAuthCheck() async { final profile = Singleton().profile; final hasTokens = profile.refreshToken != '' || profile.accessToken != ''; bool toAuth = !hasTokens || isTokenExpired(profile.refreshToken); @@ -117,6 +134,10 @@ class Utils { showError: false); if (refreshResponse != null) { profile.accessToken = refreshResponse.accessToken; + // The server rotates the refresh token: the old one is spent. + if (refreshResponse.refreshToken.isNotEmpty) { + profile.refreshToken = refreshResponse.refreshToken; + } await CacheUtils.setProfile(profile); refreshed = true; } @@ -187,6 +208,22 @@ class Utils { } } + /// Whether a server URL may be used. + /// + /// Release builds only talk to HTTPS: message bodies stay end-to-end + /// encrypted, but tokens, contacts and metadata would travel in clear text + /// over plain HTTP. Debug builds accept HTTP for local development. + static bool isAllowedServerUrl(String url) { + final uri = Uri.tryParse(url.trim()); + if (uri == null || !uri.hasAuthority || uri.host.isEmpty) { + return false; + } + if (uri.scheme == 'https') { + return true; + } + return !kReleaseMode && uri.scheme == 'http'; + } + /// Get WebSocket URL from APi URL static String getWsUrl(String serverUrl) { String wsUrl = serverUrl.contains('https') diff --git a/test/auth_refresh_fallback_test.dart b/test/auth_refresh_fallback_test.dart index 5a6a187..e0cddb4 100644 --- a/test/auth_refresh_fallback_test.dart +++ b/test/auth_refresh_fallback_test.dart @@ -89,7 +89,10 @@ void main() { } else if (request.uri.path == '/api/auth/refresh') { request.response.statusCode = refreshStatus; request.response.write(refreshStatus == 200 - ? jsonEncode({'accessToken': 'refreshed-access'}) + ? jsonEncode({ + 'accessToken': 'refreshed-access', + 'refreshToken': 'rotated-refresh', + }) : jsonEncode({'error': 'refresh session was revoked'})); } else if (request.uri.path == '/api/auth') { expect(body, contains('token')); @@ -138,6 +141,21 @@ void main() { await Utils.authCheck(); + expect(requestedPaths, ['/api/auth/refresh']); + expect(Singleton().profile.accessToken, 'refreshed-access'); + // The server rotates the refresh token; keeping the old one would break the + // next refresh. + expect(Singleton().profile.refreshToken, 'rotated-refresh'); + }); + + test('concurrent callers share one renewal', () async { + // The refresh token is single use: two parallel refreshes would burn the + // session, so a resume must not fan out. + await startServer(refreshStatus: 200); + Singleton().profile.accessToken = tokenExpiring(inFuture: Duration.zero); + + await Future.wait([Utils.authCheck(), Utils.authCheck(), Utils.authCheck()]); + expect(requestedPaths, ['/api/auth/refresh']); expect(Singleton().profile.accessToken, 'refreshed-access'); }); diff --git a/test/server_url_and_temp_test.dart b/test/server_url_and_temp_test.dart new file mode 100644 index 0000000..b81bcd8 --- /dev/null +++ b/test/server_url_and_temp_test.dart @@ -0,0 +1,34 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/media_utils.dart'; +import 'package:whisper/utils/utils.dart'; + +void main() { + group('server url policy', () { + test('https is always allowed', () { + expect(Utils.isAllowedServerUrl('https://chat.example.com'), isTrue); + expect(Utils.isAllowedServerUrl('https://192.168.1.2:8081'), isTrue); + }); + + test('plain http is a debug-only convenience', () { + // Unit tests run in debug mode, so this asserts the debug branch. + expect(Utils.isAllowedServerUrl('http://192.168.1.118:8080'), isTrue); + }); + + test('anything that is not a server address is refused', () { + expect(Utils.isAllowedServerUrl(''), isFalse); + expect(Utils.isAllowedServerUrl('not a url'), isFalse); + expect(Utils.isAllowedServerUrl('ftp://example.com'), isFalse); + expect(Utils.isAllowedServerUrl('file:///etc/passwd'), isFalse); + expect(Utils.isAllowedServerUrl('https://'), isFalse); + }); + }); + + group('plaintext temp media', () { + test('only the app temp files are swept', () { + expect(MediaUtils.isTempMediaName('whisper_media_abc.mp4'), isTrue); + expect(MediaUtils.isTempMediaName('whisper_send_abc.gif'), isTrue); + expect(MediaUtils.isTempMediaName('shared_prefs.xml'), isFalse); + expect(MediaUtils.isTempMediaName('whisper.sqlite'), isFalse); + }); + }); +} From 07a073409a0181459076cec8499907ecf7d72993 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 23:07:42 +0100 Subject: [PATCH 063/181] fix(auth): treat a token without a type claim as unusable Tokens issued before the server required typ are valid and unexpired but rejected on every request, so the app kept failing until they expired. They now trigger a login immediately. --- lib/utils/utils.dart | 48 +++++++++++++++++++--------- test/auth_refresh_fallback_test.dart | 5 +-- test/token_expiry_test.dart | 26 +++++++++++++++ 3 files changed, 62 insertions(+), 17 deletions(-) diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 05993de..91ba397 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -120,9 +120,9 @@ class Utils { static Future _doAuthCheck() async { final profile = Singleton().profile; final hasTokens = profile.refreshToken != '' || profile.accessToken != ''; - bool toAuth = !hasTokens || isTokenExpired(profile.refreshToken); + bool toAuth = !hasTokens || !isTokenUsable(profile.refreshToken); - if (!toAuth && isTokenExpired(profile.accessToken)) { + if (!toAuth && !isTokenUsable(profile.accessToken)) { var refreshed = false; try { final refreshResponse = await Utils.callApi( @@ -184,28 +184,46 @@ class Utils { Singleton().apiToken = profile.accessToken; } - /// Whether a JWT is expired or unreadable. - /// - /// A local convenience only: the server remains the authority. Replaces the - /// jwt_decoder dependency, which was used for this single check. - static bool isTokenExpired(String token) { + /// Claims of a JWT, or null when it cannot be read. Local use only: the + /// server remains the authority. + static Map? tokenClaims(String token) { final parts = token.split('.'); if (parts.length != 3) { - return true; + return null; } try { - final payload = jsonDecode( + return jsonDecode( utf8.decode(base64Url.decode(base64Url.normalize(parts[1])))) as Map; - final exp = payload['exp']; - if (exp is! int) { - return false; - } - return DateTime.fromMillisecondsSinceEpoch(exp * 1000) - .isBefore(DateTime.now()); } catch (_) { + return null; + } + } + + /// Whether a JWT is expired or unreadable. + static bool isTokenExpired(String token) { + final payload = tokenClaims(token); + if (payload == null) { return true; } + final exp = payload['exp']; + if (exp is! int) { + return false; + } + return DateTime.fromMillisecondsSinceEpoch(exp * 1000) + .isBefore(DateTime.now()); + } + + /// Whether a JWT is accepted by the current server: readable, unexpired and + /// carrying the token type the server requires. Tokens issued before types + /// existed are useless even while their expiry is still in the future, so + /// they must trigger a login instead of failing every request. + static bool isTokenUsable(String token) { + if (isTokenExpired(token)) { + return false; + } + final claims = tokenClaims(token); + return claims != null && claims['typ'] is String; } /// Whether a server URL may be used. diff --git a/test/auth_refresh_fallback_test.dart b/test/auth_refresh_fallback_test.dart index e0cddb4..545730d 100644 --- a/test/auth_refresh_fallback_test.dart +++ b/test/auth_refresh_fallback_test.dart @@ -19,11 +19,12 @@ import 'package:whisper_openapi_client_dart/api.dart'; class _RealHttpOverrides extends HttpOverrides {} /// An unsigned JWT that only has to be readable by the local expiry check. -String tokenExpiring({required Duration inFuture}) { +String tokenExpiring({required Duration inFuture, String typ = 'access'}) { String encode(Map value) => base64Url.encode(utf8.encode(jsonEncode(value))).replaceAll('=', ''); final payload = { 'sub': 'user', + 'typ': typ, 'exp': DateTime.now().add(inFuture).millisecondsSinceEpoch ~/ 1000, }; return '${encode({'alg': 'HS256', 'typ': 'JWT'})}.${encode(payload)}.sig'; @@ -67,7 +68,7 @@ void main() { bu.CryptoUtils.encodeRSAPrivateKeyToPem( keys.privateKey as RSAPrivateKey), tokenExpiring(inFuture: const Duration(minutes: 10)), - tokenExpiring(inFuture: const Duration(days: 6)), + tokenExpiring(inFuture: const Duration(days: 6), typ: 'refresh'), true, ); }); diff --git a/test/token_expiry_test.dart b/test/token_expiry_test.dart index 68775cc..d447053 100644 --- a/test/token_expiry_test.dart +++ b/test/token_expiry_test.dart @@ -33,6 +33,32 @@ void main() { expect(Utils.isTokenExpired(live), isFalse); }); + test('a token without the type claim is not usable', () { + // Issued before the server started requiring `typ`: valid signature and + // expiry, but every request would be rejected. + final legacy = _token({ + 'sub': 'user', + 'exp': DateTime.now() + .add(const Duration(minutes: 5)) + .millisecondsSinceEpoch ~/ + 1000, + }); + expect(Utils.isTokenExpired(legacy), isFalse); + expect(Utils.isTokenUsable(legacy), isFalse); + }); + + test('a typed token is usable', () { + final typed = _token({ + 'sub': 'user', + 'typ': 'access', + 'exp': DateTime.now() + .add(const Duration(minutes: 5)) + .millisecondsSinceEpoch ~/ + 1000, + }); + expect(Utils.isTokenUsable(typed), isTrue); + }); + test('a malformed token counts as expired', () { expect(Utils.isTokenExpired(''), isTrue); expect(Utils.isTokenExpired('not-a-jwt'), isTrue); From 47b5600cc972a6e241e82d14a1c188acd6346115 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 23:14:22 +0100 Subject: [PATCH 064/181] fix(http): give every api client a timeout The generated client has no timeout, so a stalled server left futures pending forever (a media download stuck on 'downloading'). All four ApiClient sites now go through Singleton.createApiClient, which installs an IOClient with connection and idle timeouts. --- lib/pages/password_page.dart | 7 ++++--- lib/pages/register_page.dart | 2 +- lib/utils/singleton.dart | 18 +++++++++++++++++- test/api_client_test.dart | 14 ++++++++++++++ 4 files changed, 36 insertions(+), 5 deletions(-) create mode 100644 test/api_client_test.dart diff --git a/lib/pages/password_page.dart b/lib/pages/password_page.dart index 539d0d8..935f758 100644 --- a/lib/pages/password_page.dart +++ b/lib/pages/password_page.dart @@ -1,7 +1,6 @@ import 'package:flutter/material.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; import 'package:whisper_websocket_client_dart/ws_client.dart'; import '../utils/biometric_auth.dart'; import '../utils/cache_utils.dart'; @@ -59,7 +58,8 @@ class _PasswordPageState extends State { // Load profile Singleton().profile = await CacheUtils.getProfile(); // OpenAPI client - Singleton().api = ApiClient(basePath: Singleton().profile.url); + Singleton().api = + Singleton.createApiClient(Singleton().profile.url); // Check tokens await Utils.authCheck(); // WebSocket client @@ -147,7 +147,8 @@ class _PasswordPageState extends State { // Add profile to singleton Singleton().profile = await CacheUtils.getProfile(); // OpenAPI client - Singleton().api = ApiClient(basePath: Singleton().profile.url); + Singleton().api = + Singleton.createApiClient(Singleton().profile.url); // Kontrola tokenů await Utils.authCheck(); diff --git a/lib/pages/register_page.dart b/lib/pages/register_page.dart index 0b1e431..eddfeba 100644 --- a/lib/pages/register_page.dart +++ b/lib/pages/register_page.dart @@ -108,7 +108,7 @@ class _RegisterPageState extends State { // Generate RSA keypair var keyPair = await CryptoUtils.getRSAKeyPair(); // OpenAPI client - Singleton().api = ApiClient(basePath: widget.invite.url); + Singleton().api = Singleton.createApiClient(widget.invite.url); // Registration var newUser = await Utils.callApi( () => Singleton().authApi.createUser( diff --git a/lib/utils/singleton.dart b/lib/utils/singleton.dart index e6d6efd..3ed2594 100644 --- a/lib/utils/singleton.dart +++ b/lib/utils/singleton.dart @@ -1,5 +1,8 @@ +import 'dart:io'; + import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:http/io_client.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:whisper_openapi_client_dart/api.dart'; import 'package:whisper_websocket_client_dart/ws_client.dart'; @@ -40,7 +43,20 @@ class Singleton { set apiToken(String token) { var auth = HttpBearerAuth(); auth.accessToken = Singleton().profile.accessToken; - _api = ApiClient(basePath: Singleton().profile.url, authentication: auth); + _api = createApiClient(Singleton().profile.url, authentication: auth); + } + + /// API client with connection and idle timeouts. + /// + /// The generated client has no timeout of its own, so a stalled server would + /// leave a future pending forever (a media bubble stuck on "downloading"). + static ApiClient createApiClient(String basePath, + {Authentication? authentication}) { + final httpClient = HttpClient() + ..connectionTimeout = const Duration(seconds: 15) + ..idleTimeout = const Duration(seconds: 30); + return ApiClient(basePath: basePath, authentication: authentication) + ..client = IOClient(httpClient); } set offlineMode(bool offline) { diff --git a/test/api_client_test.dart b/test/api_client_test.dart new file mode 100644 index 0000000..4ef219a --- /dev/null +++ b/test/api_client_test.dart @@ -0,0 +1,14 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/io_client.dart'; +import 'package:whisper/utils/singleton.dart'; + +void main() { + // The generated client has no timeout of its own; the app has to install a + // transport that gives up on a stalled server instead of hanging a future. + test('the api client uses an explicit http transport', () { + final api = Singleton.createApiClient('https://chat.example.com'); + + expect(api.basePath, 'https://chat.example.com'); + expect(api.client, isA()); + }); +} From 5c642df6957b0ab666569d1dc61b542d31e15b51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 15 Nov 2026 23:37:41 +0100 Subject: [PATCH 065/181] feat(i18n): translate server error codes The server now sends only camelCase error codes, so the client looks them up in the translations instead of showing a sentence from the server. - Utils.serverErrorCode parses the error body, serverErrorText translates the code (unknown code falls back to serverError, no body to httpError) - both surfaces covered: the HTTP toast in callApi and the ws error payload - en/cs: one message per server code (35) plus serverError and httpError - capitalizeFirstLetter dropped, nothing used it anymore --- assets/translations/cs.json | 39 +++++++++++++++++++++++++++- assets/translations/en.json | 39 +++++++++++++++++++++++++++- lib/utils/utils.dart | 51 ++++++++++++++++++++++++------------- 3 files changed, 109 insertions(+), 20 deletions(-) diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 8105069..e237b3a 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -153,5 +153,42 @@ "mediaExpired": "Příloha už není na serveru dostupná", "notificationPreview": "Zobrazovat text zpráv v notifikacích", "newMessageBody": "Máte novou zprávu", - "insecureServerUrl": "Server musí používat HTTPS" + "insecureServerUrl": "Server musí používat HTTPS", + "internalError": "Na serveru se něco pokazilo", + "invalidRequest": "Neplatný požadavek", + "notAuthorized": "Na tohle nemáte oprávnění", + "tooManyRequests": "Příliš mnoho požadavků, zkuste to za minutu", + "accountWillBeDeleted": "Tento účet se právě maže", + "currentUserDoesNotExist": "Váš účet už neexistuje", + "userNotFound": "Uživatel neexistuje", + "userAlreadyInDeleteList": "Uživatel už je na seznamu ke smazání", + "cannotDeleteSelf": "Sám sebe smazat nemůžete", + "usernameRequired": "Uživatelské jméno je povinné", + "usernameAlreadyTaken": "Uživatelské jméno je už obsazené", + "accessTokenRequired": "Chybí přístupový token", + "accessTokenNotFound": "WebSocket přístupový token nebyl nalezen", + "accessTokenMismatch": "WebSocket přístupový token nesouhlasí", + "invalidToken": "Neplatný nebo prošlý token", + "loginChallengeMissing": "Přihlašovací token neobsahuje výzvu", + "loginChallengeUsed": "Přihlašovací výzva je neznámá nebo už použitá", + "refreshTokenNotRevocable": "Relaci nelze obnovit, přihlaste se znovu", + "refreshSessionRevoked": "Relace byla zrušena nebo už použitá, přihlaste se znovu", + "inviteDoesNotExist": "Pozvánka neexistuje", + "invalidEmailAddress": "Neplatná e-mailová adresa", + "tooManyActiveInvites": "Příliš mnoho aktivních pozvánek", + "mediaFileTooLarge": "Příloha je příliš velká", + "mediaNotFound": "Příloha neexistuje", + "invalidMediaId": "Neplatné ID přílohy", + "tooManyPendingMediaFiles": "Příliš mnoho nevyzvednutých příloh", + "cannotSendToSelf": "Sám sobě poslat nemůžete", + "cannotSendToUser": "Tomuto uživateli poslat nemůžete", + "receiverQueueFull": "Příjemce má příliš mnoho nedoručených zpráv", + "accountInactive": "Účet už není aktivní", + "tooManyMessages": "Příliš mnoho zpráv, zpomalte", + "invalidMessage": "Zpráva není platná", + "invalidMessageType": "Podporované jsou jen binární zprávy", + "unsupportedMessageType": "Nepodporovaný typ zprávy", + "implausibleTimestamp": "Čas zprávy je mimo rozsah", + "serverError": "Neočekávaná chyba serveru", + "httpError": "HTTP chyba %s" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 2dfa2a5..656e279 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -153,5 +153,42 @@ "mediaExpired": "The attachment is no longer available on the server", "notificationPreview": "Show message text in notifications", "newMessageBody": "You have a new message", - "insecureServerUrl": "The server must use HTTPS" + "insecureServerUrl": "The server must use HTTPS", + "internalError": "Something went wrong on the server", + "invalidRequest": "Invalid request", + "notAuthorized": "You are not allowed to do this", + "tooManyRequests": "Too many requests, try again in a minute", + "accountWillBeDeleted": "This account is being deleted", + "currentUserDoesNotExist": "Your account no longer exists", + "userNotFound": "User does not exist", + "userAlreadyInDeleteList": "The user is already scheduled for deletion", + "cannotDeleteSelf": "You cannot delete yourself", + "usernameRequired": "Username is required", + "usernameAlreadyTaken": "Username is already taken", + "accessTokenRequired": "Access token is required", + "accessTokenNotFound": "WebSocket access token not found", + "accessTokenMismatch": "WebSocket access token does not match", + "invalidToken": "Invalid or expired token", + "loginChallengeMissing": "The login token has no challenge", + "loginChallengeUsed": "The login challenge is unknown or already used", + "refreshTokenNotRevocable": "The session cannot be renewed, sign in again", + "refreshSessionRevoked": "The session was revoked or already used, sign in again", + "inviteDoesNotExist": "Invitation does not exist", + "invalidEmailAddress": "Invalid email address", + "tooManyActiveInvites": "Too many active invitations", + "mediaFileTooLarge": "The attachment is too large", + "mediaNotFound": "The attachment does not exist", + "invalidMediaId": "Invalid attachment id", + "tooManyPendingMediaFiles": "Too many pending attachments", + "cannotSendToSelf": "You cannot send to yourself", + "cannotSendToUser": "You cannot send to this user", + "receiverQueueFull": "The recipient has too many undelivered messages", + "accountInactive": "The account is no longer active", + "tooManyMessages": "Too many messages, slow down", + "invalidMessage": "The message is not valid", + "invalidMessageType": "Only binary messages are supported", + "unsupportedMessageType": "Unsupported message type", + "implausibleTimestamp": "The message timestamp is out of range", + "serverError": "Unexpected server error", + "httpError": "HTTP error %s" } diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 91ba397..e216998 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -27,12 +27,32 @@ import 'singleton.dart'; import '../models/private_message.dart' as pm; class Utils { - /// Capitalize first letter of string. - static String capitalizeFirstLetter(String input) { - if (input.isEmpty) { - return input; + /// Localized text for a server error code (the server only sends camelCase + /// names). An unknown code falls back to a generic message, so the user never + /// sees a raw identifier. + static String serverErrorText(String code) { + if (code.isEmpty) { + return 'serverError'.tr(); } - return input[0].toUpperCase() + input.substring(1); + final text = code.tr(); + return text == code ? 'serverError'.tr() : text; + } + + /// Error code from a JSON error body ({"error": "someCode"}). Empty when the + /// body carries no code. + static String serverErrorCode(String? body) { + if (body == null || body.isEmpty) { + return ''; + } + try { + final decoded = jsonDecode(body); + if (decoded is Map && decoded['error'] is String) { + return decoded['error'] as String; + } + } catch (_) { + // Not JSON: nothing to translate. + } + return ''; } /// Call API, handle errors and return result. @@ -60,18 +80,12 @@ class Utils { } } else if (e is ApiException) { if (e.innerException == null) { - if (e.message != '') { - Map messageMap = - jsonDecode(e.message!) as Map; - await Fluttertoast.showToast( - msg: Utils.capitalizeFirstLetter(messageMap['error']), - backgroundColor: Colors.red); - } else { - await Fluttertoast.showToast( - msg: Utils.capitalizeFirstLetter( - 'HTTP error ${e.code.toString()}'), - backgroundColor: Colors.red); - } + final code = Utils.serverErrorCode(e.message); + await Fluttertoast.showToast( + msg: code.isEmpty + ? 'httpError'.tr(args: [e.code.toString()]) + : Utils.serverErrorText(code), + backgroundColor: Colors.red); } else { if (e.innerException is SocketException) { Singleton().offlineMode = true; @@ -463,7 +477,8 @@ class Utils { // Error case WsResponseType.error: var error = wsResponse.payload as String; - await Fluttertoast.showToast(msg: error, backgroundColor: Colors.red); + await Fluttertoast.showToast( + msg: Utils.serverErrorText(error), backgroundColor: Colors.red); break; } } From 33719c6d1c50dd6e48f05ec53fbcaccc42b35644 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 16 Nov 2026 00:30:51 +0100 Subject: [PATCH 066/181] feat(chat): paint the conversation with its own color The bubble used the light scheme's secondary, which desaturates a picked color into a muddy tone (a red chat had brown bubbles), and the rest of the conversation ignored the chat color completely. - chat bubble: the picked chat color itself, same in light and dark - chat background: the accent blended into the surface (12% light, 16% dark); the M3 surface alone is near neutral - app bar: the same tint stronger (22/30%) and still translucent, so the existing blur keeps working; it used to read the global theme because its context sits above the chat Theme - caption sheet: takes the chat theme and a tinted background, a modal route renders above the chat Theme and used the app theme --- lib/pages/chat_page.dart | 33 +++++++++++++++++++---- lib/widgets/attachment_confirm_sheet.dart | 23 +++++++++++----- lib/widgets/chat_bubble.dart | 20 +++++++------- 3 files changed, 54 insertions(+), 22 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 83c7663..7656054 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -13,6 +13,7 @@ import '../utils/cache_utils.dart'; import '../utils/chat_sender.dart'; import '../utils/media_utils.dart'; import '../utils/message_notifier.dart'; +import '../utils/singleton.dart'; import '../utils/theme_utils.dart'; import '../widgets/attachment_confirm_sheet.dart'; import '../widgets/chat_bubble.dart'; @@ -331,6 +332,8 @@ class _ChatPageState extends State { context, count: count, initialCaption: _controllerMessage.text.trim(), + theme: ThemeUtils.chatTheme(context, _chatThemeColor), + backgroundColor: chatBackground(tintAlpha: 0.18), ); } @@ -715,7 +718,9 @@ class _ChatPageState extends State { final older = position > 0 ? visible[position - 1] : null; final newer = position < visible.length - 1 ? visible[position + 1] : null; - return ChatBubble(older, message, newer, widget.user); + return ChatBubble(older, message, newer, widget.user, + // The picked chat color itself, not a tonal derivative of it. + accentColor: _chatThemeColor ?? Singleton().appTheme.color); }, ); } @@ -731,6 +736,26 @@ class _ChatPageState extends State { super.dispose(); } + /// Background tinted by the chat color: the M3 surface alone is almost + /// neutral, so a chat with its own color was indistinguishable from any other. + /// + /// [tintAlpha] overrides how much of the color goes in (the AppBar uses more + /// so the header reads as part of the conversation). + Color chatBackground({double? tintAlpha}) { + final scheme = Theme.of(context).colorScheme; + final accent = _chatThemeColor ?? Singleton().appTheme.color; + final double alpha = tintAlpha ?? + (Theme.of(context).brightness == Brightness.dark ? 0.16 : 0.12); + return Color.alphaBlend(accent.withValues(alpha: alpha), scheme.surface); + } + + /// AppBar color: a stronger tint, kept translucent so the blur still shows. + Color appBarBackground() { + final bool dark = Theme.of(context).brightness == Brightness.dark; + return chatBackground(tintAlpha: dark ? 0.30 : 0.22) + .withValues(alpha: 0.85); + } + @override Widget build(BuildContext context) { return PopScope( @@ -748,6 +773,7 @@ class _ChatPageState extends State { data: ThemeUtils.chatTheme(context, _chatThemeColor), child: Scaffold( extendBodyBehindAppBar: true, + backgroundColor: chatBackground(), appBar: PreferredSize( preferredSize: Size( double.infinity, @@ -758,10 +784,7 @@ class _ChatPageState extends State { filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), child: AppBar( automaticallyImplyLeading: false, - backgroundColor: Theme.of(context) - .colorScheme - .surface - .withValues(alpha: 0.5), + backgroundColor: appBarBackground(), leading: Row( children: [ IconButton( diff --git a/lib/widgets/attachment_confirm_sheet.dart b/lib/widgets/attachment_confirm_sheet.dart index 7e2fe9c..bc23318 100644 --- a/lib/widgets/attachment_confirm_sheet.dart +++ b/lib/widgets/attachment_confirm_sheet.dart @@ -16,16 +16,26 @@ class AttachmentConfirmSheet extends StatefulWidget { }); /// Shows the sheet and returns the caption, or null when cancelled. + /// + /// [theme] and [backgroundColor] come from the caller: a modal route renders + /// above the chat's own Theme, so without them the sheet uses the app theme. static Future show(BuildContext context, - {required int count, String initialCaption = ''}) { + {required int count, + String initialCaption = '', + ThemeData? theme, + Color? backgroundColor}) { return showModalBottomSheet( context: context, showDragHandle: true, isScrollControlled: true, - builder: (ctx) => AttachmentConfirmSheet( - count: count, - initialCaption: initialCaption, - ), + backgroundColor: backgroundColor, + builder: (ctx) { + final sheet = AttachmentConfirmSheet( + count: count, + initialCaption: initialCaption, + ); + return theme == null ? sheet : Theme(data: theme, child: sheet); + }, ); } @@ -79,7 +89,8 @@ class _AttachmentConfirmSheetState extends State { ), const SizedBox(width: 8), FilledButton( - onPressed: () => Navigator.pop(context, _controller.text.trim()), + onPressed: () => + Navigator.pop(context, _controller.text.trim()), child: Text('send'.tr()), ), ], diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 5b2b532..271119a 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -13,10 +13,12 @@ class ChatBubble extends StatefulWidget { final PrivateMessage message; final PrivateMessage? nextMessage; final User user; + // Fixed for both light and dark mode (see ThemeUtils.bubbleAccent). + final Color accentColor; const ChatBubble( this.previousMessage, this.message, this.nextMessage, this.user, - {super.key}); + {required this.accentColor, super.key}); @override State createState() => _ChatBubbleState(); @@ -96,18 +98,14 @@ class _ChatBubbleState extends State { } Color bubbleBackground() { - var brightness = Theme.of(context).brightness; if (widget.message.isMe) { - if (brightness == Brightness.dark) { - return Theme.of(context).colorScheme.secondary; - } - return Theme.of(context).colorScheme.primary; - } else { - if (brightness == Brightness.dark) { - return Theme.of(context).colorScheme.onSecondary; - } - return Theme.of(context).colorScheme.surfaceDim; + return widget.accentColor; } + // The other side stays neutral, only the tone follows the brightness. + if (Theme.of(context).brightness == Brightness.dark) { + return Theme.of(context).colorScheme.surfaceContainerHigh; + } + return Theme.of(context).colorScheme.surfaceDim; } Color bubbleTextColor() { From 1a46539cc1eada2edd1d6d97c5a44d91f20425cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 16 Nov 2026 01:42:18 +0100 Subject: [PATCH 067/181] feat(chat): doodle background and chat-colored input bar - assets/images/chat_bg.svg: the pattern source, rasterized to a 960 px PNG (scale 3, so a tile is 320 logical px and stays crisp on 2x/3x screens); only the PNG is bundled, the SVG stays out of the app - chat background: the pattern repeats over the color tint, recolored with BlendMode.srcIn to onSurface at 7%, so it reads on light and dark and over any chat color - chatTheme getter: the input and recording bars call Theme.of(context) from the page context, which sits above the chat Theme, so the mic icon and the bar backgrounds used the app theme instead of the conversation color --- assets/images/chat_bg.png | Bin 0 -> 93243 bytes assets/images/chat_bg.svg | 138 ++++++++++++++++++++++++++++++++++++++ lib/pages/chat_page.dart | 87 ++++++++++++++---------- pubspec.yaml | 3 +- 4 files changed, 193 insertions(+), 35 deletions(-) create mode 100644 assets/images/chat_bg.png create mode 100644 assets/images/chat_bg.svg diff --git a/assets/images/chat_bg.png b/assets/images/chat_bg.png new file mode 100644 index 0000000000000000000000000000000000000000..f46455130f2d2fe2e3468c98d2663d5bcdc9a810 GIT binary patch literal 93243 zcmc$Fi9gie7x$Qnu~UfbvW09RB9wiSeJ6XC$(n62VYE<`Wn|x?iI5P+I!sAQ)*;(i zrV<8&!q|B}zQ5=B8=jXJw3b`8dgzIlcI zp%@K~BIw~+=1Z^M3YUUor6sI6xgZu6dbFI7NxihU!ba>gXVVHoP3t?fO<7p8`6}D0 z_N~L$ccRvm)SD`!X?7yU--ixpvFp%_JpTXjgIBi&ayqel?PSr}9PS*Smo+fYLb_?T z>*fzkj^=iZLuPVy=|z~!E}?*z$3sd)unWUwrptDREthMVYtJae*vQjPGam9a3pPhA zpJatO>DQbEhP$Cp!+-irDU(Ia?^yjo{`Bvlec39U*IDl{+yUL8FOVdsx2FT|P=;~h zPai!ejdB6?0;LLa0?U9$yjWD~7Ey6&Nk5fPokr1eK^S0-*Z%LA7L!HX6U>pGe^u;e z^)!+6yGp^l8&0rPuK^An`jWv?5Gyd?r)2*@W`AgVs`a65V?-0Y2z-3z@S!!ccK$Up zU|m{I!D^?^J>ha;;=)Acp3P=F|iTU3!2`?$Rs2z|H#CCwcoS_WV z2~7bFq;2UeTnFZmK2IAAjHPhbe~`6ZXjiP(XhF?n+m)n&vG`ej#fL%Uv3dIc>?Y!l z6mbi3V{=RCyFc|yj^u=AD`f|kNlpH589c$*MGz~93ibwOsSX5dT_pES-vq1^CeKJZ z_0EmSBGyRNV1-(@1+_=Nl-j^9QX zy%mk)3A6wu0<%IsQ%f;&UxL0CdeI*WL^feoLZJ*La@a-47|mGGg5S^BcI9B14Kq>@ zz8f!&7Nm6fCDQy~lL-5-8%f75ek=5PdYyKa?SUOSG?Agi4l4=agVe}$xaf!8OOV2= z;EUsx;y1-L3so(B^UDquPNyv~#%6<3=&-=FPmgFKi!p5>z_eD~m)0ZjDR>DyvjZe^ zM=Y2%m@ycQfhsLB$g=^nae`LL7+ROVE zF^Cq_6JRSix02Xp|33#izHN>=64}5`JA5+E*}CCzl5mibM9$FV|CvSB6M2m^j+bt!f2??fRuLP(SdYKQOlg-xRL>kJJUc2)?qVUU^y^Qx-lB0B7H?b(%(p{!tJ0F0r#Q21jXH z1olq;WD(ykhs7aw@*Q3Zi})%a#w#h&e6|2#%3*MtjF?2=%9#zVs@Vm&}j zHL|J!2|}}yaf-T21(YZ8N~j+pJ`9>f{#^2mtbyEu$=|tA6kmE>W|GEHKX8vnKoRA ze)IGkI((C{T)~1ChpeS!R98T!BqD9d1?y8EqYO{@iq8Gboa7L{4qBXu^;%O9os8vx zqui(dDAa>%1~T5_PC;V*g?bs^X0SIFhHu*Emwasd0mr-nb(@`b&~%Qy0|*r z`QU3C@zV};qXu{`Y|}S^Gk9tNHua1t-Ff~$Y1j7oE4Kd|3@+)mrr6O0n_hjQphZkh z=bgCxQp5P|%octyASg$}$QMfdfRl&gmP1-LnVY}i*Zn)=K8gA%_rF~a{LMf1l{{r~ zy2naxafDZBPEh+|VCQtcPq=_~MHLJ0=k$RKyfxIR3HP~*3$?{5v|64EYF!?5gxfE4 z19lpN(3Cd;#kY933w?za5BAyNuk?U0{Z?=INysJxs}tSs1EF7!horHKv;$zi^n6o1juwUD_de&C#o2bbm9c0GCSI-KqB{Zx5^L~83c%h?NC3{{!l@33tr<=cFnF?8fwMrn;(h@0VX?f1wG0~yUZ2lK3 zwzhtIB)2tXjD^U%TBLZ2Q(;=K_3&l^osNV~zptD+o?HUOW*3v@ zHbOGuIs9v6$+^J3j+>l??s~8ByX$<1#C^b}V-gKC@YFDT9^Mw8j|#u{^*)?soImov zM;!{-ENVenC0*Q2mxeqUvhI%H)dstyYZ&{!vq25g6n_&C+e)RdadZdezXKlqGz zBIwn$FxZ-KNh}sYn-{C#eg_*5ot(sS1HTvMfCY5kezN4c<7r0{ z^yqcvF~|CxN%4#vJDLR_GBndQ3q+MJ&xvN0p@>n>x$GpG=EPNtfM7WRGqPW*I+3Q=(92*7v)7kaPs~ zKW|`9)*9mEZbH|eV2f!2#ZA`RxpvtqYFlm*0&w0ekILthn-a7&uE7Yu z@qySArU!3Q+#tUi@hLaRiA*JbV{dSFmLMe;Sckk7!TdT)&nT35*YU8uV#s>-mcOJV z7j2I;exZBZ0E1Imp$Z4n2Gax!ZrH)hwtj}|KAN1RRlABv;nigEmmvRgk+Zz1x_1+y zQQMA@1kwUr-4Tst&mwzk;|EOKAJ$>pQ$$8v`p;~1@w)!H=mv!$%+fq9j_o!&QoL8| z_W3suq#gV>^!vU7$*o+rY@M^$Nm(>*#*rQbt{o`>g8wlb`>R|$9FJRsCfRS_+$l=<24gNAIKx(xrM25Jq zK_89;h&A5|WVQxlnIrxlFmDt}%ZZVtNSiiy{7^BKkrUjGU#WeViYkl41eZf)1PXha zlnqto?r-oWgBB;XhN#c6s!cH$;kQU4_M1u5eE8L|xx2Bv3Rq?85Y}mcZTqCO$UE_(O z%mzIlU}LER5D&Mke?u!)Ee~gcRe?9rT1^9I_FGiOw=sd6p|>1gHpKn=h~JFqOC$bl zfiOQjO?+@k-qAlC9yMSWqlxP>)Jv?CtqTdi5wBDD2L1e+7kp>s$f}|zmIOE^k=tZ8 z6k$hX`ontm7E#Dv4)K)rkk$SsA@+4RZ`M`=W<)#y;t!iTR~y(w!)K(9%;QIJv+T|q z*T=b5{o{sZFR&`o|7YH1@-z+I5E`$D?+jS?ZZmmJr#lGba}h0}Ti=*f?u6a~0wy^G z=JR~p1Xd1~+!8Tt@}{E#PP*MkCEz<+Lc>TzJe7meu8@h*hSbm_Pd{XOyj}*>AkDPEkbaa`m(9l zIgWgJ6ekSye87eui36?9Ya*NUryBOUA^ckC!}U1G5?uaY!U1$6aax3~yY>MP29`N! zgOA3}$koQYr0j(xGI-YGI5()%*YyW3-G3h7q74=#g6t+@jn{;K>T7_z)bx*>xKeat-U<}q%PMJH>1Q3|+ue|RdYV*67nM05@UiB-My1~B4TlJVh}<+?Q}0$o(H*1T zY5jxD?tL1OKQP*->Om)ql1K0F`NDQmLZ`uaJCrkd{pd$1{+Cx9HDP};7P^rM z8k1SsnnNjnTmEP@ z0Q}6l-9SY+cKfHbE+_99DalKOh-|FqUD+Br(f{j|dI|@dW(foepMd{^bYVIpwnKyAajh_&B-Pwr35KL2Mjmgn(| zv8M5og6ETQKKLhzH2tRe*0GB_-{0WbLK1nb|4UQMz0LZ~J89$VlgWq@v!t`Bh=qY+ zb`6^G$>ZKgrE~s+caesqbA-Gp^`M-d4`I&SSzGcX*{zxjgSW86(O`HQB~#-D_xVO= zo3nR%#(YPnMyVIYQx0f{#sVG{foCP*LwQju2B$fsv>wegzY>jhQ;gf1u#{#T2x z^4B|f8hikDu<1yO*fts4M3J95<_hMnurTowz_gkBbzOnQL0D@xRScdcD&$Vaiq{6L z@jFKc>5osAm99MZioUg4eP{J|j90(I@`oBsj)UE6--lc}OSzQr_|88AXI&P|Nx!?p zYRx%_hUhW(L~3pYap67|0WuYyxf^Fo$bHSPBpJ-4;A1BBy@l3ZI(BZeE=FN!+i|yV z4QiXVb)$*<67QE8#y%H^%Hcw3vWfV=2l2-dSv8+3@cF-YnqB?_zBf{WbauZpLH_ot zuNxc8Dg=5#4_hu-z0LoHl1lgSA%{v6Z!(1o#&%pbyBcRnP&K@^W`a)|Is9?Cy+L>NgWB|c&3fs(NZ$gM^dBog$iki&Y7{yu_AVsy-J`<68u{jz$4v`xu6b%cofH@=T zns8bhhHh6BXeZvi*VG6Yr0-+93~Ddkoij$~Mak+e-;2q?437QXcYlCw0=rygdi8|$ z<>;{B7k#0}H6wGw>nvi<%Cj`xv3+c5SzgLBq4@K4i$QU>dj*6aD=5faWF(dCgA}@{ zf{N9ZA>lO$rtRel?j%fdK&OCOb@SK>P2)8F{A*`~!T>h3`{hbnk6a7HdLCaIKhq3F0@CqP<1=VV z9f2CkC|Z9cRyc4{<`C$QT=<((lYub|!BG|JHFHO|k>;y(hu^70|G_I$G}y&j9Cxtn zk$kKO7v8JD)i3EDzbN^jMVC3_zZ&{aDt@FrEWpV(YjC2&j8FpD^r1&5Q6+SdUXxr& zGj{2i`5mP1MqcRyKmBnQN-ZrsU`N;?Z*-m#MH~l>)9la;LaNdkhbI4Z%N)%Tx4^sC zNnOC``Tsd4Z7YYO4d#gOW_F1AP8C3#_6pnuwWs93enh0&g%wsjLBUvPx`Hpv58_~$ zhls}Mn+En%RAzKhKB-v-wz8SO>jJnoAh%+n#L)tz`jj$h)PMOr?Rk;#b9Y{jiiF&g z{F)mDm;CAzFKHyy%JzJ>m8rR6x7CKQ8M6mv=vqBPcVOVgejCc~cR&XVm=Ud$8XFW4 z-ujFg9GsOy=UJJ=%(VqJz`tU5XtIRN-D831EjU>)(W05uUgypmwVDw-M^Q{EO$ z*zgfm12Y(e@-(;>7fY(b1f)cJ5v`JcI>qy$;%Kr#c9}dZOh25ml_{EAb0N3QLEP`l zqG&gWVw!mxpKFuA&1^|*Uw_2+qgafDFig~IU&IK}DQ|MiEFMubQ1$Vls8F$^room^ zs9H_c4ZbPoLoL0$Yjv04bNx55oWbps05M#e#%&^yc`cYQFc-E|&EGEuMbNR<9q|!v zXY(0#>LMXE@+oZ`YWH4lBFgf9aT5+!4!g&bM%u69e`Dj=_}L2hJI7<{qt-yW{&nac zXBK}~pES94-rayT_O8ljn?IosDc`Vj9tW355rn5Js_~SixW5`j`bI(nJs?$L$1t@7 zt15RjoXuSaD@oJou_YC2;$!*qIND7MCIi`|S(h-;=D+I%E*=ypeKRH^c(KWO61;1O zsrXh8S_hkotDI5KIN^GgO0&-6ski8?xp3L<%7!h#nRNzqwwTputh(fD;Mtwt&fixZ z&nwm7TVz$}D+Rp=7-0X-VX8dLFCv!dL0UsrlWZ297F_|;wAaBUVm`Ou9UY$Ub}*Ls zsRdWO1Ue#ZtEXZ_L|jvnyokX;pfQ|(KtQ4|Q2L}d@Z;IMDr=fMtNkr>8%l({8TbV? zh`li(N_0>*OXJTHXNU5J1~IX_YjvOVB+yezPs?k)CVwJRQ?TGJr@jfTe~tUW0fuZ= z4$`>7~46#Ly&l|lCtH3B2`FksW!?Zt4QV>voZG1&3sqL-p(Z~blZ#{K}~? z`>F)Xkxhhw7Y7r`#(xk9G^aQ+#!61kexvST$o)uknF(v9c)UF5q%kIeA`7sdEN(~# zQcr{5%sK~NL!2UB(I@ySdraUhO_qepKZZZmIT|;XCgapKZxUXkk1vzC(Xo>7>0h>l zYWx)b$xOmKphBF>{ksiy=qvhG zzhbTof~7llI}pOo*}OYp)-Ce|hn-XKS-UI{37W7b{1qrr@^g0QT{!ydR#i}1=gx_z zjNhlZewHZnoc~99m}&*XLb^?-3$(+c-6!!LP8vu%?e1;iCVZNn5m~A;HSnhoj49oi zDYo8?%^Vevn5Z^&A}5MO5U+;pT;DjG$*+U1W?4t;HAObp2gIcFE<&+T_dSD| z^WGb6kJ%m(Xlp5CgM;VwnmEcI|8@9*4#|D(Hm621z__`_cdZPcA)8!oKYBm< z>+|ijX?2H(8v|_?V`O&3YjM#DU0G|e-LQMaNI{@bfRu)aHQ3fPZbYT?uRFM}v|9-txI;*c z#5VnmcM;Np=K``d3}J>w`!^>aCI8w{`}K3Y!Nm_*H7&v`%}9zsaxP&+W=pM=WbW#d zg0Kj|Jr-CKgfD~o`@LT$p)KC&UMp3>@gk6sSa?>IoyRMJ3qG22;{o|(K-3`S!0QTJ z=(Ck)K(LH}9`6PJ)=mgA6JU(X@QTcP2S0hHuFT-(O8=U)9hq24j)+uESKhr!D#xbs zw*1M#EQ-YxG(1=;VRQ|x{H@`C$n}N$iE%6&BG})`2hokrV@{wZ3{tTeslmE|>XTW} z9WP`(AcI`PHi2A#XJSYN1!Y)QPClX7pfcct4QsK;YRYzKqVFqH>@0o%2-*5~qu&P;5}!mXY(<o0u$xEQ8h*B9TdzU4_? z7ksco69l!*410?CE~a_;8+t8kiyKxf7SI&J-cPpQTbSV9_3}8=j9a5Up89#s#x!0K z&Poy^8a^k8PoX=Y?`|#XA2hILhuxJI>3UlV8mP%QO9EVL(yuaFzdj=ewl4d`H%;|J3K-?>b#|AMYIXdfO&|?pcsgJ5g!$%D)g~dBr*7t-=h%zAP zc!7^28wdzd)fpLLg{-TVW|$O;2l5L5Y%y>4#_?~!ZXI;tGN$pF)EcFJ7yMwPUZm{j z#Z4IC^5ps_4=PU=Y>koPb^YNH{VV1b!!1pAY3~@7@csx+`~~I*i=IS3bQ!D4HdOm? z@D`>_*y)xuPGA4+k3`?V#m^PT!enkQ)&@<6-3v#BAzRN(ljkbLj(Vy0@!zo~38tg39lmRO-`)-t003)!eX5R1j7Vn)i2$}o#YPFMjSq>Gy_A>#TbTK(7U z!4nd?+aH}&=)6CHd8Ib!ZU|ly(qhyxhvIu!EP~O~sJVF%yS)_c3UF<#XN{-Ps*{y%F2+`@S5J=jMG+qa+Y1_z-kp&XO?kJ7j!Y#7s3M zb88j|qy2cT@LHT=Fe{+r4NqfOhgarVugqgHlil+8vjUu*$q?7K*9MKsw=ECBMy*fo zHR+Pa7V1n-^aua2vbX*l0fKkt;d*=xM6T%wF!SAkb2=G0TWKB7pDZ&IUIV!{j{(F1 z#QkIh{+VO{YCcpA*^nSy5;U8ofj=V%W?d!i>XJ{8pY*w$7pIfnk0iq|@F5X^mu+QJ zd)*Z}Yi^h(cN^NCZB6g$aqtKm%DvFF7UjVk7Pw<1O}rHHP5sf<(%)&Cgkd}vUccwd zrC4a!UDC_Q<(W9FPsv{QfCyUfQs^s6KdNc8z(@H6V1_tM|1M`xLZQA-o895X97)^t zg}%R#Bz3$6UK3kWf22X2!{Wl$+`9A#oP@l8X=akeHO6CHrQp;BR)yzul^{9wv10~% zVMLaB?qvK(fP5}MeM}~7t#?!if;yZQZV*R?=fXQjqOqkb%3evM3)sc40;M#!!ui== zg!oHBxt%1hMqNlj{ecl%C@i1%508_f?opYJ$JX|hSWaAW@oQ!}VB=~^RuDJO0h)2I z?3n_Guy*F7;VtrDqLH){X9v_CH=yv_z5hnLu|M0&6>eNPkuI< zIr&hx;cu;TFKWsfZ2$(Nxpc+4WRCbr88~ezgyE&2l7NvTfcSHx*G$*IrybbkK1vE) zv(bG1zRLvQa9_t?LdDmd9f?c$NQY@OD{=7yn-ncX>p@?4wtT<``5H6A6o$hje} z)CTBBRRTi%y|V+)>-rZz0gpg40&tKmSmp)fygV%*k|LDCfL0mNLMY7 z3Rq`e&DSto%HNqdHeX|h1ddG8eEEC%k71k-9koVv;Ia3a4#IDhh%yH@G1~@Q@EUt= zx33fO(7>|%1UGAX9Mh!n7Ywi27;**LArw9fLIdTaR;&I4YVXxe<{$UMY5bAmq^Hx@ zbmjycS2y{Whv&h&kuXHo^$0sc#@zI*Pg~UmX>7J=e=s}`P{z|7IQb~|?YS4*tNw9r zw>ntbu`X#*}+QgYHIesrP+_PWyw$aQac0|`r)3VL8={_(Gm(Ztw}{0}Bm zwa?Cy9vlOC;L4AzQUp-X5~jdByLA1rl^n~B?7?Axd3;&&+7hXmXgS%aRd37}xQU`h z@Ow%sH{1G`yG~eb(4E_%ZBsRX{^hL-_A(TjA_-a={&3=X7x%uaP0gpN*J`w;^5~1M z&+%#bbpS;5t1X}oAboKE(F>lS@}V>V+F>%lr;SY9ZZOFZl0K?^u)aK4MK(!i-ox^8jh@%3HWioUe$#WI2w>ENj)e}qnX*o%q>Qk49xMIJ-VUB ze=^a;WLquxj-=#75$(jABDKaOuv)4q_9w#+X&VsHh1b4z;WDmS>~s~ad^sMSbABlO z5FauDhnJ6^gN$di(hsm+W_riAYN|9Qi|vNstHfq9HNFbh9tpVBOkXqjt6W=)Nt93@ z0-9CcCuQ6-`_Z;&^aAJoT>!&me2aHVB^W#S#(`*+sYt7KPR*Qv;}GyiijtJ@S>e#C zk7v>9_i}s>aQM`fXI51v;)VGdpA|kFffUTv_;nZLU~hO8r(#tFwCGnvA)AIA@2*d& zfe&q_91gW0heEXtnABV9&V)EIO);`9%m=oArS|$p6ye4FoQd|&V@5WP;s}&tfkoM_ z?5d7NlB?0mB+>p*C)!uFPi|1)m2N5x(Re>N_ZRmod+jzZxIE>m$%|MTHB9m*^{u** z&~>u|!xiFc9A|wXgoAJVsaOsz z#hiqN=-iL{yPWrLl-&DlO-85sI2VA(egFWGDD8Cs?-ou5uv$$~xbvN=qzKYYQaD=O zQRX7~mq+!cYrMlf*j0O0Y)lfSJOm1tA#OsL<_8p$dg4dE^ZO#X@-&h(eO*pr86b_) zmL@+Gtoa*GxKgNUlU8n8)>hr6WfPvJ)uI5@ggZOaG}6H=!Qvb2aQM6qCh=ztCdyb` z2y%R90q-ICL_%I_6_XME);>S!n#{jWRdULGA%5|zX>o&QZ#-!mb!nU;kl zCN-7<;hlSAg)b!BD!U=C8UvDkTYoR-iBk zVidEyz2TR*!MKr+bs9jqh&ajOJV5x2W~m-RjQUfi7Kk{PS2+Zt-&xJe-f!9}f<)lI zwidaK1V+9`s`LwV3+e?tFnd2W*#fzZ$HTZ>Hx0R5Yi>z~)!M0nu-V{QXRD&tnTt}< zPv#MUYaoGUfr+;na~U32f3?ofQOR)9^DEG)SlW%e=-*qI(GTy}g=R~L!%2C4`*4Ndw5UUQ2VDO0 zTJ2kbtJSKeW~S*|{s2$+ewbEagTbwATBLRB&Xe(^fHZX_fm2OcR@rb3BzoOsFXrE@ zrB9kd*@Y0OFG?Fgd`i^4*1(an&h<(1`AFN8xBwS zCg$NvGCdNiW!s3cEbm7C`y$nZGyGe7Io9wW&px<0=h!}?OsBKo2iY$z?+c{onbI|r zkD&2507n6MIxZh_xpcmN0wX7p!MRAIN3F5|JH74|RnEDR`rV!*(yP!tdMm@jY&*?C z6e!9^AVPhGuMIcTsHQ703%#arfv~`JtmZYuQ*7E68*DCX%K{c8OxbLeg3B)_UeS|o z>sdBXMz)R!C&#USs{zOo!ym;$L2s_@upZo6Ubgfh zEHdQ6kxSlg;Roog*5?ggBloS_IO`a#P@bWQ^e`)}&jwR;_SX?l86RLC`mKWBIe!dK z7`{uQwCFZuVx-UmnGKTUo%=zgH7$cnPM{!5pQj4%eE^R?mEgt;H8_7;ge&5LcckCj z#Ak>fH3K2U_+VW=1&~LcFGpI|S4dQTP+UTDx%ge=hDrZm4wZ&w-3d2csCNJuSvU+8qspA%k!h()`akfnPt3kaT%N=o|5LbMO|Jtn30^( zYeK()zBCt%glD*%MI?JpO`o+0(GFZSmLvW=z!YXOOZPU&-xd5WL!*bsly-J{WmJRM zHuU`L^R{>!jeuoOqzcJ$YNnkc;pT8ETrtS|9Nf)o5uYo>pVMF5FPhLwISvrQKEY@s zkRK>84C`N^6_G9`JOvY%xRX(anq#_t{Z}&?rEg?an+-9bmQ31OuAUItU&x>WcP`Y>8<{9#n&6IuOG}1OnSnJGGGn#TAd*1>htZ+{^8Hy zT@Jiz=;GUnempDsR`}0)oG{SqRPSiTlBz2nK61&+4e0mXz4nKCtjRTDM(8wX890yM zc^k_%D`Xsf0!Y!bN!D)@kCBd+{=>GlnoxM$w8W0UuEYk})Q~M8i1Cmvrz*?3aIXxL z!pA>#tVS+z&evqRJWFm}9MbN-67L6J=-3(u`GwUM4t<}Pebm4mJj47BAd~4HVG(Cy zul=eKf@(n?#7*s}6MN8ET(jUi&JUa!?$Az~cQ5VoT%cv|4ysqaKZ@x;`1is~igb=R zCznJ7nz*~DrLDO?frfw)rN>n}pO|&=s=C)76X5ZquBk_F@M2V|OR@x`TeE;*0Q2@gp$N>Wp~ZsHm|W$fl8_ zC4o;|K$xrt8y~Yd)Y;E{`l~65R|V{klp=&ZGWb(DF@pbwVfzO~IlxxVxacl>Yj|Ss zJ_>-qxc{)GJJpTt+-sdH-@i#p#_t%UT%2@a+hzE1eQ)+AAxJ{~E0qn!X15Vt5}FN5 zqKg>;%G+B3bD6m?)f8>0+{>_$k=&n~Omz-0#4HCDH3xmK+~ovE@)DJRu! z4^bF!D4qRc*GJdFk|T=9Qd|`!6HgB`7Q&;=Co9jk&apvcj9cqRI06P?%e+UkziM3M z$*D7Rb(*4N!I%qf4g}Pg4C;x|j>TsB+HaqWEa2-mqET^L!KE0Pwit?ejR994b_db{ z9O*npuGtN)YwRtP$5&@4`PT?7_yh5o>%aEv(XolzIzdXeZ8O4t0027{t<`6%;b=uv zVkE92zx7hRFl(;^{_(@7NPRar${V$5{H4hRQ?rH`wOYgN^!+t{n4;1`f z`-kkipY=?blP5!wX;{{k@qZ~huzeWN*-#X}HRKmgLZGqvq+K%X3FQ{%A|e;wasG8v zk)97kC@U<6ZJb`k*OBId2wY70aiy~)yn9+CL^^4N7~dk(I{zCliF$2lx?YE42xgWK zdT%oZ_EK-3>Ucs8f)i{3-W4c1O*{_*@C+@X%xR196tTiF^0QN|zEaEbe12G~!0oT) zJkQ!0a(qfXm0Gi{f$(uhlQKo}=t-m)vGpD7-B?$K1+8vh#A+MoRY!DU_6#2c-E^}f zyxhn{aT&3lEdS%IO~%}elINv=A%#ko65SbDqcG^y%gR@*P7&g*esA^7L4?x6dY+Ew z3+&R=h9-_9X>#tD8fbQpe(8aG%Rh48h(pu4JA1uJ8h*S2b8>$?OA#S|H8qnSJ90VG z=MsbINFJU${~-oMaX=nlh9m0^U{=xDuTP4ro4|gzqF;?OnT)(!5roz7{Kc7pp*#D$ z0@19IuQ6p2^g`+;t@o#2UW(PlMaNc7ge3n6o2f=s1$6pNb-vuPue)%Bggv?Eu#>%N z*><@6`eBW%V^IcS)};Q-_?<>RGTnvOI;Zt6wAh+B;xpJOJi{m=$_ z2S=0p%(Yfr-9hg6;*w5M{^5SeM87cY10BBQS!H4w!sPeJhC=BfLDNU`33yKx7i1s_ zXghUQo{CP#c*2AX?4F0r3SjtttfPxw3hD5w$cdI|EpC4ZsQZ*0%RHT_q4!-txZ-z_ zaQA*^22a7+-B6F^Pz_i#|5MF;NpHgC51lq4ibzkAX7`CeK<5TmWn`h;Wu3fe0p3?I zt5-GRb8KEbtUDQFS*%_f(Zpo5y44uP#gZdA`@zOUQLZ&H4SQUkA|(2vd6wy&a)|XLRdjx3=m-H@xf@MUcwz7y#BJuE-Crom z+`h;2E5=iNhIQ+=!95z1GI35eX||%~qyeJ|JJ^V6$o|zd^f(5V_=Cmb&~z!7fQ>C_ zFONq=SRI~c^$t#QMR}I)2B^XY(b#3aUg)}b0pkN~HWTN{(K<*@TxFqvCi3a%^`N_d zWh{T!sQY|=;bTM0xPptwF%V^Rb7P41Qxep1;F|}?5JTk2_6@vYym1m+`ALkY-p{*8 zI->EEOIc)+lda9nJKe?8I+mQoH#hiaVE7^etu9bJ(f>`qt0boC#mgU$@W()QF$+`A zZdi3V^NUe~lZISZ&{W+$j`HEG0V zq{!Ro^Di5cFgU}tTZ+Bc5XMt1_AF{Gn@gHxjFj(Nm=z=GjZ$X^%&+l$y0Rp^ejNdN z6RW6O^)6rIhN*ty6asDFwExH5;K2sbg-0#5p@%eI5ofYIwSU!e`1)|z_9fKjX?1(` zlEGE2Obx?Fnr!?ae^K&mAV8c6k&u~Xz3Y~QC2Jmb^qPplmSNs^>TM2zy9c`XV$@L* z<%P5;nHLr$($9Lmv)3>6rxf9a)7Q(4q`N^dq3kfp_Ga6^XGq(heK%e?U?<8$ePR3Z z6{1vM=iHTzL<`W>iBX+or@=Lv@MC&ZIH3-Ny5Ulb80|sLzkPWJfSR2te-rV3g$T> zN^C0-i)GvHRN8xN!-#$_5CxcIv4AuF#(AdB*`W!IXZ=R>XqfGc_Sbyp(!w<1y}msB zN*QAXY$`BS@Jd?Jp!(b@O{@~-qz$m&(QL8Cu%#3+NKA7{J4d-{l^fgR93n*yb9?bC{KRU%xU`_6-b5Fo{HvmZ z(h2#kRah~+DE?wk#PPbyK2m7&@qU0Pa2-n|?=w{f_PXYKnjrgShRbLAtoW~Rkl_>~ zGxXJ3p}oZ}3|uP}j5Lal&KuuXfY;3Bqr6&Uc<&u#<5Ok|_@e(=z~+E{i2(m~R{nGi zL)`~f1j)8*!&H9^We{6+)l&2h2skD801++5KS+P77<+by#IgYnzDQn-^Crn+9PV)_ z2HW1B<-&NkD$%T@dk4#D_g))B8@%ki{y}%^yIhe$Zj-32XNAY!w0pNHPYDh0-|s#L zH~)o)&FB)+e+#%B_`8j0{ekB%8i_t_N@FZ;LD|6gVpV_ih<95x%S{$RB3qY2i2Zx6 zBGm^Ph6HcTd9|X3Mc1X8H{vtEwjpw=T5*Hq`6xU(>ls@are+^-YQc;Z_xoQ(@z~@1 ztzHcU>O;QbLKk^FQqcyUo#N#5XRKJ9Vg>tb-rBu#tN12ZbY*g=F3ShAc)8ZDh3Nsz zZH<4r_soX1nlh-^d{@HMX-|hKjA-QeQn~u52S^=mrBJOEUW$>21C!@IX?7ROn6#M% zb4wf!F=n=1O`2Qd9QlF}??>}Q2%OAvk6e)VQULlQXG(Vkqz}%{Y=!1MYA~7U$7*{b zsef5dg}5MLmJNQoX}f>nWocA_SYyu4el!lW5NCBc)S>;eq7Ufgt%gxDKlGh2d84kV z0M_b20FG0Oz-7PIXPJ9Jg3F;2WL@{01d|(0f|U}cOE;8*$?+J!3-56E+8XaqLITXN zF`V#uMEw3muWeCSXRpA;tyGK;it=p6AS9n}_e!wU@MXV-H!kw%tw9go%}k+j^B1Cf@OHP;71S|Ac61{agE}0-v4368spW5J1v9|UL|-L1z6pqT-_3PY z<=xu)f;H-%#p3(KJx2X-bx1AjS&2HuID@J>$yVN6eT0G2MIr5=+=Ac zcMrHQ7F%}Kd=)Zp1f!WbfZH=bo=Y4~z*-!da<5ym1>mZvw>gm4T^(zB}#bIo0P<yA++HDJ1 zUE(S|wubJ@jO{C^>&vY@3ztwYg7V&o*v#g?kuTmz6VivIe=qi~;I;52UWRW2*1`PU z#zNh2M7`BPl)VsE5NnV~j2ebyBBOaue5ug10 z$6wossRzpMe)oe=jQGuxs3N))XzV4aylfVf#B_m|{3n=6datR|;rR-VKMF0$4MUxh z`ims1=v1p`QGnj|su(>xzoH--TuKqIY;{wVg@1a(q^b5g{}=ZS0v!L5Yw;Ud-r{iV z*9yi!$~}^2*NwB&T@2;mZ`@eTE+?3lROJbL!xiex zp__PXpP?cGoJMUw3d&)D?=~Dysy7^QzP*FaBcsksmv2Wu+&3ojaj^us+(o(**Xv^# z{&))%*csp2wW}Fv6xaOX_Izzd|K8BKd*-VwEuz6eYnMwRT$dwkVLZ~sbRESSdORcY zD2j*cT!fzv&GchttC%+v(e65E)4P$guPXT|u^pfMwt+TQ3!{A*xN(A`YeHDp2{-8` zF|O%|jkuGhE-wgq2l4kqK4ExoV@LDARDXQWN`L$tnH~m6wu)cHW|;jU*Ry~tg#CZe zTG_z$I4u}JT)71iUhWO?&(TJt41T8i>HOXEUjvQU^G%dI`mH_SHcc|c^pZb?T1Qs9 z=+Ruq#=gIq$NY}=9qVO(db>FX@r|+1Wp4pxSy!p=^R26d zep{Z)8K{1MDx+K^_u$7qucj3U3Wo=1Uq_^w7Xtf(4Qvvf_d#vr!_loC%hlvImSCTN zXaAf!S4TI_T?P92aY=A}&r7_U%3gk1u-nrnEhzzwmCLp>3rA%_(2hc&(=I*i%7#eZ zb_-8so&FlABu4D$!USitI3i0VjJ7rf0M7bna02fX*1(s-G&V6-(+h z)l2Hv9yBd63+~@04CA3sFGdc1rVn1aRj216OX>q|M}9SnXGuaHD!2g?KT#js*!G|! z^@wVWrWg{m<5klPOz4J>aRvU!Xp(uJ(snbP&6)R2q=HSfgq{#^A$6^L@GQ2x>4{ zlmc37jJW{+p5tmh$LTrz8v-IG4;NfuE8Ir|z0rw05olA;EQ4Op@W(n!z{t2H)?ru4 zYNnLxkxGPkZ5ie@5Qw&WT>wGwsdDw}XTV)wcS%Vjb)ku*j|CnFqQv~LXf&k|1*uFO zY2-PQEwN{64_f0F?Ss5?ICN-gBF?tvb0n*5CPGH+_$uU&A^f=-dPZVLNy^I{Y+`g> zy+BJARb~t$$EH_e`+^%)1F6YUUV0G#$pvU&KX7(h?6Z8|Xp$OHV8-9Lm3{*KQKrEg z5*u`2WmR69(nIyfcG48wfCyr5dk!79jT!({NKnY)*QH3JK)9TI(p*qRQr6Y|u)Z|k ztY6*;-Mpqdm%`*2N#+bNHe;Z{W_02Gbd=+&x|=TS0G1T6l%R(#{Y*_nF`@KBy)MCF z1e0Jx(QD{qgXPEvh5{v5@}6zIT$LuSf6!cMm}`(F`b}uDH|HupoOl`DX{8ddQeAc+ z_9K94^lB)0kvLn|_Yuo|CYEK@#;2~wpdq7Xn@ zklrj2r1##UG!YO9y(3ERy~92J-h2Osdp_{#usfOEot^T`b9PV3cdOl=?0QYv>Bj66 z%MB|Mz!PdC4YsS7hjZ4i7L|~gFm@uNv6yj8Wyil3bX82pUl^P^cEtmC-);|f?gVgM zvPg;gVx&V8&?taNwV$Fo@f#0g@-{7I&n>0X>p7FN3i_e<#@WwA*S%^52ei9SqL-eB zq~UYXzIT91FjRmjp(EiL=l)>z>SOB`@uR31S&!~S8Lj!wUUHsF)SIh(hIL9nf8>oK zcYuw-jkzd_v;}Ogmph+j20h^vyS}%+3 z3RqbAde0%1y6(2~kI~OeD+lyND8Qz3(V)XVOMfr`0GNtYewU0y+)~F1I9F6(sQdjq z|K;VCqLua*lV1*Yfk5k_m`n0XzpR1|#f`YjqiGuMoc?kg$d9mKYF?F{%3Y2Jy0V%z z?;fFRt{Xw6#k}Hw#oSF4y>>&30<@N%7l74;^etnD%pl9Ck&*eo`>8Z~{da);BjCkV zX+wgl7LHcP)Z+zgMfHe;q(zBk)(Qu zUm@)&$h2hOA`(&&8(aa}P2Ls1@a^y$hjW>?0%{E%;YD6};DfbyVFMD^%f#&=6DK70}UbaIlTk|B6FJqf1o zpIbB8y|rB`qUW*Hx!UQTRu{xTf)sJ} zZWQ=5K_>5xg6d&%d<0{=Tbr78)hiK zw~w;de(G|SZkQ#>;WEPswYYKD+BcbU9MS?_R}In$RZ)FGr$JSdFVnhWjhvjX!hB#4tWtq)FoLBlaKbg7rRETy!ci zBFZSUyCz{TOt3n`-oOn<=Dc+XV^5KTEsf-ph2WyMy*LdD2oF(yj7IU|EStKs(T?_| zGcfXHi}bfLVu%XlisocUU&m=^T};H1s4k^eEc^Xf0o>ISC7&Q802v>5422Tk07Gw$6XkYsRNINFDZ0YM@7}~(Oud*YueK?!kf(9H z1~;66H6Lcp(;Ry0vP2KgM6}}ma9N)Lla^~x9*}N89Ow(nF)M?a{0F*wRF&5YQ^E(G zw7l~j^|*m$gh&cmq=0Dlq)4j1>_fbWfW9SV;s8XeIqqYJy9&y?qT~rN{^m-4x{{ZG zWWgMcjceMg8d5AD##dBJmBA$#Qz5SvM(}roJ|3XK^u~mJ6Ovh!=q3!lCHdC~N87&0 zfTrIppY#RoL)X`)Jpxhk{f&j>;NcG77aOBfrlh_z{#3r2ZMgUt-lKOHZymbuft-a_ zAmmF~5(wRMFzc%rA1*AGl9zP9c)$WQF+0FdEj(GZO6_-9=}FgDF|w^KbA*|7?QN}q zj;lZp+VXlwQZ2_V3DL7_*!B@^m;P}J0BC}{OAjBUT0<&~m;1a-FH>l0F9ctO$0DZ7 z2u7i0-D_sYrxfjpU>n=`p6}=OVPyKd9i?n8ailmOwp)nR2!c7@19K#p?{-FA(81Qs z8BUl4$r0m6Ocd%sbzF#_9c+YtJ(L*(d^E=PRTPB1os}ZuE$RibwQX9SIVX*9hQivJ zIygviD_qP{Snh(e@lC?(sU@S?Y5eQ`o{g$X>2?Pwp zaC4{cSVF5WXL>RU_@(tZKU`3(SC+#Q=H6j#r=DQ4_G*wmVTApcs64ftZ+mopu@so_ z*>WtQ3is}uQmkD3O;3&@XVkHz7w3Qge8aCt&&^jCpK^kyvD@|ksz=)U(S?`6_ihFM zG4>QIO*N^wODvOI*V7Gkal(h^?NP=o}?jjvp79<@eU$5yEP7u3e zHrUz8lto)as>a9S(vBE^KD@flHWdrkS-fnl(|$BgW+(fU^~}9Q`zaxIf3P)+5Vvno zuFSK%XuE?90N1tA`sUda<9X4bp3IkT8YV&#`3!*C9T)ze71$n#v&9~8|yIy+St>_YQMGdM1^KB2y@ zLOv?i_IV_8y>_-E(UyD1-;4twbV@G#;b7}&gknvXyP$z|qDsXZzI!*rYL!9o7VzS< z)ijX5)o{+JYFa}9(m5MaVrzTg9@osE5e(znsqsLVrTgNvsh;g@b?H#3$R*@EWGeC) z$=alssuUzfOs5nY9}iy_25ZzXJ*-D3(@Mu}A2ro%U3EdDjzxgcgYHq(Nyw@nA>S%h znwR)lCp$ZNe(7zR)ETp0s-qK*5bD(@KMVJ~Q?By}tN`{lTs0cmE+u%Yt#Ufr6RGw= zSe5qFq$cb&@FWx#d7)BQls}2&fe%LuUd~-lAq-V~Ebi*eyP~kt5>7BhSW8h()3swq zj*Zp^r~`NxE@4vUV76fd?^ll=A7+jfmo0oB0~S#(z=SJn4nT=SReJQS3VLiNJ=Wt zE;*?s+VYI|tzLH28Zor5Kj3v?b+P`*%!x6j@>qLZg+-aA%3W}<>=9bHN{N_rOlryw z;>A4&O@;mnwqljklGFoa-(cU3%h~=E zTAb2u?OGP89Ew58ly3rj-(lU6k}l$=HgCK4L>42ZBt2Q^9W)k zHAM?Ac4cO~-Fk9){mq@$-0v#zV&hfLJb7X~)dY0;ia?@FYKbPb5Vw=lzDlE^TjFpt zvOccQt=16GUd}E&dxMW{Z6%Vyt8t_VO#M;t zrOP~v||ub2r&RppiMF-Ue_n`sx=?IfIjZ$Z|JUs zc!Dd=*>Ts7kSA<5%KeTvcYda8u$Kb$7wu^r9 zUaZWWbnqxD^hiV*@4k#xF~Pek7LQER9B~^K*QV+?nzi1)E|s|yduiF}0iTgx2vm}m zsu3EXX5X=6HS67(2W<)34PRKDSP+I6`&7e$b(UImi8ab>LQ8#HnuC#|*fWU73q<*tzH@e8c*pjwWIX3Ep37 z3cq*S|FyC*wZg-?kTFw@sT16u!pe{dD> zgh;0!nyebEY5!iIi?+?qg#L^cZ~Gp^Ey%lIJvFJm@>JEduI3^CMmu5Obd|HS)6p*V z^4Qqdjb}A2Nl8iiS`=|&fXThlS3KTLUkXq3xD@vQEEI8D6qBXlQ?S3EM$9w;b1r;q zP@PB#k2_RLNlMy@Aa%)k7n%rq)!EugB9UFU7Cx%$79L8QYxQEzkalVeGce=huen zrC;0BO}yX!X?!=Qu`u)mBll>F%?6lA6q8c15#XV`D&5t&+)tfDyKeOET0;lkz}F&W zUdSqoa4Y|P6mUFQUVaX9PxDtm1Q$=1CMER~NJ=py1?8I}MW~*fuFg(->s!0p4E>Q( z(A91>jf(*^c`~vGapH|6Y%TLciZv--R1+N_d=9AHT@Vu!n+pHqw`#=OXlolEM{40d z$^ZDY`oyKmh9JCn@7 zRB5s9?S#EN8g9)DIUX^wQbQee&hDSlogUNd82$>vi3HF{GBpM2gz^2d3B91w97EnE+f@Hy{yj(Lfp1KGr&S+G>idZ;zW6f`-$$`4 z+xc;^P*{lPgiZdP+*LrofPi=ez`P_im$v>6d4i_63r@>DEEMvTNbhLdzj5}^xNqk0 z4T-1h$({eb?ZAU6Ma!xl?6#-B*KvwOY6>s>g|*3)v4j|hB0U@LuES{KG&=2IQrKtLvGl zdcysVkJD?B8?#l$v{rNnA~f8{oj;ioX#77J#2hdbTcUHm$iY!|rp0dEE7DOd>sqF0 zLnMtxc$JwU+JvNZmi*tal0ukX%!noBOkL~r^oveQIx=5q;RAcCe1pm{5Kv~m#c7CR zC^1Ca`N>AoKV1SBu?kju6{w5~-vl2gs0!*Es0VPYxQ>~dHrKm$_rxy=VOX};EPn#K z0(fc=SQ$(f#^*x_(j`U5rU1FnSU(q^oTFAm5{?&fX6E5v$xY7>JTv)EoB=URxW-{T ziC6ByIc*k+pRd%#zSY;fd@FtS=-W_zjV8tPa7!3CZU3IQXz@Z)cTRnMtuWfey}7zq zy{3wU+*)TS?#g))@94FpgW-q~_YXYN|4)>>JL>Jrw#1*5p^i_1vWuyE@rjNFy@*Uf z4c10FVa(wN()q(ZVXOZJ_vgieKPPpwsB#ChL`mCHW6o~f{_Xeh)5vZ5LFp3G#^}yR z5(nDkLt)_W|NbF9L)UWhKGI)P_wD|^BsWibR)p(H&qZ(j^aS^hq|ZltQV##U7{R&V z%gys%uAC{b{aPDG$9?tClWCb#7;yA~XGFq$6%=e{-0?aCBxJX-!KQvAP#nw%;RP#2 z5g7SuBLBAp#@JNQoW246ix^@$n}K7pfwYme&*CDvenO}!{R_Bu{~kUdt}1NPxH0#- zhvQ*RL!Hh=n@LbAB$WCYG=x4H1bIgBsHr(X3@w&eeI9Sc&+^A1s*&4s_n zFX4VF2i&xrY3~X-f=h8*03h`|i}Q;J zi*Sf2iL^0=C_?0^548E$rK3{$%^<7yl>s3)xG0)(*+2CdEMmyO-}a$7%o1P^b)6u zU%|04`F1@nN~->`19krZP& zr-ke4ROi7e0xX=$Rt25E`+8=`G4PEgAXL=HP~MW4(6nR&DhnC`n1HIirKBcplaewp z#*7El1+rdA@Xii#?dqidpLU376OiRmC2#F55OsY_!3A+m?^Q!YmtK>GG5H-8 z)D`C#+F5!MogqS00kp@8i1ZHDs3c>_f3nv+TK+vsvwscCk+Cy-Z|XgvN(Kl3ZElYw z)YEzMuk%<1*TFrOF;ntWj#HKJjYohR+IjfnVi6ExAf0Gg&kF!K46xY6efISO!oKCI zRVUy@D<{v4vke8$a@X6u41RYZRD#6o(XcSm3Q{RuIh4lHaOMmIXANSH~ka!q6faJJYkCgI>dnTM-CCEhGCX!ujA6vBQCYqvgt$R%c(Afo z=DIW`g7|*B*6xizr1&Ru;Koow$elJZ_vCd=Yuf=sVmz zmG?3%=O+iUTqH%oOB6{#BkQdXXn~FbV^_HM-%~Bh&+Dn7~&Mo z3#c^^269b_TP=(gU;g5N8#h}S_<{I$NOjpFUjhO2s0YA_7iBJ=%L<$U$1j*<_`Yb7 z9xwo}aCDeW8jvi@rN#7uLckeK{Bk+Fmt9;?snK#*9SW>l_hLzkW2H}EShQayIA zP6Dy|6HrnHNdo@~zw@F^*DVUP_Le~72Bo`OT+;^z8SljDvVTps;gWcnG{_jT8rO7^?k7j4 zz&}aD52MAQF1L$JW*_D?@<4o1&CI|du}3H4AGQ0>jTH}7MM4#?!(#!H@e*wUm1Z-N z^b)uty4w8!u$Rx=PamG$uCKY?tws6oz} zSBNrILKMuqzE$1SlNMvKBPvG3S_T>8EE(V2%lnPg)ZkkL#Cf@UUTgco`c!P$1?*Bx z?BuS$XX;-slc`!DIsNp3^{VMNrij1HR$?qh#0l{6xwC>&L$fQ6tp9dubB$gnE;X3O zLSkGBF&#a2*GK}HfByKI(JeqRFI-T5rTx5NN!uJctDaH3c$pAaiQtTeq+w;^wybXW zdEQ2#@}}Iua@pZ+;qSj*S6Kzx>uaFVqzL@vpTCuIpBq>H9~OWvBqH|sr~1gMj%R+* zFy`b{NF-o5SfpE0TF$_wGm$O!3lJ4rbq6L42NmomTS(mOEzDXw+v_+riYa~zFY}^} z!fDBrtC>hTz-i#R_-l5L=_5=X{_UfyX`sABxeK}ZoGW*?Aw=q!vWw~U9OB?qB=%$s zZ?uM7QCX}Ku>m&a-|vKdzg!^9WUNYjR9?-eZ7A*e@4hU>>z0`e33{;__-asD0<)H@ zQHUf@wccm2mLF1dE)^sdV8@Kdx^rSjd&;V9u+h)ent4t9?@`RiYq&W6x>GT7J$*F&TgZJ%3BVYi2fRjT!<*vO&{BfoRQw>Zzn62Ocp%Ti2tco?wGDrT_%X8)V15m< z`7!4gExxl6JX9$Yz-q0vPTomg+xWs!ee#T+`{Eu=p~* z?9IQ^ajJ2XAK)7RciK=Na^(S^ofJA96mZwa%1deedJ$(4U(uER)jfw-K!qxyI;bcV zGjds)aqVEGxtgp6-4^+b=X0~b zYnb%&4VPKz;Mx%$(Lg4;3A2W2nr|fkIDMHXg>ir|PCL_ZnM03XKRSOjLGV_mER#Y^ zm!c=sl&-_OBNU6PXiu1bMUl3jlWX7`MjQqD8d^A~FBlW(5REq!i*@5or;gu9aStF0 zQB9=EMc$}QFRNT_ch(XL>orpu;gbLIe=BgIB+hX&+8^CJ{^S9;tEn86QK~5myjCEd za|i&#O`hhQ#Kc=}xGb7j;m3;mngen7aU5P-3Z{;~4{x3vygUP6{+3NTYnjK7kqddlQ2HeAh%evH_z}+wVDB7#Iz+T4jwcn^!Pa@_b=?5 zMFnHfmfHzu(c{{7VdY}^7hY3yaVq-HNBC%a+W?3OV)Ciilld8%~TR zNYS*_NWueyx~xv=HzG1{o|tt5uHv-|Lv^F~#8h-@a`A(4H}u8isp^Cf?0~;ee~*&A z|GW8m6qSQ&v-voTb3ueMK**6-&XGQ;C+xRH*wuNN>0W#lJGSy<_byC39eCa|fvz!U@`y=zvLO6PUk%O9AOI zHt+(V0O~~2V066ivR3uXLE*W9y$MoX*z|+SKZ~({s(BIdLT<{Kx!#ORan)uw;3sxU zj|I^_VlFzX(&}XvD6`=XPz&G=;DPFDwrfQgVap9Fx{S<+nq7L3A@eThB&jcR-gQcX zWKp*ywo~8Q0xw>ekLA{+@uM2zFsj;LKOwu4D^(2xz) z9?LT`pb^|XhT{Jo=_J=W*+1IKe0B|^$6Z5=bmXe=MV^>Y;6%^3vJy&DvFF*9tk|*? z(r9aS>&-O(XW|Jd2BXR`+w45_kYvjB?$9@Cp zGlrigP^wjW4yYxsoI#CVxi@b5=sJ|z;PxVA=Lpk@)wo)8Y0bX~7F?;?{3k6CBP{GO z!8{bPT`Hc=g&e;QxAAv^G-E)diQ|r7V!XU6E`6f(@Ie zuv=JO-SfZh?zR5ALE={=FBYw0MlS7N z3Ca+2WPryxHr@(oJh?Cw>MmSujT%#2OdQ5N18g{Zp#%$dcsH|UCw|F=poT9;O#if) z{vyZtwM12q?@kd1R@kn;tEv0NW=aNWFvd2_(K=jTWVVz3t+86jEX?Zra+4KzW3;n- z#~sU18;Kr2^4IDhCQ0HfSj%=j))HNsA9ssSU`^AWTUv8t@>A5yoRq(Y6dJSf~#$RGy`mc1qI}LbaaYcv(_Grd$A?U|sL9l6U4Kp(bta~F5y@CJ+5eNF9=SdS;O($wiB3AB`ZQ0BW=p)CSq$xq+*yOe@Cs1;-7 zq91c&A;6a!{>*=(jpn;;xUirT*bqiy#_W}MfI1@g-OgLJhuN?=F=86u5;C?AYW#n5 z{~C}cDxNdD8%T49wYSY-cu4VkEf_z3x7UI9saI;Rg7`{a|5&(D z#A~s0r{y%LLA(_9&Sb_f<+stHd`mj90g+8?zl#yuQjcluISTZO-KL#l258v_N$f*V zkSXQtuUFWgup4rawu?m)syg3Jymjx4bSt{=#pE0stG2}U(Eg45g!eRDoHPoig>1!( z8_)^RRPnmJ35(|ps>}JKSDz|?HK^P304nu+021Q@u=@H>o~uO%SOA|)_}bs`&Igjw z%DH%`4I?497@yDuNfjs1zFOL4bQ;jzXx?KaF_Qz19;4nFcQ)5-X<2<3yDR=n zoSaRZU3_{K!%vkV$V*aXZm!SvC=u&lew-W5hSbzw&tz-4-{{7a?!UKkXjgorg^%-J zRlWMpcRTtibhooxyT7D1GG%ZG^st)?@c!RR}hlSgt{1TdSiC6#?IyWGs=y!=r_VRVHCd)O^ zfq?x?5?_t_lRxK%0IrHnG6$Ys?2U^)>R6$-Jf9PbnbNHOV^`IMoAf+HnNseMpOR+C zO?I}auOHo`ydbLrJ1A%YC&ulcS@oOEaN}t8j@4)m#Gy#R4JtxF3SL-F04{ywYgG>^ zgEd1eb%-MSjmbf(QPpN&wQ^b63r1OcBK%S;>-~TwYrk03Z&3Vq^V*aIbCa~(pYj#@ z+TW9gPrd1|fxSX1F|neU#)ga&io~-8QH|&3p*19SionP#Mswzc%f47`?%D3qw<*Hjm!rxF)5Ic zgd5oM32y8-Ajeaq3GckeVHHe_(UMbhWoD?cB$?n32G=dCf_|sr^L{kqwlK6wrx)e# z@rjg*7u^hMlq#j8h0v%plK|^`4I>rnV+_kp!13ak@y2)BC@82(bL9)D=&i87s}^Ka z#a2(@qNjjq>%sqt*=C@e)99_BH@}ic2mir_E(DJG%Jq)M)5}2N_gxCt^pzwVCLa}v z*4!6ukMBPRz%k-pR{;#dF*#^ovAM=e1C^I5N4R@)!DT8ISSQ>WF<#88U(ATIN^ak- zOu;1W5(pf#u#bju+chO$4VK}?$z@X3o>oE>x+dfBvy3-=9gf%5{}Plk5ariv7^{>J z>2{*KX5{DJGmfc_6}>>z-Ur$JO}pgJfVJdgiBUSJ2TQZ>%VkqGfuB;M`XtQ=LkR;M zHXuybqKpBpe1Gf+2l#MqCpviG{Pgkr>UMxpjQBH>kOf5IG`wWVOluxbr>O`MUx`M{ zwMpH0dyLQ9cULFD$MjY7LveoR3sq~SfoaK+)ew;;m7yOMuCq%Suw?~%^BDEiv z-h+W^ClD{WeiS-iJ=1+PiC(%8{YrS{Z!=*ZPtr%%2d3D;bxld1fC_!WKPQ z7z)e729J${emGncd7f)*zm)Njs(8xjZ3D*$6m?(!x|H1a1 z^LyRdp2d_00368GRt^5^-BX z_w2XC*6SU<-k1@6vqZV*O#a=o*#{zl(gvHR`(j$S6l;Hsn@Y1yH3VA};kr4RKa8`~ z7~w>m4yB;SM^opnwbj3eN_Mfu$$n{oDFI>COx<2Z7lTk zUj<#p0o}A#{u`k>?ZP1V2FKKjvia_f{0uo9IL7yEt&7fYqVX)n#wS@W+<@_D7WV%4 z?D+s;?1mQLr>o(;VhtE2dU!_{94rjAa3MGn7U=|(O-N5^+KA47ZyZI8LIHj(t0DT1 z&A|?~5dBq^sm@|WX82yrh(tf0Zt8_&>cQcj*7`x?HrECIE`w@_U5>RxtEpRCPw*VN zqfD5`c2ZwY!ML=)%Sd?dqlH*ae*|$qfZeRsg=1aFs+=I5t>2MGsNzC2Toj;PRoplw$G;d2YR7!dZbCPCEaVIM8gQ zRn&tIognwpq2}{V}Aw6aH3L` zO)jq6&Gcw4YY=5?0z(N$_$b5c+Wi19V^bNgT1ms-f)swPc8Vua9QYEYDv zHkrVin6_A3!9A$$;{BnZ<+Q7d2Ss*e$WG7Dv+Vbb7LO*UJac!xhshDXi} zjh61tzKaRav5U)N_N`tBxT_eJ+VdN!+PatO89KSPX-kVrD4R1qr(R7rZQ|3YZsqgi z4_sJL%E*~^Z_V0j8R^wcMvSa6NT5<{K2P4$2>;?+ z2yPez*qt2r8kFVMLOn`2i#%32Wq}giC+nA6Gh}2F$~w)I6IfVPWfivV~+MB zQ|^DO-)O&8CBql-5jdj0VwS5QJ1(%$rP8#)5TiWS+&S2L46^Iu+v*aL*ix?PDDJmg z+>1RX^DD&Ng}<)}Rdo9=R5l)EyLP-!1I_K2Q}jM+Id&7S?7}x#UHp>nGN)jC8guJy z%U`U5@?Hpo8XdQWWO6T)?sotKXCw2emlNe+Ry&fTac_syJM5pqF=BJDk9Q?MTkt!8 zBKd8i302U2CuW=xl44x`X!&Q7YdFn71l`mFq!UeDeMc{CY}q>DOzEO` z!`_!X5xRxn%`!yWZnn;7pZotNZj2;&R5zg^jLnyoh6&H=Sf0-7Mc+60k@oPS2Su1);@g!{ly9NrCYso z2=i2anyn|=+rLos%?)*YZQoqt_oGamBU~Ej87CI(b2cO9vs;y>o-O>?-e#S^UHR7;rkW@2FB16QL5Q}uVw2c_00%EEw<4pWoG7FmBNxvV@7vLxIvfcrgwcZv-C&6DXh>^ z%H~N`7f=matds`-{M0*PWy5^%fBL=!RAPhn!Q6e@!Z~ye+J%gJRNi;JWKt?+)RBoe4~uS3ubi6`T3SSO!N#T zWB`ChoJY-r@5wVP@Qnva5Y^X6HWc5tV#g$#s1L;e)cP|{Gx6{wkb$yRwSb|;&hhMI zS`y2+KWOED`B5Uao*xPeBRFuUK^^t{(E~xU`r(D8vK4Pl?o&FQcHca2o8^ws%jDF5 z6JWD3 z4_X3G$?0DP^22D^=ttF+_A6z-veQ2Lk}X|6inRC;zG&W zHZmJ{xFJL-Uy^kxW>Svl;kJ6g5?}6pq^9LJY0KM>-}3oeP|8-=&9)_+e^^YZsFh>$ z1$oKLsMk2l1d+b^2J2PBA*EibEcFpFFHXpJDZrEW)D2v*$cHXNQ)Le6T1rZ?6)o@; zzOn1WIuCOw}_oyZd#FGybFPq(84Du7tb{Us=;6JIu8?cr*bg3GW zNd8UqoS$v}Xg=dQ6Relijj{K|0B0TW3BP&&0FtCY@z)yaCQBwt##zNB4+pOE# z)21>PrRBV?O1Pn+Z2?KA0;SzE#uUe1Yk08%YMBkr5kaU&SPNP`raaicZ~UpuxxZX^ z@46WHjCX+(<1}-Nn3=E*pE7&jKaePE0-JYd85h+*r;G0g>=lfcOdneYwoxjVscHMY zbd2;&>^z^UC!SC_(SLGfnSCmVd<-vELHXT5G%&-})S5rQi|MnWzlF#<#$5R!S-7Zo z5=JQbPJXG$j&kY0JtYMak*%kzf)!KC;IU}A_#4Ki6xDy))CP0pNT-_>Kn)@ZO^9iw zd>DanrrKh1a&LE& zV0-eG7shn-MYv7)yg(~1RAx6Z;n95c`TW>khLBX~*gzAvYC^b|#}7ZC=ke`KV9-}j zc#$f~&#TV!%D*<7<9CljH(xiX7;0zm#YbwPDTdts?yqcK89KY0th61|uJh-NU!%%STKausH||kOf^~Wrb@~jp`OYO^P_JUXDF*gZ{#M;3mO) z8nX8(&yZ|<3#LHM`BY;>YiRMV9i70%y3+BW@Q?(}stj+GO%HUBV6UwDp=1^5E}uDRKlI+NzR98 z;L>DQy4m2}u?96`CYVQQ4#$AP#fw7@K9XxO`QIDVO?0+xDK8c>kGw%kNsOE4w z_ThUdzZ=rUW6}0&%vKrGcPC$mHICjsdL0#CHaTyD6ugpZcD#mcU0`O0OQ|#qkrbX! z&c*pRJ@syAE-nGGdN@Isr*>%mFAXERU*Ts|t-cR?uXjUyBP%~Xm2Y{l-Y^r~C&5dm zbFik8|878SLht67?F~BXSp0TdbLAO64P>ZHF~w<@?e`fyFW~r8YaG@iMlKJWzH=_~ z{7(VrJ|~enw0eNAQ{W2_HuI?w>vedgm-kO7rsD-fT8mPMT;W-8B5HBzd#9H)&aZp6 zMiJx?*1}dVb-`cmT>H(d&h&`^G3`Tnupa2vrVB~&*aV3oe!f4@_z-v%u0X#NM&QRS zsfT4TdSo!?2Jr~u*%_RkH{MFMz+9hsK_%}P7S^3bIb8Gf$H+yU0?k_JS4N_F00xK&#F3hI|%z0S-kX8)25&^KE*P&_4~Sl zZxryxVNrqMWj``wi`OCu{+Q79P-S7kr1a(AV<;@H<%HM(O8d`NLywK<49I=_Nf7mCFJZb>eTek~0Y z)!qKwzkEDQ5Wy2;f4P6S?mua+VMf@8oL)7>Q)iBh8q|eW)SrD>-@G<&UD4Axwm3sW zWawl=LHe;u)1{<)T2E`L{%$P(Rhdcy`lB9y{utdKg6`NE07*iCe!QpQiz9k50C}O3 z`bc&fa~+|o5dGRxn=ihaoEK|3QdAL_#Imo-%ZqB>c&qm=Kl8`2 zx!mt=6Ao{Vqy5Y-He3XNKq-VpHoo#{q!r}O9+-Tth3nX&*UjGb?9>`*+U09038wvJ z!QC{cs!+YNIp+g3%a2qC*(J(yll998%zaON0PxlL0)}V+Zn$!Mk5WyvnEZV(8XF%J zQ3uY@U0>9~9BCxGesm2(0rU}$TU~Ul7JDa#3gLu8$a8D&z4MJ(x9o;PPw*W%7cvnv znttffc)&GxzOuMBP_m!iII)YZJXJ0}KR-y{)*GINtL3gQv~x9*JAHf$Pb#-7&U;Dq zJfUo6o>sNFpXA?6$6P;VR}ime>xGBEL#R5 z^zgTzM~{Lk(KTg>U)lCDO(>Vh##}!+oLngu)3w}ex3IIJ)?tKj^pW!3ryWT2Gp>(X z9ozhRkM_*t4%eh|?}4%y-UyD$-OOhg2JbsO)roUp$2?u>AN@jd^>OuD1=$x2h`nef zD)TytFInJEB}lR?0DFw@s+Fo6)!3(LY}ZA1;L9G%Oj1uW9#3bjeo8p>F2wrR8>% zEIsGhcQ*2cwB>f};CqFi1dZ&u^@cEso$|CiFwSITY+;y7GqeJ7~@OW4Wkvj zmz>sMN@)wT|6&tHNI*=VqdeFwuB*9o&}fn&k%*YyAPmua%iR~*Qutv_>c8j|PEf-M z;sXt@=^RXqEP-0Odmqtmi`h|&`UU?#EWnST5Hlduo}6G~^}XG7tD#cBC7xu7HbHuc z=m9bGxJ6k5-l6RdnO7}P1d&d?`}p{yz^B1e;jyQe2RPKwo9rvQ0GbL1pH0{vA-3fq zvVYEGkmFl41J#iEm;4GM?lU4!BF!2155H%8nyzW{bQykw_LW2{ zbyl%`r!tO|G$K>m$zVxzZCylM|X2{GN%_JSsW}s9^+nQ0PcKjJe7uhQ)uEJa1wZpu@5A{g7!8jX_j-OV%!%$5RQ2a>obUA*be_l662EPVwB#K-9R89r$ z&HmX|+>+&TIcAcw;&{5u{p?e?g7{PF{qvNFtwzj|hiU`6km8_zU^n%?_bMp){g9eT zmhlvAyngeCFY5C8<$tJst`Es0oL4rF|6n@8Yd5lE&h*O6>?^6x>7oN zIb4B6*r5b0hfwu)`{8qrDJ1}W8B&eQsL<2*BN3|3c{A=5X8Na+uE;82faLmGwps_B zaA3MJN}lH3ct82aV7tOMl{gihd?!2$vi`OqNDEhs#5zxriNT}iy!ZZ{&?ZvOulzpO zi`!hJONmOzuD5F%$vb9m+&{^fqB@!2Td3xb@Z!!dgMKY@ncQ8!@=$yiihM;Ux^XFX ztHSG2m_^U(Fs1T;CsO7nNpBS6_lk9kzVN* zKQZ1}^JQGUb}8R86iQg??EYPf6h7!ho9MSvpv}NlzY>Brp{;uDv)!>g@b2&4;lE#q zaFM7t9Bkl3R4_^G4&I)-+fquZ@U+|_{@A5|6TJ(8aVo5{KJry``MwKk>wZPe&#wj}6~{ z7h@$<+~ZWm%#=8b?0Ohy-c|ne1riIhnjkQh0-ux3MQc!UL_*&!TjEnbgPZ1i~3^zOoEo#;dDFaD&S$zccZb_NK#_nd(7Rj?7`;4 z3!%haE_$cjqsdToZoczP1@8=o#DqTfWsknX$I+PL$_+T)DdOoIr}z7~J{T^UN)l2ynyBKlwZrBnXHRbJV?#9zn-6FXrP z))2gQb4A-!#!WikPZHrHm@fG%?9x{@-emuE0qpLdcb>iz48CSRKMuFAouS*Gn`)EP z_zzFgwV$;p@NDK1y!$O~V=}Vpe^6F@7^L4DEjqCAU6Nl_9f8(9nXpse0WE+ZNS&X8 zA@mWzz4)>qf*=800OyE55#{2gK5|Nk5x!JDtflVb?7P7Ciz5kN{GOKvg1x?cvGC#O zr}y877U@cf<+Y^awZWFFny}qWo6npJ=WsJSN_;?pt72f0e)Eu)0jr=s+$hi2|6t0scC|1tB z;9>$We~i4OPV~(?3XehNYm7uG-QocQXuqi3I>3E|(LXnv%-_E=8BQn$a-V1lBfh)r z)BH$A(wLgIb$RM>QFAXtT4pCt$&IG6exX+sqivpX}XmCT(6GfIB+ z2zzzccwB45)GH7;GlwGUE1UQJ4{zuF*TnX03+ zcMwyZIYqb|mK9yZEJASN@`J2rAQ}pCNtkePRr$36gIVn3gPWCK##j zbf)0;h`vAE?Jv}UPqRDpAkx4tP&|ZD57Mu1j|ZwA2)VrFZtt6= z1Fg^!Q07*_IOKQjA2_$+B@k18!v{0d%D>wtoGJ3Yjp8-_T&bHrPZ6OBt z;Oc+VpC$@_xO_P~^h4-}YnT^Aj?+Z?m!xYLA)R>j_)Jft3{asTDd1i&EZqBPlogOa zu&;bLziBXT_I1;1uyHQ40b^Y}5EKF(aGhHYxhXQ!?bUc?ypyz%y0&bUP%gN@XgzEt z$amlG18h+4HpPd$UgIgVV1Ugqie=?IWb1lUKkIh*{%0AHkvMxf%cg1(33?7MCMa=W zs)#N^e|Qp%{?@;?|K$~IEHk-ESpH|^*xl+WO0iWc+=gjO^6?5A+hDj)i(i-Z0^zRXRU*J>vhTwPYN!L4;f=A zvmsX#y693?f?mp>9|`{xK-oQ3+EsFUP})#;UDJ3gju?q`obaoG^Q09xWeSE@!57y2c|gXzO3TZ6u!8qZC50?)kjSXUQ4MgS@~*HEXgw4$w< z>i~(|ZFu4n#y{`a@m6&Y%;FYiLAn?r{f*J(E=Xgtnf@QpA3 zxU)r2C}dW=^k590on7AG2*nybU|LDTjK=2*7M{~wUn(UzhsV!KG~S?2pQdDQT%jgR z>AHxeHQqJL`o3}#dt~LLY;*y0HQonlV&9-Q^2N^x$(2wp<1n#a@Q(DX3us_TP*V|@ z3xg^JKe&fRjrHJ{c-EFLe^|=coP?TJt#3GJQijSI+FAN@z>?bU8S&u~MveYR3diR7 z@9&u9k(Zl~C>*I)e?;@}PIsocnKEoQBTQ_*O4hdyUE%5KXsweM4Hq9lOfdj`O}bSf z-D7}0E)y1uuk@5)0+md{=nLm~z_(TR4+{{arHFLR6!zei3sbp1Y+Pz^spjA!XZ_)( z%@Ce0E#0FK$w|Mi2SY(oz^L?Z(6AF`ol^)yB!#_D!?_4h%+IGACwiJK~zIgI~5eI`F`sZ8V)yzuwwsRO>$hL;9~ zX({T{lZdG`(oNSVmx?aFNy>egQ&#&kikvN6;l*+p@hXNOl^APTW7G3v;&M#Fr&)mA z43%9DV^u8@IDx)FN`r@0ctMQR|9at;9q;maV25mqs@F0z zEca-DE~`KD=^r?_jd6@WidDU*RU)@?f9w~}Q~e1Qqx;EoI*qS%7Xx3eSX7ICIJ9O2uhKJHnj9a;ohtR&HWKF{jHgiP>{Y;6f?Ee>(TxO zDzV^{R`U_ueIBh3^82BFh_~hIaALBgk+19Jtj~wiB~lLNW>qey%AdipA=qfraeSrU zt2+~%AKw%#hAZXNUdDy;dkU5~p?G^%cRevn2}TR~w?f=RDd=h(hwC3U@m+5V2+jl* z4GRXe-HZ#+A~Cz-N+E<*Bw-vci^*Y?xE>^~lU)-CCM|=E8D!ghqkcumxxb6S0uuKZ z#egKBJpQ}iDBHxV(>aRNAL-o89^X}c$ZeA5pUq|cvfTM?q#a3G*Wdq}CV6MRAbR|(ZVn-RmOEFgnlGjr7F=bPxbsq=5Q(RaYQ6(Lb6 zzb3TcLor$$4}D&n_NKePwCBzsN6gQnf3tFCi|CVM3EA2xbNTZ^x>pvsDHli|SFIFu zC`eb{NVSd1m!7W>10=@NdrwnHLUQ3A)rOMw=ZVr` zx*Q1@h&VvtmS3@O2D+H(TK2k<9fUP%FGw$d;v`o%}*?$5#UXp3yiqn2@qJgi; zHn0Ag)8Y8Jow?=-jzZB&%{6TviE61IKH7aeevAqZecHo>NSEEgnJ$~0XPe=sN&cf= zy&f#jf`_khk#pL6NKf^sZ{O~F!

!{Oa7?EJi3jO(X3bzb9io-&5@%<3gHxd zVMSV(IQ68Cc}NIxG`{*gQmy?xsjelgj$~%#3R!c-IX){+^x~j(0<#SlWj97Q@M<&} z&=huN8pGN|Q4GjvlJdPe$LFQ*8HGh!3+UoB|n5>1ld| z0CD5M72RT!^Qk!nj>cqW^4~23zK)5Ykx<)R;@*>PRP%@9aN!_kg?eVckBf5H7P|@U z00!U3?eWDs&%JVY>@dugo^Z?(3`dvybE+!xJ%j2?B#QMw1Q&WH1Cpt$G*|b;w56Ej z5V_Hq`><(>>w)q79ifKY9t%{a`rc8n18i{TYDsw1WMCv83lci*VSjzNmTXDX8Fjb- zFV<={g_kPc;94MbPTU@iSret6;%b_CL1@EFP8QToIMLk8yks=DB$$?ebesos-3fTy zg`P)Dy)k-q&EcJG{)XRebNkqW>4Rn1YDIj!~^ei}Hn^E6AV7LryV-`sM)98by?0Ky^@NCPsyW> zDZltBS)=dKKwRujRtq(}qyHr9M#w5ewkOIp)ZATwrh+{p3|&F2N-llT%nnrnZrO&_ zr%l3#@%h4qsypDt8%qE;vw$D&snuK$FTINjltvVF#P^5eF4MBduITuHxo~Tpi)feZ zCAY9+=+OBJVJlvuvbAy$fJN1Vd&91jc(i<3IXxFGAL>fae{rTXt8czzm)%E3Q>BAt zd2&9?5)vmqm(g^Z>;v!V8)Cy;B2HX(iaQQoYG!bIB>7gp@^=LQV+@iM8>6(EufTie z+1tW_>UT$s_K-54Y;}u?W{inIFU~$iieXUorvt+_H%hsbS$S2~xinL@97BtVv;I~F zvr(GO(&VP^^>!%-8RddsbwHN}G^8sl2Vn(`rAsCdY7n;X2qub%3zzw>4xQTxNRd_< zpiT!yOAhN%0%MeaFi`&WD1v1F=y;6-7_~hKH?|v&bGD`t;sBJ#hiay$rU1jGZ(=0d z&ErtcP;j(4!jAT^l#m0ETEbQ@ch6V3q|psARqH-5wC5f@6`38S4VEB;Mtk|?IgDC)oD$Y7CB2IfU{p-ZLF#9_KVOvG0wx_{BGdDp&1)+MnKr8(% zg*7KuA+el0cv7vWk2LO{<1trdgHC_7$tcqnl2aAReu4FjmSJW;lFJqUp)5qJS+qu@ z4^LVM-N#IS@o%A@79eU5S4BJKC zsQ#J8;@g&U&Y9^o#G0gk!u=~S2@3C zZH^Om7Ot842pzIiJr*zd@pOEvflj&J?;9?RIwlf1SqvSVo~l|^1p{cwA$>U{6RG{; zNPF>Cy^j0#ZWY{JKR3!6!^~yRTKujFc+pK$3*IB9Bq(w}AH+ethNH-Zu;9b~sSwv? z)Vlf3l`YX=Ygl6<5>+f_G#Ce531Coj8S{fL;A|T2Dv6C@VxrOeff3Suod#r|9F>0= zXf%(mu6;*AcH$-f=-5wkPF6Q86V1iSLRg ztZm~ziy_Y=d8;Ua zo<39tjO!hL9m*kbmFQJWO2Is8sC*{q$d=NRoli7HH8XoH*x%QzS7&}`6z;~KmG!Rv z+ci*Ue9d+!-kRXkpsZW_O@4ivfjYxhKQR{V@dz8qR{ym4UsFgiL*}hMR}N2Th?YOh zvEk7(U{q|WS9miQ7629K;v=yhOICXNM3Z*$DwuK4{f7PZBF(E7OMGgG&g$_SxOfo@ z241CkPh(ge^bW>M3Xz^Rj9fp}$?EzzW zf)RMVad_$oWyT%AVG_TIEBA@8E;F6Rum%c9?tdY^M@aY-m<0xA_T=V9zaZFfp}`c< zpsdTd5o*IGAb()N=iyR!%m^|Wz2j#C1_4eA_^){jF0l7)Pqrw472Wq!bQH$y?9j{d zkvg}F-~&>SJ6fpROUWjnO9XPn_%c`{Pq#R6qMDx{z8$woo|;_SBBkYM04}~04M_cR zq2}dTN2-h_^m;~=bP++LC|`eSBuy!=^oLDnptV%2cqTBQm;F&eHVTV+ijgL2UFzT3 zpS&#(1F?|22h)N*G4`@^+nV9|&^&}~UobL;xGA$B9;{|AjW{AsKac9Ea7>8&S%L1v zS49%kShsnb?(>9`CZ+d&dY0YtWA=&?TInR&FE0M##&&CUg>s2mIzqCc1N6zuZk4qg zkq-o}*S@vVRMJlVngRNH-h3^*!HKMGyi;4#uy)VhQdmMu$yh$nCiHqA9M-N zx+zm)i&9QUqMO8AgbukI=yjtclbESCXeBP1 z-_0dpk0v476)}ctm>X7Q&14v323=R0JaMwp4wAc+mbNcD0k|9&CL;+uIkW8ea!4M$ z9bp+bTuMqB1tfuW8xIN0qQs}uYjRgq*oN|w4|-pi+kl;T47gVYCJ`|QKT76OLGeMo;~F!$VJ&%8Gw305~(Q9 zyXqmz_t*XBXn%pcoVA0RGOvGAGM39##W4Yprfbt?vRnGpN8U>#R=HEJNB7*d?6OYp zAWNk49**^qk{5v6Q>8T;wvi;wqkYW!Mhdh6WK0a5dAf4GBqnO|$k0jcNXSit$$C~4 zyGs~y`7mWn`9zewJf6CL>ub~8UL}c>$4?#eP-jn#DzK@wzOTX6)PEjc3=R0z)uWC~ za!;^TYX9@ZBLBSzWU|0~o!JV?pG;DNW_M?Ox666+&cA{NR>&S< zlPI0^Sed#2J&MlQ9J+JW-)2CHd>`J^-kJPNpVC6E1^0tYkDYm=MU>T`$dNHKsE_Za z5w>k(SImCW`Ett&6jJoN7%K^c(ir7x1u=i+{&||pk1+VpQd!|^>C~~ml++v#=h(@u z@S9g~XY<3ST8HA$bFQO)lhRNH-kqa+tV==?47|7f*M4*?0Z!u_OYOifvL$J_sbOB` zLCU~LA@A0C40B>5TW)98J6I8u>crw8cHL@P%m2|;EwNWuW1a-4;^K{bnKx-;GVk_W z-n;+?u)fQ36*12RH!MgsZm+ zIDiLxO9X#rprNhW`N&$EawVqHEo-QjjA>`IE0AmdTl8iiolt#h2eZmM04gZfF9=m0 zOr_7jgANgZrK?;z(#EC{c1FqiI_d9H)BLaIRlCfn^s9%t4sql+HPk*ocETnSxKoe> z+2vEz;u;OFf4hJdkVo}z5eH6+#i~__t4mflcbL+Q;eNPo2z;itf1f>1ZcBg!OTMtV_`*CVg#3s&xcwr zHuiqE4~^(ylK!#ivhH&R3&A{$H^R?}UVUKx2k56fBIad@c2_Irt#5d8EM>M~=Bh!r zX7i#ZWsh7+UjC~53yqD#n|nujHeQ9~zdUObMo@6Q_ufi*Ukp1*pcQ5EB$g|>`LFWw z{SjHPSnDK77d@o&gylo;*mW2RU)5^%0q&0N473|U&iaeoPW{p%2vv*L=R$lMBXo(Q zpnL`VQyb8fbEFlW!$6~4V-=PHPWbi=+X>+Tv{Kz2+5F8z?S)k>>WoAi93=OgotLBL zXm|y$Rup}j#)DSl<}vkxAfg_9WoOpcPkuZmq5wg`N3xutQ>hQ|WGb;4H=L?)xxQ|; z;tP@~R-Euh=xMab!pO4o*eZG}{TBNEW{4bcPi=t&VebT~K`G(W@5b)M( zM@;ch=JU<6O-pfOX95uje!#5t*FYV-Dqrypd9c3U)qN3ze7KtM;Zl@VP}mA8eS4Jo zh@s#{wR>v6xqEN`j5<7KTCfCUZDJk~*FZAqr^@Mi<;5KF2){e^Mx3oT4&)JIUWGvW z=0r6&m|hz*!^zU}2((K##0*jOyl^$%9T9y1Y8Y;Ml1@rZmVwb4h}Ksl)=5R5^ELm; zK>m46@Z}idaJ#y8bIEapP<`C85Vjd`P^h$$&D z+fKNLnlJZI{i9|k*1xUn{JQ)wZrQM*uXf%0# zE|@7D7!XI+DdIxUDMK>#pDhKe-B2vKR&vXM`Oep`O=6F4QOn3{BQ*rDN0CY?Mo@A0e9EmL%yKxa?EW&Vb!SdEPu+fpttcP45_Opdku6y$Mu!xdos=A;O?q42TF%d`x=IN2VR%G&*7CCerBHA2_w16?9pS&AY8EQWrGhQhY~nQ7@-vmVG?254-a#mRuSz!NO8iOUJy!aV5YL1482BV#k3rg zrC55O`HI+X4R@$=?VS($8Qarxr(kep?o@7XkQZL=vNVie+)k# zyFmfm$6dbU+ydhZ@4@pY_?-*_?Z7)f@)EjJ&|DY`3cQaAlcR9%KlVm;#n4=6zIHPp zos?Tyvwrg65c`}#*9L+mU8E4gXDwx%&#-C3*awr_(?;yY7nwcvV$pouDQ; z7vaK@$vb;j8c&t*mdM?B*lMAnD36fq;QKOh=K*9=c%0?8?w2nAFt4^=C9^%5pM!%Ny{R_?9$mo1Xo((uvt(-mSl(oNw=(ad`qKaN1)9u5_KbWG?q zB(l)~Q zlR^t?sdT7rdf=id*-oP{Q)f@GpZl|XYS%9rK4_tbT8&Nk;{E%o?{u3pOm2L;_(|sPKC7{HJk9pfaM;Yu(Y%*ooN)&3~1Qa&??3wBUw-R)^9ANYD{uAfeOlfkU#Sy z$0hkn#PKcE19I8!*cGS8@O2rQFqVmu?C%&8Dux-)Qo8^LnyP;b?zb2`_r~OG^Yi?C z19l8Cgz@m}!E;xfch{2b(R?4+83$mq(S+ww8T$5`&37z2Y=b`T1UK>0QpQY|`9h#Z z0A%IC^zBLH7Z5w_==)JT>|B!$nMDLZt>jT?bK7FG+N-3aT(>DVrNMU1O$u9n<7l_{0;_i_MxqFJ z(8z0G4R{xq2@{{5+P1WUy8PACxmtB{zy(5eeik!2JyIsIH_H`i|Bg_79e2txo75kg z4SDB=pONGi6XU)< ziW#iiS>ZdeKnUbDVcs!bRZdd@r6_<-)kbCNjNJD=GjZSW{b`c(?46n&zI0})2*;>V z+_$Vp^pgqYprtYysLI=fXG<}M$~cIaHOk_2Aji;|YNTtr)5u7Wt(_fM(?EPth}VbU zX1jV}E{sM|Cq53($80`+XK>qyrL*ehv*mtBH-}EoAHJ%So>|@y&`5bWjM|2A&9d2K z-OprKl|>}e8$n{3fER?3{BBGXfEx-SiiF3}6KUn%gXtRzCBh4-* zWefLbCcK!i#K=6Tk-!dK$*lD$&2edThL=wOMkA`3jXXy7AJ`VrgbHsf z1(ZHc@z}}-x$exd!y0`|I@b_nN3>y3#!>l(IcldfGA%9XFG>fw3Z4IDRe!^(J7HE- z0Bopc*dEGDhMEg4$Y7(!6nSX$fJ1hRs*V-U`w1j`T%j}TgX;3j9PlgmO?^s5aWxit{_I779ZCB5-7I93;Y1jD3Vu@# z>}^Cao*OPV>v>9ex0K#`0MP^p;{eRJ=&g09ap($O|6y@<;z}yS0(x++x??nRbdCOHg0_FHUN#D8(OK^xE0fngv~It;iuXH| zb+NM>7jd|S^#&-wM@RK9M*f_lX;Y&?CV2Hm1DGfoLMwlbM7hch(No0bila>zgjN`M zlaWkrk5S97{<{`=j5^P|a@CRxdEK4AOf_O$lpRWcA*fS?Y8B5{jbH`TZSnhO)Sc@| zMxQ&p^wH|sfeZkgdKR8ghaYGYoT}}(2*z|mgTew_9P|^6UZ~OCO_JrPXBb2A#Q93( zz4+DcC%7fRMHY@P=W&xg^yHq@+E&h6@Am}hfi+^e04*mP&JVjl`(rOHov(y>NW4&x zEG(O0!DDhNl`Hk_uaryrJa|8OH~V#WE;k&i-tf1hX`%%r1w~097lAPD36K;ub@F}j z&maw>=bpd+#_^Lza1*=@jwXS52-$!#6C;17Ma88>9%s3v<~GvTD^aI0l<_^X1p z7TRIv?f)Iki`<0fGcRniJPQZRY@5R?8+U)t2u@YrEp`R~$^jYIVF{4!XLHhg7WnvZ z$rKwgcBP=0H)X-w6}(=+C%mWWs!?!v6*q%b-sJvD(9Z>i%D9M$|6f{do1L%j34XG& z8X`HVO7fW<2#E#nD3IDcItQogn*ZJ2$dWleGbjT-c2mx}83PZ((~eK*ZY($jN_RJd4SOO6KgrstbekVW0u0?IaEqUa+d|{b$V?3n1bp z%*9W@hmAywAvi$rXV_5(@wmGy>{886#hL2rJH?(KqpZO%=8FM2!PX;cJ-DJr^iBeB zV?d2yw4gj6cO!g{(7NZ7v? z1Ae;Qz)e-y7{f`@k4^l)@Q*~;(E{r#46}EsL@Pq_m~mlwEr+kR5x`VU+rS2w88O9) zwWNZ6$N~;72ogNBa{uVLw5fHp6oZfSgOv$DEw6@l({+PD$9Y$<#2pn4HbzdT2EFEM z^`UA@KPpaWtF^5RZd{sxjie8Wo9VKZ*p<$k-WVEF?+AByj3}xzMjaGu44yz?mw2+F zUAHNJk*!0Yd)SwTA0`+a0P+uE7%iki*I_&*e9RcAgfN(rJvr(pu=F#wuyh*Y>rOtK zdB$meYVg^VwXoHa1Xi015U%Y8#4I58=RkK6cs;gfwP0Ogf0=#?sCO!9lQ@_K4M z{Nz&g-JqHGQOd9awu39U3mMG{0KPpmnQv_*&HmCWD+Ho;ec?aca1xbH0eB{`4xJie zN{v^H74C)tKI9`1j5>Zk6t*=n;%9 z&~6xRe#EeR7M|iQ8htXRhSiXw7jMPZJ;-?SCBNRj0ZTG?q;qT;%S?-TMw=h815pz) zx%p%O{sP(ow7c966ZrwjxyP!(sUwFhM=EO!>E>%KVCJ!esv;0&VsBh=HibJvI4Vj5zQu>tt$n6bPQw z^ZDMb#25SIBUb(fL1AKfBI%;%F-|U@2UEwgC-0deLu zz4%+?*@!Qdk-{>mhH9Qp+ekG`CS4D8g|)*{AWd-ucfW@xCo==yXY8!k!qs2}P;m`e zQX%y$(Sn7Gu?(+Zuc8Q5W%U1}JfHl=|Hr>FJ;E6D-`vYu#Q-OPQe3w4srP1U1T61YcOSisVKiwmG`Pbm7Pq5XKn zsJJ+ykw^Y4E0vM@jJie!4TV}0C$0u8|9x!0kob4`mwi7hANC3McflJo=?m4TtIsJ& zAy)s*1j~TdPr4y+)=GMmU*LAd;HBt1?O6LRZbRqj=CqnSYrdwY4U;SYWH!xI8=W3q z{?6|aHJ{Auciy{SgJioS4|m7S0#vn;8}tPK{tlE*XslRd?P&GKk422J!i6k#FOt(t zwf=W`97NSKPV7$VvKb~be-Lg;ZYY#;JTf}XRL$eRuSbL{Y!n9M483scWg$pm0G$t_(LO#ScwJVqRiqjdY!jfN-iwW3p# zuTBmOR+*FYVofNQq)B7f$4vcShDwL7X*Hiexw0+9e`6$vz}$&HGwJPNzi_@d;V3`= zWQ}In9@z~5DbWeHI$o&r6t51Cy^PrR)eqks9KbuV~S8=1ip$oqIDGJ|NFFevwaPz;ruon#;Y5{1#T$k;; zYIYN;lWn4{osswd{z(9{3S{TNYxSK!=MVxR*}>P`QSe=v@mt5LXmq#Y=sm&BO_t#tczO@ve4!l|Ya=sga%D-KCN z_P)B4yH?LS+x@XR`3YAJF+>}5RCc{wP|$XpP4m{00uZ#d^49cv9xI+7x`mkN;%hEo zA--q4098HJ0bHa4J6Jnd>f_4K+cG}Lk``VF|6@XNk%D$ZyDtdnLjjlux~wI)UGry7}iZ=8#-!umGbm z#2Qpoz|Mf63{1g_s&pM0tza%GK|7tq*2ImuE( zRHm5`f0-V!T-BkkhXc%jC%^@r8xC|DH(~KI(j{y(MXUriw*Cc=+^ce>Kt;EkZaD$Z z`=U-x<~kAB_zf}zx!j^UUt_LdZcB zaI54<(i-P8YzqY7TrB>}^5~e*5qD#hxC%90jj2)dS?antjhl9Zc514?zE|po~3gT5aZypdu&^NLz(~G}S)T@dS9*

    7H2I(HD|RjVpZx& z+%PgSgo|r>YLI6`8pF=kX!>+`nSs~r;5bXznHw%Y%hJaNl8(pPd!~nt9qt}!XNErP z>{O97(As$iR`qoCbYq&DTqEp>tA9%{ir+stX7~CzGdVkMyAw>cqS`%h#Kmcqd>1=9 zTxM`OeOLaA##}TZmq}$iklOC7wPT1{zC}&%?%8V^kHEJ_#)*wvj*MJ!(4h=cazXTJ z=ErFQ&JqYGCNZ@z6Mu5<1f5S5VOm=A8KzX)k?X-a^3JS+;U>h5+f4^mpM<=t<_R6U zLVSOjvnC%Zz%&4v?dEy*bQ;}4lOR`+y~(MB)Ogt>Q+3J|xsg1`9W?lz9{c^XbrW%w zF4;-?dpO+P#l1l>G$ibPFBE zy)o9&XY?uh`qy(3YiRb34wq{Iacy`Q`guv+Cws6FMG=#k8d0J?#>Ai1zP z)>S)axl~eCs5MYbR`^`W!~NZT&F)@7dTcol@Ox87DfeZeIupvTxp9>EtcuHeF_jpj zEM9@~x;u1?5hQ{IV2zN#=N?@bjXHg))};QtD75+eLk)_O7HIz4#`8UG)c7R`FD0KH z4CG6#j4_GOY@UD>;jZVc8(nQUa{yJig*fW}Irxc(SS~};AK4#~gAK_e*!T`@j4G#2 zeI2^b|3|sxYqKTV@G|J1Rih%Smjde~85%)_>lYhE$^s&vcg;S)MP+jeSpd`yRnDw_8W22!I9Z<4)wrtG`c?Z4|?Zz{nuOby(fLKD})`#)ys$PcZLV&<%W7gEj_nm;z3)ONQqk)uga_h zWj|X((6;;%VnC!D>T>UBp?}QAKg&2&`<~OCUAhuJhq@eBZk82c zsyH>3P%Vw)&X2R@T#6tiXg%TZ9@K1ZV`^wUAQiP2?r@b%HJ36FXA$G{?Lm#lY}jr> zHNumv{WfLbB>PqJY7;oo$pHzC-~vOsfQ^r8-owpDd<2=(m|ob`_&pC3dtFE@{U7(L z`7Sqgd3wxRN;y02lp8oxX7fUG9s8{m5MKq zlt;}gXE2?gR^!VxdwzZ11Aa)DN5O22@0ZDUSPUUmw|f0q+^Egg=rdH4^fjGv)`yU~ z_^#(ck~r=qUH~7o$|}>#h$=s%)Xu$-%T~L(VBZ%+^huD>t-}lH3NH9k0u;CXzs&`a zF+@GF>9u}hqohtG=cGm`6FvwZ>vCn`p@4|DM7=3k;vz}|Bj2-utot$*^krbmhUs=B zsE+XU+0brhR)fPOoE5dZh5egRRgk$RCY^8R2}p;?%O!4tjQ-xg4Z@c8!5|w5#T;LC zh&7UYuzaod@5L4WMSF8dh?swZNygqMNHPbp@yx-cA*RXU#qgQXrVI8LQaborYxAFu zcyj)ruuqG;ETyYoBiGbv{&Y7n&#QH0rgTMp?BVtKB- z&%XqT!D0?ETDU0;=uqU@*?AgQQDlCx8bdi#6V_)r$w_YE>Z~9SlLOPHH*;k1qe6Vf z92W+@3h7EN%#mU%#)nju4N6Dn12xfK=b4H>@u?r4iDSS#N<1;(9J%V?M_mFLvPo0k zAw?WP)m=ZL2+3J;ktR>s`K}RJ8m1xYZ)w3^U1RIrsj*m57QA}ddqDnCe53>{BHr%9 zR%dqIlofp=;6Q<>aYn4`Vu{aL*r1*$WAoy?>wj+BUs`X z^D?$Bfy~}UxZ}(uzJkHr(nvkbw6)X&rx(I0h~O|_A#IuJNFp{ zP2)js``4KI;s>cSpKa?lN~>!O4J~#2!;XAG+LH~y&bf$22XzZ?2|JY6;!)Cje{Mm6 z$;BN;Wmk0yFZE(OTiRy{@*aHsX_@{@0OJoM@ky7#$}R{9U@3-&RiT4;W3=lmKhrB= zS>GBpgq6z{`;THFXPw#?HvL`#4t4Xrq;M~0SbluhukFYjLEAylw2(y#iEs4rsLqz5 zd~&JF+RHj|+n|ASe4ooqojQBmLs}6qa+ZPyXg9BeD-MWcybG#{|I&VkL=(0cXG}SE zy03L3MG-!iXqn$I`7ZfM0yi^q@mq+gY>mVBq%_R z%|nrbwoWgKd!)gRU~gp0J?oiYv{%9OOM!Y1Y{&6H&2?j8 z^^e;s#E5@r%an3NW>-3YGk*}Ti_khg5?xcfY9hUikmC01>~{uq{A(OrAEr zk`p=6S#5h~jgW3_f`gb%%akxu>}nZ0gW%^6u742<)V{NAfwt9)zL z!Wp99bk!C3lK1@^D<82lhC;H42HQh|wSiy=k_fwWuXBnED~Hvl7L$tJO(x2i&)!vZ zii?^Q-3=ByY1{) zEJFg-pQ^>4_4~+_Oniu2tbcQ6P#!JT5XL6}56fWAy8X=dQU47o+9PU@t(TcK$3HEL zYZEn|Lr6)%Aihd*1pTtsi10(>OI+GI1)h?feB@^mp*h0NsYrBxf8)st#RdTy_S%Y( zfFQ796J4DQUXqRl3x^Cp3*|So>|`sVJ86;-D?xAEL=bgaXax#d0iy@%^Dts>9|;Bd zlrwFIIc1Mf0~5Vc^A> z3*~1V-+x6v5J}LQtuaeM@13DB{SJ}xOYAFOOo3&Xvc5C1%s?QHdCaA+2Xf;6|Jq_ zF|y8)_jyjRCd}ZzvvH_!C!IxX)MW5YF1Hv`5=eieC>rjHP z=e>1M@3m@u0^UN>#P5lOtPk?C-xF4 znW2RAJah?vl1jFem0q~(X1SKR9sPECL-CiI4~@Iz4_V8o^V(`<_KT{FffhCNqYVGy zq8ivxfW;)<@#r0FaQS_q@NT%xTxJ$BbSwHv=y}j0_;yT8UN;f68FoGGcEOk3Z(u7} zyNTIFD_sOob2e-Yq1vBzHLBHN3Cf(%Xa!6-MZ2i1fn$s$i7_MRN1~K`&&nI_p5fotx+-ZV(^p$@esJ}zGtl4|w#d!*g1P?c_Z>C$8Lx(-3h|7ZC`7qV$1EaZO5vfIze-4%%p-X=8vkM=YLp88YzHe! zylOAru}Eu#Xo8EPTzVd8n5A2Lb4cnHMD+q3Fby;SA{UF|r7zGujAJ!Whkzn8P-TvZ zngcXqgp4TJ{%!$03NnXTd@j#vxOx6#1@j|f1|LXCqId=1#c{Oyl*r?tIR#Br{qsvU zGrvVkFeoR(%(hiyYr4H7R*WWaB^+K$subJxS1d&CX#oA+x*V;2OtJPChI$_EzJ0Ih zA~1i~_Le^vKXD1H|6D`dLy)1<3gKP_A7d{}jZfPK+@4$V=7NY-?*!%UZN}t>oDnNAU7;Je=>Om)2oLUJN zZCpT}+W`;1k)t+;bWUMV1|)x$?Pj!dM&Q8((wAKdp*n~>XMIJsWlwTpzxz4R=Nj6G zP3q%W5no2T68q;@`m?M`PPx^SzKsIqTMT}y{e{8B#OZCPtUq@syF*r9YHrxDxRq9) z{W82aVroGv`z#!&h(o9uefg)X_y8lAU?FO_duN1MK^(`nbXq^rD7DtRtpo@bl4Ue- zjbot^?17FbQkh|gEsuJmU<9@F!5$1wV48i5nTc+>csbSs|-qt z>(g2k#a~rs4WT4Kyk&b-pL<+ z$fQBwa-V~kYIJGxb+__8P5HQ!i!L*_U-F6N;bC&(J1IGno(YYA3#cO+k8?kWiyg(p z)Y;J+iH!3uMrc{d!;o4ijp^RVwTl4|HM;jJk4vJhAa-#C5GrndochqrN6J=fm~w@$ z=V|d@TgdRLJUyU575pmu^O?cTDJPZ^?8P^=kFyCtXnc0u=mlLhx3#C(4ID`EdIq0` zGtIKymv70atiy=CHl)eXn5p(BEg3h?a~@|U3&uP(iIb5oKR0PC_LvuxOEXhIYye!g ze3fyrjLNV~x=arEHro~in2g7s3yhfXPgH$*n*5EF;VzGA78>Oj?)+=Nz)odIPQLGfGk8$4v;ovy$i~I=qKV=g!zEygVLu%=!2d% zB_w~YCco12&B_`iz=*e-k=Vt5{Aryt5wG7 z)wlJHd8Pgv{zE=jdd9bQo^dPWob$Excn_VNA& zZ0V=gr7-PKO<|QRWPI?qS|ytR*0(#_b*oI0mz_ftnW|$q?_6rF;<#ZTZQgLr3cK{6 zf5TY!ZZK46T-d>t(mkm}7PwgSowASmjVzM&V7d`5jhU;gQyRR!z(UzT-&JOdr~pDA zmPoo-;9RF2w@N>va;{9UU!)1bo|JZQ!9~ii{$nRAiy?E5(`mPx`5OW06`HRnix7s1 z<|cquJdj+TN7@pWxRY)=8E?QUAMMOF+T&QJBJf7FWxlAB?{;yd6@Csgl5Ft#Hxs$q z@WZ85S27UQ-?y){r#Jczc*4N`_u!9=jo^YB*}nbs^}eycTTDCeHCV&u0QH%v$<^Mr zaQ^;iT;zAda!LQZzi;OM*_|?3y!USnUA@%TIte#r9MRvi@ERbI;woy<6ncz3W+eLm z5%tw^O?T1%8>7phm2LrP=}-{ZKvKFxdXzLHA3&56Mz`RQE`gDQDIy9AI6z{QqTs** zDvXBT$LINef8Rg%+IHjIbI(2Z+;iUVknP>`Sju^6GR7NXd&zCYLe==X4}h;G3+o*e z9Ys^ud9Id43e>;Jz%n9*0sND7OEM4OeMB^tw=Q><38n`w$d$3I#faHWCu#j!?1d0Y zy{8JzOea|{$Qd$WSLbqj}ke&d6 z+?fK0?wnk3MbTEfFr%%=^2fMF%r&MzCc+2DN%m;APE0FNIqj+KPo?ZVEmLU^npHQf zUy-)h7#*tJLEFOcr9tSiddY$uYV)nTO5?X*TIx4*0bp=GLYVXHVo=DJpZuh-y@sy6 zbS%=H!7?Ppx~K8iaU)DU9f3O_pCf%h5wFkF1CFP?B{Z5S07rrNsc&3CJ7)6Ia#Wt^nXAFIz*9isfA;@J$dWLQh?4+Vi+!{d^J3gy3g-_7fL*vl22R^dW zPO8Z_{Q|V&w(zHRxF~n}2PcBge`Mc|e!C4bTy&Vs9uUT&3xrw1iYqG){2ng}a+!Q~ zMsM&n#p=+ddUIG?;Q%z2IwrgUNb!5-^B3Dx9+>UQ4dPV zN172I4yIere4e~7RCXU2(?LyZDbErQJd#)k zsR?w>6njgc6@|Fm;lCwkQxc94H~+B?KU*e?kVlzonrp})`i$hy14rCh?UGkLN|w)--QA%&$p_6X zGtND8I`A#j?jv?8WkPCS^q=rrCzva%_VbU>88JQSpg3W}I-n=IFeStzgTd?&S?{rf zZ1<-QmB|Sf!BnQfX{IZRFbkH{wArdxv$NM|zpwzHwj^MKC>i-}RJpn;>t!SFZFg~&FvWzPb-;P6e3})fgN!>TGg^1`87NQvlt|w z72g@}ghYO6hX({8@^SvW>U`dM&IZnl?e}lB0T{VH&Eo;cdfTGrt<-SQi7mhaep49b z!m@LdozJd!`dV_lQ(C7SZ$JAU)~7pn&P%|Aac$Lv_@>?2*;;C0S)DMQXg3NCGDvpQ zvqODqy4_C4lIv~Z{2AcUS@ebW*=Le(cf}MEJ4dhC<6x-ewvB>Y9?3v1HUNJ;VE63q zPOaBsX@HM*++DKLCq%{jJ1cF$s$Rq%-RkW007{(C@jhD99Z^hUfd9khAUaNV{$Z6E z3)CAK*X}j`Chu0-ntqu91FhP?CM=X^KCg%_whw+*2>-aj+3YuEA1fGdb-`%W>Q_9gmSwMe9n zOMp))yC+Cx=zyC*?(odIQo<{Z1)F2vJ7s%o1>eQ7*G~c~UPM)X{e|~a(rC2gA0N;P zZO{Pc3ko%c(?0F?aT z=H;I#npbvyJno2WN6MTK3GXzVn>)ExLO1|D{&pF#jzQ5ijR~oybs&X zqHvZKlRQ&7ViL>Fh>I%EaH~|u&%R_`c`Wu%KELO>oiU>hn|nhV(Z9CUetWh_M{Diw z%_rw}$x#(|FqMhrF9RCnk&|@^>QweNWcH=uCvc0kONC-|Y>k#*<`Tcj^+4Wv>1@V? zd6|3!{nWR;a$ZbqjzSsqW_K(^xfQ+2bFP+caJf_{eA>tPps&VN9$i2lYi_1i$pM^J z&eSt8C&41>*n&EV)X5Cs{5HuGTiJ^xD}4U?7u9<`F;2u7?FhFZKF<_YTbU2&byf+( z99#G2Fe@FA)UVcCWV87k)=xcng;#Z_k}O`@#1G=PeSE8lNAXioy9@1|W)YU99*|e~ zt(z%NdLZmtp)I{}hE%hRX5y81THih^hcpX<(dz202o|?XwHbZ|13Di_FR%~YpQ=9d z5Mc4)&{bz~r>(a6CpYl4+ROXX71$-@GPQ$K)PtoozsaUsE)?v}MyvApmA12mFmC6Q zTWC#Mdy2h~adptHU~4i8Ksv2JbtWVytjUhtDuw|g5Jr2xIA_Wz>o~UWekrP@xbAwp ztJIftEbIc=ofEX&l?fBx07`)OO$5-233;P{I%|8D8GuC z;HwhwK>@c#_~!Xri2~t9kg*Je(D{uLU%^BC&`XSj@6g**aZ-F(8eylJ`GfU98kHaC zAh!!T7zisp{;m|=gZbcv;?mLD9Dl)V)oJ6h6NB)kdU7Q(jWBB$$ijIiabh4}OKCFPcb@Q#euoj-$8-gLp^dS>sy1E4+cL;9M*mIWcW+|)Rv z1VPK$ZS@VkOsLPvBKX1XUlE!5f$hB!OGey+1X?q{ghjte)(_Daz4d=M#(&)-OdYwb zPGOC(qr)58kpq$hDK`gR0u4@iOXUg6>UsT%OxK8DXCG6bzw=wML>dQajz5F*IQKP(fblzgLdDAEcf)QtX4RMqzEOot>?xu$F##r*PP@$Dc@>J`oG$n1 zK%VpGx+0n-!|3-F7HpPwj!qr(v@M^%kt><+IKxglBZ&e)5*-J`7^nt(H;oydi{Y}z zhZY(u>_d9<5I9#+Xe9IP}2Jdo+T_i1{pOPE#87Jh`#Q%BQdmDF#-8o@0nq>u9 z0_c@Im`v*)?|%qT;)6`d)bft45^P)pO`Ts`wV!R9KC5o9yti*~-=_KSMG#Et-~QCW z+YkN`zPcJ!JVnCZ%+1A+^;4K0R!NA1HWoDAl8SZQiB@gu4a9JkCp%@|mIe?ls4%o$ zW>0m4FnXNpHV;NJ98@WQ2XD;zZ$+Z#B7fQZE+0!HkFd=aOtJ)Mi-qf&9D9eiQ&m`s z5dc@z5K0s}Ynt(xo_lL`p*K!y2tL0E&TaZh9#MlFxgJJ_7TP~Uyd^cETRLLeh<#A} zlM9%Bba2;<*8#&)L;>o$4v%AYM=ZxHlXcYU<4-7kfde@^RxP4lU zgg4_$M$yZYuwrt1#~=wz6dlBNzd0EiUqWcY4*GSSsI@BA)x#Ov$kdvE)aA=Q-`TK6 zWrBk`XOET|=<39?K?hb$=<2ZF_Oov`4~JXHS zxNcY6C0n#lL#Dc6y!+{dmLR7M$629>&km%ds^YK~~8_h2Jvej4X%1D)YT)4ZtX|AVrm|VX?IA|^6niB1yS}Q{z+ASTnyqaXjMNZ_G&@tPKC#1s|}O z%n-$FhtaUaukRzKWZ%+e?1xazD)2?xd?J-1DPtO39nyZOfqzn*>f+vgw$TI6IhL7o zM4oAkSSmJ^1vnS{BkntKmGQ>MNC5n%Js z7D*ErGDB29aixf0E-`7*qOZKLC0%e0GxVF~k#ukz*}X!pQ{b)dj8&I5tL;MzOsG=N75YfvSx85ly1o)m?~lqJPdx)#1{tK}Nlr zVc{aTpy7|+tK!&1msQ%_ygblgA1X*IxD#V0MxbyO$8o&15&S6Rt&7V!Dn>0=hl=KQ z-q{8nKl6Y8-W#inT#$UhPe?&k6uBHQ;cr?Er3Js{Aq1=4pC)=XGWI$g(R~bsv}U4q z*oJxgIzfSY%6xg7LaTu5L|@d)PUbmjyPZzHbr59#N|kXtuKB9P|d2 z5!w2Os}`8px0_%8n!16a+bZ>KRVX?H7a$ufEy`k5g-fctZiv+gSk>C%MOb=ICL!q; zW}I}J<;K=g$qn?Hgrk;3<-ESJxloyIRHbI!&o+Dqykt1JxY6kSdkv(@y#B>YSN`vG zLL*amgCSOP8lOqVemqo*_f$km4f^YfJ~!R2v53?Db4q1xf$K^wGp^2(H^mu4mlVsz zd>6Tgk5=2|)#S^u^^M3c%#mQsx19j9)imj=l!Nwci~pyh8%DGPUNTMtixTDv2SbwTw(f zvjBS;^({Vdd2^y~MWaNj$s=gIo^?x-j8=OQZPy;lMm1Vwg6^je$M(G9aOzfY&l<=m z-&~hdBv)Ej)JhQB1iS^j`lGhXWOik6CHxb<%MCeB8CG|!;n&RzXlX4CO`r%6YO|JYni%-a?t;27GY^aotJ9X@Y? z(C!FNJbuo<$6XgEv==A7ml`wR#25;VA5+ne^@Ob@{eD9m=o?xa!V@J&qr_@$iK~hF zv1RuNBfEU^+tn`aM~kpvdYK@$jiMJAw7*V^I95FOs*YE$fdRXl!Yc2oG1dmHhrp?I zBq2gwuizn}+m*>Gf>^mcc_WdH46QhGGahHqo>~z5%OVh`j(&7kPKeufykME}013L` z-n-MfRqyqnqO%OdrYcg!VivQHpz^4WGK^1g36)51N&n1f4Ax_d15nJjM1^K2st1ja z$?}P7XAiqo!$GL!eD}w&o~X#Gobqw)bulx3mf|(jRW?-9xGJ=_au)12I79Np_mj@h zJTEb)q6PMgzG@Ds>DFZ4xDdwq#KW2Jq4KBaNeGPVfUE<< z-l|6-lf3+fc4KZFV6IzLS(U;%34Z@^D^6io#@QR+pzjlzIZLwbm*r5ky+nBFb0dWR z>T0xDN$HLG(~iLy1@!INDJ=2#4|lpf{%V~o#hb@38=Mv#vvN<#LT1dgaCcz^`p4C% zCLs(BkQql8$X`~l5H}`D(L)L2Lf?_1=fo2%z3{=v1viGM&g~a6*`TK|90p}EGO0NM zx!|2CwYCR9QU)q+98oB_)?a9RAaM#vwW=%bmegtN&zip749BF33+dz?MC+DN*Od&b zbd#2YI+J++Hy2>EiW*a^-IZkqoU&0tuMZ0Z(cv92NyM)7V8TYt@ea;XPjHEs;0&_^ z2Sa?pD-cQNQ{tc;?npWRMGxSrBp-l8(mzpdS-_=eN{3e2#C)sl*5J-|t}NYAUC4!> znClUVsBi-nsF}^#$cQ^a1z*vLIh(F12$2kY_-nQcVzsb5O!65XVT%`!?_!x<1f4by z9|nLe>wjMNY61e!mC?v;5f=WYJ|Wd^1zM5M_qlqLbL$JpBc637KSGDR+$Xf7URzkr zEx(wdKzBg~%uYjP2@D2=RF;kEqlM zp4GgH_c4Mo&xe)xKMF6~>*%Q9<-pg$JQV2FJXe980{K?YvecW)mvU+zk6H^u3cwe9 zXM=?qAp<8(%89goM;)jkAkZ7GlTerv@%@M1Qj896!ZxO|_RRoyD_<+E_rv-oTSkZ8 zioHii>tEM=%q+edJ?$}nO?r*hKpp7cA6!v^;qnEV%jlH4hdZ;vZk*8^B2nJsP}Ym> zgHJ1NyjHMOBi^EUjm*8}x^bX3&Vgue-9Lgr?%DEex*=eCK>YX~Mi9FJ+RA6s_bS}c zU+_I0b96x%uj11$g2RP(9br

    }yll7MO8X0T~+`51W2eZBE3(_YXsjk=?Id$(B(F|rfb1$O=Hh#0hl#c=IU1CoB$G>EsOoE*b zO_)M!yHayZMCDgEFzznC6!k4)bY$8>*NI+-5V4g(WJoxR{H``N?a1$U z<>Uow!&WT}Y*r<03p=|G^NgCHlFTw+u)Kzs+n7_CHAaU+VvAHW`F7=ZwO0$=_E|bH zD&9J^PXfqQ7Wia;!gt;^r18znP$D-&?5iw+SB%{B=;BXyESP9z?}9g9gq9GjxO_rv zzZ8PI(8-KxVV7PW&jZRF)gGo*)6yu|m%rQ@q^XYtW;)kMnWKvd= z@Dbls?g)Q>0ogs*e=fFi2RQ(gw7n1&E7HXNXh;r~u@Y3D5<{!(P)1W0R_CN3g`*E{ z+{hFHs^IWq{Bw!V1&JoV)U~d|C-mgRL;{2eZ^9%yFmlq9s@vDrU0|4wt4-C8S64SU z;vUJ-zj&&DtgRW~g>YNl<4%dpH~&d^fa7TN>el#&xaEaW;fV^DY8|!CQEQqj2OqN4 zJ&e2$7pt3HnXPm^F?ViX3`$?iKym}2atG!<`2lG0v*Ll2N+U`Qk-7~nIrNI2Pma0! zoyO3#&6!F{_zHzYp=xH(&l>~;(Vji$S7-1elp(OG(9QL?@#RI(*pwLotds0wc-Pgp zg?Z*KhqG99^n{ccgOuItxkUbv3%pC4VazdO;7Cn$!tuDW;b%|T4lY)a>TZ>=4;Bl|Rq&zv|?y3mb=M$jfKAM!x zZ83es3SC)Fnn0cLyy^WC08<@uVdbi3q2h>30>Y+~LH)g#&ADPam0rt+zz3H|38*qo zJ!I-kp0~$p@bg7PD4r_IHrt+_)9qx)Eq&h*_o+gRQ{p{K23PN&3gE)(aue@o$jqYY z)Hd`?qZtUbvh+sriI4X!n)-`Yf`uUlA-1QZBrPB-g{A-xfVRh61K>ji%E0ACA>0uZ ztIDvGF7}O_+nNjY_PS!z`!$w%wNz!qt%T~}5gBK6-t-i01u@TCH()74s0^qX5f;1J z=m6M+%orhJw(8^9Rt)d%9cMeUm9_dM3Geq;WKPNEFvFb_WWM^ny)(CUKD`@D$j40g z?NPS|Ht^^1@!%V>X`jt3Z6eR{UWfzoWEKg#e^fMm zKYY|bQ71kqZEY@A7uR6fFUaMOPqjA|U{a-Ois=RU;g-&qG6$iVnBiVG^oB?$-^pd~vG6X{@4cUV zHr{x7s(MnKdmva~Pcu%dPzd-A=(OzjKng_QsHu7ks%N~MrJ5DgNY#-Cf^3+x=^6`z zFL*me`nV!q9G>>0C`vOp8p&RTUvm9Tx1@PPmrSiRcH#S4FTpSZcso?a6(q!kap={o zi(vRL(bNg_))C z`WVSK_2yf|{6Oin+u?0zzvGfqvX0{=4&R#PD(sFPK3|d`|16hw3Z;15#&4xP9K5~q z*B*zec9Y_6FVSwF6-|?c1jAPH_EcdbEId@uW2IKpq0=ZO}s{DY= z>H6B%%Jb4cxl~=Y-i)1}EYm7Ke3tCJmfoO56|Fn`t7A(UC-dS`M%OhlZzO6Ec^srz z+4?1dAI!~nb@j^>adT%Rs(a%U8-#XJ-4{t?`*QO~fULA!U?cIxz8leUZ&lp5h~S<9BDYBid zjz=k|jRYceV#6@Z2zaT%`CV!J@#&VmB!#6o+8Nz6cP(6zz+fiDm@ogaM+skor1jYk z)>`*=7J_x{{VI>KYW%iHEm5wT4-V`@=^(gJbL)rH(pEcs7OugtziG;s=gzP00wy$f z)d-irZ4mF9fQJrVs%B&BP?u_DZhi3Um!)%LaVYmrG;F8zmFNUf zv-W_{gn2bULd1uovtwtxuCLNCMKymewwr@=Jre-F;5EA<$Z)E^3&PM$ ze8iF=x3|16pAe_JcveEO4?l5NbD}*3FmDx(qlu!z*_Pcqy!*$|N#@uMQ=IZt_QrRS ztYy$(xqOidllKe>_&@5a+@G8#^<3!M`Vl}Lk0xoO&Nf&=X72Q8n$W6g| z^Lgf-T1y^P_r0&NxGfhuIx(*E(*oiO_82qJJnxw3vFF3>9ROPa+yaYU!}tw;^&5{~ zg(Fd69u-c*q!6IQ%}zgcjlzsS_D&jti#GZN>ZD@`D~oL2SyMl0j$n$t4y2`6Q)0Q1 zB%*t~%tGb#D@J4{kblnGhG8Sv`>=C2U0n^cim#cwk2?VL#M-p)pYbqKw2s-mBn3dP zvckwZLdO+yHWIoz5%zCM3fKy<46l$a1C^Te1b77v-1@C`Oh*+e;U}1WNd((M@u*pI z^KvoNcBZFtii*|K{lfO4+Eb8k`eLm8soFUt!s`9O^|9IjS;{9w^?06*OgE4kNaAK) zL-5vcbIDfS2FGe2G*8BkWtYa`rTV41xfOVi8%<0wK=)R2oF@|AYKb`wnaN-tX%CbFF*1qh zM|t$8)wHSui`2bByx8X3@8ACMW5o*|VC>T}&)lVd?T0|1!#+4){uL<=rH@Hm<;F3c zsiSthEpbe*uhNIVYFP=%Ic2T?F{7%u8;W;54d7yFF|MK!}D6t-*m0Uf`i|4_F9Q&@k$6~HQT1e&;`q%x3HhkE0TnS zY^U6iHev;61@6|^qVpTCv;q_!o-Y$N9on>=VK|%Py!gC?@JYPj;y%_NIsS9~71B`@ zd2GCYSzB>jQvB%VqV-qnvq?Wp{M#SBi-W`zZ_?*?R4@zP3t>WBlcXp*YUg&8R-_w` zTSMXqOx*HP=rOh`Zb#>P%HGRA2^oTz`mdEl3Mf&6wRU&;en04g?Qf@A?S9VhU74U!raTsubba!)zUv zK4RR?rAl8>#k+2X6+#w@P1wtVSaX64l4y(A!E(i8~TKFf)WAvXr#H}@5dU$R%}jN!bdmFF|xf1yM0w+ z+hc-Dkp7bM4!vTU2yLG2`&5HfHpYvgVe!NY^c3AEk{t~HcC+|YO9jvQK0rrMo$hCz zYUZS3Q`k&sU!Q9*p2u&W0zk8^;AIi?b?4t5mfX2c`55&c*<1ib9~^|5Xg)ADGDdSL z<$2T1f=_SbHgtst(N3NSbv#c8rieI?fBfYk?yIh5-qKV*tPds0z4whR$_{)ka;6?^ z^XLTX>DIix{tB&0e_Cvw@i425su6GaT@~Muwcxln^i(jWL5F@TXPn#$qZ4=TD1M@l zOneG)=pv(@iU1ul?6SdT?;Sm8lWkY2iz9_$eeE>+StZFoXO2$Hi1~2Z8!QyFQ{v?} zwxc9|AF|hF>W$6Txr*;u*+mmJkOPa~)wK=hfV{ud4%a@>7ES^pHRRilKaMfy0;~uM z4?P+PPyt;2P*_ZCOWxl8m01b!Pi?Uu3j3d4r^ExBqTRTYNQ~DExn_4MR-mrqYdr%n zuR@dn;L3Iap0z+c*BD*(LnbK9!MGhdEcHtn8|_YRp)Ca#53&0)N4kMUj52uNyNT$S zU#3;cl$_}4dWD4#(|*K?qwhG})*sjE*%rY_4{%#&MTubUvs*XJZcI&b<4YhS-!lcw zwGc~(TXc4tIvpW>UF-hHZI#cHVU<-TQfNiKPHFoWLn#^%d!tP| zgp9Y)ZsygmHgrmfR93CYPDo{9r1I3EJRg zQT7SrXALMO{uz{_lyZMVqb4%a{m}r;dnxRf>{HTHpq6qic;t$hmF|_s>}B7+@2<(H zjrf-I!#&CDQ-vJj?A$VsQpR|WQ~WG=3*;o+$=$m|(ncG%onc(Z9_n?*!KJ86we({v z__^-bg8;%Rd*rf)<8L}%Z~ikPw9Qo&->%wf@x;x7@Yn?!>k@HwH4WPCQk@lYCD6-e zZRVZf9*O)9Q`DTrWc4iB2tIb>9Z&{dEFbJR%=$4$oW1>XsvO_oIG5hL?K`;nmPx0+ zY|DGESAFt81wmoE1!y~TcXkM8-DeQ?)9?cWuNT@k1|cJAD2JF8k+OrBIg%kd&humq zU2tvV7b44+-H>wmCXl+mO?(;uBOA-*pw@g{4t#TBGQ7T!{1D3FX7PdE!+*+5ie`7I zTE`S4Wnt13?nK$Z_A+52y|HnTlsHAo+}F>jjcLzX5NJ~PO^0Lzht(_!M)23EPf8yv zd{iE}THn@(0-mH~;Hms^z`3YbYhI+&`a*$f_m9lLxel&MmxV~D%`>;0f8I%JOE&k! zoDFy(zO-`;u%jAa;*k9kc zLA+tEUWDLJ>C3V!4ciF$gZ&B%Sa~=^n1f>hkAd@u0!9U@c+pRsJc0FgqS~%iL!&id zw;DDp&yBM8MgR}KE%8U3YSyG?J8Sap3roxWIX`&I)Fz#d%VejkYeP{gzd6E_{!0c{ z0sHmlfP(R_4I81QEhRJY53v!DT~EBj!5uV4_2b+*{88gZG$1cOY_L0pS>+!w&XZi) zk?k6M5sA}8M1w-Y!At^E2vHg$$zvFVxQrIYaa;3`f@=pp-fx1bB+t>Rr*l`uiPKk7 zz;d9&A}L?fKWAN=cWn9ar~4#>L;(xWi>R1%Dw!PoYT{))sz&@ru!Vmt1F z1m9fcL2qyzj9!87jLxY_ZGL;>;uRy`*$l9u8~kDrdTW+v2aKqKC38tCC!tI*G!*@T zWIyfu*~@>m(G;!CL)UmmWot1b4rHgha-Wywz1QoVIMI{@V`vm_IPZ`VF7yq@&pQgT zV98*MFcy4Co|0p2O1}6BM}HkK6lRO1f#K~(&CuS|^X7;a3j3MuolIg6{Nl=7#rfod+(i@jG)U(WK7 z%7k4x5>i(zkFvBI6c?uvW`Sc+sI~CA%Jex4tM+#eBp5)Nm@6X{p>!mdfU}IeDiVl1F9!u@lRQJCXnT6 zQoJl;rR@_k`>t2(ULQ;nZh;4Sb4BZCUhc&`DQ?A7=Fwmo)y-qdxs{TZ;~v$^a|J#l zLhL@O=tn_u8c0jwkM_;<{RJImUN>NLumz!U-3%j~RQ%9iJNF0F+KFNdrn>5Ah#Nu) zcF$_GRXQ#!ecgF#8ThnGoL%nQp9gOd6%=q@Z$sEr<2(Ig5PV!5wtE#-RoAt!j4HU! zHVh5lc29ToH`Wi?5WLwfKNFD3AE8|{`|UgbXhWl2o{%{A#XieZr#y_%zL{Z&qVv(q zf9mEWv2lJ+djTRrH>70FUN}H_wMi=7l|JU298)+pF=mSQOC_mRJ`yZ561&H0F;6w} zZf0Ig*m=d`RUuzR!*TTB695`{6seFKLb7Hv=w-9c=y2P8fNSo{5v|O83@{HokK*!# zs%u^9yIs<}F=K$Y0tZO(<<~FLNSMJn#Pf(kKL(ze8F_+BLi(z^<}^Z;rGx8CEdu!K z-XC0gUTEBt`bU~AXZ$GX)h-Nn0boo^Yv2)C<8PAJPijyZF97FBtKj zpkm^k)-wfizxv(On6>1eOo)Ul?jKsRSI$L6+a`B)Uq2LUeTHf=FFiFfw*7>`lI-x2 z>8KMZQBC_qQn+k_+jb}mq%9U=Uhn$IrL~!K^?fxYN-eL)({OD}amlW3C`U^BW`o9$W)2kajK4fk+w_3mZ;u)G*wfab(R| z7Vx8z5cVDn>vd+n89(5DB8ji~`Qs6(6uT0Ckh6JEYS-xh^gsz59P+S*Pm$&@`qOxr zS6((i)NyR7Xt&_l^-X5*L&vb#=Jpn{x4g9#!8n+_u$;1g>>jvjCNZ-Tia3(x84wgdc2;N0M+~D1*i44XFyX z+$SJn`t~k4Y8 zuOVL#gpSj*bzqlAu&5_!zlR4HsEo-uY+JwXKBtB|?OD<@SP8xo0hN3QvYft0!CH#p z=orr31mxSe0#sa{yk%|CS5Be`Y-g@va>*BMcaqx$iRzx6ReAEOHGBc3wMdG-5h-)!O~ zd?zWOtpp4Q4x&Pc#jZbf79SwM7X?dE5~Hkeg=4@5sRQr4B_CuK~LKF668Md%Di}z z(i+z1zA-8pm97B2Ukd7oc|7pKgJK;8F!3^>{;_fp8BFGp=?2{J8-N>LfI`41?`G_N1=>^qAyhU(r z|GY3Ry!G)3w*EfbXPO}$+)Wg$Rtd5|F9Irf3UH%&rZs&Cpkfs0jN~LZu9`S2!M%EoH2K*GNNpj7%1ljajDzkg6c@s zLg_4=VV9d*LpKTUbM`93y(F+PQPOuTk)6k z@NpJ2$`K$04ux*q*H#t=P^iT9eqYxWAVAHWPJ)9+t}0!(hT+DuPanl*?^!w9;e2(y z2AJZ@_>Z`pSi~iXtRB>uKHx#@6b&p5+NcaHVXbez9~RNyQ_BMbYWa{zG@D$?REQO_ zoQ;&le39>R54jEcOhw|2J$Tp+IgCd!2s)GjV~-X*ONRbK^{NO}W%cW#jiK5s`^jrmxamF40`3ld0j%#Y>-&`Xz6eXhCl4BB7s>b zSWhC&M>j;!>IQbb$Bl#R60%;7N0gAf_$tW+o^lQe67GI74qjgJHIlwpuM!-7TW9T2 zNAI}Jx;h9^w3H`FBbevxagG?v;Lfusv(60{SS+7~ zIs*eAAq02y#xMSdn_|;@fZXOKGAwT|VmtmdHbNpC1o@$0HbWE=;$jZ4)aHVzP|d|B zM&6wJ-&}y{n*!4-I|&CPe_$J8u=uoZKUc-xa=UIo#G%Is;Gl~Y2xM*bnJ~RI0t8e( z04IMs5LwBDhba|y<%2xI3b=^bu7E5l>d%T@b=KIol9^%uoEMp6Pgf>zZ zQ3KUHj{wuMJQvH*DzvM!T2?ef=&Ffd$sRw{9sX&;ffvb&ozM#3CeH+Ail(L~Pb#4| z$j`NGuQ2Y*(9AjD?({&sUydI8>qlKX)B$q9pEN*c><699e)mb#P3%Yu4T4et(~qa(!tLt)?O3H>vX1Wf$d*usJ{LI4-}YJQBp{S@Bvo%J&2dMk8W$;V4JkfLsK z<2}}0Mw#VNGBFQoSGCqtc@YbVzJoL9fp9RNLE}AzSehg6&m8!)7R0;7^BDBjHQw=? z&|2ty>1X4n@SzEd|4QSgG+$oU!4(9-jqc)XAjO}_ap~Jd*c;etWYwX`yK#~nwy|fe zHUW{4mTtwEn}oP3R3DpMLT^xf7AfO$%--vh(c{tXzTSPUJIj3L4C&=?dGkd? zqTPXjz>EF^DJdjv*fQm!WAx%Z{V;6UliOBCj{+Y|OGHgs+hH}#Qe5_m``|dI@u)>=77P6G#;QOJ+NMN~_nGf{_ zx2@bfL3S2xzwhTZYBJBg_}O-S{fhIv?1X8`mj@@IC``*xyI{3`2K3=&2a5x?JvEUE%b~aCj*XmR?yW2!+;&bMsJ@&1@~vNY zO2Wi{v{8|pB>LAvh8AW&6`UZW0;L%&Sm2)bK(1NF7{{mCWR}H0IU5LPXtZFa|B*_x@Vj6FNJ;f0 zT^N!QT~DCYe0vXs^owh6zNf>oB7u@jD0QVA5+EPA8X;b%v?VR_+8BI7MrW{Kh*JmJ z3{$p@&kniKYMhDiBq^-Ml&N9S@PG#=4{-H6ePT}<=f_3Lq%QF#O=A95ljc3a>Is$= zsAgT(IsjmcSVe)ylO%*#UD|8u?rU=_g-$r`wy$IZovsZtLRft8aMpV!>?7pc zpY7J>(|FdoI}k<=ByYp@$5S0-FoLsI@0?l$iy4 z(SUhUdMS(rp*1N0K3Gl;%w7G*o?~242vLGC`B&|RTDdxTLw}scdtr)7^wRFCI za=19*FkL3;vd?SMSF8#O72)9grTUZskt$);W)_cSN=ndLh!1Fxh( zFi)=hjc{JRBx!2+MaiCrT#6@jf>7h$8%JHa4woWt)K`)0hW~0)l8$-bRZPFguz1f0 zA9W?L64j?aVEnF@_3wtOPDp#wgmr-f9DVu#`PRR!rB>i5ANDt|s9Oc(P_yCG16AsM|hLT*)X zwBjR8;un513gW-}f;#avNhD!NcJWwcb*b$oupE^YFZaOQ8K^i=#RL$Dt!{t?=-Kdo-KsXr!J!YuWF`>S{2!cxxegQ`^Aig&BORcdy0m?LoV1npa zPE3CQHD3~FI=tam0rcdkYm^K6Zrcnux---Rq2WsccW|8{qyl;BaDRGYdYyouN@pxI z0WBBPM>7LS%o2PJQwjS5fBPSet~Wk75^s$b9OO&7{IJ2DjNYVlKU%R)HiTVc1XN-W zCH$|b9>WK7rp-|L#$*-Qdtlg8^XQh#TGTG~ordvXL3IlFy#>nak46%(B&6`a%1t@v z2?U=WI2To+^??3O=sJB8<*(s^`#!)EpYrM!&0#O9;``riKv_hjNU*DWaj=8I0_C4J zujYV(Xc_wel&3mvem>f(^^0vuqiVWhVJz=~S)1>SykpF~8aQyw8)a&zxc9$8w z0Wu<6E>g`msTYrL5?U(%yHnXi&?}%taDQ_n9{`!Sk`>|$b9)2~JJ0LyUy$V>1)#c{ zKJkmFa}(ePQdb5H+>U&|V*}LXqMv+I1V+Im??Vwm3+Q?ZSk;|TC}hWUl?iF|0kAB5 z^mO=kq-EU3c2F%{e2h@pVz9~Iar4~z`wtjX!c&MQuOEi?ts=zs|?mnEhtHTgw*2gFDf zD^56nxkd~0aa{N7Uww{eN~nG~a`kOUK8hh2IBKYe-jS|hll>ge$?Kl(v|$M{-W!%5upRi|Tc$`q+;toD_bcH0A#Z1<)f=gf?FNA9&XG-#`zf4b%a{D`KQC*oFnr@! z{WRxz<&dHEA>g!4%OO3+{(q-R45zfa(}E7*Mw*|rYDnc$mp%LcYuL9IFsU#mK`v?l z4kvyNi8r43zcKYck_4Ami6Zx7a7U{GFyM04Sq@Y+{m*P782rf8l2Ls^L~02zC#XM5 z8FeQNAcy|nG5h`i#w-Z%St#N@|A=`)?6v5Y3J3i=AHJk7EHt~+Nbal-svB3%B?H6P zvnbyKr9A&N%}3t?)GF{1Twn-r09b)66C&)vP=Dk~q4b}yvJ3^WYgzI(I87lxhy>$L zn#Ek@#uuq9tN$YqptSe){dq_3Im$!cx_C?Wm1{`Je^>k8RZ!9)vnRuggY2@<`Ynw2 z0K>gdY=B$qN&Mf=YoPH49tZ_zbu-yhNwbPCgokgGdhKhzXHo}Hy+;d_1~>~J|9$-= z9ig*9DV6RBVdq&H$)m7ASHQdj-2k5ad3YRaoF6{z`+2PPyJ3>&$kACL{DiA#jsCx1 zIL|x2BB4g_JDvPqT=Avunad}ZEF7vI`EFZl|DEU~9e4t_7P6TQHl6u?H#Ekd-w$W)=*e30q>se_HTr)d>iT+thoH}WsE7!px&j0*!$Z% zLjV0H;lat|)#Z*AAH?zEiUDwoF-PF56y4N$90`ztE(d=`q)31JF-orSj|JvcV zj31glUl?*b$lcTO&Q6-VCtjeoeD72falj=E`+qcDcRbbK|G#z!Es>e5tSEb2Lb#XA zY#Al{8f9EuJLqRTBw%Dj`aT}Nzj@qy-{*bK>%7Ku zSP>o`9spq)yPH_7cF!fz*aznIg^y`~yUF8YGjnbFWD)H%aIE&@%XZjvBBx;ew2y!F zws&axQEsTK7wB5eEU*3z%Zm&_7B5pVxtZ00ovH!V6gwkKlpJu zyzX>~_S@Xg_Vix~Iz_k-FF(p`Eur{Zszm+ol?=qutDL5eid9E)jOk)4Sj7IjRv*gb z^wWjxfSe8f-#Ud`h!F49R$z8`-%(xQ%{JUdr=}iY*x!A+MeMjxL?h$LeFxQDj#0t77!YK^~4H^xxrFco# z|LuJ4_(x14uH{lMq#4Os+m6#8V172ph3J4! zY1bRroJ1fYTeUEl&xAPmZ zlc?LZ#zDLDap%z~ArP)RlMrjHdxd4FF7u zyvUJkpoY+J7Uc~(9?b^p7AWrJ9in#X|}OghLy3JqT=f zAvyGSFIK>W(3BULV6+VU#oD_tVeg5bL{%KWj53TTMK$k?PU4Gy*U-cR6m)iT^5NE7 z5414GRRo%^o^eL4kGe@*Ko39y-Puc|2Ou7_-T(R?AlglzVGcMY)YwCPdXrrBTt{MB z3@UeWMIb}BrUA+ZWZJD}g)=+LCX9&>aYY<8^Xy`v00rAa=s%_L;|sudM&(23>AQ@F zFp@FolNQ{@bJ4cb{?YL^9X55MiDKdtTY3Q+rDs}AOUjSI(U8p+K|=1)Ug11?J4DsP zr+?))J4LA{WKiy)4>10N(O~R}zm1~f7(doE|4$B7_!s~8>((gX9zE-O`mmEajz>ji zdoF6@xf&x+2PiM)tbNSXEq?-slRMUGBf~^K2>quISWP;oC~<#1x5ZspXHCfBejH^41E5+CS7!o=tN$1$An)(6{ol)gho27> z0(b*oK?cA2BVqE;grsFZRRqrgsTRY|NcJ)2_#X7yvat&RV&*BKR3erCX5)`V{%9ur zt1VkF0`RYg3I?eC%Ubt)Q;61Bzy5z8o(Mj?zy)PR?x-h(fU%`b_zl3kwv@t#GezG( zUM|=fo91qbheZWuFtvQ5rvK}~d=>^v2_ZMoq|?qot~C?%ekbYdyr6H{>D7@e3{0Yg zcAS1wOW+8g`PbImANxf#$D6(kfeUTrtNgs6vl#|_UIxz7b&t2(k?ve_WtkE^H#;rj z;_Sjq&QH6**`aF`8#w7u5& zcygq+&R#b5o7}ZFKx;~43J-tVkc{k5q2t?ks;mEdrk42H6!_XE&}90SIO zSs58^{6EdFK}W>EsT_t%APppkV*(&cC_vy3Iv`AS%Q@3(T zH;2MR(;{h+M&Sh9=%NHjlG;5`=Vw0%X(}?>YLh7Z>=HpjWFtD{uYa&OFPD_vw`X|V zP}Z}uIHp-M=Mx4^nI(TvEKil$n%Obh^4ikaUfh-2OUOw88n8f8l@8!ZMSC*m%Hm;Y z-I<0X50|2Qnnzr4b9(WYwl1B*V`l5pl2`U7p z9F9Z0O(GpQ2a6ugt^nz2(N>!aR6MqxUdZvkrdX&(zxM)%_m6muF%g^8a%J6p{+XD z-BDYC7HQq?k>yvPpZSo4FlG6Zqn?m7vPFFJuX2Gco+eAtbOUsXr5_i02FyV{^L;r} ztT`avkOmL-GTy%1lKWwa6q!d%-zq~hI3l~KJh=J(S3Jc)_^%hYAH;opW zG*DCCeFPpf7%_1A@H`OTmM##UX0VR?GB{O{k)x4iIii}nU>OTSv>cum3P= zfqNo*cN~Wc(BY5>VdOIw>G(kxMP{^0&_Q9Qb3jhg$rPdDg6T4+j@c|Cf zpbA-#;h6o9Cqpezg@7<5;TOrivLGrYf9wrfWX0PsRu>&<`uWqy8-`aLmFmdW5@Z5+ zHvTG{?!!@GfSW3k>OrInZq!(DCL8U$u3rAI9?P%NM)QnhPe~taMPl-4wO%QRA?2QQ z(K#%J>G^*rV`7YW9?8H*Qx&Wi?{{Txc0ihDR_|asXrgKT#I`l_n8r@+-Y|y;*4m)m zM1g~9(qMbx%$hM6F}X6^5ojZBky5~pJ`aH40kjW;WSTo@)eXbJ@P)4H;^H7j0`A=} zE|>Xp-7Jn@sD;G0Th5y((b_`XhzP&fk{Fx=-l|V(CqBYC#r~lCMpH7DCjuhD1!r;W zOj3JIbS^+h6%^h$(0cK!nf*J1UxQJ&Q3acSooXAb-I1y)4VDwNIw2e1#n$| z%_a;{Z7?&bf)=Bwj35D(sHmVzWZopPj^$O=*#jcH6Z&8xFSSv9`5Ez$|7DfUktJy- zkZGtU)?T*ctV3Q~*F0`6Np^wdGAP~hTmh|k2DROaaGAs2L*F zh&{Y`U-5w_D@n^)7g}^RVubCyvoco9Hi6eGMvv5nHMyKS-cjc|v|a5#er&dSc|Vzw ziT(<5j_gW~Nf#96F3l}kKD7_jAiR{Uwm*u|!fLww{P2x9@0e>YDDPQImwJ%Q5WR3! ztpknM^>3eJ^GA{e!D;aPvVchh+@K4<8Uj%~QI6xnu%VeGmvvh74qK{{B8{v zpkW$CVE`wn>ZAc4hIFAJ;48$4hLwi(LdS2WV*Yt*ItHyb3+?i*`3633~@|sufuSYg7z|SL_k(+u& zqPm{&p?+5e7h@MI7q1D_SZ={?q_xYQkmd=VVgTb98KtwKLnau<`VQz%P$$d2U#J@? zOB|cVPMb!tMHrL($vh&yUTRNZQ3egC%X0f`Kp56-VFB8!!E=XAQ~usX<01P72`u=tRig^7gM6kXXtU^S=d3v;X`7 zA;qIv^u*30M|p{^tN$@-iDLJA2Qy%#R+g)ch-TS^%DG=U=9Kk<+{*md7LQ9c=wn+DAnxMclK+ndh5$U~rCb^T6Wp^t2goMdVbSQ9Gbk=C|(}Juk=*IH+c2&Lfp5fE^NKq5vu%Dz!yN!AoQpH&Q#H-+K7OOpkB-E0 ztW(u~%$&C9?boG+hpH}Ir0>7w3dBXbIA#Sr4vL7Bt<{Ig*Ma($iEl9azS42fQ_a>h z`dm`_idKy*;pqKl=6x-=mbB|-@@Ps(Xv}v4leEac`NS5su)mj$SO`L0TI+?eTciW4 zcGv~=Q$NR?I;r{S614OAo;6r8=%1Fp@=e|!qk02+4>G%F?F)_x3yX44J{tf|$%iET z>tj%kL`?j+^rB>)j-%3kiQbJZiMdXt*S@@V#|ro zwmTV>ED7!Id=wUCt+5!xQwzGF;j1b+9y1P zQnoZzKEOc>hBhT>*}l~@szBm2KOo+y%Q?y4YVoHY}fJ6^NCDLJ!~KQ(udb# z<+JdE-Aiintw~jXP846NcKZGe(uS8uQ z0&@U|6wBR6{+2|AZ2kt%`7n9#>LQ@+`)x(IHV06i?i1Hu1%SZQXjk^^61X5t-lqygKec zjIBaM;-O~)t}kgk$UWp3<4`dnk&7JfUa(NTFxIk6G~A+rQQLCrW(pk<2GyEmkjBBppS-bs9gUG@BRpWFZ@KHqB; z%ELqXcAw)$C-|>|Q*#e>X%^w~ezI=sMT4j>z^R!Dkd00y2W# z->P{rRie<5Kk;}ZLqajiKEqdB0#6f?K{3GW1$LWbl`$2V6*xyi1H_0no0J`My!?fD z7rXEFrdkx7)T(f5LkVU?6gt^!+=csI*JyXT#^})A;%gOOcPxDi)7W&LrQGY6N~a30 z8^B^?GoghUH(SAr6>Vd-wX*o;fcA|(*YaOD!QhY+5L{m+0xk@?@eQh;R9N1hhW!qL zhn9r>_sMKPeoN7mT56os9=0+kQleTb_QS_PPMo}zXzh2+dN2{UlQ{T}Lt1L7I)w3s zyr5%c>1M=LuN7SYNaK`$OPB}1o~z^PL@xW=Q655^gB5o+4=#JnH&-?6V6VMF*%K;# zQ2^kvmD%dM!$A-hYtRolbCi2X`)3q{O0&k_hhponFrg9BN8-Q)zsR}SYgU%!8gye) zNa@Js7oezkG?sU9_wK5SAypo}(-^uobhC`YXjq$$J4w5qgmcBPe&MdTU%1nLZN;w- z{Cgf4LCGO%PXEEGC-j1@(bVc?>@ba?%>KRw`eX$P z`3%KiIbN(5b&Z>o)#)5w@faWYrED!=yC<1KYkpm?Fl&yEbK0o`AOA{&^^hx65qVkI zmPmaDh;PbW<0CT`HT(vucWv(vb^e7h2iK^V=4K1itlrRTYFFl~g=Ib!a75vX0PL)nf0w041$P2q-laP%v&_ztWAqQZ%b$i3kP+uQ5ry*2r>SG6Z>+9GJv2B@1qB z%^f6ssy6(B{ymgHxX;MKIe0o)z8^Prk95`le2D!-dG%PK?puj`_|n2n**0$5+oV-& zHQ!yXo1{K0^-AzZ6%C{RIvv!IkYI3C{i}+HKOTuDj#^_%uWd%_ZPXO&(N2n9*{e#s z6sx0MaNw)Ih9HEeTSAJw@LI;uX7aHC=?Q0iQB#NnaztyaHxaC+6RSSzuy0kgZNnCgq3xRBHMyYNEm)JfK!T3mVnbF@!az@G zg1Q7m1{Yy)WBBR%Zvd@q33m}~oe7-Xp-gau&z5y^Y__ZUW z+QE46D$Cm_SrGYdIQIM`IBbRnf44B5g`s`=sj0ZwH+7p1vT<~yWG6XLe<ocZy<r)?oBl#Rk!cfDS0G`bE=()@BqopTug zFQix8P@pFNV&5%RXVa<8-!nA{5Im@lxrg2noqc8h6(x;*fVqTCN9)?Z+mUmrKj$hz z{-Brtn>3!sm_dlGldAQrh|$#1y$BHlJPdA98&C|QsL_R%{P%Ez)1buSUdJBTY4X_@ za=9n05wiYo)gGl!3{g+_O@dCZ@i?H&KLVwz?r)~*7Xr~!MYbDuS|9?c+LDa=rXQe$ zU5Z%dB)*AQDl@k@U5`@ENKq-Wf1~on!a2RMzRj(6&f}Ms;qwy5zu;*ZsUU}9GuB_} z&R{$^H|QT@UsBkUz?=*jO`@cgdT8~_z1u@eAqKL*LnXaI8(Lpf|08PexqT0HWp;M6 zv+QF(XMCHh-cM^$yta);0@!Nz((I~^Fz33xt(@~wO$5eT9RN}E76$?&yAyeWyB*lM zC8d0y-*aFG6ni3rE^bf18Y{m}EE+E2*5kZL-!BnPjtO^AL_$PWEi9yB3h~7#>kFgx zj^1ZW=O&|?fdWtHDkR)?^~Kk8OeFk#U>t-DK|Y8t)y$fny74&Oh_AxxsGVUS=yR4{ zrxE8$p*NONQ_C^+zrEUgpN-76R{Na3ML*Um^UhM=r4OB$anVQ^=@2IqNv0cJV5n&C| z5*~h&ln-;*%J1j4aqP96v%T|5#kwMVW3O5WUn0Id@zULU_8i$kIWUDXj*eSevvxR7 zLskrYSeoch>jScCS|-DZJEZ9DsGFo{kt1``GVu#>e(!_S)HQquxa#BzN5Fo1oFWSS z_8~Hx6zPxsYEF9POD5B{0jd3GGWJ&5wMmLJ$L+Xij^o!jF0>;JQWIxy_xfYqE9r-o z){0i8CEW-ksF={QpXBUqvcb5(L)y>O2Y3K{)L;99@G^Z~OUYiGrZl49YLz3|zW(ev z`a8!tj=H2^K)+K24i7zlUEK%@az4p_*dsAVyvtMNmEIh5tVZ5GS6+MWQT;cyb~L5S zWF7p*+cAx^XL)um1_%Yn2XHLGhzdBzR392%$Q#Q>({o?JM;Sj@Bi=Myc|P@#({9ss&|B_H^1}3}qnN z_xhe=;;L~JO_Za?=he~M^DA>6e>mU{9f4YqW>-~kLv0cO4SVL2#GcF_qj2I~9Not7 z&|_T9fdiRu!D#p=szcW1W?ViQFt_|!Ecz0P@waRit!Go7MET`<9B|KiFV}VcI8VG@ z9-D2Q}Ia1s_0P;g}T<|6q)~7#)ekoE#)lA+$j8srR>kD{{JkE4w?f4H%>x# zu=l-eoW+O$)lPTn&6sZ~TpfNwPwhD~V5T|#S#RoCZg3kkcUw{vzJ7~y67t1F6^--8 zJz8D(7P-L5MAjvlgB14#C2(<7`DY1cPn0kUlAfJ!xIwsm63ZLd@dQs$#i>lSr>!IV#5!VRha5mTw^JJo>lQm^xvQI{p#I!4Ky-)q z;rRaM9~Y)y_B4!R<;ig(x%7PY52b@cVkv1^Zwp{i90i(yjPl?JFI8!a@n4>~HcWcn zT`fX@9~f|ck%O}FZ3Fm6QQ_hpU88Ns)drxwuQl{19_vJhr;oA@x6GC247lGxSQ;@O z@~+HId48S9+&68xRlG_K+@|?`&3#<=?ISTF@3<5Gy-x?jVci!OZ-n=(1(}UgN@^eD zL>o~=D$Uw4X=5O?4wgKRDB{wXBq|0kIcs{ipLI^kyug9e0(mTx4CJo+!EJJbQecsY z(Z0aCVr#SL$1lVL@RE8BkZUb1CKghhmCaZDE7Hx_X#@cZhvQ2oB#v>Q#gIqW`$zD- zH)lsiw{U5*yuSYGp&psO<4!}=Wa5+IKup2XPZy|5Cy37$8e{*y+fj2l;Ry`=ckf17 z>%9&j^4(1>{QH_r2$q)~-Ui&C;ZC&bP$?-pMA@^Co&;%oBwPNh&az&;+ma6}7*#jr-bcbc* z*$7#kNl0gdawyJB_x=EP~@Jl+GbtiNPQVhLCFdv@GP=>mqI1Rqy z@~b4%%Hq^D&E>j^#jkkYYFlZqmpK3Ab3c&ftWv3q^OH0|V?6)PbxT#Lwp`W%Y>K;| z@fyRiaeIE1RKivd46VM#iql~SUGZe>Y_YYz=uzzIZ87DhDGDLJZDbg9D27nD*y6s4 zGZ}W9I?T<}%{ zl06oWZ7jg)!3QqqGgMdHAPPw11a) zGWLafA6zraSQBhxIZhRG32lriD(${ROwO74!v;#&qn()PbL!8_AKI)!7;WiWUXSMi z`ZdjWrl{LHAx4YAktqw2}bc7lXU7 zVw?YNWif6P(^ndOPJZy#N67$dtkbKYWE>O?EINby`uM&F*e@NtmD%=XIA=d@0a0jN6wQl<{05+uf%L;@0Sj4T#x< zq``|2h6JDM%u%`|8+cmiiB7cd^ z4wfHaPw2>?S-E~~o!{j;{FzbsgLMYrD6l2(Vm|A#*(cx+Ic)4f0n=+sZE36Vrc4nn z1#pGnku^HumbTYxUm^H(r>g3Fwu^!O&8d zm!KBvIJF4|l{X_hEb!5ke%C0b(28E7&K-f|EsNF5YMvMnH}Sb*Wx3NMT9+w{8WHQ_ zB2cEB(NAOXKp?om7*i~%X8lXX#TBk4JN?JNvR7b@?$7OZO{aq~zm~)@5GFT5j2ia# zU=%4GIN~dH73auqfW^KaN7r#A0%L5(Rb9htYj{GS`I|@$Y+ib!%#sF$HTQY+ne)s6 z+|CG0b-xzaPLF{K%*FG|#!?AkhkUj?Dsf{Mb33&HnFb}g4!k;>?&|pF4*ot8=j;Fi z1bE$u;|Zm1!M>c%NFZ$6KL)1$F}b3S(|?SyCSq1;z1q0;=Y5t>+XZ){f`!snSwU#! z?CSi{gZqfYGx|I5shn-;r1Izjvx3{RMMMU-kK_Lxh$xQK_fTIFmpQx6Z&tJhz_i+~ z02;{H#g@ul0sj}cXdr}RnevN7y22XYB8-IaE657oR(rM@l#T0XR{c~)9Lp`95t#d{ z+^l-+d4;CGi~4}5|Mur)Ussi)_=9Lh4Qp#TLgN1ZQEB z!tI}oMoHo3`DTr0coK0Zu!)zA{B?IC|M+?R$cuk&^}&g%4=RH(tKn$3AmiC^vhTJ{ z8u(^5_`;KwyxpDHC_{A7iT{pz;}lKoRPn;aXvgo=;V0L^GQ2xvpXN$~=pDWS`R0~z z@AP_62!Ic>=a!8r<+#BXl6kLqonF^#b!~cJVZmE6$Oy)b*02d7i^r&RiYa>-W((z_ zH@m9jTyeGv(esirK&VI%M|geTRTH6Y;e_ zy8?J+1h|lPXgkW~@^1KMsiXbeQ3A8#qU@?%WdWUM@g+QmaQIGgxpcn5``meNNgBKi z3Folrm<+L5nH-WWi?M@~3phOA=xn)Q{n8tuW!JhAVU)AFVFEG}iqyD!=Mx7x*`>Uf zUw)?U`1(V?xCu%`MKkQKnQ_5dO-aYti$XGThb*DRndoO{nFI8LuLf+5-e64Lx)9)h z$+d}xcD+q(K#L!SRLFBiKCcogc<9XZ<@iK=R*LA0PtToADT7V+GotnRnlhRzeVW4!3FHYl%u=773fk4oZlio4sJ4zZ*}l!bBD<6mXjr zy!Np2nIT^VXJAVIj?yjC3UPWQ=1!IbW*cm>E}rTO(~tEqyohMGQd2`U0o%;Y=GDn> zItQ3EqXePh0V!}w9!`bwx!obv#gh`Wz}(O?t%bh!q8F2`GM_|wMU=V+KXbs2+AUIP zunABy{sxa@&|>UwA}HV<?HB7r?SiB zqa`;K{e6DqSs6wgnVGsFSXp&z37lSfMZA6NAh`-9ziBr$0t4R=9B1Ylts7t2vbZZ+ z3Ow+=w>~rfeb)eRiWe&#y-aPlm4$=9g`N$~w7liRNE$s!z}h>BByDBkQbem5q!|y- zg;rx6#4mZf@c=iWi3!kxOnr2*X!nYD3%_|+l%nO#_X60BvIUmU_rnq z&JjM$nqH6+BSTO$MbvS>n^GK^g0eq?bqSz7L_=OlvM*)Zs~y%0VOVV<^p)Bu!AXHw zc5EYet@L`}>`=XP3DcCAgn{5*P9cK@a{r-lMTaYAo3!#}sB7X>v4*f5-gz&O_#4~L z6Hx;wT!LOGUou-X;X>79yKz<$Ijd1p11r>aAEY8x|LSPlR@}o^LVY(z-xm@E;+>?I z{D(VQdUEhwpohc7vwa)hqe*|)G1k z0#8}@PU>4%iJlx>U>FzKsWz4?Dd-t)4Z?~|a5_v1>TkLuGuH~&qB^WnU*Mv){AV-V z{jpnlxF>M+4JD>1LrGk-s$2(-m2u{d#!4RDACn3G4a?-yHA<7QlruF43Alz>s~>Kd z^O)vmEkU1uskPsfvOuInB!?erMbTt9kj$L9*%~70%dVO^9&!Nr(e`FXG56Z)1au`COLuMtb|_^&1LQRanYrs!2a$9j}4QOJqm@f zIC(gr%bDB;5m(q#D>&$tE#s9WkLFQ~(eg{VX*0P>Kg$HP7EGL;E6KRy`c9JFk4BVW! zxBJjS{bLkR)hphQB_A^b@wXyhZGngxb6i7bd`qq+!+sE)Z7oW&d~S^`B7RF+QTsdL_l35l?Cq4r=`l={}t z-2HTl(^-DM8u#Q8(~y^AEp3Emz^Q;Ev!1hPN*cWDl{Mvo%cXa$Kn(K7D-XTC|LVGG zjRzvZHk7|jsHTy~{yv|5cJGE=QYI_5flzJ*(ZJ0{*yHlwj2|CG7xNXh; zQ8@7$M3)1BBUjV&LCO)KGNM9L=?p50jScN>TRSKx0JY|_5%lk@&53BDnjP-@c zJ6J6@-q0F*Kr{er=PLqb=1W$635Qo#X4SSe5! zlE=n6Zll0dT5cURdyhOLP)=}2muO&cwDbGZ{j1r`{h+V@9YaLx&@Zk}oT2+PwRB$C zwowh8l%ue?k(mO36KT3&4f!rrZAYULF$>aO5vwHskq8{TS3DM&%Nes6(B94Em}ht4 z{z}(O)@;p)$wX6Pd{409yf-NSj|EVOYj8Cv^69%kZ2uSM3}^e7KX^Gf+8YOF3l2S) z{}mg--tvVynH&E8{;P0|3Bl>}Z{S}PBt@1=?oa8u_F|(?H=H~21JxgaT%kwslTY&l z8_<_dJ^aKoz{#qn$XQ7UUP4Pwvff5@p@`JJMyO=}mf+a06@)h`fRan+b#jC-v>-Q= zeVwiO9wKZ(B73uL|F7EA#>vhllIq6=xC7^JdQE-gN6kS8T$MiC_UA@|R6srpOu1r ziKjm}9rAX>paI+Duo>$q2p?09-PT?ul*|iB{{;e232Z<_H_u@;7>xS(cgo@dMVlNU zO~u{34%@bROyMVfzhYvq$QfJRKkexC5MIYJ`Ff79OK*`sG5F2~zGhsKQcn23N$8>8!tscA z`hM*#kd1SWcSA`nH_1fm!B0GqNpmezuEWjCp+$a>?}*|vd6Y8r0sK6*N=1h>$`~J} zQf3jDIW6Y9a=ZuYss~AxqW#g_Dav?Xh%SLI?#i92-ur1w_AYeruZ9!Oq^96V;-Z)y zsYQC7?sb8{5T|NjDaXV#X3I=<@@;VPgxJv(^)Xw!bpz#=&d#3T(huR6AO7`@jV3mM zmgh>bDF0H+ncYOnd4&Hx)I{&Y_&Yf(nu+0}9W^xFV0hfXJVEQeb*k*ZfE;VBVFMc0 z`m!l_O=Sm$DCdc<{?yu|I&HxN_Vt^*uIz4)X2pqbgy-o&o?66S5qspRmL=7eU*WNw zg7cmPa^TW;PD71JWZ-r!`KnepfPJX|cgIPjNtGv&5(Xb(?LPiPIA z?1`4pBRmlVRq{*a;TdC2PSX_$ycY8$!(nPTzH7-^p0*9*@vm|9mf}C*R9C7!XpZ-& zKjOD=C^1$)+AmTuC!IWEO18^AH(MVa;^Z`Eo2&FR^-z=4Ym8qgI-0|rr|F&$KwfyW zXxJcM)@MHcovykTx^0&Khbns5nsprsiTtyI=kUi>J;A9XW*DVMF)f!x6}xE;VBukp zO(!ZKKG^b`ruu555$XZSxO$Jz`;T$T@S~+;vmA!Iw6$X0MyH8J{OzEyZXCObn*&uM>O7ROD`_}$4ZizVsl~MdA>D^HIwtXn}Qa` zDK}mlF$)!9khDzS0n>I2kDqK9-{iFVkvtD?h zw$BS|Ey7*}OOU(HSzb~6j$4o~u?1HN!hW`VSiw10H1HBN7sroY@$Df$&*-fw8pmv7 zW?mlM9MW<7Ge=y@stnsOT|Pl}=@+O~0>5%W1r0=(n9HZ^cTp}Qn4TKn z@#&PUo9gzP>VtoXqWA?_#SeoLbPn=qjyXPAL$b_{f7a;823u0(^Wd(7U@+Vj9zItHIM9tT>|1Z6*7}36)&5+ z;}?ZTytoZWRhG@D5MA<5-)`_2JR2v99gf*8_*jdhwUmjmKR4E;ODSHkivEt`rWaV% z=YRF4yj{#w6JKdiQ$-WGmfapd_CESV#pApSJRnjJ*u@oA_h_P>2)jp4@TxzJWkx!R zsRrnyfAiAdaj|!s0WnGTjkka%D+TI8)_0I(x7<3MsyT>N_)8f}XVAw!O`Y zu$v22PgSuVp?ba{Kc_HwK1$bT6{9ub8?&yu>e5EHq}q!3$zK4*lK)$qCD?+yfmQD< zt-GWZO{PlWr9+IMwEJ7Xf_G^htxb`oGUPksnq;aeV(mWIY5e}YmRpnR_}!ITIPU>B zUm1W=K|&4SQ0X??+mgtdOs2!Vp1GYjz8vGG!@xCLwh?NnxYn9S&@d!f0qL>=ROtZf z8;5Umq{a}nl{g{#@f$M}eBTj_aTwH3Zc47(H8F4peX=D%aq?|$yfv}G7v7iaZ+TZf z%Z2L|^E|v%i^{G+YSkv=Hn2;DkEdUxqLkhh$oC6vXEs2E*9jQG<|B5Ax1q0w>woOc zjYCBqkE!dn_M zt*;Ycq;L2RxZ3gA^Sx7ULYiYN2OfYA=RF%l=4IDN_e7l~g`C82hm%jFbt9yk4bYKb zI~ZV{nj;0b$8Nkkv+g>v+bo$-YekT>eITs%hzA zJR8Bi^LMQc_d%_K7CC;*?=|=E5~*{wu?rLh_bWNo&prG(%@h(}H6YxY5H3Q59E`P_ zl3w&p+gi$LVYc!dk)w3#$_^Wsh`>5_=PQSorNKnIF^TB=w~g+rdH?7DH=}P);dLU`}Xn4>e{B%qHpk>a>PxJ}}Qmn2(bn#GKrKGhZNXXOun@aKc0Qmg|_ z=buOpodE3!`;ZLWBf;e+pAA`}DJTFKmZ_CjNY;zdW77ep@Z~y$sb%H!X_`O7We{?J zR&5@x`245)s2x?}={E)=EqdtljK&$zTl=aftF=f)_s7SRLs~Vo|Db7L;s=?12xr^w zYl^(EJ}>r3lV|q}@o$*kw{=!@T6S!G7|=7TnFCBDJhJ5P0@8_5^V-s}q_fDkXtIlJ zQol{^l_g5@H2`UqU!lZ7tb6>?CGY4WE~=?i_fd*<}?i zu|%fRGP`{%2kz}LTnXHMuJ1kp+1cw-r%-di98@ua@dUT!P#j?%8ax|DE;ASpX~ckO z7H9ST%gkTj4a`NT%)-aQobvPWT%(31AfTX(;DsB!>bt+uFn zaPtY|FD#bUgH6(!-CC@Q8*vMnGrHoYg$=r?P6wtUTkUEGo}(e3+i=3B(Lhb6xi(VT z>#?Ne&xaP92cA;Oc%gg*dB{DHw-w z;scfyM+;h;5?7Yo0NQ_DH33H`YNs`i( zHS1@ZpVq4;44QWgEvE*E2BJq&$jb!W7(@LPFVxR-#QVfTqJk*lBP*`zIY)}O;a!f& zD@(?pb7TXNf3;;F93oLB^`RvYg|`tke&xuXb9pK2haaB6xUS11dw*O4U|M7W^7Rww zOUO^(i4XDh{IX4Sf5Q4n@e9?OxHP=r`QBxX?f|A1v@Q-n^M(PVG@3f$)Uaer`ajaM z99Vtn_DjI>2+?5@(JJ`U3!0mu>mSm=DZl;_HuN- z8rx_B2o*7uahST|Z_&uLKAm!y2LI0;|LDxEqXV_2$oUT36%*N{W#gA)j|QllIQrW3 zlvy%N%Hn4%=HiH(|ARx#c4TtG+4yFulHKM|{CSMh5(m-5O2c3a%&(GTFF$>hLx<1` z)h;&gsw<1*K3Q;ZcNhl#(CVx%Wj=_l2W z*dS{3dR?lQRD7+X4P6^Bz<9+9Zo<=yQ7nf6E;QeZ8Eb8XWhR4kH(9;jASKAoz|zw0 z$)`)R%cs-jVl*_BCK&YArU|eZY_;gN*dc#FGbI}l9r~PHK9&$68*rhlaOp0#9mwmH z0WQm%RYr9#=qX&1Ltb)(rH-?dW=aciEUAyL5J4Wl63q!BGNv163i{viti!KRmxk1R;Ni18pjqEcWeFh`7 zTn{<3m0=zkc|xLZO;hlrP=~`kEn6+36EyX&c6!=&UXw-0xh}fjT8|J zoA|+;K=eSOwX2JW9&16|Vnji&PZAgW7yZBX05X zptuO(0m^aKg>=hCxs_%2H<4p(`iu&Y8GL4MSJioGwgO`;LIC1R0)Y}d0h`BHU6_Ys-JR|I9{xnr z1Ac5g*>;4YJ=-e#M5QInW+#zdLXs3IUu=E^tDGqiC~JVg*7{x?vvY zx_!r+30J+kErqMBp6;(zwdT%x9@8T(^!V?^)}-i%$TPHX?%Fc?_ ziqGBmiNOdapWApZp-Og6Xgx$&qsU0m_-AdgwGkLEW^Y1GAQ@j(KqX zmCPR(0#ss?FC_F4&L^7>$w>Z6KF*=!k7<6TKEXA7=Av^h$b+73bGi=S2E;vuA9sk` z_|XRF8vrPpp!&n(XVmw^nk{2o7yb<8e9gu^%Ny(#If}ESY}s1qSbNMQ2d#{CTu2El zp^He;=2%KG;VNffM=hg-z*e!1J`6v||$XD2Y0`8T%)fiB974-bWt)u+bmSpV4 z_T8v~HW*Ml2)*Aw5wsYKA=Bcy3<6d|CjovIb5IU1hVbJ#S63~~3H|0EBMaVi+UrZ`Ac0x3$WDGLa;S{CN$dq+r#uA1GMPnJu@AUQk`8)s2b-ma7zUO|P z^StMI&z$qzH<;gi&GX0AiN>;n8WW^mJXeX!?yHjO6%%* z6vjAJSeV_YLl@5x5VR)oZn@spI`gOP%kg`q@H)nxY!Qq5QK9IDgnWs!isNI#$%wvF zD^fncwRvUeffUQk^uW{Mj8ICQuFlug+1y-QOcs;aGXR^lErg5g>3Q+ z+CJIhR!Ek0U4N;GdA&s?=AYx%o$!dcKpk|d=75`-(9!RD7cFM9B*sk2h#LMRd;&?T z!!;+QHhHeSgc@PgKX=Q0aqMox6080PaX7YpeR-XgNcClTy0i?jP?Zgl)n`wy9EV#5 zaotb6PTC&|`N6yG_o1;vAZAs)qfs?lGv!H@yj{1#rGY{2m0JJ>RcWbL^(?MS`3!$C z)lT268^_sxA;7D-0P6$~3~9_~IN3_h8&p*Xr9HJoMMvM56arwGuk&sS>nsFS=i9H& zuoOAxl?{2!B4Zd$RnctuJ389EYCm^fg9VY2WDl&C3=C$?%P1Vy1DYoYN%cpNrixne$zTMov)T^5zbw=FqRV7u1t zLLR{EP7J*Zsqte~W=(CCjI}JG$EvD)xs{M9)8Y;6_EF;B@q71yWks9FzztV%k=h*{ zT1-#hdz{;O-F^XM8T#S(VZp#@10kLE{EG$(pL8nkg5)QGhNJT>LNN%&p#jfNn=~7{ zG+Ho^#PB3zmoI*S>8Xj>>j1p={8bBP*CowcKRJuAQQ)yCEPYAjH?i>NnEY)R{vLK& zI|1q98+V(sTp>~9JTlv0_Vs60$aIl8n}GziO!G>Crjwni>?@UkgYZK0v2*0Wtjggy z@|4xMbJNX=Xgra~_!Lb2u6&QtJvzaqQ?%3=D4DM?=Be>Hb}Kl39Y`g%d< zc=fFKW)(65<(`ZQf8BP8{LnL9#$Sf61vj&Z)mpKqSz09#q7G4?jBTWnvtvKs9{=)a zC$mcRHG6-oW!Zx1^ea2NsW&KU7{ z{3~|)JFu##@q?@OF*dUx$SC7iSZp?1&89G%WwUdT;;MFa`9TL;351!OHLYyu9e0Z+ z@s#lbdZz8FZIJJgkT6qc^8)Oy=;aF8cx7GOP_=Aq?Qz38whD>Ww-v8+Dcx4o;8T#Y##ag@v=)!>^6@h&oiXe#0u`*itEYm z`ji(p8Ec5|Vd!ImI|`!oayu@Qi?-Y}iIB4z=|MY3HZ;S%q8!&U8AQc<9#oK!M;kF& zV(Ba~_Bz{s=T}6J%;n01GW8s>G3{K+FJM0VqY8t5@_dee6Jy48JG4#o`$Pv!D!hXDdg9wfJe!4>T8b=JsjG3;! z;Ohoc2`Jo53}5}a$V-DWE^ehfkT(oWX6>PFYBduSERLpx?IZfLbb;EL#cQvpS21-} z(x#>n`vTl)AG3a1h+l5svv!x?{Rg|3_e*V#EgiNp{~Q0EvO*BYd=0gx;)>aOPW;CCq*oc%0TCjBnsh= zmv^#m*ok|Mwu?1cW`5A!s>RM(M^IM_S=Mv*7G@)1eP3PWwtAUn^VgRa5AEdF9oZWG zvSUW+y;6Y=<}i>Fz5b9Us(YDSn0%{V2r%|%9rCIi)71-4#vbG%ny;E{*?N_~ksbeN z+oScOHL@twu{fQpc=VUy+;lmn-Cf^Ah~QM#w&GG5l`~(xhsPx@RscWx>xww4`7GQOiS>HZ3|)A@A;3F_f2fjcSCMLX^ZmP5~( zm)84=zs$DHXbz`gnHs!4S&Yktk$V(tgBwDTDXRXQg;5(3A$7ssE97LKue5h z_=mi`FgtdBijOc{8ZYSD48no2tM(dKi;Aegj*P{O4ysZ5pK5k&o&g1<0;?kuCJvSz3eIN_kBNk9U-b^LfT(;cJInJ7Q=dsyhd`0L8*_KF=+Hy!@){_o=!>~BPE zT8B?09^(kVwER8o?$2qj9j#M7EPu`^8>5bTNL0F(Ls0NRFQ6%rOehSVt$eRIe!c;UH4;pRfgoL#|a-bFEwN-C& z&Ahv5WbSey;Ir1+>WKlKT-#Ktf!zICdAfy{9c|4y@xu$C0yFEP+5JzD$H_1rtWnR# zh%4DFD8-!3ZJ0}ueX{#af>^jmpa!RRW7O2zdmpcov12|=xgxXt@m!TfwZZRMYJ78F z`3?`9f#+T}y_!7zl(X z7;bXjzD~p6u*YKjJD@7B^75$i`&33cWEoc^I~#H>)f2>B#E4_-zEX@$yQ_ixB=3GE zm%on46E2!=qB??CF9hWL4)+oSH&dl2TzFp%N0J|^dB=&< zC_rjMy~!M@A~|EW;jW2^)l2`$c^;rD2ytJ3Qx9*c(S7@xAJ5wU z$7^OiACRJ+DcB8|Cnj-UFr3aUF+I1xhcGA9As}!B-f|@7;PkD3@clTB3F(0DE2@dd zP6DzYnWZ!Lhd`Aakl|0r%$LL*1HWn!3`E>_ROUDfs$e`?l#wxg0Mfqie0b}jQVCH7 zi*y*$_1VyveWM=t>pq2!gJE+h;$h=5C14IGc;OTGcXRBA~ zzY8<6L2xg z%6iWYpU|@$2G2HKBm@Lxt;xE82GZd557OZtwND%v>lZNpc3VjLX?O?JgQqDfC$I4f zvM4A8-6EHe|LfY8HW)$=b1v&OEFYuKj(N+-_%I6uGW*%jn$xL=7~m7T96k+OW4>@J z1fu~Mdc|q?1e&b%a%3IBz5{)59Z!^5N%T_v1-U5%<7`uNFP4?r>SsbNRMQ#)5%gwX zR3j*49F;-9LY59tr1mkvW#rFL2TSDUhWHLY>t3LM~ zfyl#tx$hV4woOeQYQw1K~7!z6*odc;_I z4i1;6U-sha$)P+CIFy?;EJ%< zLAX>#qyys|2*gEhT!tP2jAaSjOL`#@koAxumkDA~pv%#e0Gl90{<&@lkDMRN>NRe& zV*7}fdr$u0^a-i@o!SIQiJH0Z zTP9H{;tthv*DYl-0u%`jeF2j@p2ARov|i?Jb2!m0Ca(=OgQP(A3Rj6Boc)w_C;{rh zZ@}LaJ#OOgN`>AwcC01iLO>r#GGP0p+C{%NujRlf0!SE%0;{ndw7_# z$WCEXg=oE!K!}n!()P70(|`QCIMg+(-ikwcP@k0epDw$ev5&UScpbnvnnsT` z`@|_FUxd%AQ4fx*Tru&h(|W)(auCJU5K|R|T2+jw58JyTfHxA*6Tw}rVVaK*Ua8G z?g*uI?5y91y_J^mdWO{4#2e*#GoWnXNJmWHCakJCjn&C z-aT@)G_=gQS#m=xTr}K%7X9x4>c|9tOm9Z$x(@t7a%4@QEu{NNQ)I>j^s0Hj{FaHS zFMgehvO{^Ybwj!>TgpSRphwW?&3d9<_*uM9ccb1F@^Ki|R}KqFLydTdU4;aH+iv3X z1EO;;{=AeWR)%0#&A%fO0|@;#=6RS$+{`te$Upu8Q(}FBk=KD0WRB{NCA>d) zvp`nmB=Bc$FxOd;4+7D8O>1WQP5%G(HtE_PO|W&cI7HTgUTw~DKHn)b&9Xtbyy!KpT35$Rfz zbcMD0w+)^5m|@4Mm>5=1gfsd}D}qsfJI|+=@UPUSSZq1Cp8so-jGk}Y;%(fnM=0x9 z!>ZX|lzpj;!8vD02QG^F-+a2Y#F(^q%QhiZQA<}cH2yPi=jN8g#JUAYmb`Srssy}b z|Ms5GjhI_$Z?$N_*2@`YLUsNF{3z2aZr&`=-7v*96yG)(`s6 zKW(EP5y?~QJ{10%B8|TgeWVGw^$DxvLLEulwO#Ti)j|I0%jK#<~AY`~N@lReM~p7jS6 + + + diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 7656054..dc84d01 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -530,9 +530,9 @@ class _ChatPageState extends State { decoration: InputDecoration( hintText: 'yourMessage'.tr(), filled: true, - fillColor: Theme.of(context).brightness == Brightness.dark - ? Theme.of(context).colorScheme.surfaceBright - : Theme.of(context).colorScheme.surfaceDim, + fillColor: chatTheme.brightness == Brightness.dark + ? chatTheme.colorScheme.surfaceBright + : chatTheme.colorScheme.surfaceDim, border: OutlineInputBorder( borderRadius: BorderRadius.circular(30), borderSide: BorderSide.none, @@ -601,14 +601,13 @@ class _ChatPageState extends State { /// Bar shown while recording a voice message. Widget _buildRecordingBar() { - final color = - _cancelRecording ? Colors.red : Theme.of(context).colorScheme.primary; + final color = _cancelRecording ? Colors.red : chatTheme.colorScheme.primary; return Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), decoration: BoxDecoration( - color: Theme.of(context).brightness == Brightness.dark - ? Theme.of(context).colorScheme.surfaceBright - : Theme.of(context).colorScheme.surfaceDim, + color: chatTheme.brightness == Brightness.dark + ? chatTheme.colorScheme.surfaceBright + : chatTheme.colorScheme.surfaceDim, borderRadius: BorderRadius.circular(30), ), child: Row( @@ -749,6 +748,23 @@ class _ChatPageState extends State { return Color.alphaBlend(accent.withValues(alpha: alpha), scheme.surface); } + /// The chat's own theme. [build] and its helpers run above the chat `Theme`, + /// so `Theme.of(context)` there is the app theme, not this conversation's. + ThemeData get chatTheme => ThemeUtils.chatTheme(context, _chatThemeColor); + + /// Repeating doodle pattern behind the messages, recolored by the theme so it + /// reads on a light and on a dark background. + DecorationImage chatPattern() { + return DecorationImage( + image: const AssetImage('assets/images/chat_bg.png'), + repeat: ImageRepeat.repeat, + scale: 3, + colorFilter: ColorFilter.mode( + Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.07), + BlendMode.srcIn), + ); + } + /// AppBar color: a stronger tint, kept translucent so the blur still shows. Color appBarBackground() { final bool dark = Theme.of(context).brightness == Brightness.dark; @@ -828,34 +844,37 @@ class _ChatPageState extends State { ), ), ), - body: Column( - children: [ - // Messages and avatar list - Expanded( - child: _firstLoad - ? Center( - child: Transform.scale( - scale: 1.5, - child: CircularProgressIndicator(), - ), - ) - : _getContent(_messages), - ), - SafeArea( - top: false, - child: Padding( - padding: const EdgeInsets.all(8.0), - child: Stack( - alignment: Alignment.center, - children: [ - _buildInputBar(), - if (_isRecording) - Positioned.fill(child: _buildRecordingBar()), - ], + body: Container( + decoration: BoxDecoration(image: chatPattern()), + child: Column( + children: [ + // Messages and avatar list + Expanded( + child: _firstLoad + ? Center( + child: Transform.scale( + scale: 1.5, + child: CircularProgressIndicator(), + ), + ) + : _getContent(_messages), + ), + SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Stack( + alignment: Alignment.center, + children: [ + _buildInputBar(), + if (_isRecording) + Positioned.fill(child: _buildRecordingBar()), + ], + ), ), ), - ), - ], + ], + ), ), ), ), diff --git a/pubspec.yaml b/pubspec.yaml index e888af5..2ec7495 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -64,5 +64,6 @@ dev_dependencies: flutter: uses-material-design: true assets: - # - assets/images/ + # Only the raster: the SVG source stays out of the bundle. + - assets/images/chat_bg.png - assets/translations/ From 304e75f68d390a95a63568b7012870df7ea0f051 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 17 Nov 2026 13:48:16 +0100 Subject: [PATCH 068/181] Add resend action for failed messages Long-press on a failed outgoing message offers Send again. A retry keeps the original timestamp while the server still accepts it (so the server deduplicates against the failed attempt); an older one is moved to a fresh timestamp and key. Media without transport references in this session re-uploads its local copies. --- assets/translations/cs.json | 1 + assets/translations/en.json | 1 + lib/utils/cache_utils.dart | 31 +++++- lib/utils/chat_sender.dart | 173 ++++++++++++++++++++++++++++----- lib/utils/message_actions.dart | 11 +++ test/message_actions_test.dart | 30 +++++- test/message_store_test.dart | 41 ++++++-- 7 files changed, 253 insertions(+), 35 deletions(-) diff --git a/assets/translations/cs.json b/assets/translations/cs.json index e237b3a..ffe43a1 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -149,6 +149,7 @@ "mediaAlbum": "Album", "messageSending": "Odesílá se", "messageSendFailed": "Odeslání se nezdařilo", + "resendMessage": "Odeslat znovu", "messageUndecryptable": "Tuto zprávu se nepodařilo dešifrovat", "mediaExpired": "Příloha už není na serveru dostupná", "notificationPreview": "Zobrazovat text zpráv v notifikacích", diff --git a/assets/translations/en.json b/assets/translations/en.json index 656e279..a7d651f 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -149,6 +149,7 @@ "mediaAlbum": "Album", "messageSending": "Sending", "messageSendFailed": "Sending failed", + "resendMessage": "Send again", "messageUndecryptable": "This message could not be decrypted", "mediaExpired": "The attachment is no longer available on the server", "notificationPreview": "Show message text in notifications", diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 94b9c8f..5a2d8cd 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -343,8 +343,7 @@ class CacheUtils { /// Older versions stored a whole conversation under the user id. Move those /// messages into per-message keys once, then drop the old entry. - static Future _migrateLegacyConversation( - Box box, String userId) async { + static Future _migrateLegacyConversation(Box box, String userId) async { if (!box.containsKey(userId)) { return; } @@ -548,7 +547,32 @@ class CacheUtils { await box.put(key, stored); } + /// Move a stored message to a fresh client timestamp and key, and return the + /// stored copy. Used when a failed send is retried too long after it was + /// written for the server to accept the original timestamp. + static Future retimestampMessage( + String userId, PrivateMessage message) async { + Box box = await _openPrivateMessagesBox(); + await _migrateLegacyConversation(box, userId); + final oldKey = messageKey(userId, message.sentAt); + final stored = box.get(oldKey); + if (stored is! PrivateMessage) { + return null; + } + final oldSentAt = stored.sentAt; + // Never collide with the key it already occupies. + do { + stored.sentAt = DateTime.now(); + } while (messageKey(userId, stored.sentAt) == oldKey); + // Hive refuses one object under two keys, so the old entry goes first. + await box.delete(oldKey); + await box.put(messageKey(userId, stored.sentAt), stored); + await _deletePendingSend(userId, oldSentAt); + return stored; + } + /// Marks the message the server acknowledged as sent. + /// /// [receiverId] and [sentAt] are the values the server echoes back; the pair /// identifies the stored message without keeping a client message id. @@ -568,8 +592,7 @@ class CacheUtils { /// Remembers a message that is waiting for its delivery ack, so a reconnect /// can resend exactly those. - static Future addPendingSend( - String receiverId, DateTime sentAt) async { + static Future addPendingSend(String receiverId, DateTime sentAt) async { Box box = await _openPendingSendsBox(); await box.put(messageKey(receiverId, sentAt), receiverId); } diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index 9bf6d37..d9ecf09 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -239,18 +239,9 @@ class ChatSender { } for (final message in entry.value) { try { - if (message.isMedia) { - final references = _outgoingReferences[ - CacheUtils.messageKey(entry.key, message.sentAt)]; - if (references == null || references.isEmpty) { - continue; - } - final envelope = message.isAlbum - ? MediaUtils.buildAlbumEnvelope(references, message.message) - : MediaUtils.buildMediaEnvelope(references.first, message.message); - await _sendEnvelope(recipient, envelope, message.sentAt); - } else { - await _sendText(recipient, message); + final fresh = await _withAcceptedSentAt(entry.key, message); + if (fresh != null) { + await _sendStored(recipient, fresh); } } catch (e) { if (kDebugMode) { @@ -261,6 +252,66 @@ class ChatSender { } } + /// Resend a single stored message after its send failed (bubble long-press). + /// + /// The original timestamp is kept while the server still accepts it, so the + /// server deduplicates against the failed attempt and the bubble stays put. + static Future resend(String receiverId, PrivateMessage message) async { + final recipient = await CacheUtils.getUserById(receiverId); + if (recipient == null || recipient.publicKey.isEmpty) { + Fluttertoast.showToast( + msg: 'userNotFound'.tr(), backgroundColor: Colors.red); + return false; + } + final fresh = await _withAcceptedSentAt(receiverId, message); + if (fresh == null) { + return false; + } + await CacheUtils.updateStoredMessage(receiverId, fresh, (stored) { + stored.sendStatus = SendStatus.sending; + }); + fresh.sendStatus = SendStatus.sending; + await CacheUtils.addPendingSend(receiverId, fresh.sentAt); + MessageNotifier().notify(); + try { + if (!await _ensureConnected()) { + return await _fail(receiverId, fresh); + } + await _sendStored(recipient, fresh); + // No ack yet: the message stays `sending` until the server confirms. + return true; + } catch (e) { + Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); + return await _fail(receiverId, fresh); + } + } + + /// How old a client timestamp may be and still be accepted by the server + /// (`models.MaxSentAtSkew`, minus a minute for clock drift between the two). + static const Duration _maxSentAtAge = Duration(minutes: 4); + + /// The stored message to send again, with a timestamp the server will take. + /// + /// Returns null when the message is gone. A timestamp older than the server + /// accepts is replaced with now, which moves the bubble to the end of the + /// chat. + /// + /// shortcut: a retry that late cannot dedupe against the first attempt, so a + /// message that did arrive with a lost ack is delivered twice; upgrade by + /// keeping the server-side dedup key separate from the display time. + static Future _withAcceptedSentAt( + String receiverId, PrivateMessage message) async { + if (DateTime.now().difference(message.sentAt) <= _maxSentAtAge) { + return message; + } + final moved = await CacheUtils.retimestampMessage(receiverId, message); + if (moved != null) { + // The old marker is gone with the old key; keep the new one watchable. + await CacheUtils.addPendingSend(receiverId, moved.sentAt); + } + return moved; + } + /// Mark a message as sent after the server acknowledged it. static Future confirmSent(String receiverId, DateTime sentAt) async { await CacheUtils.markMessageSent(receiverId, sentAt); @@ -268,17 +319,92 @@ class ChatSender { MessageNotifier().notify(); } + /// Hand an already stored message to the WebSocket again. + /// + /// Media needs its transport references; when this session no longer holds + /// them (an offline send, or a restart), the copies on disk are re-encrypted + /// and uploaded once more. + static Future _sendStored( + User recipient, PrivateMessage message) async { + if (!message.isMedia) { + await _sendText(recipient, message); + return; + } + final key = CacheUtils.messageKey(recipient.id, message.sentAt); + final references = _outgoingReferences[key] ?? + await _uploadLocalCopies(recipient, message); + if (references == null || references.isEmpty) { + throw Exception('mediaUploadFailed'.tr()); + } + _outgoingReferences[key] = references; + final envelope = message.isAlbum + ? MediaUtils.buildAlbumEnvelope(references, message.message) + : MediaUtils.buildMediaEnvelope(references.first, message.message); + await _sendEnvelope(recipient, envelope, message.sentAt); + } + + /// Re-upload the attachments stored on this device. Null when a local copy + /// is missing or the upload failed. + static Future?> _uploadLocalCopies( + User recipient, PrivateMessage message) async { + Future upload(String? path, MediaType? type, + {int? width, int? height, int? durationMs, String? fileName}) async { + if (path == null || type == null) { + return null; + } + final bytes = await MediaUtils.decryptAtRest(path); + if (!MediaUtils.uploadFits(bytes.length)) { + _toastTooLarge(); + return null; + } + final transport = await MediaUtils.encryptForTransport(bytes); + return _uploadReference(recipient, type, transport.key, transport.blob, + width: width, + height: height, + durationMs: durationMs, + fileName: fileName); + } + + final references = []; + if (message.isAlbum) { + for (final item in message.album) { + final reference = await upload(item.localPath, item.mediaType, + width: item.width, + height: item.height, + durationMs: item.durationMs, + fileName: item.fileName); + if (reference == null) { + return null; + } + references.add(reference); + } + } else { + final reference = await upload(message.localPath, message.mediaType, + width: message.width, + height: message.height, + durationMs: message.durationMs, + fileName: message.fileName); + if (reference == null) { + return null; + } + references.add(reference); + } + return references; + } + /// Encrypt [message] for [recipient] and hand it to the WebSocket. The /// original timestamp is kept so a resend maps onto the same server entry. - static Future _sendText( - User recipient, PrivateMessage message) async { + static Future _sendText(User recipient, PrivateMessage message) async { final data = await CryptoUtils.encryptMessageData( utf8.encode(message.message), bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); - Singleton().wsClient.sendMessage(WsMessage.privateMessage( - NewPrivateMessage(recipient.id, data['encryptedData']!, - data['encryptedKey']!, data['nonce']!, data['mac']!, - sentAt: message.sentAt))); + Singleton().wsClient.sendMessage(WsMessage.privateMessage(NewPrivateMessage( + recipient.id, + data['encryptedData']!, + data['encryptedKey']!, + data['nonce']!, + data['mac']!, + sentAt: message.sentAt))); } /// Upload one already transport-encrypted attachment and build its reference. @@ -321,10 +447,13 @@ class ChatSender { User recipient, Uint8List envelope, DateTime sentAt) async { final data = await CryptoUtils.encryptMessageData( envelope, bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); - Singleton().wsClient.sendMessage(WsMessage.privateMessage( - NewPrivateMessage(recipient.id, data['encryptedData']!, - data['encryptedKey']!, data['nonce']!, data['mac']!, - sentAt: sentAt))); + Singleton().wsClient.sendMessage(WsMessage.privateMessage(NewPrivateMessage( + recipient.id, + data['encryptedData']!, + data['encryptedKey']!, + data['nonce']!, + data['mac']!, + sentAt: sentAt))); } /// Connect the WebSocket if needed; toasts and reports false when offline. diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 67c085d..7c01170 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -7,6 +7,7 @@ import 'package:fluttertoast/fluttertoast.dart'; import '../models/private_message.dart'; import '../pages/forward_page.dart'; import 'cache_utils.dart'; +import 'chat_sender.dart'; import 'dialog_utils.dart'; import 'media_utils.dart'; import 'message_notifier.dart'; @@ -21,6 +22,7 @@ class MessageActions { static const IconData forwardIcon = Icons.forward; static const IconData saveIcon = Icons.download; static const IconData deleteIcon = Icons.delete; + static const IconData resendIcon = Icons.refresh; /// Whether [message] can be saved or forwarded (the file must be on disk). static bool canSave(PrivateMessage message) => @@ -38,6 +40,15 @@ class MessageActions { return SafeArea( child: Wrap( children: [ + if (message.isMe && message.sendStatus == SendStatus.failed) + ListTile( + leading: const Icon(resendIcon), + title: Text('resendMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + ChatSender.resend(conversationUserId, message); + }, + ), if (message.message.isNotEmpty) ListTile( leading: const Icon(copyIcon), diff --git a/test/message_actions_test.dart b/test/message_actions_test.dart index 195d8fc..0ec905c 100644 --- a/test/message_actions_test.dart +++ b/test/message_actions_test.dart @@ -5,13 +5,19 @@ import 'package:flutter_test/flutter_test.dart'; // ignore: depend_on_referenced_packages import 'package:shared_preferences/shared_preferences.dart'; import 'package:whisper/models/private_message.dart'; +import 'package:whisper/models/profile.dart'; +import 'package:whisper/models/user.dart'; import 'package:whisper/utils/message_actions.dart'; +import 'package:whisper/utils/singleton.dart'; void main() { setUpAll(() async { // easy_localization reads the locale from shared_preferences SharedPreferences.setMockInitialValues({}); await EasyLocalization.ensureInitialized(); + // isMe compares against the signed-in user, needed by the resend action. + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); }); testWidgets('the sheet offers only the actions that apply', (tester) async { @@ -33,7 +39,8 @@ void main() { return Scaffold( body: Center( child: ElevatedButton( - onPressed: () => MessageActions.showSheet(inner, message, '5'), + onPressed: () => + MessageActions.showSheet(inner, message, '5'), child: const Text('open'), ), ), @@ -65,5 +72,26 @@ void main() { expect(find.text('Forward'), findsOneWidget); expect(find.text('Delete for me'), findsOneWidget); expect(find.text('Copy'), findsNothing); + + // Close the sheet + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + // Resend is offered only for my own message whose send failed. + message = PrivateMessage('1', 'hello', DateTime(2026), DateTime(2026), true, + sendStatus: SendStatus.failed); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('Send again'), findsOneWidget); + + // Close the sheet + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + message = + PrivateMessage('1', 'hello', DateTime(2026), DateTime(2026), true); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('Send again'), findsNothing); }); } diff --git a/test/message_store_test.dart b/test/message_store_test.dart index d3d69e6..fa43b12 100644 --- a/test/message_store_test.dart +++ b/test/message_store_test.dart @@ -96,7 +96,8 @@ void main() { expect(byId['b'], 'other'); }); - test('a legacy conversation list is migrated into per-message keys', () async { + test('a legacy conversation list is migrated into per-message keys', + () async { // Format written by older versions: one list under the user id. await Hive.box('privateMessages').put('legacy', [ message('legacy', 'first', DateTime(2026, 3, 1)), @@ -109,15 +110,18 @@ void main() { final box = Hive.box('privateMessages'); expect(box.containsKey('legacy'), isFalse); - expect(box.keys.whereType().every( - (key) => CacheUtils.conversationOfKey(key) == 'legacy'), isTrue); + expect( + box.keys + .whereType() + .every((key) => CacheUtils.conversationOfKey(key) == 'legacy'), + isTrue); }); test('the delivery ack flips the message to sent and clears the marker', () async { final sentAt = DateTime(2026, 4, 1); - final outgoing = message('peer', 'pending', sentAt, - sendStatus: SendStatus.sending); + final outgoing = + message('peer', 'pending', sentAt, sendStatus: SendStatus.sending); await CacheUtils.addPrivateMessages('peer', [outgoing]); await CacheUtils.addPendingSend('peer', sentAt); @@ -131,11 +135,32 @@ void main() { expect(Hive.box('pendingSends').isEmpty, isTrue); }); + test('a retried message gets a fresh timestamp and keeps its content', + () async { + final oldSentAt = DateTime(2026, 4, 3); + final failed = + message('peer', 'retry me', oldSentAt, sendStatus: SendStatus.failed); + await CacheUtils.addPrivateMessages('peer', [failed]); + await CacheUtils.addPendingSend('peer', oldSentAt); + + final moved = await CacheUtils.retimestampMessage('peer', failed); + + expect(moved, isNotNull); + expect(moved!.sentAt.isAfter(oldSentAt), isTrue); + final box = Hive.box('privateMessages'); + expect(box.containsKey(CacheUtils.messageKey('peer', oldSentAt)), isFalse, + reason: 'the old key is gone, the message is not stored twice'); + final stored = await CacheUtils.getPrivateMessages('peer'); + expect(stored.single.message, 'retry me'); + expect(stored.single.sentAt, moved.sentAt); + // The marker under the old key is dropped; ChatSender adds it back. + expect(Hive.box('pendingSends').isEmpty, isTrue); + }); + test('an unacknowledged message stays pending for a resend', () async { final sentAt = DateTime(2026, 4, 2); - await CacheUtils.addPrivateMessages('peer', [ - message('peer', 'no ack', sentAt, sendStatus: SendStatus.sending) - ]); + await CacheUtils.addPrivateMessages('peer', + [message('peer', 'no ack', sentAt, sendStatus: SendStatus.sending)]); await CacheUtils.addPendingSend('peer', sentAt); final pending = await CacheUtils.getPendingSends(); From 75dd859e92191c63939e19f50ac3fadb51b8ef5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 17 Nov 2026 17:43:20 +0100 Subject: [PATCH 069/181] fix(chat): clear the unread row when the chat is opened Opening a chat marked the messages read in Hive but never told the notifier, so Home kept the conversation bold until the next incoming message. --- lib/utils/message_notifier.dart | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index 2586de5..d26919b 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -172,6 +172,10 @@ class MessageNotifier extends ChangeNotifier { await CacheUtils.getPrivateMessages(userId, markAsRead: true); await NotificationService().removeNotificationsById( messages.map((x) => x.notificationId).toList()); + // The read flags just changed in the cache. Nothing else tells the Home + // list, so the unread row would stay bold after leaving the chat. The chat + // page's own listener is skipped: it is still inside `_loadMessages`. + notifyListeners(); return messages; } From a40e7818c4fb48c36484cb154a9f673ad76dd055 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 17 Nov 2026 18:47:02 +0100 Subject: [PATCH 070/181] feat: F1 foundations - device registry, archive sync and history - clients pinned by v0.1.0 tags; app sends X-Client-Version - device id in secure storage, signed into the login JWT (did), device list with revoke/unrevoke (the lockout is immediate on the server) - reconnect asks for the archive delta by seq instead of draining a queue - chat history is paged in from the server and backfilled on scroll - archive retention selector in settings - new-login push is shown when the app is in the foreground --- .github/workflows/flutter-e2e.yml | 15 +- .gitignore | 3 +- AGENTS.md | 2 +- README.md | 28 +- assets/translations/cs.json | 28 +- assets/translations/en.json | 28 +- docs/adr/0002-client-versioning.md | 2 +- docs/adr/0003-client-pinning.md | 23 ++ docs/adr/README.md | 3 +- integration_test/app_e2e_test.dart | 9 +- lib/pages/chat_page.dart | 68 +++- lib/pages/devices_page.dart | 175 ++++++++++ lib/pages/home_page.dart | 18 +- lib/pages/settings_page.dart | 97 ++++++ lib/utils/cache_utils.dart | 57 ++++ lib/utils/crypto_utils.dart | 22 +- lib/utils/notification_service.dart | 26 ++ lib/utils/singleton.dart | 7 +- lib/utils/utils.dart | 479 +++++++++++++++------------ lib/utils/version.dart | 3 + pubspec.lock | 4 +- pubspec.yaml | 12 +- test/auth_refresh_fallback_test.dart | 41 ++- test/crypto_test.dart | 15 +- test/device_and_sync_test.dart | 68 ++++ 25 files changed, 965 insertions(+), 268 deletions(-) create mode 100644 docs/adr/0003-client-pinning.md create mode 100644 lib/pages/devices_page.dart create mode 100644 lib/utils/version.dart create mode 100644 test/device_and_sync_test.dart diff --git a/.github/workflows/flutter-e2e.yml b/.github/workflows/flutter-e2e.yml index 7c6da16..66abf1c 100644 --- a/.github/workflows/flutter-e2e.yml +++ b/.github/workflows/flutter-e2e.yml @@ -19,19 +19,8 @@ jobs: with: path: whisper - - name: Checkout OpenAPI client - uses: actions/checkout@v7 - with: - repository: jsfraz/whisper_openapi_client_dart - ref: ${{ github.ref_name }} - path: whisper_openapi_client_dart - - - name: Checkout WebSocket client - uses: actions/checkout@v7 - with: - repository: jsfraz/whisper_websocket_client_dart - ref: ${{ github.ref_name }} - path: whisper_websocket_client_dart + # Both Dart clients come from their release tags (pubspec.yaml), so no + # sibling checkouts are needed. - name: Install Linux desktop dependencies run: | diff --git a/.gitignore b/.gitignore index 0ad2648..d002995 100644 --- a/.gitignore +++ b/.gitignore @@ -48,4 +48,5 @@ app.*.map.json firebase.json lib/firebase_options.dart android/app/google-services.json -ios/Runner/GoogleService-Info.plist \ No newline at end of file +ios/Runner/GoogleService-Info.plist +pubspec_overrides.yaml diff --git a/AGENTS.md b/AGENTS.md index 12a04f9..21e9b90 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,7 +43,7 @@ not in this repository). Use them for the fast loop, but the shell gates below s ## Where it hurts - **Media upload**: `uploadMedia(file, receiverId)` — the argument order comes from the generator, not from logic. Verify call sites after regenerating the client. -- **Path dependencies**: `pubspec.yaml` pulls both clients via `path:`, so CI cannot see which client version the app actually uses. Pinning to a tag is phase 2 debt. +- **Pinned clients**: `pubspec.yaml` pulls both Dart clients from their `v0.1.0` tags, so the build records the contract it was made against. `pubspec_overrides.yaml` (gitignored) points at the sibling checkouts for local work; never commit it. - **Firebase**: analysis fails without `lib/firebase_options.dart`. CI decodes it from a secret. - **Login needs a challenge**: `CryptoUtils.generateRsaJwt` requires a `nonce` fetched from `AuthenticationApi.authChallenge()`; the server spends it on use. diff --git a/README.md b/README.md index 36d1a30..15c66cc 100644 --- a/README.md +++ b/README.md @@ -10,14 +10,26 @@ Also see [Wiki](https://github.com/jsfraz/whisper/wiki)! |---|---|---| |![Screenshot 1](screenshots/1.png)|![Screenshot 2](screenshots/2.png)|![Screenshot 3](screenshots/3.png)| -## Delivery model - -One account is one device, and the server keeps an encrypted copy of a message -only until the receiver acknowledges that it stored it. A message that was sent -but never acknowledged is re-sent on the next connect; the server drops the -duplicates. Media is deleted from the server when the receiver confirms the -download, so an attachment that was never fetched before its TTL (or before a -reinstall) shows as expired rather than being re-downloadable. +## Delivery, history and devices + +The server keeps one encrypted copy of each message in a PostgreSQL archive: +that row is the history, the offline buffer and the delta a reconnecting device +fetches. Nothing is pushed on connect — the app sends the highest `seq` it has +stored and receives only what it missed, so a phone that was offline for a week +syncs in one round trip. A resend of the same message is deduplicated by +(sender, receiver, timestamp). + +How long the ciphertext stays is a per-account setting (7, 30, 90 or 365 days); +the shorter setting of the two participants wins, and an hourly sweeper deletes +what expired. Media is deleted from the server when the receiver confirms the +download, so an attachment that was never fetched before its TTL shows as +expired rather than being re-downloadable. + +Every installation registers a device (id, label, platform). Revoking one in +Settings locks it out immediately: it loses its socket, its refresh sessions and +every API call, even though it still holds the account key. A new login warns +the other devices. The app reports its version (`X-Client-Version`) and refuses +to sign in to a server that requires a newer client. ## Download diff --git a/assets/translations/cs.json b/assets/translations/cs.json index ffe43a1..d17d456 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -191,5 +191,31 @@ "unsupportedMessageType": "Nepodporovaný typ zprávy", "implausibleTimestamp": "Čas zprávy je mimo rozsah", "serverError": "Neočekávaná chyba serveru", - "httpError": "HTTP chyba %s" + "httpError": "HTTP chyba %s", + "devicesPage": "Zařízení", + "devicesSettings": "Zařízení a relace", + "thisDevice": "toto zařízení", + "deviceLastSeen": "Naposledy aktivní %s", + "deviceRevokedAt": "Zablokováno %s", + "revoke": "Zablokovat", + "unrevoke": "Povolit znovu", + "revokeDevice": "Zablokovat zařízení", + "unrevokeDevice": "Povolit zařízení znovu", + "revokeDeviceConfirm": "Zablokovat „%s“? Nebude se moci přihlásit, posílat ani přijímat, dokud ho jiné zařízení znovu nepovolí.", + "unrevokeDeviceConfirm": "Povolit „%s“ znovu přihlášení?", + "deviceRevokedToast": "Zařízení zablokováno", + "deviceUnrevokedToast": "Zařízení znovu povoleno", + "retentionSettings": "Retence historie na serveru", + "retentionTitle": "Jak dlouho server drží historii", + "retentionExplain": "Šifrovaný obsah zpráv zůstává na serveru, aby se offline zařízení dohnalo. Platí kratší nastavení z obou stran konverzace.", + "retentionDays": "%s dní", + "retentionSaved": "Retence upravena", + "deviceRevoked": "Toto zařízení bylo zablokováno. Povolit ho znovu lze z jiného zařízení.", + "clientVersionUnsupported": "Aplikace je pro server příliš stará. Aktualizujte ji.", + "invalidDevice": "Zařízení se nepodařilo zaregistrovat.", + "deviceNotFound": "Zařízení nenalezeno.", + "invalidRetention": "Nepodporovaná hodnota retence.", + "invalidCursor": "Neplatný požadavek na historii.", + "confirm": "Potvrdit", + "newLoginTitle": "Nové přihlášení" } diff --git a/assets/translations/en.json b/assets/translations/en.json index a7d651f..b8c3fef 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -191,5 +191,31 @@ "unsupportedMessageType": "Unsupported message type", "implausibleTimestamp": "The message timestamp is out of range", "serverError": "Unexpected server error", - "httpError": "HTTP error %s" + "httpError": "HTTP error %s", + "devicesPage": "Devices", + "devicesSettings": "Devices and sessions", + "thisDevice": "this device", + "deviceLastSeen": "Last seen %s", + "deviceRevokedAt": "Revoked %s", + "revoke": "Revoke", + "unrevoke": "Allow again", + "revokeDevice": "Revoke device", + "unrevokeDevice": "Allow device again", + "revokeDeviceConfirm": "Revoke \"%s\"? It cannot sign in, send or receive until another device allows it again.", + "unrevokeDeviceConfirm": "Allow \"%s\" to sign in again?", + "deviceRevokedToast": "Device revoked", + "deviceUnrevokedToast": "Device allowed again", + "retentionSettings": "Server history retention", + "retentionTitle": "How long the server keeps history", + "retentionExplain": "Ciphertext of your messages stays on the server so an offline device can catch up. The shorter setting of the two participants wins.", + "retentionDays": "%s days", + "retentionSaved": "Retention updated", + "deviceRevoked": "This device was revoked. Sign in on another device to allow it again.", + "clientVersionUnsupported": "This app is too old for the server. Update it.", + "invalidDevice": "This device could not be registered.", + "deviceNotFound": "Device not found.", + "invalidRetention": "Unsupported retention value.", + "invalidCursor": "The history request was invalid.", + "confirm": "Confirm", + "newLoginTitle": "New login" } diff --git a/docs/adr/0002-client-versioning.md b/docs/adr/0002-client-versioning.md index e612315..5585d41 100644 --- a/docs/adr/0002-client-versioning.md +++ b/docs/adr/0002-client-versioning.md @@ -1,6 +1,6 @@ # 0002 - Pin clients to tags once releases exist -Status: accepted (2026-11-11); supersedes the `path:` setup once a server tag exists +Status: superseded by [0003](0003-client-pinning.md) (2026-11-17) ## Context `pubspec.yaml` pulls both Dart clients through `path: ../...`. CI must check out diff --git a/docs/adr/0003-client-pinning.md b/docs/adr/0003-client-pinning.md new file mode 100644 index 0000000..d512451 --- /dev/null +++ b/docs/adr/0003-client-pinning.md @@ -0,0 +1,23 @@ +# 0003 - Clients are pinned by release tag + +Status: accepted (2026-11-17) + +## Context +`pubspec.yaml` pulled both Dart clients through `path: ../...`. Nothing recorded +which client the app was built against, CI had to check out two sibling +repositories, and a local change to a client silently changed the app. + +## Decision +Both clients are tagged `v0.1.0` (pre-1.0: the products tag `v1.0.0` only after +F1-F10) and the app depends on them as git dependencies at that tag. Local work +on a client and the app together uses `pubspec_overrides.yaml`, which is +gitignored, so CI and release builds always resolve the tags. + +The OpenAPI client carries `lib/version.dart` with `clientVersion`, the WS client +`lib/version.dart`, and the app `lib/utils/version.dart` with `appVersion`, which +it sends as `X-Client-Version`. The server refuses a login below its +`minClientVersion` (`GET /api/version`). + +## Consequences +A contract change needs a new tag on the client before the app can use it, and +the app version bump lands in the same series. CI no longer checks out siblings. diff --git a/docs/adr/README.md b/docs/adr/README.md index b98636a..e6760f8 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -3,6 +3,7 @@ | ADR | Decision | | --- | --- | | [0001](0001-local-encryption.md) | Encrypt on the device; the server sees ciphertext only | -| [0002](0002-client-versioning.md) | Pin clients to tags once releases exist | +| [0002](0002-client-versioning.md) | Pin clients to tags once releases exist (superseded by 0003) | +| [0003](0003-client-pinning.md) | Clients are pinned by release tag, app sends its version | Cross-cutting decisions live in the Notion Engineering Standard. diff --git a/integration_test/app_e2e_test.dart b/integration_test/app_e2e_test.dart index 876e514..fad9c39 100644 --- a/integration_test/app_e2e_test.dart +++ b/integration_test/app_e2e_test.dart @@ -74,9 +74,14 @@ void main() { final challenge = await authApi.authChallenge(); final jwt = await CryptoUtils.generateRsaJwt( '1', keys.privateKey as bu.RSAPrivateKey, - nonce: challenge!.challenge); + nonce: challenge!.challenge, deviceId: 'e2e-device'); final auth = await authApi.authUser( - authUserInput: AuthUserInput(token: jwt), + authUserInput: AuthUserInput( + token: jwt, + deviceId: 'e2e-device', + label: 'e2e', + platform: 'linux', + ), ); expect(auth!.accessToken, isNotEmpty); diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index dc84d01..a3f981e 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -14,6 +14,7 @@ import '../utils/chat_sender.dart'; import '../utils/media_utils.dart'; import '../utils/message_notifier.dart'; import '../utils/singleton.dart'; +import '../utils/utils.dart' as utils; import '../utils/theme_utils.dart'; import '../widgets/attachment_confirm_sheet.dart'; import '../widgets/chat_bubble.dart'; @@ -47,6 +48,12 @@ class _ChatPageState extends State { bool _firstLoad = true; // Guards against overlapping cache reads bool _loading = false; + // Guards against overlapping history requests + bool _historyLoading = false; + // Whether the newest archive page was already asked for + bool _historyLoaded = false; + // Cursor for the next (older) archive page, null when the archive ends + String? _historyCursor; // Voice recording state bool _isRecording = false; bool _recordingStarting = false; @@ -65,6 +72,8 @@ class _ChatPageState extends State { _scrollController.addListener(_onScroll); // Load messages from cache _loadMessages(); + // Then top the conversation up from the server archive + _loadHistory(); // Load concept message getConceptMessage(); // Load per-chat theme @@ -129,11 +138,60 @@ class _ChatPageState extends State { if (!_scrollController.hasClients) { return; } - if (_scrollController.position.extentAfter < 200 && - _visibleCount < _messages.length) { - setState(() { - _visibleCount += _pageSize; - }); + if (_scrollController.position.extentAfter < 200) { + if (_visibleCount < _messages.length) { + setState(() { + _visibleCount += _pageSize; + }); + } else if (_historyCursor != null) { + // The cache ran out: ask the server for the page below it. + _loadHistory(older: true); + } + } + } + + /// Fetch one page of the conversation from the server archive. + /// + /// The first call fills a chat this device never had (a fresh install, or a + /// message older than anything local); later calls walk backwards when the + /// user scrolls past the oldest message. + Future _loadHistory({bool older = false}) async { + if (_historyLoading || (older && _historyCursor == null)) { + return; + } + if (!older && _historyLoaded) { + return; + } + if (!utils.Utils.isOnline) { + return; + } + _historyLoading = true; + try { + final page = await utils.Utils.callApi( + () => Singleton().messagesApi.getHistory(widget.user.id, + before: older ? _historyCursor : null, limit: _pageSize), + showError: false); + if (page == null || !mounted) { + return; + } + _historyLoaded = true; + _historyCursor = page.nextCursor; + for (final peer in page.peers) { + await CacheUtils.addUser( + User(peer.id, peer.username, peer.publicKey, peer.admin)); + } + if (page.messages.isEmpty) { + return; + } + await utils.Utils.storeHistoryPage(page.messages); + if (mounted) { + // Show the page that just arrived without making the user scroll again. + setState(() { + _visibleCount += page.messages.length; + }); + } + } finally { + _historyLoading = false; } } diff --git a/lib/pages/devices_page.dart b/lib/pages/devices_page.dart new file mode 100644 index 0000000..6f93fa8 --- /dev/null +++ b/lib/pages/devices_page.dart @@ -0,0 +1,175 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:whisper_openapi_client_dart/api.dart'; + +import '../utils/singleton.dart'; +import '../utils/utils.dart'; + +/// Devices signed into the account, with revoke and unrevoke. +/// +/// Revoking is the hard lockout: the device loses its socket, its refresh +/// sessions and every request it makes from then on, even though it still holds +/// the account key. +class DevicesPage extends StatefulWidget { + const DevicesPage({super.key}); + + @override + State createState() => _DevicesPageState(); +} + +class _DevicesPageState extends State { + List _devices = []; + bool _loading = true; + bool _busy = false; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + final response = + await Utils.callApi(() => Singleton().userApi.getDevices()); + if (!mounted) { + return; + } + setState(() { + _devices = response?.devices ?? []; + _loading = false; + }); + } + + /// Revokes or unrevokes one device and refreshes the list. + Future _setRevoked(ModelsDevice device, bool revoke) async { + if (_busy) { + return; + } + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(revoke ? 'revokeDevice'.tr() : 'unrevokeDevice'.tr()), + content: Text(revoke + ? 'revokeDeviceConfirm'.tr(args: [device.label]) + : 'unrevokeDeviceConfirm'.tr(args: [device.label])), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(false), + child: Text('cancel'.tr()), + ), + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(true), + child: Text('confirm'.tr()), + ), + ], + ), + ); + if (confirmed != true || !mounted) { + return; + } + setState(() { + _busy = true; + }); + await Utils.callApi(() => revoke + ? Singleton().userApi.revokeDevice(device.id) + : Singleton().userApi.unrevokeDevice(device.id)); + if (!mounted) { + return; + } + setState(() { + _busy = false; + }); + await Fluttertoast.showToast( + msg: revoke ? 'deviceRevokedToast'.tr() : 'deviceUnrevokedToast'.tr(), + backgroundColor: Colors.grey); + await _load(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: Text('devicesPage'.tr())), + body: SafeArea( + child: _loading + ? const Center(child: CircularProgressIndicator()) + : RefreshIndicator( + onRefresh: _load, + child: ListView.builder( + itemCount: _devices.length, + itemBuilder: (context, index) { + final device = _devices[index]; + final revoked = device.revokedAt != null; + return ListTile( + leading: Icon( + device.platform == 'android' || device.platform == 'ios' + ? Icons.smartphone + : Icons.computer, + color: revoked + ? Theme.of(context).disabledColor + : Theme.of(context).colorScheme.secondary, + ), + title: Row( + children: [ + Flexible( + child: Text( + device.label, + overflow: TextOverflow.ellipsis, + style: revoked + ? TextStyle( + decoration: TextDecoration.lineThrough, + color: Theme.of(context).disabledColor) + : null, + ), + ), + if (device.current == true) + Padding( + padding: const EdgeInsets.only(left: 6), + child: Text( + 'thisDevice'.tr(), + style: TextStyle( + fontSize: 12, + color: Theme.of(context) + .colorScheme + .secondary), + ), + ), + ], + ), + subtitle: Text( + revoked + ? 'deviceRevokedAt'.tr(args: [ + DateFormat.yMd(context.locale.toString()) + .add_Hm() + .format(device.revokedAt!.toLocal()) + ]) + : 'deviceLastSeen'.tr(args: [ + DateFormat.yMd(context.locale.toString()) + .add_Hm() + .format(device.lastSeenAt.toLocal()) + ]), + ), + trailing: device.current == true + ? null + : TextButton( + onPressed: _busy + ? null + : () => _setRevoked(device, !revoked), + child: Text( + revoked ? 'unrevoke'.tr() : 'revoke'.tr(), + style: TextStyle( + color: revoked + ? Theme.of(context) + .colorScheme + .secondary + : Colors.red), + ), + ), + ); + }, + ), + ), + ), + ); + } +} diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index ba2d9e9..973bee2 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -90,13 +90,29 @@ class _HomePageState extends State // Enable FCM notifications FirebaseMessaging.instance.setAutoInitEnabled(true); + // A foreground push is not shown by the OS; show it ourselves. + _fcmSubscription = FirebaseMessaging.onMessage.listen((message) { + final notification = message.notification; + if (notification == null) { + return; + } + NotificationService().showSecurityNotification( + notification.title ?? 'newLoginTitle'.tr(), + notification.body ?? '', + ); + }); + // Register with FCM, the FID arrives via onRegistered _registerForPush(); - } + /// Foreground pushes: the server warns the other devices about a new login, + /// and a foreground app has to show that itself. + StreamSubscription? _fcmSubscription; + @override void dispose() { + _fcmSubscription?.cancel(); _adminTabController.dispose(); MessageNotifier().removeListener(_onMessagesChanged); if (NotificationService.onChatSelected == _openChat) { diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 739a2b7..0120243 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -6,6 +6,7 @@ import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:sprintf/sprintf.dart'; import 'package:url_launcher/url_launcher.dart'; +import 'package:whisper_openapi_client_dart/api.dart'; import '../utils/biometric_auth.dart'; import '../utils/cache_utils.dart'; import '../utils/singleton.dart'; @@ -15,6 +16,7 @@ import '../utils/utils.dart'; import 'scan_invite_button_page.dart'; import '../widgets/change_password_dialog.dart'; import '../utils/nav_transitions.dart'; +import 'devices_page.dart'; class SettingsPage extends StatefulWidget { const SettingsPage({super.key}); @@ -39,6 +41,56 @@ class _SettingsPageState extends State { setState(() {}); } + /// Server-side retention of the ciphertext archive. The shorter setting of + /// the two participants wins, so this is a limit, not a promise. + Future _showRetentionDialog() async { + final current = + await Utils.callApi(() => Singleton().userApi.getRetention()); + if (!mounted) { + return; + } + final selected = await showDialog( + context: context, + builder: (dialogContext) => SimpleDialog( + title: Text('retentionTitle'.tr()), + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Text('retentionExplain'.tr()), + ), + for (final days in const [7, 30, 90, 365]) + SimpleDialogOption( + onPressed: () => Navigator.of(dialogContext).pop(days), + child: Row( + children: [ + Icon( + current?.days == days + ? Icons.radio_button_checked + : Icons.radio_button_unchecked, + size: 20, + color: Theme.of(dialogContext).colorScheme.secondary, + ), + const SizedBox(width: 8), + Text('retentionDays'.tr(args: [days.toString()])), + ], + ), + ), + ], + ), + ); + if (selected == null || !mounted) { + return; + } + await Utils.callApi(() => Singleton() + .userApi + .setRetention(setRetentionInput: SetRetentionInput(days: selected))); + if (!mounted) { + return; + } + await Fluttertoast.showToast( + msg: 'retentionSaved'.tr(), backgroundColor: Colors.grey); + } + Future _toggleBiometry(bool switchValue) async { if (switchValue) { // Enable @@ -205,6 +257,51 @@ class _SettingsPageState extends State { ), ), + // Devices signed into this account + TextButton( + onPressed: () async { + await Navigator.push(context, stepRoute(const DevicesPage())); + }, + child: Row( + children: [ + Icon( + Icons.devices, + size: 24, + color: Theme.of(context).colorScheme.secondary, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'devicesSettings'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.secondary), + ), + ), + ], + ), + ), + // Server retention of the ciphertext archive + TextButton( + onPressed: _showRetentionDialog, + child: Row( + children: [ + Icon( + Icons.storage, + size: 24, + color: Theme.of(context).colorScheme.secondary, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'retentionSettings'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.secondary), + ), + ), + ], + ), + ), + Divider(thickness: 1, indent: 10, endIndent: 10), // How it works diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 5a2d8cd..554c096 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -3,6 +3,7 @@ import 'dart:io'; import 'dart:ui' show Color; import 'package:bcrypt/bcrypt.dart'; +import 'package:uuid/uuid.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:hive/hive.dart'; import '../utils/biometric_auth.dart'; @@ -29,9 +30,65 @@ class CacheUtils { static const _biometry = 'biometry'; static const _playbackSpeed = 'playbackSpeed'; static const String _saltStorageKey = 'whisper_pbkdf2_salt'; + static const String _deviceIdKey = 'whisper_device_id'; + static const String _syncSeqKey = 'syncSeq'; static const FlutterSecureStorage _secureStorage = FlutterSecureStorage(); static const _chatThemeKeyPrefix = 'chatTheme:'; + /// Id of this installation, created once and kept in secure storage. + /// + /// It is the device the server registers, revokes and reports in the login + /// JWT. Losing it (a reinstall) is deliberately the same as a new device. + static Future getOrCreateDeviceId() async { + final stored = await _secureStorage.read(key: _deviceIdKey); + if (stored != null && stored.isNotEmpty) { + return stored; + } + final id = const Uuid().v4(); + await _secureStorage.write(key: _deviceIdKey, value: id); + return id; + } + + /// Human readable name of this platform, shown in the device list. + static String get deviceLabel { + if (Platform.isAndroid) { + return 'Android'; + } + if (Platform.isIOS) { + return 'iOS'; + } + if (Platform.isLinux) { + return 'Linux'; + } + if (Platform.isMacOS) { + return 'macOS'; + } + if (Platform.isWindows) { + return 'Windows'; + } + return Platform.operatingSystem; + } + + /// Server platform tag of this installation. + static String get devicePlatform => Platform.operatingSystem; + + /// Highest archive `seq` stored on this device. A reconnect asks the server + /// for everything above it instead of receiving a full queue dump. + static Future getSyncSeq() async { + Box box = await Hive.openBox(_settingsKey); + return box.get(_syncSeqKey) as int? ?? 0; + } + + /// Advances the archive cursor. It never moves backwards: a sync page can + /// arrive out of order after two overlapping requests. + static Future setSyncSeq(int seq) async { + Box box = await Hive.openBox(_settingsKey); + final stored = box.get(_syncSeqKey) as int? ?? 0; + if (seq > stored) { + await box.put(_syncSeqKey, seq); + } + } + /// Opens box with password hash static Future _openPasswordHashBox() async { return Hive.openBox(_hashBoxKey); diff --git a/lib/utils/crypto_utils.dart b/lib/utils/crypto_utils.dart index ac39f57..7fa01a3 100644 --- a/lib/utils/crypto_utils.dart +++ b/lib/utils/crypto_utils.dart @@ -132,16 +132,26 @@ class CryptoUtils { /// /// [nonce] is the one-time challenge from the server: it is signed into the /// token and spent on use, so a captured token cannot be replayed. - static Future generateRsaJwt( - String userId, RSAPrivateKey privateKey, - {required String nonce}) async { - return await compute(_generateRsaJwt, - {'userId': userId, 'privateKey': privateKey, 'nonce': nonce}); + /// + /// [deviceId] is signed too (`did`), so the request body cannot name a + /// different device than the one that proved the account key. + static Future generateRsaJwt(String userId, RSAPrivateKey privateKey, + {required String nonce, required String deviceId}) async { + return await compute(_generateRsaJwt, { + 'userId': userId, + 'privateKey': privateKey, + 'nonce': nonce, + 'deviceId': deviceId, + }); } /// Generate JWT token synchronously. static String _generateRsaJwt(Map data) { - final jwt = djwt.JWT({'sub': data['userId'], 'nonce': data['nonce']}); + final jwt = djwt.JWT({ + 'sub': data['userId'], + 'did': data['deviceId'], + 'nonce': data['nonce'], + }); Duration expiresIn = Duration(seconds: 5); // dart_jsonwebtoken writes `nbf = now + notBefore`, so a negative value // backdates the token and a server clock a few seconds behind the phone no diff --git a/lib/utils/notification_service.dart b/lib/utils/notification_service.dart index bb228a7..4141826 100644 --- a/lib/utils/notification_service.dart +++ b/lib/utils/notification_service.dart @@ -200,6 +200,32 @@ class NotificationService { ); } + /// Show a server-side security notice, e.g. a login from another device. + /// + /// It carries no message content and no payload: tapping it only opens the + /// app, the device list is where the action happens. + Future showSecurityNotification(String title, String body) async { + AndroidNotificationDetails androidPlatformChannelSpecifics = + AndroidNotificationDetails( + 'whisperLocalNotificationSecurity', + 'whisperLocalNotificationSecurity'.tr(), + channelDescription: 'notificationChannelDesc'.tr(), + importance: Importance.high, + priority: Priority.high, + ticker: 'tickerLocalNotification'.tr(), + enableVibration: true, + playSound: true, + sound: RawResourceAndroidNotificationSound('notification'), + ); + await _flutterLocalNotificationsPlugin.show( + id: title.hashCode & 0x7fffffff, + title: title, + body: body, + notificationDetails: + NotificationDetails(android: androidPlatformChannelSpecifics), + ); + } + /// Remove notifications by ID Future removeNotificationsById(List ids) async { final activeNotifications = diff --git a/lib/utils/singleton.dart b/lib/utils/singleton.dart index 3ed2594..8baf1cb 100644 --- a/lib/utils/singleton.dart +++ b/lib/utils/singleton.dart @@ -7,6 +7,7 @@ import 'package:fluttertoast/fluttertoast.dart'; import 'package:whisper_openapi_client_dart/api.dart'; import 'package:whisper_websocket_client_dart/ws_client.dart'; import '../models/app_theme.dart'; +import 'version.dart'; import '../models/profile.dart'; import 'package:flutter/foundation.dart'; @@ -56,7 +57,9 @@ class Singleton { ..connectionTimeout = const Duration(seconds: 15) ..idleTimeout = const Duration(seconds: 30); return ApiClient(basePath: basePath, authentication: authentication) - ..client = IOClient(httpClient); + ..client = IOClient(httpClient) + // Every request names the app version; the login gate reads it. + ..addDefaultHeader('X-Client-Version', appVersion); } set offlineMode(bool offline) { @@ -86,5 +89,7 @@ class Singleton { MediaApi get mediaApi => MediaApi(_api); + MessagesApi get messagesApi => MessagesApi(_api); + bool get offlineMode => _offlineMode; } diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index e216998..3dd8809 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -13,9 +13,9 @@ import '../pages/chat_page.dart'; import 'package:whisper_openapi_client_dart/api.dart'; import 'package:basic_utils/basic_utils.dart' as bu; import 'package:whisper_websocket_client_dart/models/delivery_ack.dart'; +import 'package:whisper_websocket_client_dart/models/synced.dart'; import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import 'package:whisper_websocket_client_dart/models/private_message.dart'; -import 'package:whisper_websocket_client_dart/models/ws_message.dart'; import 'package:whisper_websocket_client_dart/models/ws_response.dart'; import 'package:whisper_websocket_client_dart/models/ws_response_type.dart'; import 'cache_utils.dart'; @@ -25,6 +25,7 @@ import 'media_utils.dart'; import 'message_notifier.dart'; import 'singleton.dart'; import '../models/private_message.dart' as pm; +import '../models/user.dart'; class Utils { /// Localized text for a server error code (the server only sends camelCase @@ -177,13 +178,20 @@ class Utils { useSecurity: false, showError: false); if (challenge != null) { - final token = await CryptoUtils.generateRsaJwt( - profile.user.id, + // The device id is created once per installation, signed into the + // login JWT and registered by the server, so it can be revoked. + final deviceId = await CacheUtils.getOrCreateDeviceId(); + final token = await CryptoUtils.generateRsaJwt(profile.user.id, bu.CryptoUtils.rsaPrivateKeyFromPem(profile.privateKey), - nonce: challenge.challenge); + nonce: challenge.challenge, deviceId: deviceId); final authResponse = await Utils.callApi( () => Singleton().authApi.authUser( - authUserInput: AuthUserInput(token: token)), + authUserInput: AuthUserInput( + token: token, + deviceId: deviceId, + label: CacheUtils.deviceLabel, + platform: CacheUtils.devicePlatform, + )), useSecurity: false, showError: false); if (authResponse != null) { @@ -264,199 +272,237 @@ class Utils { return '$wsUrl/ws'; } - /// Handle WebSocket message - static Future onWsMessageReceived(WsResponse wsResponse) async { - switch (wsResponse.type) { - // More messages - case WsResponseType.messages: - var messages = wsResponse.payload as List; - messages.sort((a, b) => a.sentAt.compareTo(b.sentAt)); - List decryptedMessages = []; - // Media references of each conversation that still need a download. - final pendingMediaRefs = >{}; + /// Decrypt, store and optionally announce a batch of messages. + /// + /// Live frames are announced (a notification per conversation) and their + /// older echoes are dropped; history from a sync is stored silently. + static Future _storeMessages(List messages, + {required bool notify}) async { + messages.sort((a, b) => a.sentAt.compareTo(b.sentAt)); + List decryptedMessages = []; + // Media references of each conversation that still need a download. + final pendingMediaRefs = >{}; + try { + // One isolate for the whole batch: a per-message decrypt used to + // cost an RSA key parse and an isolate spawn each. + List decryptedBatch; + try { + decryptedBatch = await CryptoUtils.decryptMessageBatch( + messages + .map((message) => { + 'data': message.content, + 'key': message.key, + 'nonce': message.nonce, + 'mac': message.mac, + }) + .toList(), + Singleton().profile.privateKey); + } catch (_) { + // A batch failure must not drop the messages: they become visible + // placeholders below instead of disappearing. + decryptedBatch = List.filled(messages.length, null); + } + + final decryptionTasks = messages.asMap().entries.map((entry) async { + final index = entry.key; + final message = entry.value; try { - // One isolate for the whole batch: a per-message decrypt used to - // cost an RSA key parse and an isolate spawn each. - List decryptedBatch; - try { - decryptedBatch = await CryptoUtils.decryptMessageBatch( - messages - .map((message) => { - 'data': message.content, - 'key': message.key, - 'nonce': message.nonce, - 'mac': message.mac, - }) - .toList(), - Singleton().profile.privateKey); - } catch (_) { - // A batch failure must not drop the messages: they become visible - // placeholders below instead of disappearing. - decryptedBatch = List.filled(messages.length, null); + final decryptedMessage = decryptedBatch[index]; + if (decryptedMessage == null) { + throw const FormatException('message decryption failed'); } - - final decryptionTasks = messages.asMap().entries.map((entry) async { - final index = entry.key; - final message = entry.value; - try { - final decryptedMessage = decryptedBatch[index]; - if (decryptedMessage == null) { - throw const FormatException('message decryption failed'); - } - // Media message: decode the envelope and create a placeholder. - final envelope = - MediaUtils.tryParseMediaEnvelope(decryptedMessage); - if (envelope != null) { - if (envelope.references.length > 1) { - // Album: one bubble, one download per attachment. - final albumMsg = pm.PrivateMessage( - message.senderId, - envelope.caption, - message.sentAt, - DateTime.now(), - false, - downloadStatus: pm.MediaDownloadStatus.pending, - ); - albumMsg.setAlbum(envelope.references - .map((ref) => pm.AlbumItem( - mediaId: ref.mediaId, - type: ref.type.name, - size: ref.size, - width: ref.width, - height: ref.height, - durationMs: ref.durationMs, - fileName: ref.fileName, - status: pm.MediaDownloadStatus.pending, - )) - .toList()); - return (albumMsg, envelope.references); - } - final ref = envelope.references.single; - final mediaMsg = pm.PrivateMessage( - message.senderId, - envelope.caption, - message.sentAt, - DateTime.now(), - false, - mediaId: ref.mediaId, - mediaTypeStr: ref.type.name, - mediaSize: ref.size, - width: ref.width, - height: ref.height, - durationMs: ref.durationMs, - fileName: ref.fileName, - downloadStatus: pm.MediaDownloadStatus.pending, - ); - return (mediaMsg, [ref]); - } - // Plain text message (legacy/unchanged path). - final textMsg = pm.PrivateMessage( - message.senderId, - utf8.decode(decryptedMessage), - message.sentAt, - DateTime.now(), - false); - return (textMsg, const []); - } catch (e) { - // Log individual message decryption errors - if (kDebugMode) { - debugPrint( - 'Failed to decrypt message from ${message.senderId}: $e'); - } - // Keep a visible placeholder: dropping the message hides the loss - // from the user and from the server (which still has the entry). - return ( - pm.PrivateMessage( - message.senderId, - pm.PrivateMessage.undecryptableMarker, - message.sentAt, - DateTime.now(), - false, - ), - const [] + // Media message: decode the envelope and create a placeholder. + final envelope = MediaUtils.tryParseMediaEnvelope(decryptedMessage); + if (envelope != null) { + if (envelope.references.length > 1) { + // Album: one bubble, one download per attachment. + final albumMsg = pm.PrivateMessage( + message.senderId, + envelope.caption, + message.sentAt, + DateTime.now(), + false, + downloadStatus: pm.MediaDownloadStatus.pending, ); + albumMsg.setAlbum(envelope.references + .map((ref) => pm.AlbumItem( + mediaId: ref.mediaId, + type: ref.type.name, + size: ref.size, + width: ref.width, + height: ref.height, + durationMs: ref.durationMs, + fileName: ref.fileName, + status: pm.MediaDownloadStatus.pending, + )) + .toList()); + return (albumMsg, envelope.references, message.peerId); } - }); - - final results = await Future.wait(decryptionTasks); - - // Filter out failed decryptions (null values) - final valid = results - .whereType<(pm.PrivateMessage, List)>() - .toList(); - decryptedMessages = valid.map((e) => e.$1).toList(); - for (final (message, refs) in valid) { - if (refs.isNotEmpty) { - pendingMediaRefs - .putIfAbsent(message.senderId, () => []) - .addAll(refs); - } + final ref = envelope.references.single; + final mediaMsg = pm.PrivateMessage( + message.senderId, + envelope.caption, + message.sentAt, + DateTime.now(), + false, + mediaId: ref.mediaId, + mediaTypeStr: ref.type.name, + mediaSize: ref.size, + width: ref.width, + height: ref.height, + durationMs: ref.durationMs, + fileName: ref.fileName, + downloadStatus: pm.MediaDownloadStatus.pending, + ); + return (mediaMsg, [ref], message.peerId); } - - // Show toast only if all messages failed to decrypt - if (decryptedMessages.isEmpty && messages.isNotEmpty) { - await Fluttertoast.showToast( - msg: 'decryptionFailed'.tr(), backgroundColor: Colors.red); + // Plain text message (legacy/unchanged path). + final textMsg = pm.PrivateMessage( + message.senderId, + utf8.decode(decryptedMessage), + message.sentAt, + DateTime.now(), + false); + return (textMsg, const [], message.peerId); + } catch (e) { + // Log individual message decryption errors + if (kDebugMode) { + debugPrint( + 'Failed to decrypt message from ${message.senderId}: $e'); } - } catch (_) { - await Fluttertoast.showToast( - msg: 'decryptionFailed'.tr(), backgroundColor: Colors.red); + // Keep a visible placeholder: dropping the message hides the loss + // from the user and from the server (which still has the entry). + return ( + pm.PrivateMessage( + message.senderId, + pm.PrivateMessage.undecryptableMarker, + message.sentAt, + DateTime.now(), + false, + ), + const [], + message.peerId + ); } - // Self-sent messages are stored locally before sending; dropping the - // server echo prevents a duplicate bubble in the debug self-chat. - decryptedMessages.removeWhere( - (message) => message.senderId == Singleton().profile.user.id); - - if (decryptedMessages.isNotEmpty) { - // A batch can hold messages from several senders: store each - // conversation under its own key. - final bySender = >{}; - for (final message in decryptedMessages) { - bySender.putIfAbsent(message.senderId, () => []).add(message); - } - for (final entry in bySender.entries) { - await MessageNotifier().addMessages(entry.key, entry.value); - // Kick off media downloads now that placeholders are persisted. - for (final ref in pendingMediaRefs[entry.key] ?? const []) { - // Fire-and-forget; updates the message + notifies on completion. - MessageNotifier().downloadMediaMessage(entry.key, ref); - } - } + }); + + final results = await Future.wait(decryptionTasks); + + // Filter out failed decryptions (null values) + final valid = results + .whereType<(pm.PrivateMessage, List, String)>() + .toList(); + decryptedMessages = valid.map((e) => e.$1).toList(); + for (final (message, refs, _) in valid) { + if (refs.isNotEmpty) { + pendingMediaRefs.putIfAbsent(message.senderId, () => []).addAll(refs); + } + } - // Everything is stored (placeholders included): the server may drop - // these entries from the offline queue. - _ackReceived(messages); - - // Remove messages from notifications if user was not online when they were sent - decryptedMessages.removeWhere((x) => !messages - .where((y) => y.sentAt == x.sentAt && y.senderId == x.senderId) - .first - .recipientOnline); - - bool homePageOpened = false; - var currentRoute = Singleton().currentRoute; - if (currentRoute is PageTransition) { - if (currentRoute.child is ChatPage) { - var chatPage = currentRoute.child as ChatPage; - // Delete messages of current open user chat from notifications - decryptedMessages - .removeWhere((x) => x.senderId == chatPage.user.id); - } - } else { - // Home page is opened - homePageOpened = true; - } - // Show notification if there are messages to announce and HomePage is not opened - if (decryptedMessages.isNotEmpty && !homePageOpened) { - if (Singleton().profile.enableNotifications) { - await NotificationService() - .showMessagesNotification(decryptedMessages); - } - } else { - // Vibrate if all messages were for currently opened user - Vibration.vibrate(pattern: [0, 150], intensities: [0, 255]); - } + // Show toast only if all messages failed to decrypt + if (decryptedMessages.isEmpty && messages.isNotEmpty) { + await Fluttertoast.showToast( + msg: 'decryptionFailed'.tr(), backgroundColor: Colors.red); + } + } catch (_) { + await Fluttertoast.showToast( + msg: 'decryptionFailed'.tr(), backgroundColor: Colors.red); + } + // Self-sent messages are stored locally before sending; dropping the live + // server echo prevents a duplicate bubble in the debug self-chat. The + // archive copy is kept, because it is what a fresh device syncs. + if (notify) { + decryptedMessages.removeWhere( + (message) => message.senderId == Singleton().profile.user.id); + } + + if (decryptedMessages.isEmpty) { + return; + } + // A batch can hold messages from several peers: store each conversation + // under its own key. The peer id and not the sender is the conversation: + // an archived message we sent has our own id as the sender. + final byPeer = >{}; + final peerOfMessage = {}; + for (final message in messages) { + peerOfMessage[ + '${message.senderId}|${message.sentAt.toUtc().toIso8601String()}'] = + message.peerId; + } + for (final message in decryptedMessages) { + final peer = peerOfMessage[ + '${message.senderId}|${message.sentAt.toUtc().toIso8601String()}'] ?? + message.senderId; + byPeer.putIfAbsent(peer, () => []).add(message); + } + for (final entry in byPeer.entries) { + await MessageNotifier().addMessages(entry.key, entry.value); + // Kick off media downloads now that placeholders are persisted. + for (final ref in pendingMediaRefs[entry.key] ?? const []) { + // Fire-and-forget; updates the message + notifies on completion. + MessageNotifier().downloadMediaMessage(entry.key, ref); + } + } + + if (!notify) { + return; + } + + // Remove messages from notifications if user was not online when they were sent + decryptedMessages.removeWhere((x) => !messages + .where((y) => y.sentAt == x.sentAt && y.senderId == x.senderId) + .first + .recipientOnline); + + bool homePageOpened = false; + var currentRoute = Singleton().currentRoute; + if (currentRoute is PageTransition) { + if (currentRoute.child is ChatPage) { + var chatPage = currentRoute.child as ChatPage; + // Delete messages of current open user chat from notifications + decryptedMessages.removeWhere((x) => x.senderId == chatPage.user.id); + } + } else { + // Home page is opened + homePageOpened = true; + } + // Show notification if there are messages to announce and HomePage is not opened + if (decryptedMessages.isNotEmpty && !homePageOpened) { + if (Singleton().profile.enableNotifications) { + await NotificationService().showMessagesNotification(decryptedMessages); + } + } else { + // Vibrate if all messages were for currently opened user + Vibration.vibrate(pattern: [0, 150], intensities: [0, 255]); + } + } + + /// Handle WebSocket message + static Future onWsMessageReceived(WsResponse wsResponse) async { + switch (wsResponse.type) { + // More messages + case WsResponseType.messages: + await _storeMessages(wsResponse.payload as List, + notify: true); + break; + + // Archive delta after a reconnect + case WsResponseType.synced: + final synced = wsResponse.payload as Synced; + for (final peer in synced.peers) { + // A fresh device learns the accounts it is talking to from the batch. + await CacheUtils.addUser( + User(peer.id, peer.username, peer.publicKey, false)); + } + await CacheUtils.setSyncSeq(synced.syncedThrough); + if (synced.messages.isNotEmpty) { + // History is silent: a week offline must not ring once per old + // message. + await _storeMessages(synced.messages, notify: false); + } + if (synced.hasMore && Singleton().wsClient.isConnected) { + Singleton().wsClient.sendSync(synced.syncedThrough); } break; @@ -483,27 +529,43 @@ class Utils { } } - /// Tells the server the received messages are stored, so it can drop them - /// from the offline queue. Batched, the server accepts at most 100 per ack. - static void _ackReceived(List messages) { - if (messages.isEmpty || !Singleton().wsClient.isConnected) { + /// Decrypt and store a page from the history endpoint. + /// + /// History is silent: no notifications and no vibration, the messages are + /// older than anything the device already has. + static Future storeHistoryPage( + List messages) async { + if (messages.isEmpty) { return; } - final acked = messages - .map((message) => AckedMessage(message.senderId, message.sentAt)) + final wire = messages + .map((message) => PrivateMessage.fromJson({ + 'id': message.id, + 'seq': message.seq, + 'senderId': message.senderId, + 'peerId': message.peerId, + 'content': message.content, + 'key': message.key, + 'nonce': message.nonce, + 'mac': message.mac, + 'sentAt': message.sentAt.toIso8601String(), + 'recipientOnline': false, + })) .toList(); - const batchSize = 100; - for (var i = 0; i < acked.length; i += batchSize) { - final end = - i + batchSize < acked.length ? i + batchSize : acked.length; - try { - Singleton() - .wsClient - .sendMessage(WsMessage.ack(acked.sublist(i, end))); - } catch (e) { - if (kDebugMode) { - debugPrint('ack failed: $e'); - } + await _storeMessages(wire, notify: false); + } + + /// Ask the server for the archive delta above the cursor stored on this + /// device. Nothing is pushed on connect, so this is what catches a client up. + static Future syncArchive() async { + if (!Singleton().wsClient.isConnected) { + return; + } + try { + Singleton().wsClient.sendSync(await CacheUtils.getSyncSeq()); + } catch (e) { + if (kDebugMode) { + debugPrint('sync request failed: $e'); } } } @@ -569,6 +631,9 @@ class Utils { // Messages that never got a delivery ack are retried now; the server // deduplicates them by (receiver, sentAt). await ChatSender.resendPending(); + // Nothing is pushed on connect: ask for the archive delta above the last + // seq stored here. A phone away for a week fetches only that week. + await syncArchive(); final onConnected = Utils.onConnected; if (onConnected != null) { await onConnected(); diff --git a/lib/utils/version.dart b/lib/utils/version.dart new file mode 100644 index 0000000..c156336 --- /dev/null +++ b/lib/utils/version.dart @@ -0,0 +1,3 @@ +/// Version of this app build, sent as `X-Client-Version`. The server refuses a +/// login below its `minClientVersion` with a code we can translate. +const String appVersion = '0.1.0'; diff --git a/pubspec.lock b/pubspec.lock index bed3ea7..30987dc 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1783,14 +1783,14 @@ packages: path: "../whisper_openapi_client_dart" relative: true source: path - version: "0.0.1" + version: "0.1.0" whisper_websocket_client_dart: dependency: "direct main" description: path: "../whisper_websocket_client_dart" relative: true source: path - version: "1.0.0" + version: "0.1.0" win32: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 2ec7495..f6c2dd6 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,7 +3,7 @@ description: "Secure private self-hosted end-to-end encryption messaging app." publish_to: 'none' # Remove this line if you wish to publish to pub.dev # Bump before every release; the release workflow tags v and fails if # that tag already exists. The build number after + must only ever grow. -version: 0.1.0+2 +version: 0.1.0+3 environment: sdk: '>=3.4.3 <4.0.0' @@ -46,10 +46,16 @@ dependencies: uuid: ^4.5.3 vibration: ^3.1.2 video_player: ^2.11.1 + # Clients are pinned by release tag: the app records which contract it was + # built against. Local development overrides the paths at the bottom. whisper_openapi_client_dart: - path: ../whisper_openapi_client_dart + git: + url: https://github.com/jsfraz/whisper_openapi_client_dart.git + ref: v0.1.0 whisper_websocket_client_dart: - path: ../whisper_websocket_client_dart + git: + url: https://github.com/jsfraz/whisper_websocket_client_dart.git + ref: v0.1.0 dev_dependencies: flutter_test: diff --git a/test/auth_refresh_fallback_test.dart b/test/auth_refresh_fallback_test.dart index 545730d..6d6a2db 100644 --- a/test/auth_refresh_fallback_test.dart +++ b/test/auth_refresh_fallback_test.dart @@ -55,6 +55,32 @@ void main() { const MethodChannel('plugins.flutter.io/path_provider'), (call) async => dir.path, ); + // The login now registers the installation, and the device id lives in + // secure storage. Keep it in memory for the test. + final secureStorage = {}; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.it_nomads.com/flutter_secure_storage'), + (call) async { + final args = (call.arguments as Map?) ?? const {}; + switch (call.method) { + case 'read': + return secureStorage[args['key']]; + case 'write': + secureStorage[args['key'] as String] = args['value'] as String; + return null; + case 'delete': + secureStorage.remove(args['key']); + return null; + case 'readAll': + return Map.from(secureStorage); + case 'deleteAll': + secureStorage.clear(); + return null; + } + return null; + }, + ); }); setUp(() async { @@ -65,8 +91,7 @@ void main() { 'http://localhost', User('user', 'tester', 'public-key', false), 'public-key', - bu.CryptoUtils.encodeRSAPrivateKeyToPem( - keys.privateKey as RSAPrivateKey), + bu.CryptoUtils.encodeRSAPrivateKeyToPem(keys.privateKey as RSAPrivateKey), tokenExpiring(inFuture: const Duration(minutes: 10)), tokenExpiring(inFuture: const Duration(days: 6), typ: 'refresh'), true, @@ -98,8 +123,8 @@ void main() { } else if (request.uri.path == '/api/auth') { expect(body, contains('token')); // The signed login token must carry the one-time challenge. - final token = (jsonDecode(body) as Map)['token'] - as String; + final token = + (jsonDecode(body) as Map)['token'] as String; final payload = jsonDecode(utf8.decode( base64Url.decode(base64Url.normalize(token.split('.')[1])))) as Map; @@ -108,6 +133,8 @@ void main() { request.response.write(jsonEncode({ 'accessToken': 'fresh-access', 'refreshToken': 'fresh-refresh', + // The login answer names the server build now; the model requires it. + 'serverVersion': '0.1.0', })); } else { request.response.statusCode = 404; @@ -115,8 +142,7 @@ void main() { } await request.response.close(); }); - Singleton().api = - ApiClient(basePath: 'http://127.0.0.1:${server.port}'); + Singleton().api = ApiClient(basePath: 'http://127.0.0.1:${server.port}'); } test('a refused refresh falls back to the RSA login', () async { @@ -155,7 +181,8 @@ void main() { await startServer(refreshStatus: 200); Singleton().profile.accessToken = tokenExpiring(inFuture: Duration.zero); - await Future.wait([Utils.authCheck(), Utils.authCheck(), Utils.authCheck()]); + await Future.wait( + [Utils.authCheck(), Utils.authCheck(), Utils.authCheck()]); expect(requestedPaths, ['/api/auth/refresh']); expect(Singleton().profile.accessToken, 'refreshed-access'); diff --git a/test/crypto_test.dart b/test/crypto_test.dart index da2c404..d8e007d 100644 --- a/test/crypto_test.dart +++ b/test/crypto_test.dart @@ -18,7 +18,7 @@ void main() async { var keyPair = await CryptoUtils.getRSAKeyPair(); final token = await CryptoUtils.generateRsaJwt( '1', keyPair.privateKey as bu.RSAPrivateKey, - nonce: 'test-challenge'); + nonce: 'test-challenge', deviceId: 'device'); debugPrint(token); }); @@ -26,17 +26,18 @@ void main() async { var keyPair = await CryptoUtils.getRSAKeyPair(); final token = await CryptoUtils.generateRsaJwt( '1', keyPair.privateKey as bu.RSAPrivateKey, - nonce: 'test-challenge'); + nonce: 'test-challenge', deviceId: 'device'); - final payload = jsonDecode( - utf8.decode(base64Url.decode(base64Url.normalize(token.split('.')[1])))) + final payload = jsonDecode(utf8 + .decode(base64Url.decode(base64Url.normalize(token.split('.')[1])))) as Map; - final notBefore = DateTime.fromMillisecondsSinceEpoch( - (payload['nbf'] as int) * 1000); + final notBefore = + DateTime.fromMillisecondsSinceEpoch((payload['nbf'] as int) * 1000); // A token whose nbf is "now" is rejected by a server whose clock is a // little behind; it must already be valid. expect(notBefore.isBefore(DateTime.now()), isTrue); - expect(notBefore.isAfter(DateTime.now().subtract(const Duration(minutes: 1))), + expect( + notBefore.isAfter(DateTime.now().subtract(const Duration(minutes: 1))), isTrue); }); } diff --git a/test/device_and_sync_test.dart b/test/device_and_sync_test.dart new file mode 100644 index 0000000..9012568 --- /dev/null +++ b/test/device_and_sync_test.dart @@ -0,0 +1,68 @@ +import 'dart:io'; + +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/utils/cache_utils.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_device_sync_test'); + Hive.init(dir.path); + // The device id lives in secure storage, which a unit test has to fake. + final secureStorage = {}; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.it_nomads.com/flutter_secure_storage'), + (call) async { + final args = (call.arguments as Map?) ?? const {}; + switch (call.method) { + case 'read': + return secureStorage[args['key']]; + case 'write': + secureStorage[args['key'] as String] = args['value'] as String; + return null; + case 'delete': + secureStorage.remove(args['key']); + return null; + } + return null; + }, + ); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('the device id is created once and reused', () async { + final first = await CacheUtils.getOrCreateDeviceId(); + expect(first, isNotEmpty); + // A second login must reuse it, otherwise a revocation cannot target it. + expect(await CacheUtils.getOrCreateDeviceId(), first); + }); + + test('the device label is a readable platform name', () { + expect(CacheUtils.deviceLabel, isNotEmpty); + expect(CacheUtils.devicePlatform, Platform.operatingSystem); + }); + + test('the archive cursor starts at zero and never moves backwards', () async { + expect(await CacheUtils.getSyncSeq(), 0); + + await CacheUtils.setSyncSeq(10); + expect(await CacheUtils.getSyncSeq(), 10); + + // Two overlapping sync answers may arrive out of order; the stale one must + // not rewind the cursor, or the same messages would be fetched again. + await CacheUtils.setSyncSeq(4); + expect(await CacheUtils.getSyncSeq(), 10); + + await CacheUtils.setSyncSeq(12); + expect(await CacheUtils.getSyncSeq(), 12); + }); +} From 784b7a3013b913ddf3381c1e0a0aec5ffad725dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 17 Nov 2026 18:49:30 +0100 Subject: [PATCH 071/181] fix(ws): keep a refused reconnect silent The backoff loop retries every few seconds; a toast per attempt would bury a revoked device in identical errors. --- lib/utils/utils.dart | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 3dd8809..1f171e0 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -592,9 +592,12 @@ class Utils { try { // Attempt to get WebSocket access token + // A refused handshake is retried by the backoff loop; a toast per attempt + // would spam the user of a revoked device. var wsAuthResponse = await Utils.callApi( () => Singleton().wsAuthApi.webSocketAuth(), useSecurity: true, + showError: false, ).timeout( Duration(seconds: 10), // Add timeout for API calls onTimeout: () => null, From c1713ad60ca622e0e24ef56ba0a807a56b32859b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 17 Nov 2026 18:50:39 +0100 Subject: [PATCH 072/181] fix(sync): move the delta cursor only on global batches A live frame is global, so storing it advances the cursor and the next sync does not return it (which would overwrite a downloaded attachment with its placeholder). A history page is one conversation: advancing the cursor from it would skip messages of the other chats. --- lib/utils/utils.dart | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 1f171e0..543471b 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -277,7 +277,7 @@ class Utils { /// Live frames are announced (a notification per conversation) and their /// older echoes are dropped; history from a sync is stored silently. static Future _storeMessages(List messages, - {required bool notify}) async { + {required bool notify, bool advanceCursor = false}) async { messages.sort((a, b) => a.sentAt.compareTo(b.sentAt)); List decryptedMessages = []; // Media references of each conversation that still need a download. @@ -444,6 +444,21 @@ class Utils { MessageNotifier().downloadMediaMessage(entry.key, ref); } } + // A live message would otherwise come back on the next sync and overwrite + // a downloaded attachment with its placeholder. Only live frames may move + // the cursor: a history page is one conversation and says nothing about + // the messages of the others. + if (advanceCursor) { + var highestSeq = 0; + for (final message in messages) { + if (message.seq > highestSeq) { + highestSeq = message.seq; + } + } + if (highestSeq > 0) { + await CacheUtils.setSyncSeq(highestSeq); + } + } if (!notify) { return; @@ -484,7 +499,7 @@ class Utils { // More messages case WsResponseType.messages: await _storeMessages(wsResponse.payload as List, - notify: true); + notify: true, advanceCursor: true); break; // Archive delta after a reconnect @@ -495,12 +510,14 @@ class Utils { await CacheUtils.addUser( User(peer.id, peer.username, peer.publicKey, false)); } - await CacheUtils.setSyncSeq(synced.syncedThrough); if (synced.messages.isNotEmpty) { // History is silent: a week offline must not ring once per old // message. await _storeMessages(synced.messages, notify: false); } + // Only after the batch is stored: a cursor ahead of the local messages + // would drop them for good. + await CacheUtils.setSyncSeq(synced.syncedThrough); if (synced.hasMore && Singleton().wsClient.isConnected) { Singleton().wsClient.sendSync(synced.syncedThrough); } From edef0078743ea2016bd12fdea5339f5a071d92a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 17 Nov 2026 18:51:29 +0100 Subject: [PATCH 073/181] chore(deps): resolve the lock against the pinned client tags The lock recorded the local path overrides; CI and releases resolve the v0.1.0 tags, so the committed lock has to say the same. --- pubspec.lock | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index 30987dc..f81726e 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1780,16 +1780,20 @@ packages: whisper_openapi_client_dart: dependency: "direct main" description: - path: "../whisper_openapi_client_dart" - relative: true - source: path + path: "." + ref: "v0.1.0" + resolved-ref: "6e97e025fa4408ae0b93c90ce500b4d83b1694e1" + url: "https://github.com/jsfraz/whisper_openapi_client_dart.git" + source: git version: "0.1.0" whisper_websocket_client_dart: dependency: "direct main" description: - path: "../whisper_websocket_client_dart" - relative: true - source: path + path: "." + ref: "v0.1.0" + resolved-ref: e590c319d5074442ae4a5ee7d0891a4bf358982f + url: "https://github.com/jsfraz/whisper_websocket_client_dart.git" + source: git version: "0.1.0" win32: dependency: transitive From 13c44dd85e0af793862ba93c0872a96eab089d1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 17 Nov 2026 20:14:21 +0100 Subject: [PATCH 074/181] UI improvements --- assets/translations/cs.json | 13 ++++---- assets/translations/en.json | 13 ++++---- lib/pages/settings_page.dart | 59 +++++++++++++++++++++++++++++++++++- lib/utils/cache_utils.dart | 6 ++-- 4 files changed, 75 insertions(+), 16 deletions(-) diff --git a/assets/translations/cs.json b/assets/translations/cs.json index d17d456..708aa82 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -59,6 +59,7 @@ "userSearchFailed": "Hledání se nezdařilo", "settingsPage": "Nastavení", "themeSettings": "Motiv", + "languageSettings": "Jazyk aplikace", "chatTheme": "Téma chatu", "useGlobalTheme": "Použít globální motiv", "notificationSettings": "Oznámení", @@ -191,24 +192,24 @@ "unsupportedMessageType": "Nepodporovaný typ zprávy", "implausibleTimestamp": "Čas zprávy je mimo rozsah", "serverError": "Neočekávaná chyba serveru", - "httpError": "HTTP chyba %s", + "httpError": "HTTP chyba {}", "devicesPage": "Zařízení", "devicesSettings": "Zařízení a relace", "thisDevice": "toto zařízení", - "deviceLastSeen": "Naposledy aktivní %s", - "deviceRevokedAt": "Zablokováno %s", + "deviceLastSeen": "Naposledy aktivní {}", + "deviceRevokedAt": "Zablokováno {}", "revoke": "Zablokovat", "unrevoke": "Povolit znovu", "revokeDevice": "Zablokovat zařízení", "unrevokeDevice": "Povolit zařízení znovu", - "revokeDeviceConfirm": "Zablokovat „%s“? Nebude se moci přihlásit, posílat ani přijímat, dokud ho jiné zařízení znovu nepovolí.", - "unrevokeDeviceConfirm": "Povolit „%s“ znovu přihlášení?", + "revokeDeviceConfirm": "Zablokovat „{}“? Nebude se moci přihlásit, posílat ani přijímat, dokud ho jiné zařízení znovu nepovolí.", + "unrevokeDeviceConfirm": "Povolit „{}“ znovu přihlášení?", "deviceRevokedToast": "Zařízení zablokováno", "deviceUnrevokedToast": "Zařízení znovu povoleno", "retentionSettings": "Retence historie na serveru", "retentionTitle": "Jak dlouho server drží historii", "retentionExplain": "Šifrovaný obsah zpráv zůstává na serveru, aby se offline zařízení dohnalo. Platí kratší nastavení z obou stran konverzace.", - "retentionDays": "%s dní", + "retentionDays": "{} dní", "retentionSaved": "Retence upravena", "deviceRevoked": "Toto zařízení bylo zablokováno. Povolit ho znovu lze z jiného zařízení.", "clientVersionUnsupported": "Aplikace je pro server příliš stará. Aktualizujte ji.", diff --git a/assets/translations/en.json b/assets/translations/en.json index b8c3fef..de29ca8 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -59,6 +59,7 @@ "userSearchFailed": "Search failed", "settingsPage": "Settings", "themeSettings": "Theme", + "languageSettings": "App language", "chatTheme": "Chat theme", "useGlobalTheme": "Use global theme", "notificationSettings": "Notifications", @@ -191,24 +192,24 @@ "unsupportedMessageType": "Unsupported message type", "implausibleTimestamp": "The message timestamp is out of range", "serverError": "Unexpected server error", - "httpError": "HTTP error %s", + "httpError": "HTTP error {}", "devicesPage": "Devices", "devicesSettings": "Devices and sessions", "thisDevice": "this device", - "deviceLastSeen": "Last seen %s", - "deviceRevokedAt": "Revoked %s", + "deviceLastSeen": "Last seen {}", + "deviceRevokedAt": "Revoked {}", "revoke": "Revoke", "unrevoke": "Allow again", "revokeDevice": "Revoke device", "unrevokeDevice": "Allow device again", - "revokeDeviceConfirm": "Revoke \"%s\"? It cannot sign in, send or receive until another device allows it again.", - "unrevokeDeviceConfirm": "Allow \"%s\" to sign in again?", + "revokeDeviceConfirm": "Revoke \"{}\"? It cannot sign in, send or receive until another device allows it again.", + "unrevokeDeviceConfirm": "Allow \"{}\" to sign in again?", "deviceRevokedToast": "Device revoked", "deviceUnrevokedToast": "Device allowed again", "retentionSettings": "Server history retention", "retentionTitle": "How long the server keeps history", "retentionExplain": "Ciphertext of your messages stays on the server so an offline device can catch up. The shorter setting of the two participants wins.", - "retentionDays": "%s days", + "retentionDays": "{} days", "retentionSaved": "Retention updated", "deviceRevoked": "This device was revoked. Sign in on another device to allow it again.", "clientVersionUnsupported": "This app is too old for the server. Update it.", diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 0120243..5b5dba7 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -27,7 +27,7 @@ class SettingsPage extends StatefulWidget { class _SettingsPageState extends State { bool _isBiometryEnabled = false; - bool _notificationPreview = true; + bool _notificationPreview = false; @override void initState() { @@ -91,6 +91,42 @@ class _SettingsPageState extends State { msg: 'retentionSaved'.tr(), backgroundColor: Colors.grey); } + /// Language is stored by easy_localization in SharedPreferences. + Future _showLanguageDialog() async { + final selected = await showDialog( + context: context, + builder: (dialogContext) => SimpleDialog( + title: Text('languageSettings'.tr()), + children: [ + for (final locale in context.supportedLocales) + SimpleDialogOption( + onPressed: () => Navigator.of(dialogContext).pop(locale), + child: Row( + children: [ + Icon( + context.locale.languageCode == locale.languageCode + ? Icons.radio_button_checked + : Icons.radio_button_unchecked, + size: 20, + color: Theme.of(dialogContext).colorScheme.secondary, + ), + const SizedBox(width: 8), + Text(_languageNames[locale.languageCode] ?? + locale.languageCode), + ], + ), + ), + ], + ), + ); + if (selected == null || !mounted) { + return; + } + await context.setLocale(selected); + } + + static const _languageNames = {'cs': 'Čeština', 'en': 'English'}; + Future _toggleBiometry(bool switchValue) async { if (switchValue) { // Enable @@ -162,6 +198,27 @@ class _SettingsPageState extends State { ], ), ), + // Language + TextButton( + onPressed: _showLanguageDialog, + child: Row( + children: [ + Icon( + Icons.language, + size: 24, + color: Theme.of(context).colorScheme.secondary, + ), + Padding( + padding: EdgeInsets.only(left: 5), + child: Text( + 'languageSettings'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.secondary), + ), + ), + ], + ), + ), // Notifications TextButton( onPressed: null, diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 554c096..a08cf6a 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -327,11 +327,11 @@ class CacheUtils { await box.put(_biometry, enabled); } - /// Whether notifications may show the decrypted message text. Default on, - /// matching the previous behaviour; the user can hide it. + /// Whether notifications may show the decrypted message text. Default off: + /// the text stays hidden until the user opts in. static Future getNotificationPreview() async { Box box = await Hive.openBox(_settingsKey); - return box.get(_notificationPreviewKey) as bool? ?? true; + return box.get(_notificationPreviewKey) as bool? ?? false; } /// Sets whether notifications may show the message text. From 970679d628856a39737c9542d953e8ea1200d4c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 17 Nov 2026 20:36:17 +0100 Subject: [PATCH 075/181] Retention dialog fix --- lib/pages/chat_info_page.dart | 74 +---- lib/pages/settings_page.dart | 504 +++++++++++---------------------- lib/widgets/settings_tile.dart | 52 ++++ test/settings_tile_test.dart | 28 ++ 4 files changed, 254 insertions(+), 404 deletions(-) create mode 100644 lib/widgets/settings_tile.dart create mode 100644 test/settings_tile_test.dart diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index aa86b7a..4ce7d01 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -11,6 +11,7 @@ import '../utils/media_utils.dart'; import '../utils/singleton.dart'; import '../utils/theme_utils.dart'; import '../widgets/media_bubble.dart'; +import '../widgets/settings_tile.dart'; import 'home_page.dart'; import 'media_viewer_page.dart'; @@ -112,23 +113,14 @@ class _ChatInfoPageState extends State { child: Column( children: [ // Chat theme - TextButton( + SettingsTile( + icon: Icons.palette, + label: 'chatTheme'.tr(), onPressed: _pickChatTheme, - child: Row( - children: [ - Icon( - Icons.palette, - size: 24, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'chatTheme'.tr(), - ), - ), - if (_chatThemeColor != null) - Padding( - padding: EdgeInsets.only(left: 10), + extra: _chatThemeColor == null + ? null + : Padding( + padding: const EdgeInsets.only(left: 10), child: Container( width: 16, height: 16, @@ -138,33 +130,13 @@ class _ChatInfoPageState extends State { ), ), ), - SizedBox( - width: 24, - ), - ], - ), ), // Drop the override if (_chatThemeColor != null) - TextButton( + SettingsTile( + icon: Icons.restart_alt, + label: 'useGlobalTheme'.tr(), onPressed: _clearChatTheme, - child: Row( - children: [ - Icon( - Icons.restart_alt, - size: 24, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'useGlobalTheme'.tr(), - ), - ), - SizedBox( - width: 24, - ), - ], - ), ), Divider(thickness: 1, indent: 10, endIndent: 10), @@ -208,7 +180,10 @@ class _ChatInfoPageState extends State { Divider(thickness: 1, indent: 10, endIndent: 10), // Delete chat - TextButton( + SettingsTile( + icon: Icons.delete_forever, + label: 'deleteChat'.tr(), + color: Colors.red, onPressed: () async { await DialogUtils.yesNoDialog( context, @@ -223,25 +198,6 @@ class _ChatInfoPageState extends State { ); }); }, - child: Row( - children: [ - Icon( - Icons.delete_forever, - size: 24, - color: Colors.red, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'deleteChat'.tr(), - style: TextStyle(color: Colors.red), - ), - ), - SizedBox( - width: 24, - ), - ], - ), ), ], ), diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 5b5dba7..f713ab6 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -15,6 +15,7 @@ import '../utils/message_notifier.dart'; import '../utils/utils.dart'; import 'scan_invite_button_page.dart'; import '../widgets/change_password_dialog.dart'; +import '../widgets/settings_tile.dart'; import '../utils/nav_transitions.dart'; import 'devices_page.dart'; @@ -29,6 +30,10 @@ class _SettingsPageState extends State { bool _isBiometryEnabled = false; bool _notificationPreview = false; + /// Guards the retention flow: the settings round-trip is slow, and without it + /// a second tap stacks another dialog on top of the first. + bool _retentionBusy = false; + @override void initState() { super.initState(); @@ -44,51 +49,70 @@ class _SettingsPageState extends State { /// Server-side retention of the ciphertext archive. The shorter setting of /// the two participants wins, so this is a limit, not a promise. Future _showRetentionDialog() async { - final current = - await Utils.callApi(() => Singleton().userApi.getRetention()); - if (!mounted) { + if (_retentionBusy) { return; } - final selected = await showDialog( - context: context, - builder: (dialogContext) => SimpleDialog( - title: Text('retentionTitle'.tr()), - children: [ - Padding( - padding: const EdgeInsets.symmetric(horizontal: 24), - child: Text('retentionExplain'.tr()), - ), - for (final days in const [7, 30, 90, 365]) - SimpleDialogOption( - onPressed: () => Navigator.of(dialogContext).pop(days), - child: Row( - children: [ - Icon( - current?.days == days - ? Icons.radio_button_checked - : Icons.radio_button_unchecked, - size: 20, - color: Theme.of(dialogContext).colorScheme.secondary, - ), - const SizedBox(width: 8), - Text('retentionDays'.tr(args: [days.toString()])), - ], - ), + _retentionBusy = true; + try { + // Blocks the page while the request is in flight, so a fast second tap + // cannot reach the tile and nothing else can be tapped meanwhile. + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => const PopScope( + canPop: false, + child: Center(child: CircularProgressIndicator()), + ), + ); + final current = + await Utils.callApi(() => Singleton().userApi.getRetention()); + if (!mounted) { + return; + } + Navigator.of(context).pop(); + final selected = await showDialog( + context: context, + builder: (dialogContext) => SimpleDialog( + title: Text('retentionTitle'.tr()), + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Text('retentionExplain'.tr()), ), - ], - ), - ); - if (selected == null || !mounted) { - return; - } - await Utils.callApi(() => Singleton() - .userApi - .setRetention(setRetentionInput: SetRetentionInput(days: selected))); - if (!mounted) { - return; + for (final days in const [7, 30, 90, 365]) + SimpleDialogOption( + onPressed: () => Navigator.of(dialogContext).pop(days), + child: Row( + children: [ + Icon( + current?.days == days + ? Icons.radio_button_checked + : Icons.radio_button_unchecked, + size: 20, + color: Theme.of(dialogContext).colorScheme.secondary, + ), + const SizedBox(width: 8), + Text('retentionDays'.tr(args: [days.toString()])), + ], + ), + ), + ], + ), + ); + if (selected == null || !mounted) { + return; + } + await Utils.callApi(() => Singleton() + .userApi + .setRetention(setRetentionInput: SetRetentionInput(days: selected))); + if (!mounted) { + return; + } + await Fluttertoast.showToast( + msg: 'retentionSaved'.tr(), backgroundColor: Colors.grey); + } finally { + _retentionBusy = false; } - await Fluttertoast.showToast( - msg: 'retentionSaved'.tr(), backgroundColor: Colors.grey); } /// Language is stored by easy_localization in SharedPreferences. @@ -174,261 +198,82 @@ class _SettingsPageState extends State { child: SingleChildScrollView( child: Column( children: [ - // Theme - TextButton( - onPressed: () { - showDialog( - context: context, builder: DialogUtils.themeDialog); - }, - child: Row( - children: [ - Icon( - Icons.palette, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'themeSettings'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), - ), - ), - ], - ), + _settingsTile( + icon: Icons.palette, + label: 'themeSettings'.tr(), + onPressed: () => showDialog( + context: context, builder: DialogUtils.themeDialog), ), - // Language - TextButton( + _settingsTile( + icon: Icons.language, + label: 'languageSettings'.tr(), onPressed: _showLanguageDialog, - child: Row( - children: [ - Icon( - Icons.language, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'languageSettings'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), - ), - ), - ], - ), ), - // Notifications - TextButton( - onPressed: null, - child: Row( - children: [ - Icon( - Icons.notifications, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'notificationSettings'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), - ), - ), - Spacer(), - Switch( - value: Singleton().profile.enableNotifications, - onChanged: (value) async { - setState(() { - Singleton().profile.enableNotifications = - !Singleton().profile.enableNotifications; - }); - await Singleton().profile.save(); - }, - ) - ], + _settingsTile( + icon: Icons.notifications, + label: 'notificationSettings'.tr(), + trailing: Switch( + value: Singleton().profile.enableNotifications, + onChanged: (value) async { + setState(() { + Singleton().profile.enableNotifications = + !Singleton().profile.enableNotifications; + }); + await Singleton().profile.save(); + }, ), ), - - // Notification previews - TextButton( - onPressed: null, - child: Row( - children: [ - Icon( - Icons.visibility, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'notificationPreview'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), - ), - ), - Spacer(), - Switch( - value: _notificationPreview, - onChanged: (value) async { - setState(() { - _notificationPreview = !_notificationPreview; - }); - await CacheUtils.setNotificationPreview( - _notificationPreview); - }, - ) - ], + _settingsTile( + icon: Icons.visibility, + label: 'notificationPreview'.tr(), + trailing: Switch( + value: _notificationPreview, + onChanged: (value) async { + setState(() { + _notificationPreview = !_notificationPreview; + }); + await CacheUtils.setNotificationPreview( + _notificationPreview); + }, ), ), - - Divider(thickness: 1, indent: 10, endIndent: 10), - - // Biometric authentication - TextButton( - onPressed: null, - child: Row( - children: [ - Icon( - Icons.fingerprint, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'biometrySettings'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), - ), - ), - Spacer(), - Switch( - value: _isBiometryEnabled, - onChanged: _toggleBiometry, - ) - ], + const Divider(thickness: 1, indent: 10, endIndent: 10), + _settingsTile( + icon: Icons.fingerprint, + label: 'biometrySettings'.tr(), + trailing: Switch( + value: _isBiometryEnabled, + onChanged: _toggleBiometry, ), ), - - // Devices signed into this account - TextButton( + _settingsTile( + icon: Icons.devices, + label: 'devicesSettings'.tr(), onPressed: () async { await Navigator.push(context, stepRoute(const DevicesPage())); }, - child: Row( - children: [ - Icon( - Icons.devices, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'devicesSettings'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), - ), - ), - ], - ), ), - // Server retention of the ciphertext archive - TextButton( + _settingsTile( + icon: Icons.storage, + label: 'retentionSettings'.tr(), onPressed: _showRetentionDialog, - child: Row( - children: [ - Icon( - Icons.storage, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'retentionSettings'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), - ), - ), - ], - ), ), - - Divider(thickness: 1, indent: 10, endIndent: 10), - - // How it works - TextButton( - onPressed: () async { - var url = Uri.parse('https://github.com/jsfraz/whisper/wiki'); - if (!await launchUrl(url)) { - await Fluttertoast.showToast( - msg: sprintf('urlError'.tr(), [url.toString()]), - backgroundColor: Colors.red); - } - }, - child: Row( - children: [ - Icon( - Icons.help, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'wikiLink'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), - ), - ), - SizedBox( - width: 24, - ), - ], - ), + const Divider(thickness: 1, indent: 10, endIndent: 10), + _settingsTile( + icon: Icons.help, + label: 'wikiLink'.tr(), + onPressed: () => + _openUrl('https://github.com/jsfraz/whisper/wiki'), ), - - // Repo - TextButton( - onPressed: () async { - var url = Uri.parse('https://github.com/jsfraz/whisper'); - if (!await launchUrl(url)) { - await Fluttertoast.showToast( - msg: sprintf('urlError'.tr(), [url.toString()]), - backgroundColor: Colors.red); - } - }, - child: Row( - children: [ - Icon( - Icons.code, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'repoLink'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), - ), - ), - SizedBox( - width: 24, - ), - ], - ), + _settingsTile( + icon: Icons.code, + label: 'repoLink'.tr(), + onPressed: () => _openUrl('https://github.com/jsfraz/whisper'), ), - - Divider(thickness: 1, indent: 10, endIndent: 10), - - // Change password - TextButton( + const Divider(thickness: 1, indent: 10, endIndent: 10), + _settingsTile( + icon: Icons.password, + label: 'changePassword'.tr(), onPressed: () async { final changed = await showDialog( context: context, @@ -437,32 +282,12 @@ class _SettingsPageState extends State { await Fluttertoast.showToast(msg: 'passwordChanged'.tr()); } }, - child: Row( - children: [ - Icon( - Icons.password, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'changePassword'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), - ), - ), - SizedBox( - width: 24, - ), - ], - ), ), - - Divider(thickness: 1, indent: 10, endIndent: 10), - - // Delete all chats - TextButton( + const Divider(thickness: 1, indent: 10, endIndent: 10), + _settingsTile( + icon: Icons.delete_forever, + label: 'deleteAllChats'.tr(), + color: Colors.red, onPressed: () async { await DialogUtils.yesNoDialog( context, @@ -472,29 +297,11 @@ class _SettingsPageState extends State { Navigator.pop(context); }); }, - child: Row( - children: [ - Icon( - Icons.delete_forever, - size: 24, - color: Colors.red, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'deleteAllChats'.tr(), - style: TextStyle(color: Colors.red), - ), - ), - SizedBox( - width: 24, - ), - ], - ), ), - - // Logout (delete account) - TextButton( + _settingsTile( + icon: Icons.logout, + label: 'logoutAndDelete'.tr(), + color: Colors.red, onPressed: () async { await DialogUtils.yesNoDialog( context, 'logoutConfirm'.tr(), 'logoutConfirmText'.tr(), @@ -520,25 +327,6 @@ class _SettingsPageState extends State { } }); }, - child: Row( - children: [ - Icon( - Icons.logout, - size: 24, - color: Colors.red, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'logoutAndDelete'.tr(), - style: TextStyle(color: Colors.red), - ), - ), - SizedBox( - width: 24, - ), - ], - ), ), ], ), @@ -546,4 +334,30 @@ class _SettingsPageState extends State { ), ); } + + /// One settings row in the app's accent colour. + Widget _settingsTile({ + required IconData icon, + required String label, + VoidCallback? onPressed, + Widget? trailing, + Color? color, + }) { + return SettingsTile( + icon: icon, + label: label, + onPressed: onPressed, + trailing: trailing, + color: color ?? Theme.of(context).colorScheme.secondary, + ); + } + + Future _openUrl(String url) async { + final uri = Uri.parse(url); + if (!await launchUrl(uri)) { + await Fluttertoast.showToast( + msg: sprintf('urlError'.tr(), [uri.toString()]), + backgroundColor: Colors.red); + } + } } diff --git a/lib/widgets/settings_tile.dart b/lib/widgets/settings_tile.dart new file mode 100644 index 0000000..4e817d8 --- /dev/null +++ b/lib/widgets/settings_tile.dart @@ -0,0 +1,52 @@ +import 'package:flutter/material.dart'; + +/// One settings-style row with a fixed height, so rows look the same whether +/// they end in a switch, a badge or nothing. +class SettingsTile extends StatelessWidget { + const SettingsTile({ + super.key, + required this.icon, + required this.label, + this.onPressed, + this.trailing, + this.extra, + this.color, + }); + + final IconData icon; + final String label; + final VoidCallback? onPressed; + + /// Widget at the right edge, e.g. a switch. + final Widget? trailing; + + /// Widget right after the label, e.g. a colour dot. + final Widget? extra; + + /// Tint for icon and label; inherited from the button theme when null. + final Color? color; + + @override + Widget build(BuildContext context) { + return TextButton( + onPressed: onPressed, + style: TextButton.styleFrom( + alignment: Alignment.centerLeft, + minimumSize: const Size.fromHeight(48), + padding: const EdgeInsets.symmetric(horizontal: 16), + ), + child: Row( + children: [ + Icon(icon, size: 24, color: color), + Padding( + padding: const EdgeInsets.only(left: 5), + child: Text(label, style: TextStyle(color: color)), + ), + if (extra != null) extra!, + if (trailing != null) const Spacer(), + if (trailing != null) trailing!, + ], + ), + ); + } +} diff --git a/test/settings_tile_test.dart b/test/settings_tile_test.dart new file mode 100644 index 0000000..0527491 --- /dev/null +++ b/test/settings_tile_test.dart @@ -0,0 +1,28 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/widgets/settings_tile.dart'; + +void main() { + testWidgets('row height does not depend on a trailing widget', + (tester) async { + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: Column( + children: [ + SettingsTile(icon: Icons.palette, label: 'plain', onPressed: () {}), + SettingsTile( + icon: Icons.notifications, + label: 'switch', + trailing: Switch(value: true, onChanged: (_) {}), + ), + ], + ), + ), + )); + + final plain = tester.getSize(find.byType(SettingsTile).at(0)); + final withSwitch = tester.getSize(find.byType(SettingsTile).at(1)); + expect(plain.height, withSwitch.height); + expect(plain.width, withSwitch.width); + }); +} From be4a5a60b61c34a04cd67b51cfd70a752fa0b762 Mon Sep 17 00:00:00 2001 From: Josef Date: Tue, 17 Nov 2026 23:17:56 +0100 Subject: [PATCH 076/181] feat: F2 chat UX - rendering, navigation and chat list Reply quoting, inline formatting, emoji-only bubbles, sticky day headers, unread divider, jump to bottom, multi-select, swipe-to-reply, unread badges, pin and delete in the chat list. --- assets/translations/cs.json | 8 + assets/translations/en.json | 8 + lib/models/private_message.dart | 41 ++ lib/models/private_message.g.dart | 13 +- lib/pages/chat_page.dart | 781 +++++++++++++++++++++++++----- lib/pages/forward_page.dart | 48 +- lib/pages/home_page.dart | 73 ++- lib/pages/media_viewer_page.dart | 2 +- lib/utils/cache_utils.dart | 99 +++- lib/utils/chat_sender.dart | 18 +- lib/utils/message_actions.dart | 8 +- lib/utils/message_format.dart | 286 +++++++++++ lib/utils/message_notifier.dart | 7 +- lib/utils/text_envelope.dart | 96 ++++ lib/utils/utils.dart | 10 +- lib/widgets/chat_bubble.dart | 516 +++++++++++++------- lib/widgets/chat_list_item.dart | 82 +++- lib/widgets/formatted_text.dart | 199 ++++++++ lib/widgets/linkified_text.dart | 60 --- test/chat_bubble_test.dart | 172 +++++++ test/conversation_meta_test.dart | 91 ++++ test/message_format_test.dart | 125 +++++ test/text_envelope_test.dart | 64 +++ 23 files changed, 2399 insertions(+), 408 deletions(-) create mode 100644 lib/utils/message_format.dart create mode 100644 lib/utils/text_envelope.dart create mode 100644 lib/widgets/formatted_text.dart delete mode 100644 lib/widgets/linkified_text.dart create mode 100644 test/chat_bubble_test.dart create mode 100644 test/conversation_meta_test.dart create mode 100644 test/message_format_test.dart create mode 100644 test/text_envelope_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 708aa82..8083260 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -138,6 +138,14 @@ "attachmentSaveFailed": "Uložení přílohy se nepovedlo", "forwardTo": "Přeposlat komu", "forwarded": "Přeposláno", + "showFull": "Zobrazit více", + "showLess": "Zobrazit méně", + "newMessages": "Nové zprávy", + "selectedCount": "Vybráno: %d", + "moreActions": "Další akce", + "jumpToLatest": "Skočit na nejnovější", + "chatPinned": "Chat připnut", + "chatUnpinned": "Chat odebrán z připnutých", "noChatsToForward": "Zatím žádné chaty, vyhledej uživatele", "mediaFile": "Soubor", "fileTooLarge": "Soubor je příliš velký, maximum je", diff --git a/assets/translations/en.json b/assets/translations/en.json index de29ca8..eb0da38 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -138,6 +138,14 @@ "attachmentSaveFailed": "Saving the attachment failed", "forwardTo": "Forward to", "forwarded": "Forwarded", + "showFull": "Show full message", + "showLess": "Show less", + "newMessages": "New messages", + "selectedCount": "%d selected", + "moreActions": "More actions", + "jumpToLatest": "Jump to latest", + "chatPinned": "Chat pinned", + "chatUnpinned": "Chat unpinned", "noChatsToForward": "No chats yet, search for a user", "mediaFile": "File", "fileTooLarge": "File is too large, the maximum is", diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index a4aa1df..8d091bf 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -5,6 +5,7 @@ import 'package:hive/hive.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../utils/singleton.dart'; +import '../utils/text_envelope.dart'; part 'private_message.g.dart'; @@ -162,6 +163,19 @@ class PrivateMessage extends HiveObject { @HiveField(15) String? albumJson; + /// Sender of the message this one quotes, null when it is not a reply. + @HiveField(16) + String? replyToSenderId; + + /// Client timestamp of the quoted message, null when it is not a reply. + @HiveField(17) + DateTime? replyToSentAt; + + /// Preview of the quoted message, kept here so the quote survives its + /// original being deleted on this device. + @HiveField(18) + String? replyToPreview; + /// Cache for [album], keyed by the [albumJson] it was decoded from. String? _albumCacheJson; List? _albumCache; @@ -183,8 +197,35 @@ class PrivateMessage extends HiveObject { this.fileName, this.sendStatus = SendStatus.sent, this.albumJson, + this.replyToSenderId, + this.replyToSentAt, + this.replyToPreview, }); + /// The quoted message, or null when this message is not a reply. + ReplyRef? get replyTo { + final senderId = replyToSenderId; + final sentAt = replyToSentAt; + if (senderId == null || sentAt == null) { + return null; + } + return ReplyRef( + senderId: senderId, + sentAt: sentAt, + preview: replyToPreview ?? '', + ); + } + + /// Stores (or clears) the message this one quotes. + void setReplyTo(ReplyRef? reply) { + replyToSenderId = reply?.senderId; + replyToSentAt = reply?.sentAt; + replyToPreview = reply?.preview; + } + + /// Whether this message quotes another one. + bool get isReply => replyToSentAt != null; + /// Stored instead of the text when a message cannot be decrypted. It keeps a /// visible gap in the chat, and the receiver only acks what it stored, so the /// server still has the ciphertext. diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index 6585502..a8cc2a3 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -33,13 +33,16 @@ class PrivateMessageAdapter extends TypeAdapter { fileName: fields[13] as String?, sendStatus: fields[14] == null ? 1 : fields[14] as int, albumJson: fields[15] as String?, + replyToSenderId: fields[16] as String?, + replyToSentAt: fields[17] as DateTime?, + replyToPreview: fields[18] as String?, ); } @override void write(BinaryWriter writer, PrivateMessage obj) { writer - ..writeByte(16) + ..writeByte(19) ..writeByte(0) ..write(obj.senderId) ..writeByte(1) @@ -71,7 +74,13 @@ class PrivateMessageAdapter extends TypeAdapter { ..writeByte(14) ..write(obj.sendStatus) ..writeByte(15) - ..write(obj.albumJson); + ..write(obj.albumJson) + ..writeByte(16) + ..write(obj.replyToSenderId) + ..writeByte(17) + ..write(obj.replyToSentAt) + ..writeByte(18) + ..write(obj.replyToPreview); } @override diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index a3f981e..46654e6 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1,10 +1,12 @@ import 'dart:async'; import 'dart:io'; -import 'dart:typed_data'; import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; +import 'package:sprintf/sprintf.dart'; +import '../utils/dialog_utils.dart'; import '../utils/nav_transitions.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; @@ -12,13 +14,16 @@ import '../models/user.dart'; import '../utils/cache_utils.dart'; import '../utils/chat_sender.dart'; import '../utils/media_utils.dart'; +import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; import '../utils/singleton.dart'; +import '../utils/text_envelope.dart'; import '../utils/utils.dart' as utils; import '../utils/theme_utils.dart'; import '../widgets/attachment_confirm_sheet.dart'; import '../widgets/chat_bubble.dart'; import 'chat_info_page.dart'; +import 'forward_page.dart'; class ChatPage extends StatefulWidget { const ChatPage(this.user, {super.key}); @@ -42,7 +47,7 @@ class _ChatPageState extends State { int _visibleCount = _pageSize; // Buttons bool _isSending = false; - // ScrollController for content (list is reversed: offset 0 is the newest) + // ScrollController for content final ScrollController _scrollController = ScrollController(); // Indicates whether messages are being load for the first time bool _firstLoad = true; @@ -50,6 +55,8 @@ class _ChatPageState extends State { bool _loading = false; // Guards against overlapping history requests bool _historyLoading = false; + // Guards against overlapping "grow the window upwards" passes + bool _growing = false; // Whether the newest archive page was already asked for bool _historyLoaded = false; // Cursor for the next (older) archive page, null when the archive ends @@ -65,32 +72,84 @@ class _ChatPageState extends State { // Per-chat theme override, null means the global theme Color? _chatThemeColor; + /// The message the composer is quoting, null when not replying. + PrivateMessage? _replyTo; + + /// Oldest message that was unread when the chat opened: the "new messages" + /// divider. Captured before this page marks everything read. + DateTime? _unreadAnchor; + final GlobalKey _unreadDividerKey = GlobalKey(); + + /// Client timestamps (microseconds) of the messages picked in multi-select. + final Set _selected = {}; + + /// Bubble keys by client timestamp, for jumping to a quoted message. + final Map _messageKeys = {}; + + /// Newest message the viewport has already shown at the bottom; anything + /// after it while scrolled up counts as unseen. + int _newestSeenSentAt = 0; + int _unseenCount = 0; + + bool get _selectionMode => _selected.isNotEmpty; + @override void initState() { super.initState(); MessageNotifier().addListener(_onMessagesChanged); _scrollController.addListener(_onScroll); - // Load messages from cache - _loadMessages(); - // Then top the conversation up from the server archive - _loadHistory(); + _metricsObserver = _KeyboardObserver(() { + if (_atBottom) { + WidgetsBinding.instance.addPostFrameCallback((_) => _jumpToBottom()); + } + }); + WidgetsBinding.instance.addObserver(_metricsObserver); + _start(); // Load concept message getConceptMessage(); // Load per-chat theme _loadChatTheme(); } + /// The read state must be captured before the chat marks it read, otherwise + /// there is no divider left to draw. + Future _start() async { + final firstUnread = await CacheUtils.firstUnreadSentAt(widget.user.id); + if (mounted && firstUnread != null) { + setState(() { + _unreadAnchor = firstUnread; + }); + } + await _loadMessages(); + // Then top the conversation up from the server archive + _loadHistory(); + } + + /// Keeps the newest message on screen when the keyboard opens. + late final _KeyboardObserver _metricsObserver; + /// Reload the conversation from the cache when messages or media state change. void _onMessagesChanged() { _loadMessages(); } + /// Whether the viewport sits at the newest message. + bool get _atBottom { + if (!_scrollController.hasClients) { + return true; + } + final position = _scrollController.position; + return position.pixels >= position.maxScrollExtent - 40; + } + /// Load the conversation once per change instead of once per build. Future _loadMessages() async { if (_loading || !mounted) { return; } _loading = true; + final first = _firstLoad; + final wasAtBottom = _atBottom; try { final messages = await MessageNotifier().getMessages(widget.user.id); if (!mounted) { @@ -98,16 +157,40 @@ class _ChatPageState extends State { } // The first content frame decrypts every visible attachment, so keep it // out of the push animation and let the spinner ride along instead. - if (_firstLoad) { + if (first) { await _waitForRouteAnimation(); } if (!mounted) { return; } + final newest = + messages.isEmpty ? 0 : messages.last.sentAt.microsecondsSinceEpoch; setState(() { _messages = messages; + if (!first) { + if (wasAtBottom) { + _unseenCount = 0; + } else if (newest > _newestSeenSentAt) { + _unseenCount += messages + .where((message) => + !message.isMe && + message.sentAt.microsecondsSinceEpoch > _newestSeenSentAt) + .length; + } + } + _newestSeenSentAt = newest; _firstLoad = false; }); + if (first || wasAtBottom) { + await WidgetsBinding.instance.endOfFrame; + if (!mounted) { + return; + } + _jumpToBottom(); + if (first) { + await _jumpToFirstUnread(); + } + } } finally { _loading = false; } @@ -133,21 +216,85 @@ class _ChatPageState extends State { await done.future; } + void _jumpToBottom({bool animate = false}) { + if (!_scrollController.hasClients) { + return; + } + final target = _scrollController.position.maxScrollExtent; + if (animate) { + _scrollController.animateTo(target, + duration: const Duration(milliseconds: 250), curve: Curves.easeOut); + } else { + _scrollController.jumpTo(target); + } + if (_unseenCount != 0) { + setState(() { + _unseenCount = 0; + }); + } + } + + /// Opens the chat on the first message the user has not read yet. + Future _jumpToFirstUnread() async { + if (_unreadAnchor == null) { + return; + } + await WidgetsBinding.instance.endOfFrame; + final context = _unreadDividerKey.currentContext; + if (context == null || !context.mounted) { + return; + } + await Scrollable.ensureVisible(context, + alignment: 0.15, duration: const Duration(milliseconds: 250)); + } + /// Extend the rendered window when the user scrolls towards older messages. void _onScroll() { if (!_scrollController.hasClients) { return; } - if (_scrollController.position.extentAfter < 200) { - if (_visibleCount < _messages.length) { - setState(() { - _visibleCount += _pageSize; - }); - } else if (_historyCursor != null) { - // The cache ran out: ask the server for the page below it. - _loadHistory(older: true); + final position = _scrollController.position; + if (position.pixels >= position.maxScrollExtent - 40 && _unseenCount != 0) { + setState(() { + _unseenCount = 0; + }); + } + // Older messages are above: the window grows near the top of the list. + if (position.pixels > 200) { + return; + } + if (_visibleCount < _messages.length) { + _growWindow(_pageSize); + } else if (_historyCursor != null) { + // The cache ran out: ask the server for the page above it. + _loadHistory(older: true); + } + } + + /// Renders more messages above the viewport without moving what is on screen. + Future _growWindow(int by) async { + if (_growing || !mounted) { + return; + } + _growing = true; + final before = _scrollController.hasClients + ? _scrollController.position.maxScrollExtent + : 0.0; + setState(() { + _visibleCount += by; + }); + await WidgetsBinding.instance.endOfFrame; + if (!mounted) { + _growing = false; + return; + } + if (_scrollController.hasClients) { + final delta = _scrollController.position.maxScrollExtent - before; + if (delta > 0) { + _scrollController.jumpTo(_scrollController.offset + delta); } } + _growing = false; } /// Fetch one page of the conversation from the server archive. @@ -166,6 +313,9 @@ class _ChatPageState extends State { return; } _historyLoading = true; + final before = _scrollController.hasClients + ? _scrollController.position.maxScrollExtent + : 0.0; try { final page = await utils.Utils.callApi( () => Singleton().messagesApi.getHistory(widget.user.id, @@ -184,11 +334,20 @@ class _ChatPageState extends State { return; } await utils.Utils.storeHistoryPage(page.messages); - if (mounted) { - // Show the page that just arrived without making the user scroll again. - setState(() { - _visibleCount += page.messages.length; - }); + if (!mounted) { + return; + } + // Show the page that just arrived without making the user scroll again. + setState(() { + _visibleCount += page.messages.length; + }); + await WidgetsBinding.instance.endOfFrame; + if (!mounted || !_scrollController.hasClients) { + return; + } + final delta = _scrollController.position.maxScrollExtent - before; + if (delta > 0) { + _scrollController.jumpTo(_scrollController.offset + delta); } } finally { _historyLoading = false; @@ -224,17 +383,131 @@ class _ChatPageState extends State { await _loadMessages(); } + // --------------------------------------------------------------------------- + // Reply and multi-select + // --------------------------------------------------------------------------- + + /// Quote [message] in the composer. + void _startReply(PrivateMessage message) { + if (_selectionMode) { + return; + } + setState(() { + _replyTo = message; + }); + } + + /// Adds or removes [message] from the selection; leaving it empty closes the + /// selection mode. + void _toggleSelected(PrivateMessage message) { + final micros = message.sentAt.microsecondsSinceEpoch; + setState(() { + if (!_selected.remove(micros)) { + _selected.add(micros); + } + }); + } + + void _clearSelection() { + setState(_selected.clear); + } + + /// Messages currently picked, oldest first. + List get _selectedMessages => _messages + .where((message) => + _selected.contains(message.sentAt.microsecondsSinceEpoch)) + .toList(); + + Future _copySelected() async { + final text = _selectedMessages + .map((message) => message.message) + .where((text) => text.isNotEmpty) + .join('\n'); + _clearSelection(); + if (text.isEmpty) { + return; + } + await Clipboard.setData(ClipboardData(text: text)); + Fluttertoast.showToast(msg: 'copiedText'.tr()); + } + + Future _forwardSelected() async { + final messages = _selectedMessages; + if (messages.isEmpty) { + return; + } + _clearSelection(); + await Navigator.of(context).push(stepRoute(ForwardPage(messages))); + } + + void _deleteSelected() { + final messages = _selectedMessages; + if (messages.isEmpty) { + return; + } + DialogUtils.yesNoDialog( + context, 'deleteMessageConfirm'.tr(), 'deleteMessageConfirmText'.tr(), + () async { + for (final message in messages) { + await CacheUtils.deletePrivateMessage(widget.user.id, message); + } + _clearSelection(); + MessageNotifier().notify(); + }); + } + + /// Scrolls to the message a reply quotes, widening the window when it is + /// older than what is rendered. + Future _jumpToMessage(DateTime sentAt) async { + final micros = sentAt.microsecondsSinceEpoch; + final context = _messageKeys[micros]?.currentContext; + if (context != null) { + await Scrollable.ensureVisible(context, + alignment: 0.3, duration: const Duration(milliseconds: 250)); + return; + } + // Not rendered: open the window up to it, then try once more. + final index = _messages.indexWhere((message) => message.sentAt == sentAt); + if (index < 0) { + return; + } + final needed = _messages.length - index + 5; + if (needed > _visibleCount) { + await _growWindow(needed - _visibleCount); + } + await WidgetsBinding.instance.endOfFrame; + if (!mounted) { + return; + } + final retry = _messageKeys[micros]?.currentContext; + if (retry != null && retry.mounted) { + await Scrollable.ensureVisible(retry, + alignment: 0.3, duration: const Duration(milliseconds: 250)); + } + } + /// Send the typed text. Future _sendMessage() async { final text = _controllerMessage.text; if (text.isEmpty) { return; } + final quoted = _replyTo; + final reply = quoted == null + ? null + : ReplyRef( + senderId: quoted.senderId, + sentAt: quoted.sentAt, + preview: ReplyRef.previewOf(quoted.preview), + ); setState(() { _isSending = true; }); - if (await ChatSender.sendText(widget.user, text)) { + if (await ChatSender.sendText(widget.user, text, reply: reply)) { _controllerMessage.text = ''; + setState(() { + _replyTo = null; + }); await CacheUtils.deleteMessageConcept(widget.user.id); } if (mounted) { @@ -657,6 +930,63 @@ class _ChatPageState extends State { ); } + /// Quoted message above the composer, dismissable. + Widget _buildReplyBar() { + final reply = _replyTo!; + final author = reply.isMe + ? 'meText'.tr() + : (widget.user.username.isNotEmpty ? widget.user.username : '?'); + return Container( + margin: const EdgeInsets.only(bottom: 6), + padding: const EdgeInsets.only(left: 10), + decoration: BoxDecoration( + color: chatTheme.colorScheme.surfaceContainerHigh, + borderRadius: BorderRadius.circular(12), + border: Border( + left: BorderSide(color: chatTheme.colorScheme.primary, width: 3), + ), + ), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + author, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: chatTheme.colorScheme.primary, + ), + ), + Text( + reply.preview, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12, + color: chatTheme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + IconButton( + tooltip: 'cancel'.tr(), + icon: const Icon(Icons.close, size: 18), + onPressed: () { + setState(() { + _replyTo = null; + }); + }, + ), + ], + ), + ); + } + /// Bar shown while recording a voice message. Widget _buildRecordingBar() { final color = _cancelRecording ? Colors.red : chatTheme.colorScheme.primary; @@ -736,49 +1066,142 @@ class _ChatPageState extends State { ); } - /// Reversed list: offset 0 is the newest message, so the chat opens at the - /// bottom and growing bubbles or the keyboard never strand it mid-list. + /// The "new messages" divider, drawn above the first unread message. + Widget _buildUnreadDivider() { + final color = Theme.of(context).colorScheme.primary; + return Padding( + key: _unreadDividerKey, + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), + child: Row( + children: [ + Expanded(child: Divider(color: color)), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Text( + 'newMessages'.tr(), + style: TextStyle( + fontSize: 12, color: color, fontWeight: FontWeight.bold), + ), + ), + Expanded(child: Divider(color: color)), + ], + ), + ); + } + + /// Calendar day a message belongs to, in the timezone the bubble shows. + DateTime _dayOf(PrivateMessage message) { + final time = (message.isMe ? message.sentAt : message.receivedAt).toLocal(); + return DateTime(time.year, time.month, time.day); + } + + String _dayLabel(DateTime day) { + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + final days = today.difference(day).inDays; + if (days <= 0) { + return 'todayText'.tr(); + } + if (days == 1) { + return 'yesterdayText'.tr(); + } + if (days < 7) { + return DateFormat.EEEE().format(day); + } + if (day.year == now.year) { + return DateFormat.MMMMd().format(day); + } + return DateFormat.yMMMMd().format(day); + } + + Widget _buildBubble( + PrivateMessage message, PrivateMessage? older, PrivateMessage? newer) { + final micros = message.sentAt.microsecondsSinceEpoch; + final key = _messageKeys.putIfAbsent(micros, () => GlobalKey()); + final showsDivider = _unreadAnchor?.microsecondsSinceEpoch == micros; + final bubble = ChatBubble( + older, + message, + newer, + widget.user, + key: key, + // The picked chat color itself, not a tonal derivative of it. + accentColor: _chatThemeColor ?? Singleton().appTheme.color, + selectionMode: _selectionMode, + selected: _selected.contains(micros), + onSelect: () => _toggleSelected(message), + onReply: () => _startReply(message), + onTapQuote: message.isReply + ? () => _jumpToMessage(message.replyTo!.sentAt) + : null, + ); + if (!showsDivider) { + return bubble; + } + // The divider sits above its message and goes away once the day header + // does not repeat it. + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [_buildUnreadDivider(), bubble], + ); + } + + /// Messages, grouped by day: each day gets a sticky header. Widget _getContent(List messages) { final start = messages.length > _visibleCount ? messages.length - _visibleCount : 0; final visible = messages.sublist(start); final hasOlder = start > 0; - final itemCount = visible.length + 1; - return ListView.builder( + final days = >{}; + for (var i = 0; i < visible.length; i++) { + days.putIfAbsent(_dayOf(visible[i]), () => []).add(i); + } + final orderedDays = days.keys.toList()..sort(); + + return CustomScrollView( + controller: _scrollController, physics: const BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics(), ), - controller: _scrollController, - reverse: true, - itemCount: itemCount, - itemBuilder: (context, index) { - // Last item is the conversation header (top of the screen). - if (index == visible.length) { - if (hasOlder) { - return const Padding( - padding: EdgeInsets.symmetric(vertical: 16), - child: Center( - child: SizedBox( - width: 20, - height: 20, - child: CircularProgressIndicator(strokeWidth: 2), - ), - ), - ); - } - return _buildHeader(); - } - // index 0 is the newest message; older messages have higher indices. - final message = visible[visible.length - 1 - index]; - final position = visible.length - 1 - index; - final older = position > 0 ? visible[position - 1] : null; - final newer = - position < visible.length - 1 ? visible[position + 1] : null; - return ChatBubble(older, message, newer, widget.user, - // The picked chat color itself, not a tonal derivative of it. - accentColor: _chatThemeColor ?? Singleton().appTheme.color); - }, + slivers: [ + SliverToBoxAdapter( + child: hasOlder + ? const Padding( + padding: EdgeInsets.symmetric(vertical: 16), + child: Center( + child: SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ), + ) + : _buildHeader(), + ), + for (final day in orderedDays) ...[ + SliverPersistentHeader( + pinned: true, + delegate: _DayHeader( + label: _dayLabel(day), + textColor: Theme.of(context).colorScheme.onSurfaceVariant, + background: chatBackground(tintAlpha: 0.35), + ), + ), + SliverList.builder( + itemCount: days[day]!.length, + itemBuilder: (context, index) { + final position = days[day]![index]; + final message = visible[position]; + return _buildBubble( + message, + position > 0 ? visible[position - 1] : null, + position < visible.length - 1 ? visible[position + 1] : null, + ); + }, + ), + ], + ], ); } @@ -786,6 +1209,7 @@ class _ChatPageState extends State { void dispose() { MessageNotifier().removeListener(_onMessagesChanged); _scrollController.removeListener(_onScroll); + WidgetsBinding.instance.removeObserver(_metricsObserver); _recordTimer?.cancel(); _recorderController?.dispose(); _controllerMessage.dispose(); @@ -830,6 +1254,92 @@ class _ChatPageState extends State { .withValues(alpha: 0.85); } + /// Chat AppBar, or the selection AppBar while messages are picked. + Widget _buildAppBarContent() { + if (_selectionMode) { + final single = + _selectedMessages.length == 1 ? _selectedMessages.first : null; + return AppBar( + automaticallyImplyLeading: false, + backgroundColor: appBarBackground(), + leading: IconButton( + icon: const Icon(Icons.close), + tooltip: 'cancel'.tr(), + onPressed: _clearSelection, + ), + title: Text(sprintf('selectedCount'.tr(), [_selected.length])), + actions: [ + IconButton( + icon: Icon(MessageActions.copyIcon), + tooltip: 'copyMessage'.tr(), + onPressed: _copySelected, + ), + IconButton( + icon: Icon(MessageActions.forwardIcon), + tooltip: 'forwardMessage'.tr(), + onPressed: _forwardSelected, + ), + IconButton( + icon: Icon(MessageActions.deleteIcon), + tooltip: 'deleteMessageForMe'.tr(), + onPressed: _deleteSelected, + ), + // Save, resend and the rest still live in the single-message sheet. + if (single != null) + IconButton( + icon: const Icon(Icons.more_vert), + tooltip: 'moreActions'.tr(), + onPressed: () => + MessageActions.showSheet(context, single, widget.user.id), + ), + ], + ); + } + return AppBar( + automaticallyImplyLeading: false, + backgroundColor: appBarBackground(), + leading: Row( + children: [ + IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () => Navigator.pop(context), + ), + GestureDetector( + onTap: _openChatInfo, + child: CircleAvatar( + radius: 18, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 16, + color: widget.user.avatarTextColor, + ), + ), + ), + ), + ], + ), + leadingWidth: 96, // Increase width to accommodate both icons + // Title + title: GestureDetector( + onTap: _openChatInfo, + behavior: HitTestBehavior.opaque, + child: Text(widget.user.username), + ), + // Action buttons + actions: [ + IconButton( + icon: const Icon(Icons.info), + tooltip: 'infoButton'.tr(), + onPressed: _openChatInfo, + ), + ], + ); + } + @override Widget build(BuildContext context) { return PopScope( @@ -856,49 +1366,7 @@ class _ChatPageState extends State { child: ClipRRect( child: BackdropFilter( filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), - child: AppBar( - automaticallyImplyLeading: false, - backgroundColor: appBarBackground(), - leading: Row( - children: [ - IconButton( - icon: const Icon(Icons.arrow_back), - onPressed: () => Navigator.pop(context), - ), - GestureDetector( - onTap: _openChatInfo, - child: CircleAvatar( - radius: 18, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 16, - color: widget.user.avatarTextColor, - ), - ), - ), - ), - ], - ), - leadingWidth: 96, // Increase width to accommodate both icons - // Title - title: GestureDetector( - onTap: _openChatInfo, - behavior: HitTestBehavior.opaque, - child: Text(widget.user.username), - ), - // Action buttons - actions: [ - IconButton( - icon: const Icon(Icons.info), - tooltip: 'infoButton'.tr(), - onPressed: _openChatInfo, - ), - ], - ), + child: _buildAppBarContent(), ), ), ), @@ -908,25 +1376,59 @@ class _ChatPageState extends State { children: [ // Messages and avatar list Expanded( - child: _firstLoad - ? Center( - child: Transform.scale( - scale: 1.5, - child: CircularProgressIndicator(), + child: Stack( + children: [ + _firstLoad + ? Center( + child: Transform.scale( + scale: 1.5, + child: CircularProgressIndicator(), + ), + ) + : _getContent(_messages), + // Floating "down" button with the count of messages that + // arrived while the user was reading further up. + if (!_firstLoad && _unseenCount > 0) + Positioned( + right: 16, + bottom: 16, + child: FloatingActionButton.small( + heroTag: 'jumpToBottom', + tooltip: 'jumpToLatest'.tr(), + onPressed: () => _jumpToBottom(animate: true), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.arrow_downward, size: 16), + if (_unseenCount > 1) + Padding( + padding: const EdgeInsets.only(left: 2), + child: Text('$_unseenCount', + style: const TextStyle(fontSize: 11)), + ), + ], + ), ), - ) - : _getContent(_messages), + ), + ], + ), ), SafeArea( top: false, child: Padding( padding: const EdgeInsets.all(8.0), - child: Stack( - alignment: Alignment.center, + child: Column( + mainAxisSize: MainAxisSize.min, children: [ - _buildInputBar(), - if (_isRecording) - Positioned.fill(child: _buildRecordingBar()), + if (_replyTo != null) _buildReplyBar(), + Stack( + alignment: Alignment.center, + children: [ + _buildInputBar(), + if (_isRecording) + Positioned.fill(child: _buildRecordingBar()), + ], + ), ], ), ), @@ -939,3 +1441,62 @@ class _ChatPageState extends State { ); } } + +/// Sticky day label above the messages of one calendar day. +class _DayHeader extends SliverPersistentHeaderDelegate { + _DayHeader({ + required this.label, + required this.textColor, + required this.background, + }); + + final String label; + final Color textColor; + final Color background; + + @override + double get minExtent => 34; + + @override + double get maxExtent => 34; + + @override + Widget build( + BuildContext context, double shrinkOffset, bool overlapsContent) { + return Center( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3), + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + label, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: textColor, + ), + ), + ), + ); + } + + @override + bool shouldRebuild(covariant _DayHeader oldDelegate) => + oldDelegate.label != label || + oldDelegate.textColor != textColor || + oldDelegate.background != background; +} + +/// Fires [onMetricsChanged] when the keyboard opens or closes. +class _KeyboardObserver extends WidgetsBindingObserver { + _KeyboardObserver(this.onMetricsChanged); + + final VoidCallback onMetricsChanged; + + @override + void didChangeMetrics() { + onMetricsChanged(); + } +} diff --git a/lib/pages/forward_page.dart b/lib/pages/forward_page.dart index 90e857e..3ca1bf4 100644 --- a/lib/pages/forward_page.dart +++ b/lib/pages/forward_page.dart @@ -11,11 +11,11 @@ import '../widgets/user_list_item.dart'; import 'search_user_page.dart'; import '../utils/nav_transitions.dart'; -/// Picks the destination of a forwarded message: an existing conversation or a -/// user found by search. Sends the message and closes itself. +/// Picks the destination of forwarded messages: an existing conversation or a +/// user found by search. Sends the messages and closes itself. class ForwardPage extends StatefulWidget { - const ForwardPage(this.message, {super.key}); - final PrivateMessage message; + const ForwardPage(this.messages, {super.key}); + final List messages; @override State createState() => _ForwardPageState(); @@ -48,29 +48,33 @@ class _ForwardPageState extends State { _sending = true; }); try { - final message = widget.message; - bool sent; - if (message.isMedia) { - final path = message.localPath; - final type = message.mediaType; - if (path == null || type == null) { - // Save/forward are hidden for attachments that are not on disk - return; + var allSent = true; + for (final message in widget.messages) { + bool sent; + if (message.isMedia) { + final path = message.localPath; + final type = message.mediaType; + if (path == null || type == null) { + // Save/forward are hidden for attachments that are not on disk. + allSent = false; + continue; + } + final bytes = await MediaUtils.decryptAtRest(path); + sent = await ChatSender.sendMedia(to, type, bytes, + caption: message.message, + width: message.width, + height: message.height, + durationMs: message.durationMs, + fileName: message.fileName); + } else { + sent = await ChatSender.sendText(to, message.message); } - final bytes = await MediaUtils.decryptAtRest(path); - sent = await ChatSender.sendMedia(to, type, bytes, - caption: message.message, - width: message.width, - height: message.height, - durationMs: message.durationMs, - fileName: message.fileName); - } else { - sent = await ChatSender.sendText(to, message.message); + allSent = allSent && sent; } if (!mounted) { return; } - if (sent) { + if (allSent) { Fluttertoast.showToast(msg: 'forwarded'.tr()); Navigator.pop(context); } diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 973bee2..95345b9 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -40,6 +40,12 @@ class _HomePageState extends State int _currentPageIndex = 0; List _serverInvites = []; List> _chatEntries = []; + + /// Unread incoming messages per conversation id, for the list badges. + Map _unreadCounts = {}; + + /// Conversation ids pinned to the top of the list. + Set _pinnedChats = {}; bool _firstLoad = true; String? _pendingFid; // Store pending FID @@ -184,15 +190,49 @@ class _HomePageState extends State /// Get all conversations with their last messages Future _getConversations() async { final chats = await CacheUtils.getLatestPrivateMessages(); + final unread = await CacheUtils.getUnreadCounts(); + final pinned = await CacheUtils.getPinnedConversations(); if (!mounted) { return; } setState(() { _chatEntries = chats.entries.toList(); + _unreadCounts = unread; + _pinnedChats = pinned; _firstLoad = false; }); } + /// Pin or unpin a conversation. Local only: nothing is sent to the server. + Future _togglePin(User user) async { + final pinned = _pinnedChats.contains(user.id); + await CacheUtils.setConversationPinned(user.id, !pinned); + if (!mounted) { + return; + } + Fluttertoast.showToast( + msg: pinned ? 'chatUnpinned'.tr() : 'chatPinned'.tr()); + await _getConversations(); + } + + /// Delete a conversation after the confirmation dialog confirmed it. + void _deleteChat(User user) { + DialogUtils.yesNoDialog( + context, 'deleteChatConfirm'.tr(), 'deleteChatConfirmText'.tr(), + () async { + await MessageNotifier().deleteChat(user.id); + }); + } + + /// Icon shown under a swiped chat row. + Widget _swipeBackground(Alignment alignment, IconData icon, Color color) { + return Container( + alignment: alignment, + padding: const EdgeInsets.symmetric(horizontal: 20), + child: Icon(icon, color: color), + ); + } + /// Get server users Future _getServerUsers() async { if (!mounted) { @@ -305,12 +345,37 @@ class _HomePageState extends State // Indexed access: `Map.entries.elementAt` is O(n) and made the list // build O(n^2). final chat = chats[index]; + final scheme = Theme.of(context).colorScheme; return Padding( padding: EdgeInsets.only(right: 5, left: 5, bottom: 3), - child: ChatListItem(chat.key, chat.value, () { - // Push to chat - Navigator.of(context).push(slideUpRoute(ChatPage(chat.key))); - }), + // Swipe right pins, swipe left deletes. Both spring back: the gesture + // opens an action, it never removes a row on its own. + child: Dismissible( + key: ValueKey('chat|${chat.key.id}'), + direction: DismissDirection.horizontal, + background: _swipeBackground( + Alignment.centerLeft, Icons.push_pin, scheme.primary), + secondaryBackground: _swipeBackground( + Alignment.centerRight, Icons.delete, scheme.error), + confirmDismiss: (direction) async { + if (direction == DismissDirection.startToEnd) { + await _togglePin(chat.key); + } else { + _deleteChat(chat.key); + } + return false; + }, + child: ChatListItem( + chat.key, + chat.value, + () { + // Push to chat + Navigator.of(context).push(slideUpRoute(ChatPage(chat.key))); + }, + unreadCount: _unreadCounts[chat.key.id] ?? 0, + pinned: _pinnedChats.contains(chat.key.id), + ), + ), ); }, ); diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index 99a7894..82ee077 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -106,7 +106,7 @@ class _MediaViewerPageState extends State { MessageActions.save(_current); break; case 'forward': - MessageActions.forward(context, _current); + MessageActions.forward(context, [_current]); break; case 'delete': MessageActions.delete(context, _current, widget.conversationUserId, diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index a08cf6a..123a175 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -495,6 +495,9 @@ class CacheUtils { Box userBox = await _openUserBox(); await userBox.delete(userId); await deleteMessageConcept(userId); + // Pin state goes with the conversation. + final conversationsBox = await _openConversationsBox(); + await conversationsBox.delete(userId); } /// Delete the encrypted-at-rest media files of all messages with [userId]. @@ -713,10 +716,90 @@ class CacheUtils { await box.put(user.id, user); } + /// Local-only chat list state (pinned, and later archived). Nothing here + /// reaches the server: until F8 syncs it, it is this device's business. + static const String _conversationsKey = 'conversations'; + + static Future _openConversationsBox() async { + return Hive.openBox(_conversationsKey); + } + + static Map _metaOf(Box box, String userId) { + final stored = box.get(userId); + return stored is Map ? Map.from(stored) : {}; + } + + /// Whether [userId] is pinned to the top of the chat list. + static Future isConversationPinned(String userId) async { + final box = await _openConversationsBox(); + return _metaOf(box, userId)['pinned'] == true; + } + + /// Pins or unpins a conversation. The entry is dropped once it is empty, so + /// the box only holds chats that differ from the default. + static Future setConversationPinned(String userId, bool pinned) async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + if (pinned) { + meta['pinned'] = true; + } else { + meta.remove('pinned'); + } + if (meta.isEmpty) { + await box.delete(userId); + } else { + await box.put(userId, meta); + } + } + + /// Ids of the pinned conversations. + static Future> getPinnedConversations() async { + final box = await _openConversationsBox(); + return { + for (final entry in box.toMap().entries) + if (entry.value is Map && (entry.value as Map)['pinned'] == true) + entry.key as String, + }; + } + + /// Unread incoming messages per conversation, for the chat list badge. + static Future> getUnreadCounts() async { + final box = await _openPrivateMessagesBox(); + final counts = {}; + for (final key in box.keys.whereType()) { + final userId = conversationOfKey(key); + if (userId == null) { + continue; + } + final value = box.get(key); + if (value is PrivateMessage && !value.read) { + counts[userId] = (counts[userId] ?? 0) + 1; + } + } + return counts; + } + + /// Oldest unread message of a conversation: the anchor of the "new messages" + /// divider, taken before the chat marks everything read. + static Future firstUnreadSentAt(String userId) async { + final box = await _openPrivateMessagesBox(); + DateTime? first; + for (final key in _conversationKeys(box, userId)) { + final value = box.get(key); + if (value is! PrivateMessage || value.read) { + continue; + } + if (first == null || value.sentAt.isBefore(first)) { + first = value.sentAt; + } + } + return first; + } + /// Get Map of all conversations with their last messages. /// /// Only the newest message of each conversation is deserialized, so the list - /// does not pay for the whole history. + /// does not pay for the whole history. Pinned conversations come first. static Future> getLatestPrivateMessages() async { Box box = await _openPrivateMessagesBox(); await _migrateLegacyMessages(box); @@ -744,9 +827,17 @@ class CacheUtils { User? user = await getUserById(entry.key); conversations[user ?? User(entry.key, '', '', false)] = message; } - // Sort conversations by last message date + // Pinned conversations first, then by last message date + final pinnedIds = await getPinnedConversations(); var sortedEntries = conversations.entries.toList() - ..sort((a, b) => b.value.receivedAt.compareTo(a.value.receivedAt)); + ..sort((a, b) { + final aPinned = pinnedIds.contains(a.key.id); + final bPinned = pinnedIds.contains(b.key.id); + if (aPinned != bPinned) { + return aPinned ? -1 : 1; + } + return b.value.receivedAt.compareTo(a.value.receivedAt); + }); return Map.fromEntries(sortedEntries); } @@ -756,10 +847,12 @@ class CacheUtils { Box userBox = await _openUserBox(); Box conceptBox = await _openMessageConceptBox(); Box pendingBox = await _openPendingSendsBox(); + Box conversationsBox = await _openConversationsBox(); await userBox.clear(); await messageBox.clear(); await conceptBox.clear(); await pendingBox.clear(); + await conversationsBox.clear(); // Remove every locally stored media file. await MediaUtils.clearMediaDir(); } diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index d9ecf09..c56a17f 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -18,6 +18,7 @@ import 'crypto_utils.dart'; import 'media_utils.dart'; import 'message_notifier.dart'; import 'singleton.dart'; +import 'text_envelope.dart'; import 'utils.dart'; /// One attachment of an outgoing album (or a single media message). @@ -56,12 +57,14 @@ class ChatSender { /// upgrade by persisting the transport key inside the encrypted profile box. static final Map> _outgoingReferences = {}; - /// Send a text message to [recipient]. - static Future sendText(User recipient, String text) async { + /// Send a text message to [recipient], optionally quoting [reply]. + static Future sendText(User recipient, String text, + {ReplyRef? reply}) async { final now = DateTime.now(); final message = PrivateMessage( Singleton().profile.user.id, text, now, now, true, - sendStatus: SendStatus.sending); + sendStatus: SendStatus.sending) + ..setReplyTo(reply); try { await _persist(recipient, [message]); if (!await _ensureConnected()) { @@ -395,9 +398,14 @@ class ChatSender { /// Encrypt [message] for [recipient] and hand it to the WebSocket. The /// original timestamp is kept so a resend maps onto the same server entry. static Future _sendText(User recipient, PrivateMessage message) async { + // A reply needs the quote next to the body; everything else stays raw text + // so an older client can still read it. + final reply = message.replyTo; + final plaintext = reply == null + ? utf8.encode(message.message) + : buildTextEnvelope(message.message, reply); final data = await CryptoUtils.encryptMessageData( - utf8.encode(message.message), - bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); + plaintext, bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); Singleton().wsClient.sendMessage(WsMessage.privateMessage(NewPrivateMessage( recipient.id, data['encryptedData']!, diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 7c01170..af387fb 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -63,7 +63,7 @@ class MessageActions { title: Text('forwardMessage'.tr()), onTap: () { Navigator.pop(ctx); - forward(context, message); + forward(context, [message]); }, ), if (canSave(message)) @@ -122,10 +122,10 @@ class MessageActions { } } - /// Pick a chat (or a user) and send the message there. + /// Pick a chat (or a user) and send the messages there. static Future forward( - BuildContext context, PrivateMessage message) async { - await Navigator.of(context).push(stepRoute(ForwardPage(message))); + BuildContext context, List messages) async { + await Navigator.of(context).push(stepRoute(ForwardPage(messages))); } /// Delete the message only on this device, after a confirmation. diff --git a/lib/utils/message_format.dart b/lib/utils/message_format.dart new file mode 100644 index 0000000..99821ba --- /dev/null +++ b/lib/utils/message_format.dart @@ -0,0 +1,286 @@ +import 'link_utils.dart'; + +/// Inline formatting of a message body. +/// +/// The subset the app supports: `**bold**`, `*italic*`, `~~strike~~`, +/// `` `mono` ``, ```` ```block``` ```` and `||spoiler||`. Markers do not nest: +/// the first one that closes wins, which keeps the parser small and the result +/// predictable. +enum MessageStyle { + plain, + bold, + italic, + strike, + + /// Inline monospace (single backticks). + mono, + + /// Fenced code block (triple backticks) on its own lines. + code, + + /// Hidden until tapped. + spoiler, +} + +/// What a piece of a message is, for tap handling. +enum MessageKind { + text, + + /// Opens in the browser. + link, + + /// Opens the mail client. + email, + + /// Tapped to copy. + phone, +} + +/// One run of message text with one style and one tap action. +class MessagePiece { + const MessagePiece(this.text, this.style, this.kind); + + final String text; + final MessageStyle style; + final MessageKind kind; +} + +/// Splits [text] into styled, tappable pieces, in order. +List parseMessage(String text) { + if (text.isEmpty) { + return const []; + } + final pieces = []; + for (final segment in _splitCodeBlocks(text)) { + if (segment.block) { + pieces + .add(MessagePiece(segment.text, MessageStyle.code, MessageKind.text)); + } else { + _parseInline(segment.text, pieces); + } + } + return pieces; +} + +/// Whether [text] is only emoji, so it can be shown large and without a bubble. +/// +/// Keycaps (`1️⃣`) and skin-tone modifiers count as emoji. More than +/// [maxLargeEmoji] emoji are still emoji-only, the caller decides the size. +bool isEmojiOnly(String text) { + var emoji = 0; + var significant = 0; + for (final rune in text.runes) { + if (_isEmojiIgnorable(rune)) { + continue; + } + significant++; + if (_isEmojiRune(rune) || _isKeycapBase(rune)) { + if (_isEmojiRune(rune)) { + emoji++; + } + continue; + } + return false; + } + return emoji > 0 && significant > 0; +} + +/// Emoji in a message: used to cap the large rendering. +int emojiCount(String text) => text.runes.where(_isEmojiRune).length; + +// Whitespace, variation selectors, ZWJ and skin-tone modifiers carry no +// meaning on their own. +bool _isEmojiIgnorable(int rune) => + rune == 0x20 || + rune == 0x09 || + rune == 0x0A || + rune == 0x0D || + rune == 0xFE0F || + rune == 0xFE0E || + rune == 0x200D || + (rune >= 0x1F3FB && rune <= 0x1F3FF); + +bool _isEmojiRune(int rune) => + (rune >= 0x1F000 && rune <= 0x1FAFF) || + (rune >= 0x2600 && rune <= 0x27BF) || + (rune >= 0x2B00 && rune <= 0x2BFF) || + (rune >= 0x1F1E6 && rune <= 0x1F1FF) || + rune == 0x2764 || + rune == 0x203C || + rune == 0x2049; + +// Digits, `#` and `*` only appear in emoji when a keycap follows. +bool _isKeycapBase(int rune) => + rune == 0x23 || rune == 0x2A || (rune >= 0x30 && rune <= 0x39); + +class _Segment { + const _Segment(this.text, {required this.block}); + final String text; + final bool block; +} + +/// Splits fenced code blocks out of [text]. An unterminated fence runs to the +/// end of the message. +List<_Segment> _splitCodeBlocks(String text) { + const fence = '```'; + final segments = <_Segment>[]; + var index = 0; + while (true) { + final start = text.indexOf(fence, index); + if (start < 0) { + segments.add(_Segment(text.substring(index), block: false)); + break; + } + segments.add(_Segment(text.substring(index, start), block: false)); + final end = text.indexOf(fence, start + fence.length); + if (end < 0) { + segments.add(_Segment(_trimFence(text.substring(start + fence.length)), + block: true)); + break; + } + segments.add(_Segment(_trimFence(text.substring(start + fence.length, end)), + block: true)); + index = end + fence.length; + } + return segments.where((s) => s.block || s.text.isNotEmpty).toList(); +} + +// The newline that wraps a fence is part of the syntax, not the code. +String _trimFence(String text) { + var value = text; + while (value.startsWith('\n')) { + value = value.substring(1); + } + while (value.endsWith('\n')) { + value = value.substring(0, value.length - 1); + } + return value; +} + +class _Marker { + const _Marker(this.token, this.style); + final String token; + final MessageStyle style; +} + +// Longest first: `**` must win over `*` at the same position. +const List<_Marker> _markers = [ + _Marker('**', MessageStyle.bold), + _Marker('~~', MessageStyle.strike), + _Marker('||', MessageStyle.spoiler), + _Marker('`', MessageStyle.mono), + _Marker('*', MessageStyle.italic), +]; + +void _parseInline(String text, List out) { + final plain = StringBuffer(); + var index = 0; + while (index < text.length) { + _Marker? marker; + var at = -1; + for (final candidate in _markers) { + final found = text.indexOf(candidate.token, index); + if (found >= 0 && (at < 0 || found < at)) { + marker = candidate; + at = found; + } + } + if (marker == null) { + plain.write(text.substring(index)); + break; + } + final contentStart = at + marker.token.length; + final close = text.indexOf(marker.token, contentStart); + if (close <= contentStart) { + // No closing marker (or nothing between them): keep the text literal. + plain.write(text.substring(index, contentStart)); + index = contentStart; + continue; + } + plain.write(text.substring(index, at)); + _flushPlain(plain, out); + out.add(MessagePiece( + text.substring(contentStart, close), marker.style, MessageKind.text)); + index = close + marker.token.length; + } + _flushPlain(plain, out); +} + +void _flushPlain(StringBuffer buffer, List out) { + if (buffer.isEmpty) { + return; + } + out.addAll(_splitEntities(buffer.toString())); + buffer.clear(); +} + +/// Splits plain text into links, e-mail addresses, phone numbers and leftover +/// text. +List _splitEntities(String text) { + final pieces = []; + for (final link in splitLinks(text)) { + if (link.url != null) { + pieces.add(MessagePiece(link.text, MessageStyle.plain, MessageKind.link)); + continue; + } + pieces.addAll(_splitTappable(link.text)); + } + return pieces; +} + +/// Splits plain text into the things a tap can act on. When two patterns start +/// at the same character the one listed first wins. +List _splitTappable(String text) { + final patterns = <(RegExp, MessageKind)>[ + (_emailPattern, MessageKind.email), + (_phonePattern, MessageKind.phone), + ]; + final pieces = []; + var index = 0; + while (index < text.length) { + final rest = text.substring(index); + Match? best; + var kind = MessageKind.text; + for (final (pattern, candidateKind) in patterns) { + final match = pattern.firstMatch(rest); + if (match == null) { + continue; + } + if (candidateKind == MessageKind.phone && + !_isPhoneNumber(match.group(0)!)) { + continue; + } + if (best == null || match.start < best.start) { + best = match; + kind = candidateKind; + } + } + if (best == null) { + pieces.add(MessagePiece( + text.substring(index), MessageStyle.plain, MessageKind.text)); + break; + } + if (best.start > 0) { + pieces.add(MessagePiece(text.substring(index, index + best.start), + MessageStyle.plain, MessageKind.text)); + } + pieces.add(MessagePiece(best.group(0)!, MessageStyle.plain, kind)); + index += best.end; + } + return pieces; +} + +/// A single e-mail address, no display name and no surrounding punctuation. +final RegExp _emailPattern = RegExp( + r'(?= 7 && digits.length <= 15; +} diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index d26919b..1826181 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -201,10 +201,9 @@ class MessageNotifier extends ChangeNotifier { newMessages[e.key] = e.value; } } - // Sort conversations by last message date - var sortedEntries = newMessages.entries.toList() - ..sort((a, b) => b.value.receivedAt.compareTo(a.value.receivedAt)); - return Map.fromEntries(sortedEntries); + // The cache already ordered this map (pinned chats first, then by the + // newest message), so the entries are kept in the order they came in. + return newMessages; } /// Delete all chats diff --git a/lib/utils/text_envelope.dart b/lib/utils/text_envelope.dart new file mode 100644 index 0000000..81bad79 --- /dev/null +++ b/lib/utils/text_envelope.dart @@ -0,0 +1,96 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +/// The message a reply quotes. +/// +/// The preview is stored next to the pointer, so the quote still reads after +/// the original was deleted locally (deleting a message only removes it on +/// this device). +class ReplyRef { + const ReplyRef({ + required this.senderId, + required this.sentAt, + required this.preview, + }); + + final String senderId; + final DateTime sentAt; + + /// Truncated body of the quoted message. + final String preview; + + /// Longest preview kept in the envelope; the bubble shows two lines. + static const int maxPreviewLength = 160; + + Map toJson() => { + 'senderId': senderId, + 'sentAt': sentAt.microsecondsSinceEpoch, + 'preview': preview, + }; + + /// Null when [json] is not a usable reference. + static ReplyRef? fromJson(Object? json) { + if (json is! Map) { + return null; + } + final senderId = json['senderId']; + final sentAt = json['sentAt']; + if (senderId is! String || sentAt is! int) { + return null; + } + return ReplyRef( + senderId: senderId, + sentAt: DateTime.fromMicrosecondsSinceEpoch(sentAt), + preview: json['preview'] is String ? json['preview'] as String : '', + ); + } + + /// Shortens [text] for storage in the envelope. + static String previewOf(String text) => text.length <= maxPreviewLength + ? text + : '${text.substring(0, maxPreviewLength)}…'; +} + +/// Payload of a text message that quotes another one. +class ParsedTextEnvelope { + const ParsedTextEnvelope(this.body, this.reply); + + final String body; + final ReplyRef? reply; +} + +/// Envelope version of a text message carrying a quote. Versions 1 and 2 are +/// the media envelopes; plain text stays raw UTF-8, so a reader that never +/// quotes anything keeps writing what every older client can open. +const int textEnvelopeVersion = 3; + +/// Plaintext (pre-encryption) bytes of a reply. +Uint8List buildTextEnvelope(String body, ReplyRef reply) { + final map = { + 'whisperMsg': textEnvelopeVersion, + 'kind': 'text', + 'body': body, + 'replyTo': reply.toJson(), + }; + return Uint8List.fromList(utf8.encode(jsonEncode(map))); +} + +/// Parses [plaintext] as a quoting text envelope. Null for anything else, which +/// includes every plain text message. +ParsedTextEnvelope? tryParseTextEnvelope(Uint8List plaintext) { + try { + final decoded = jsonDecode(utf8.decode(plaintext)); + if (decoded is Map && + decoded['kind'] == 'text' && + decoded['whisperMsg'] == textEnvelopeVersion) { + final body = decoded['body']; + if (body is! String) { + return null; + } + return ParsedTextEnvelope(body, ReplyRef.fromJson(decoded['replyTo'])); + } + } catch (_) { + // Not JSON / not a text envelope -> plain text. + } + return null; +} diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 543471b..36a0d96 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -24,6 +24,7 @@ import 'crypto_utils.dart'; import 'media_utils.dart'; import 'message_notifier.dart'; import 'singleton.dart'; +import 'text_envelope.dart'; import '../models/private_message.dart' as pm; import '../models/user.dart'; @@ -357,13 +358,16 @@ class Utils { ); return (mediaMsg, [ref], message.peerId); } - // Plain text message (legacy/unchanged path). + // Plain text message (legacy/unchanged path), or a reply that carries + // its quote in a text envelope. + final textEnvelope = tryParseTextEnvelope(decryptedMessage); final textMsg = pm.PrivateMessage( message.senderId, - utf8.decode(decryptedMessage), + textEnvelope?.body ?? utf8.decode(decryptedMessage), message.sentAt, DateTime.now(), - false); + false) + ..setReplyTo(textEnvelope?.reply); return (textMsg, const [], message.peerId); } catch (e) { // Log individual message decryption errors diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 271119a..6bf6257 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -2,12 +2,17 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import '../models/user.dart'; import '../models/private_message.dart'; -import '../utils/message_actions.dart'; +import '../utils/message_format.dart'; import '../utils/message_notifier.dart'; -import 'linkified_text.dart'; +import '../utils/singleton.dart'; +import 'formatted_text.dart'; import 'media_bubble.dart'; -// Long-press opens the message actions sheet (copy, forward, save, delete). +/// One message bubble. +/// +/// Long-press enters selection mode; double-tap (or a horizontal swipe) replies. +/// Everything the single-message sheet used to offer lives in the selection +/// app bar, which keeps one gesture per intent. class ChatBubble extends StatefulWidget { final PrivateMessage? previousMessage; final PrivateMessage message; @@ -16,9 +21,30 @@ class ChatBubble extends StatefulWidget { // Fixed for both light and dark mode (see ThemeUtils.bubbleAccent). final Color accentColor; + /// Whether the chat is in multi-select mode. + final bool selectionMode; + + /// Whether this bubble is part of the current selection. + final bool selected; + + /// Toggles this bubble in the selection (tap and long-press). + final VoidCallback? onSelect; + + /// Quotes this message in the composer (double-tap and swipe). + final VoidCallback? onReply; + + /// Jumps to the quoted message. + final VoidCallback? onTapQuote; + const ChatBubble( this.previousMessage, this.message, this.nextMessage, this.user, - {required this.accentColor, super.key}); + {required this.accentColor, + this.selectionMode = false, + this.selected = false, + this.onSelect, + this.onReply, + this.onTapQuote, + super.key}); @override State createState() => _ChatBubbleState(); @@ -27,16 +53,22 @@ class ChatBubble extends StatefulWidget { class _ChatBubbleState extends State { bool _showTooltip = false; - @override - void initState() { - super.initState(); - /* - if (!widget.message.read) { - widget.message.read = true; - widget.message.save(); - } - */ - } + /// Long messages start folded; this is set once the user unfolds one. + bool _expanded = false; + + /// Text longer than this is folded (about eight lines on a phone). + static const int _foldLength = 600; + + bool get _foldable => + !widget.message.isMedia && + !widget.message.isUndecryptable && + widget.message.message.length > _foldLength; + + bool get _isLargeEmoji => + !widget.message.isMedia && + !widget.message.isUndecryptable && + isEmojiOnly(widget.message.message) && + emojiCount(widget.message.message) <= 3; @override Widget build(BuildContext context) { @@ -114,191 +146,323 @@ class _ChatBubbleState extends State { return luminance > 0.5 ? Colors.black : Colors.white; } + /// Gesture handling: select in selection mode, otherwise tooltip + reply. + void onTap() { + if (widget.selectionMode) { + widget.onSelect?.call(); + return; + } + setState(() { + _showTooltip = !_showTooltip; + }); + } + + void onLongPress() { + // A long press in selection mode does nothing: tapping already toggles. + if (widget.selectionMode) { + return; + } + widget.onSelect?.call(); + } + + Widget content() { + if (widget.message.isMedia) { + return MediaBubble( + message: widget.message, + conversationUserId: widget.user.id, + bubbleColor: bubbleBackground(), + textColor: bubbleTextColor(), + canRetry: widget.message.mediaId != null && + MessageNotifier().canRetryMedia(widget.message.mediaId!), + onRetry: () { + if (widget.message.mediaId != null) { + MessageNotifier() + .retryMediaDownload(widget.user.id, widget.message.mediaId!); + } + }, + ); + } + + final color = bubbleTextColor(); + if (widget.message.isUndecryptable) { + return Text( + 'messageUndecryptable'.tr(), + style: TextStyle(color: color, fontStyle: FontStyle.italic), + ); + } + + final text = FormattedText( + widget.message.message, + style: TextStyle( + color: color, + fontSize: _isLargeEmoji ? 40 : null, + ), + maxLines: _foldable && !_expanded ? 8 : null, + ); + if (!_foldable) { + return text; + } + return Column( + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + text, + GestureDetector( + onTap: () => setState(() => _expanded = !_expanded), + child: Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + _expanded ? 'showLess'.tr() : 'showFull'.tr(), + style: TextStyle( + color: color, + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ], + ); + } + + /// The quoted message above the body, tappable to jump to the original. + Widget quoteBlock() { + final reply = widget.message.replyTo; + if (reply == null) { + return const SizedBox.shrink(); + } + final color = bubbleTextColor(); + final fromMe = reply.senderId == Singleton().profile.user.id; + final author = fromMe + ? 'meText'.tr() + : (widget.user.username.isNotEmpty ? widget.user.username : '?'); + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: GestureDetector( + onTap: widget.onTapQuote, + child: Container( + constraints: const BoxConstraints(minWidth: 120), + padding: const EdgeInsets.only(left: 8, top: 4, bottom: 4), + decoration: BoxDecoration( + border: Border( + left: BorderSide(color: color.withValues(alpha: 0.8), width: 3), + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + author, + style: TextStyle( + color: color, + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + Text( + reply.preview.isEmpty ? 'mediaPhoto'.tr() : reply.preview, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: color.withValues(alpha: 0.8), + fontSize: 12, + ), + ), + ], + ), + ), + ), + ); + } + + final bubble = Column( + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (widget.message.isReply) quoteBlock(), + content(), + ], + ); + + // Emoji-only messages drop the bubble chrome and read large. + final bubbleBox = Container( + decoration: BoxDecoration( + color: _isLargeEmoji ? null : bubbleBackground(), + borderRadius: BorderRadius.circular(20), + border: widget.selected + ? Border.all( + color: Theme.of(context).colorScheme.primary, + width: 2, + ) + : null, + ), + padding: _isLargeEmoji + ? EdgeInsets.zero + : const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + child: bubble, + ); + return Padding( padding: EdgeInsets.only( left: widget.message.isMe ? 96 : 16, right: widget.message.isMe ? 16 : 96, top: isFromSameUser() ? 4 : 16, ), - child: Column( - crossAxisAlignment: widget.message.isMe - ? CrossAxisAlignment.end - : CrossAxisAlignment.start, + child: Row( + mainAxisAlignment: widget.message.isMe + ? MainAxisAlignment.end + : MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, children: [ - AnimatedSize( - duration: const Duration(milliseconds: 200), - curve: Curves.easeInOut, - child: SizedBox( - width: double.infinity, - child: Column( - children: [ - if (_showTooltip && !shouldShowTime()) - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 16, vertical: 8), - child: Center( - child: Text( - formatDate(widget.message.isMe - ? widget.message.sentAt - : widget.message.receivedAt), - style: TextStyle( - fontSize: 12, - color: Colors.grey[600], - ), - ), - ), - ), - if (shouldShowTime()) - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 16, vertical: 8), - child: Center( - child: Text( - formatDate(widget.message.isMe - ? widget.message.sentAt - : widget.message.receivedAt), - style: TextStyle( - fontSize: 12, - color: Colors.grey[600], - ), - ), - ), - ), - ], + if (widget.selectionMode) + Padding( + padding: const EdgeInsets.only(right: 6), + child: Icon( + widget.selected + ? Icons.check_circle + : Icons.radio_button_unchecked, + size: 20, + color: Theme.of(context).colorScheme.primary, ), ), - ), - GestureDetector( - onTap: () { - setState(() { - _showTooltip = !_showTooltip; - }); - }, - onLongPress: () => MessageActions.showSheet( - context, widget.message, widget.user.id), - child: Align( - alignment: widget.message.isMe - ? Alignment.centerRight - : Alignment.centerLeft, - child: Row( - mainAxisAlignment: widget.message.isMe - ? MainAxisAlignment.end - : MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - if (!widget.message.isMe) - SizedBox( - width: 40, // 32 (avatar) + 8 (padding) - child: showAvatar() - ? Padding( - padding: const EdgeInsets.only(right: 8), - child: CircleAvatar( - radius: 16, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 14, - color: widget.user.avatarTextColor, - ), - ), - ), - ) - : null, - ), - Flexible( - child: Column( - crossAxisAlignment: widget.message.isMe - ? CrossAxisAlignment.end - : CrossAxisAlignment.start, + Flexible( + child: Column( + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + children: [ + if (_showTooltip && !shouldShowTime()) _tooltip(formatDate), + if (shouldShowTime()) _tooltip(formatDate), + GestureDetector( + onTap: onTap, + onLongPress: onLongPress, + onDoubleTap: widget.onReply, + child: Align( + alignment: widget.message.isMe + ? Alignment.centerRight + : Alignment.centerLeft, + child: Row( + mainAxisAlignment: widget.message.isMe + ? MainAxisAlignment.end + : MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.end, children: [ - /* - // Show nick if (!widget.message.isMe) - Padding( - padding: const EdgeInsets.only(left: 12, bottom: 4), - child: Text( - widget.user.username, - style: TextStyle( - fontSize: 12, - color: Colors.grey[600], - ), - ), - ), - */ - if (widget.message.isMedia) - MediaBubble( - message: widget.message, - conversationUserId: widget.user.id, - bubbleColor: bubbleBackground(), - textColor: bubbleTextColor(), - canRetry: widget.message.mediaId != null && - MessageNotifier() - .canRetryMedia(widget.message.mediaId!), - onRetry: () { - if (widget.message.mediaId != null) { - MessageNotifier().retryMediaDownload( - widget.user.id, widget.message.mediaId!); - } - }, - ) - else - Container( - decoration: BoxDecoration( - color: bubbleBackground(), - borderRadius: BorderRadius.circular(20), - ), - padding: const EdgeInsets.symmetric( - horizontal: 16, vertical: 10), - child: widget.message.isUndecryptable - ? Text( - 'messageUndecryptable'.tr(), - style: TextStyle( - color: bubbleTextColor(), - fontStyle: FontStyle.italic, + SizedBox( + width: 40, // 32 (avatar) + 8 (padding) + child: showAvatar() + ? Padding( + padding: const EdgeInsets.only(right: 8), + child: CircleAvatar( + radius: 16, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0] + .toUpperCase() + : '?', + style: TextStyle( + fontSize: 14, + color: widget.user.avatarTextColor, + ), + ), ), ) - : LinkifiedText( - widget.message.message, - style: TextStyle( - color: bubbleTextColor(), + : null, + ), + Flexible( + child: Column( + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + children: [ + if (widget.onReply != null && + !widget.selectionMode) + Dismissible( + key: ValueKey( + 'reply|${widget.message.senderId}' + '|${widget.message.sentAt.microsecondsSinceEpoch}'), + direction: DismissDirection.horizontal, + // The swipe is an action, not a delete: the + // bubble always springs back. + confirmDismiss: (_) async { + widget.onReply?.call(); + return false; + }, + background: _swipeBackground( + Alignment.centerLeft, bubbleTextColor()), + secondaryBackground: _swipeBackground( + Alignment.centerRight, bubbleTextColor()), + child: bubbleBox, + ) + else + bubbleBox, + // Outgoing messages show a clock while they are + // being sent and an error when the send failed. + if (widget.message.isMe && + widget.message.sendStatus != SendStatus.sent) + Padding( + padding: const EdgeInsets.only(top: 2), + child: Tooltip( + message: widget.message.sendStatus == + SendStatus.failed + ? 'messageSendFailed'.tr() + : 'messageSending'.tr(), + child: Icon( + widget.message.sendStatus == + SendStatus.failed + ? Icons.error_outline + : Icons.schedule, + size: 13, + color: widget.message.sendStatus == + SendStatus.failed + ? Colors.red + : Colors.grey, ), ), + ), + ], ), - // Outgoing messages show a clock while they are being - // sent and an error when the send failed. - if (widget.message.isMe && - widget.message.sendStatus != SendStatus.sent) - Padding( - padding: const EdgeInsets.only(top: 2), - child: Tooltip( - message: - widget.message.sendStatus == SendStatus.failed - ? 'messageSendFailed'.tr() - : 'messageSending'.tr(), - child: Icon( - widget.message.sendStatus == SendStatus.failed - ? Icons.error_outline - : Icons.schedule, - size: 13, - color: widget.message.sendStatus == - SendStatus.failed - ? Colors.red - : Colors.grey, - ), - ), - ), + ), ], ), ), - ], - ), + ), + ], ), ), ], ), ); } + + Widget _swipeBackground(Alignment alignment, Color color) { + return Container( + alignment: alignment, + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Icon(Icons.reply, color: color.withValues(alpha: 0.7)), + ); + } + + Widget _tooltip(String Function(DateTime) formatDate) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Center( + child: Text( + formatDate(widget.message.isMe + ? widget.message.sentAt + : widget.message.receivedAt), + style: TextStyle( + fontSize: 12, + color: Colors.grey[600], + ), + ), + ), + ); + } } diff --git a/lib/widgets/chat_list_item.dart b/lib/widgets/chat_list_item.dart index 4328e9d..87c5269 100644 --- a/lib/widgets/chat_list_item.dart +++ b/lib/widgets/chat_list_item.dart @@ -4,12 +4,19 @@ import '../models/private_message.dart'; import '../models/user.dart'; class ChatListItem extends StatefulWidget { - const ChatListItem(this.user, this.lastMessage, this.onPressed, {super.key}); + const ChatListItem(this.user, this.lastMessage, this.onPressed, + {this.unreadCount = 0, this.pinned = false, super.key}); final User user; final PrivateMessage lastMessage; final Function() onPressed; + /// Unread incoming messages of this conversation, for the badge. + final int unreadCount; + + /// Whether the conversation is pinned to the top of the list. + final bool pinned; + @override State createState() => _ChatListItemState(); } @@ -44,6 +51,26 @@ class _ChatListItemState extends State { } } + /// Rounded counter, capped the way every messenger does it. + Widget _unreadBadge() { + final scheme = Theme.of(context).colorScheme; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: scheme.primary, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + widget.unreadCount > 99 ? '99+' : '${widget.unreadCount}', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: scheme.onPrimary, + ), + ), + ); + } + @override Widget build(BuildContext context) { /// Return message with or without "me: " prefix @@ -56,6 +83,8 @@ class _ChatListItemState extends State { return meText + msg; } + final bool unread = widget.unreadCount > 0 || !widget.lastMessage.read; + return ListTile( onTap: widget.onPressed, tileColor: Colors.transparent, @@ -76,23 +105,48 @@ class _ChatListItemState extends State { ), ), ), - title: Text( - widget.user.username.isNotEmpty ? widget.user.username : '?', - style: !widget.lastMessage.read - ? TextStyle(fontWeight: FontWeight.bold) - : null, + title: Row( + children: [ + if (widget.pinned) + Padding( + padding: const EdgeInsets.only(right: 4), + child: Icon(Icons.push_pin, + size: 14, color: Theme.of(context).colorScheme.primary), + ), + Expanded( + child: Text( + widget.user.username.isNotEmpty ? widget.user.username : '?', + overflow: TextOverflow.ellipsis, + style: + unread ? const TextStyle(fontWeight: FontWeight.bold) : null, + ), + ), + ], ), subtitle: Text( getTitle(), - style: !widget.lastMessage.read - ? TextStyle(fontWeight: FontWeight.bold) - : null, + style: unread ? const TextStyle(fontWeight: FontWeight.bold) : null, ), - trailing: Text( - formatDate(), - style: !widget.lastMessage.read - ? TextStyle(fontWeight: FontWeight.bold) - : null, + trailing: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + formatDate(), + style: unread + ? TextStyle( + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.primary, + ) + : null, + ), + if (widget.unreadCount > 0) + Padding( + padding: const EdgeInsets.only(top: 4), + child: _unreadBadge(), + ), + ], ), ); } diff --git a/lib/widgets/formatted_text.dart b/lib/widgets/formatted_text.dart new file mode 100644 index 0000000..e763b4e --- /dev/null +++ b/lib/widgets/formatted_text.dart @@ -0,0 +1,199 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +import '../utils/link_utils.dart'; +import '../utils/message_format.dart'; + +/// Message text with inline formatting, tappable links, phone numbers, +/// e-mail addresses and spoilers that stay covered until tapped. +class FormattedText extends StatefulWidget { + const FormattedText( + this.text, { + this.style, + this.maxLines, + this.textAlign, + super.key, + }); + + final String text; + final TextStyle? style; + final int? maxLines; + final TextAlign? textAlign; + + @override + State createState() => _FormattedTextState(); +} + +class _FormattedTextState extends State { + final Map _recognizers = {}; + + /// Indices of the spoiler pieces the user has opened this session. + final Set _revealed = {}; + + @override + void dispose() { + for (final recognizer in _recognizers.values) { + recognizer.dispose(); + } + super.dispose(); + } + + TapGestureRecognizer _recognizer(String key, VoidCallback onTap) { + return _recognizers.putIfAbsent( + key, () => TapGestureRecognizer()..onTap = onTap); + } + + Color get _color => + widget.style?.color ?? + DefaultTextStyle.of(context).style.color ?? + Colors.black; + + TextSpan _span(MessagePiece piece, int index) { + switch (piece.style) { + case MessageStyle.bold: + return TextSpan( + text: piece.text, + style: const TextStyle(fontWeight: FontWeight.bold)); + case MessageStyle.italic: + return TextSpan( + text: piece.text, + style: const TextStyle(fontStyle: FontStyle.italic)); + case MessageStyle.strike: + return TextSpan( + text: piece.text, + style: const TextStyle(decoration: TextDecoration.lineThrough)); + case MessageStyle.mono: + return TextSpan( + text: piece.text, + style: TextStyle( + fontFamily: 'monospace', + backgroundColor: _color.withValues(alpha: 0.12), + ), + ); + case MessageStyle.spoiler: + if (_revealed.contains(index)) { + return TextSpan( + text: piece.text, + style: + TextStyle(backgroundColor: _color.withValues(alpha: 0.15))); + } + return TextSpan( + text: List.filled(piece.text.length, '█').join(), + recognizer: _recognizer('spoiler:$index', () { + setState(() => _revealed.add(index)); + }), + ); + case MessageStyle.code: + case MessageStyle.plain: + break; + } + switch (piece.kind) { + case MessageKind.link: + return TextSpan( + text: piece.text, + recognizer: + _recognizer('link:${piece.text}', () => openLink(piece.text)), + style: _inlineLink(TextDecorationStyle.solid), + ); + case MessageKind.email: + return TextSpan( + text: piece.text, + recognizer: _recognizer( + 'mail:${piece.text}', () => openLink('mailto:${piece.text}')), + style: _inlineLink(TextDecorationStyle.solid), + ); + case MessageKind.phone: + // Underlined like a link: it is something the user taps, not just text. + return TextSpan( + text: piece.text, + recognizer: _recognizer( + 'copy:${piece.kind.name}:${piece.text}', () => _copy(piece.text)), + style: _inlineLink(TextDecorationStyle.solid), + ); + case MessageKind.text: + return TextSpan(text: piece.text); + } + } + + /// Underline for everything tappable: links, e-mails and phone numbers read + /// as a link. + TextStyle _inlineLink(TextDecorationStyle style) => TextStyle( + decoration: TextDecoration.underline, + decorationStyle: style, + decorationColor: _color, + ); + Future _copy(String value) async { + await Clipboard.setData(ClipboardData(text: value)); + Fluttertoast.showToast(msg: 'copiedText'.tr()); + } + + @override + Widget build(BuildContext context) { + final pieces = parseMessage(widget.text); + if (pieces.isEmpty) { + return Text('', style: widget.style); + } + // Code blocks read as their own block, so they get a container instead of + // an inline span. Whole-message maxLines cannot clip through a block. + // shortcut: a folded message with a code block still shows the block in + // full, upgrade with a real measurement pass when that shows up in practice. + final hasBlock = pieces.any((piece) => piece.style == MessageStyle.code); + if (!hasBlock) { + return Text.rich( + TextSpan(children: [ + for (var i = 0; i < pieces.length; i++) _span(pieces[i], i), + ]), + style: widget.style, + maxLines: widget.maxLines, + overflow: widget.maxLines == null ? null : TextOverflow.ellipsis, + textAlign: widget.textAlign, + ); + } + + final runs = []; + var inline = []; + void flushInline() { + if (inline.isEmpty) { + return; + } + runs.add(Text.rich(TextSpan(children: inline), style: widget.style)); + inline = []; + } + + for (var i = 0; i < pieces.length; i++) { + final piece = pieces[i]; + if (piece.style != MessageStyle.code) { + inline.add(_span(piece, i)); + continue; + } + flushInline(); + runs.add( + Container( + width: double.infinity, + margin: const EdgeInsets.symmetric(vertical: 4), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), + decoration: BoxDecoration( + color: _color.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + piece.text, + style: widget.style?.copyWith( + fontFamily: 'monospace', + fontSize: (widget.style?.fontSize ?? 14) * 0.9, + ), + ), + ), + ); + } + flushInline(); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: runs, + ); + } +} diff --git a/lib/widgets/linkified_text.dart b/lib/widgets/linkified_text.dart deleted file mode 100644 index 3e4b493..0000000 --- a/lib/widgets/linkified_text.dart +++ /dev/null @@ -1,60 +0,0 @@ -import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; - -import '../utils/link_utils.dart'; - -/// Message text where http(s) addresses are underlined and open in the -/// browser when tapped. -class LinkifiedText extends StatefulWidget { - const LinkifiedText(this.text, {this.style, super.key}); - - final String text; - final TextStyle? style; - - @override - State createState() => _LinkifiedTextState(); -} - -class _LinkifiedTextState extends State { - // Kept per address so a rebuild does not leak recognizers. - final Map _recognizers = {}; - - @override - void dispose() { - for (final recognizer in _recognizers.values) { - recognizer.dispose(); - } - super.dispose(); - } - - TapGestureRecognizer _recognizer(String url) { - return _recognizers.putIfAbsent( - url, - () => TapGestureRecognizer()..onTap = () => openLink(url), - ); - } - - @override - Widget build(BuildContext context) { - final color = - widget.style?.color ?? DefaultTextStyle.of(context).style.color; - return Text.rich( - TextSpan( - children: [ - for (final part in splitLinks(widget.text)) - part.url == null - ? TextSpan(text: part.text) - : TextSpan( - text: part.text, - recognizer: _recognizer(part.url!), - style: TextStyle( - decoration: TextDecoration.underline, - decorationColor: color, - ), - ), - ], - ), - style: widget.style, - ); - } -} diff --git a/test/chat_bubble_test.dart b/test/chat_bubble_test.dart new file mode 100644 index 0000000..2d7bf24 --- /dev/null +++ b/test/chat_bubble_test.dart @@ -0,0 +1,172 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/models/profile.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/singleton.dart'; +import 'package:whisper/utils/text_envelope.dart'; +import 'package:whisper/widgets/chat_bubble.dart'; + +/// Plain text of everything the bubble rendered, spans included. +String renderedText(WidgetTester tester) => tester + .widgetList(find.byType(RichText)) + .map((widget) => widget.text.toPlainText()) + .join('\n'); + +/// Style of the span that renders exactly [text], null when it is not there. +TextStyle? spanStyle(WidgetTester tester, String text) { + for (final widget in tester.widgetList(find.byType(RichText))) { + TextStyle? found; + widget.text.visitChildren((span) { + if (span is TextSpan && span.text == text) { + found = span.style; + return false; + } + return true; + }); + if (found != null) { + return found; + } + } + return null; +} + +void main() { + final peer = User('2', 'peer', '', false); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + // isMe compares against the signed-in user. + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + testWidgets('the bubble renders, quotes, selects and replies', + (tester) async { + // One app for the whole test: easy_localization loads its asset once, and a + // second pumpWidget would leave the tree without translations. + final shown = ValueNotifier(const SizedBox()); + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Scaffold( + body: Center( + child: ValueListenableBuilder( + valueListenable: shown, + builder: (_, child, __) => child, + ), + ), + ), + ); + }), + )); + + Future show(Widget child) async { + shown.value = child; + await tester.pumpAndSettle(); + } + + // Formatting: the markers never reach the screen. + await show(ChatBubble( + null, + PrivateMessage( + '2', 'the **bold** part', DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + )); + expect(renderedText(tester), contains('the bold part')); + expect(renderedText(tester), isNot(contains('**'))); + + // A reply shows what it quotes, and tapping the quote jumps to it. + var jumped = false; + await show(ChatBubble( + null, + PrivateMessage('2', 'souhlas', DateTime(2026), DateTime(2026), true) + ..setReplyTo(ReplyRef( + senderId: '1', + sentAt: DateTime(2025), + preview: 'původní dotaz', + )), + null, + peer, + accentColor: Colors.blue, + onTapQuote: () => jumped = true, + )); + expect(renderedText(tester), contains('původní dotaz')); + expect(renderedText(tester), contains('souhlas')); + await tester.tap(find.text('původní dotaz')); + await tester.pumpAndSettle(); + expect(jumped, isTrue); + + // Selection mode marks the bubble. + await show(ChatBubble( + null, + PrivateMessage('2', 'x', DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + selectionMode: true, + selected: true, + )); + expect(find.byIcon(Icons.check_circle), findsOneWidget); + + // Double tap quotes the message in the composer. + var replied = false; + await show(ChatBubble( + null, + PrivateMessage('2', 'ahoj', DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + onReply: () => replied = true, + )); + await tester.tap(find.text('ahoj')); + await tester.pump(const Duration(milliseconds: 50)); + await tester.tap(find.text('ahoj')); + await tester.pumpAndSettle(); + expect(replied, isTrue); + + // A long message can be unfolded. + await show(ChatBubble( + null, + PrivateMessage('2', 'x' * 700, DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + )); + expect(find.text('Show full message'), findsOneWidget); + await tester.tap(find.text('Show full message')); + await tester.pumpAndSettle(); + expect(find.text('Show less'), findsOneWidget); + + // Phone numbers and e-mails are underlined like a link. + await show(ChatBubble( + null, + PrivateMessage('2', 'volej +420 123 456 789 nebo piš na jan@example.com', + DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + )); + for (final tappable in ['+420 123 456 789', 'jan@example.com']) { + final style = spanStyle(tester, tappable); + expect(style, isNotNull, reason: tappable); + expect(style!.decoration, TextDecoration.underline, reason: tappable); + expect(style.decorationStyle ?? TextDecorationStyle.solid, + TextDecorationStyle.solid, + reason: tappable); + } + }); +} diff --git a/test/conversation_meta_test.dart b/test/conversation_meta_test.dart new file mode 100644 index 0000000..b1e2dac --- /dev/null +++ b/test/conversation_meta_test.dart @@ -0,0 +1,91 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; + +PrivateMessage message(String senderId, DateTime sentAt, {bool read = false}) { + return PrivateMessage(senderId, 'text', sentAt, sentAt, read); +} + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_conversation_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + for (final name in ['privateMessages', 'conversations', 'user']) { + await Hive.openBox(name); + await Hive.box(name).clear(); + } + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('unread counts only incoming unread messages', () async { + final base = DateTime(2026, 5, 1, 12); + await CacheUtils.addPrivateMessages('peer', [ + message('peer', base), + message('peer', base.add(const Duration(minutes: 1))), + message('peer', base.add(const Duration(minutes: 2)), read: true), + message('me', base.add(const Duration(minutes: 3)), read: true), + ]); + + final counts = await CacheUtils.getUnreadCounts(); + expect(counts['peer'], 2); + expect(await CacheUtils.firstUnreadSentAt('peer'), base); + }); + + test('a read conversation has no anchor', () async { + await CacheUtils.addPrivateMessages( + 'peer', [message('peer', DateTime(2026, 5, 1), read: true)]); + expect(await CacheUtils.firstUnreadSentAt('peer'), isNull); + }); + + test('pin and unpin keep the box clean', () async { + expect(await CacheUtils.isConversationPinned('peer'), isFalse); + + await CacheUtils.setConversationPinned('peer', true); + expect(await CacheUtils.isConversationPinned('peer'), isTrue); + expect(await CacheUtils.getPinnedConversations(), {'peer'}); + + await CacheUtils.setConversationPinned('peer', false); + expect(await CacheUtils.isConversationPinned('peer'), isFalse); + expect(await CacheUtils.getPinnedConversations(), isEmpty); + // Unpinning removes the entry instead of storing a false flag. + expect(Hive.box('conversations').containsKey('peer'), isFalse); + }); + + test('pinned conversations sort before newer ones', () async { + final base = DateTime(2026, 5, 1, 12); + await CacheUtils.addPrivateMessages('old', [message('old', base)]); + await CacheUtils.addPrivateMessages('new', [ + message('new', base.add(const Duration(hours: 1))), + ]); + + var chats = await CacheUtils.getLatestPrivateMessages(); + expect(chats.keys.first.id, 'new'); + + await CacheUtils.setConversationPinned('old', true); + chats = await CacheUtils.getLatestPrivateMessages(); + expect(chats.keys.first.id, 'old'); + }); + + test('deleting a chat drops its pin', () async { + await CacheUtils.addPrivateMessages( + 'peer', [message('peer', DateTime(2026, 5, 1))]); + await CacheUtils.setConversationPinned('peer', true); + + await CacheUtils.deletePrivateMessagesWithUser('peer'); + + expect(await CacheUtils.getPinnedConversations(), isEmpty); + }); +} diff --git a/test/message_format_test.dart b/test/message_format_test.dart new file mode 100644 index 0000000..f18dace --- /dev/null +++ b/test/message_format_test.dart @@ -0,0 +1,125 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/message_format.dart'; + +/// Renders the parsed pieces back as text, so a test can assert on the whole +/// message without caring how the parser grouped it. +String flat(List pieces) => pieces.map((p) => p.text).join(); + +List styled(List pieces, MessageStyle style) => + pieces.where((p) => p.style == style).toList(); + +void main() { + group('inline styles', () { + test('bold, italic, strike and mono', () { + final pieces = parseMessage('a **b** *c* ~~d~~ `e` f'); + expect(flat(pieces), 'a b c d e f'); + expect(styled(pieces, MessageStyle.bold).single.text, 'b'); + expect(styled(pieces, MessageStyle.italic).single.text, 'c'); + expect(styled(pieces, MessageStyle.strike).single.text, 'd'); + expect(styled(pieces, MessageStyle.mono).single.text, 'e'); + }); + + test('bold wins over italic at the same position', () { + final pieces = parseMessage('**bold**'); + expect(pieces.single.style, MessageStyle.bold); + expect(pieces.single.text, 'bold'); + }); + + test('spoiler is its own style', () { + final pieces = parseMessage('there is ||a secret|| here'); + expect(styled(pieces, MessageStyle.spoiler).single.text, 'a secret'); + }); + + test('an unclosed marker stays literal', () { + expect(flat(parseMessage('**unclosed')), '**unclosed'); + expect(flat(parseMessage('a *b')), 'a *b'); + }); + + test('empty markers are literal', () { + expect(flat(parseMessage('****')), '****'); + }); + + test('fenced code block becomes one code piece', () { + final pieces = parseMessage('before\n```\ncode line\n```\nafter'); + final code = styled(pieces, MessageStyle.code).single; + expect(code.text, 'code line'); + expect(flat(pieces), 'before\ncode line\nafter'); + }); + + test('an unterminated fence runs to the end', () { + final pieces = parseMessage('x\n```\nstill code'); + expect(styled(pieces, MessageStyle.code).single.text, 'still code'); + }); + }); + + group('tappable entities', () { + test('links keep their address', () { + final pieces = parseMessage('see https://example.com/a now'); + final link = pieces.singleWhere((p) => p.kind == MessageKind.link); + expect(link.text, 'https://example.com/a'); + }); + + test('a phone number is detected', () { + final pieces = parseMessage('volej +420 123 456 789 díky'); + final phone = pieces.singleWhere((p) => p.kind == MessageKind.phone); + expect(phone.text, '+420 123 456 789'); + }); + + test('a short number is not a phone number', () { + final pieces = parseMessage('mám 3 kusy'); + expect(pieces.any((p) => p.kind == MessageKind.phone), isFalse); + }); + + test('an e-mail address is detected', () { + final pieces = parseMessage('napiš na jan.novak@example.com prosím'); + final email = pieces.singleWhere((p) => p.kind == MessageKind.email); + expect(email.text, 'jan.novak@example.com'); + }); + + test('an @ without a dotted domain is not an e-mail', () { + final pieces = parseMessage('jsem @doma'); + expect(pieces.any((p) => p.kind == MessageKind.email), isFalse); + }); + + test('a link beats an e-mail that starts at the same place', () { + final pieces = parseMessage('https://example.com/a'); + expect(pieces.single.kind, MessageKind.link); + }); + + test('formatting and links combine', () { + final pieces = parseMessage('**přečti** https://example.com'); + expect(styled(pieces, MessageStyle.bold).single.text, 'přečti'); + expect(pieces.singleWhere((p) => p.kind == MessageKind.link).text, + 'https://example.com'); + }); + }); + + group('emoji only', () { + test('a single emoji', () { + expect(isEmojiOnly('😀'), isTrue); + expect(emojiCount('😀'), 1); + }); + + test('a short emoji run', () { + expect(isEmojiOnly('😀🎉👍'), isTrue); + expect(emojiCount('😀🎉👍'), 3); + }); + + test('skin tone and variation selectors count as one emoji', () { + expect(isEmojiOnly('👍🏽'), isTrue); + expect(isEmojiOnly('❤️'), isTrue); + }); + + test('text with an emoji is not emoji only', () { + expect(isEmojiOnly('ahoj 😀'), isFalse); + }); + + test('digits alone are not an emoji', () { + expect(isEmojiOnly('123'), isFalse); + }); + + test('empty text is not an emoji', () { + expect(isEmojiOnly(''), isFalse); + }); + }); +} diff --git a/test/text_envelope_test.dart b/test/text_envelope_test.dart new file mode 100644 index 0000000..d595b0d --- /dev/null +++ b/test/text_envelope_test.dart @@ -0,0 +1,64 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/text_envelope.dart'; + +Uint8List bytes(String text) => Uint8List.fromList(utf8.encode(text)); + +void main() { + test('a reply survives the round trip', () { + final sentAt = DateTime(2026, 3, 4, 5, 6, 7); + final envelope = buildTextEnvelope( + 'souhlasím', + ReplyRef( + senderId: 'peer', + sentAt: sentAt, + preview: ReplyRef.previewOf('původní zpráva'), + )); + + final parsed = tryParseTextEnvelope(envelope); + expect(parsed, isNotNull); + expect(parsed!.body, 'souhlasím'); + expect(parsed.reply!.senderId, 'peer'); + expect(parsed.reply!.sentAt, sentAt); + expect(parsed.reply!.preview, 'původní zpráva'); + }); + + test('the envelope is not a media envelope', () { + final envelope = buildTextEnvelope( + 'x', ReplyRef(senderId: 'a', sentAt: DateTime(2026), preview: 'y')); + final decoded = jsonDecode(utf8.decode(envelope)) as Map; + expect(decoded['kind'], 'text'); + expect(decoded['whisperMsg'], textEnvelopeVersion); + }); + + test('plain text is not an envelope', () { + expect(tryParseTextEnvelope(bytes('ahoj')), isNull); + }); + + test('a media envelope is not a text envelope', () { + final media = bytes('{"whisperMsg":1,"kind":"media","media":{}}'); + expect(tryParseTextEnvelope(media), isNull); + }); + + test('a broken body is not an envelope', () { + final broken = bytes('{"whisperMsg":3,"kind":"text","body":5}'); + expect(tryParseTextEnvelope(broken), isNull); + }); + + test('a broken quote is ignored, the body still reads', () { + final broken = + bytes('{"whisperMsg":3,"kind":"text","body":"a","replyTo":{"x":1}}'); + final parsed = tryParseTextEnvelope(broken); + expect(parsed!.body, 'a'); + expect(parsed.reply, isNull); + }); + + test('the preview is capped', () { + final long = 'x' * (ReplyRef.maxPreviewLength + 50); + final preview = ReplyRef.previewOf(long); + expect(preview.length, ReplyRef.maxPreviewLength + 1); + expect(preview.endsWith('…'), isTrue); + }); +} From 6c926659d4bf28a931bbab1cec5b0a80934767a8 Mon Sep 17 00:00:00 2001 From: Josef Date: Tue, 17 Nov 2026 23:20:26 +0100 Subject: [PATCH 077/181] feat: F2b chat search, jump to date and chat list filters Local message search with type/date/sender filters and match highlighting, jump to date and to a search hit, and All/Unread/Pinned filter chips on the chat list. Also drops the street-address heuristic and shortens the fold label. --- assets/translations/cs.json | 15 ++ assets/translations/en.json | 15 ++ lib/pages/chat_page.dart | 83 ++++++- lib/pages/home_page.dart | 74 ++++++- lib/pages/search_page.dart | 394 +++++++++++++++++++++++++++++++++ lib/utils/cache_utils.dart | 22 ++ lib/utils/message_search.dart | 164 ++++++++++++++ lib/utils/nav_transitions.dart | 4 +- test/message_search_test.dart | 160 +++++++++++++ 9 files changed, 927 insertions(+), 4 deletions(-) create mode 100644 lib/pages/search_page.dart create mode 100644 lib/utils/message_search.dart create mode 100644 test/message_search_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 8083260..77987c6 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -144,6 +144,21 @@ "selectedCount": "Vybráno: %d", "moreActions": "Další akce", "jumpToLatest": "Skočit na nejnovější", + "searchMessages": "Hledat zprávy", + "searchInChat": "Hledat v tomto chatu", + "searchHint": "Hledat v lokální historii", + "searchEmptyHint": "Napiš text nebo zvol filtr. Zprávy se hledají jen v tomto zařízení.", + "noSearchResults": "Nic nenalezeno", + "anyType": "Jakýkoli typ", + "textOnly": "Text", + "anyDate": "Kdykoli", + "anySender": "Kdokoli", + "jumpToDate": "Skočit na datum", + "noMessagesOnDate": "Žádné zprávy od toho dne", + "allChats": "Vše", + "unreadChats": "Nepřečtené", + "pinnedChats": "Připnuté", + "noChatsInFilter": "Tady nic není", "chatPinned": "Chat připnut", "chatUnpinned": "Chat odebrán z připnutých", "noChatsToForward": "Zatím žádné chaty, vyhledej uživatele", diff --git a/assets/translations/en.json b/assets/translations/en.json index eb0da38..5f61ad8 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -144,6 +144,21 @@ "selectedCount": "%d selected", "moreActions": "More actions", "jumpToLatest": "Jump to latest", + "searchMessages": "Search messages", + "searchInChat": "Search in this chat", + "searchHint": "Search the local history", + "searchEmptyHint": "Type something, or pick a filter. Messages are searched on this device only.", + "noSearchResults": "Nothing found", + "anyType": "Any type", + "textOnly": "Text", + "anyDate": "Any date", + "anySender": "Anyone", + "jumpToDate": "Jump to date", + "noMessagesOnDate": "No messages from that day or later", + "allChats": "All", + "unreadChats": "Unread", + "pinnedChats": "Pinned", + "noChatsInFilter": "Nothing here", "chatPinned": "Chat pinned", "chatUnpinned": "Chat unpinned", "noChatsToForward": "No chats yet, search for a user", diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 46654e6..a8cf050 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -24,11 +24,15 @@ import '../widgets/attachment_confirm_sheet.dart'; import '../widgets/chat_bubble.dart'; import 'chat_info_page.dart'; import 'forward_page.dart'; +import 'search_page.dart'; class ChatPage extends StatefulWidget { - const ChatPage(this.user, {super.key}); + const ChatPage(this.user, {this.jumpTo, super.key}); final User user; + /// Opens the conversation at this message instead of the newest one. + final DateTime? jumpTo; + @override State createState() => _ChatPageState(); } @@ -123,6 +127,10 @@ class _ChatPageState extends State { await _loadMessages(); // Then top the conversation up from the server archive _loadHistory(); + final jumpTo = widget.jumpTo; + if (jumpTo != null) { + await _jumpToMessage(jumpTo); + } } /// Keeps the newest message on screen when the keyboard opens. @@ -383,6 +391,47 @@ class _ChatPageState extends State { await _loadMessages(); } + /// Search this conversation; the picked result is jumped to. + Future _openSearch() async { + final picked = await Navigator.of(context) + .push(stepRoute(MessageSearchPage(peer: widget.user))); + if (picked != null && mounted) { + await _jumpToMessage(picked); + } + } + + /// Jump to the first message of a picked day (or the first one after it). + Future _jumpToDate() async { + if (_messages.isEmpty) { + return; + } + final oldest = _messages.first.sentAt.toLocal(); + final firstDay = DateTime(oldest.year, oldest.month, oldest.day); + final now = DateTime.now(); + final picked = await showDatePicker( + context: context, + initialDate: now, + firstDate: firstDay.isBefore(DateTime(2000)) ? DateTime(2000) : firstDay, + lastDate: now, + ); + if (picked == null || !mounted) { + return; + } + DateTime? target; + for (final message in _messages) { + if (!message.sentAt.isBefore(picked)) { + target = message.sentAt; + break; + } + } + if (target == null) { + await Fluttertoast.showToast( + msg: 'noMessagesOnDate'.tr(), backgroundColor: Colors.orange); + return; + } + await _jumpToMessage(target); + } + // --------------------------------------------------------------------------- // Reply and multi-select // --------------------------------------------------------------------------- @@ -1331,6 +1380,38 @@ class _ChatPageState extends State { ), // Action buttons actions: [ + PopupMenuButton( + tooltip: 'moreActions'.tr(), + onSelected: (value) { + if (value == 'search') { + _openSearch(); + } else { + _jumpToDate(); + } + }, + itemBuilder: (context) => [ + PopupMenuItem( + value: 'search', + child: Row( + children: [ + const Icon(Icons.search), + const SizedBox(width: 12), + Text('searchInChat'.tr()), + ], + ), + ), + PopupMenuItem( + value: 'jumpDate', + child: Row( + children: [ + const Icon(Icons.event), + const SizedBox(width: 12), + Text('jumpToDate'.tr()), + ], + ), + ), + ], + ), IconButton( icon: const Icon(Icons.info), tooltip: 'infoButton'.tr(), diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 95345b9..4408e59 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -17,6 +17,7 @@ import '../utils/message_notifier.dart'; import '../utils/notification_service.dart'; import 'search_user_page.dart'; import 'settings_page.dart'; +import 'search_page.dart'; import '../utils/dialog_utils.dart'; import '../widgets/invite_list_item.dart'; import 'package:whisper_openapi_client_dart/api.dart'; @@ -33,6 +34,12 @@ class HomePage extends StatefulWidget { State createState() => _HomePageState(); } +/// Which rows the chat list shows. +/// +/// The roadmap lists folders for unread and favourites; favourites arrive in F7 +/// with contacts, so the pinned chats stand in for them. +enum _ChatFilter { all, unread, pinned } + class _HomePageState extends State with SingleTickerProviderStateMixin { final WebSocketManager _webSocketManager = WebSocketManager(); @@ -46,6 +53,9 @@ class _HomePageState extends State /// Conversation ids pinned to the top of the list. Set _pinnedChats = {}; + + /// Which rows the list shows; folders without extra storage. + _ChatFilter _filter = _ChatFilter.all; bool _firstLoad = true; String? _pendingFid; // Store pending FID @@ -333,6 +343,56 @@ class _HomePageState extends State await _getServerInvites(); } + /// Chats that pass the current folder filter. + List> get _visibleChats { + switch (_filter) { + case _ChatFilter.unread: + return _chatEntries + .where((chat) => (_unreadCounts[chat.key.id] ?? 0) > 0) + .toList(); + case _ChatFilter.pinned: + return _chatEntries + .where((chat) => _pinnedChats.contains(chat.key.id)) + .toList(); + case _ChatFilter.all: + return _chatEntries; + } + } + + String _filterLabel(_ChatFilter filter) { + switch (filter) { + case _ChatFilter.all: + return 'allChats'.tr(); + case _ChatFilter.unread: + return 'unreadChats'.tr(); + case _ChatFilter.pinned: + return 'pinnedChats'.tr(); + } + } + + /// Folder chips above the list: everything, unread, pinned. + Widget _filterChips() { + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + child: Row( + children: [ + for (final filter in _ChatFilter.values) + Padding( + padding: const EdgeInsets.only(right: 8), + child: ChoiceChip( + label: Text(_filterLabel(filter)), + selected: _filter == filter, + onSelected: (_) => setState(() { + _filter = filter; + }), + ), + ), + ], + ), + ); + } + /// Get ListView with content ListView _getContent(List> chats) { _firstLoad = false; @@ -424,6 +484,15 @@ class _HomePageState extends State title: Text('msgPage'.tr()), // Action buttons actions: [ + // Search across every locally stored conversation + IconButton( + icon: const Icon(Icons.search), + tooltip: 'searchMessages'.tr(), + onPressed: () { + Navigator.of(context) + .push(stepRoute(const MessageSearchPage())); + }, + ), // Settings IconButton( icon: const Icon(Icons.settings), @@ -485,6 +554,7 @@ class _HomePageState extends State Column( children: [ SizedBox(height: 10), + _filterChips(), // Messages and avatar list Expanded( child: _firstLoad @@ -494,7 +564,9 @@ class _HomePageState extends State child: CircularProgressIndicator(), ), ) - : _getContent(_chatEntries), + : _visibleChats.isEmpty + ? Center(child: Text('noChatsInFilter'.tr())) + : _getContent(_visibleChats), ), ], ), diff --git a/lib/pages/search_page.dart b/lib/pages/search_page.dart new file mode 100644 index 0000000..c3a1629 --- /dev/null +++ b/lib/pages/search_page.dart @@ -0,0 +1,394 @@ +import 'dart:async'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +import '../models/user.dart'; +import '../utils/cache_utils.dart'; +import '../utils/message_notifier.dart'; +import '../utils/message_search.dart'; +import '../utils/nav_transitions.dart'; +import 'chat_page.dart'; + +/// Searches the local message store. Messages are stored decrypted, so this is +/// a local scan: nothing is sent anywhere. +/// +/// With [peer] the search is scoped to that conversation and the picked +/// message is returned as a timestamp (the caller jumps to it). Without [peer] +/// the results span every conversation and open the chat at the hit. +class MessageSearchPage extends StatefulWidget { + const MessageSearchPage({this.peer, super.key}); + + final User? peer; + + @override + State createState() => _MessageSearchPageState(); +} + +class _MessageSearchPageState extends State { + final TextEditingController _controller = TextEditingController(); + Timer? _debounce; + List _hits = []; + bool _loading = false; + bool _searched = false; + + /// Media type name, or [MessageSearchQuery.textType]; null matches any. + String? _type; + DateTimeRange? _range; + + /// Sender (conversation) filter, only offered in the global search. + String? _conversationId; + List _conversations = []; + final Map _users = {}; + + bool get _global => widget.peer == null; + + @override + void initState() { + super.initState(); + if (_global) { + _loadConversations(); + } + } + + @override + void dispose() { + _debounce?.cancel(); + _controller.dispose(); + super.dispose(); + } + + Future _loadConversations() async { + final chats = await MessageNotifier().getLatestPrivateMessages(); + if (!mounted) { + return; + } + setState(() { + _conversations = chats.keys.toList(); + }); + } + + MessageSearchQuery get _query => MessageSearchQuery( + text: _controller.text, + conversationId: widget.peer?.id ?? _conversationId, + from: _range?.start, + to: _range?.end, + type: _type, + ); + + void _onTextChanged(String _) { + _debounce?.cancel(); + _debounce = Timer(const Duration(milliseconds: 250), _run); + } + + Future _run() async { + final query = _query; + if (query.isEmpty) { + setState(() { + _hits = []; + _searched = false; + }); + return; + } + setState(() { + _loading = true; + }); + final hits = await CacheUtils.searchMessages(query); + if (!mounted) { + return; + } + for (final hit in hits) { + if (_users.containsKey(hit.conversationId)) { + continue; + } + _users[hit.conversationId] = + await CacheUtils.getUserById(hit.conversationId); + } + if (!mounted) { + return; + } + setState(() { + _hits = hits; + _loading = false; + _searched = true; + }); + } + + Future _pickRange() async { + // Tapping the active chip clears it, which is the only way back to "any + // date" without reopening the picker. + if (_range != null) { + setState(() { + _range = null; + }); + await _run(); + return; + } + final now = DateTime.now(); + final picked = await showDateRangePicker( + context: context, + firstDate: DateTime(now.year - 10), + lastDate: now, + ); + if (picked == null || !mounted) { + return; + } + setState(() { + _range = picked; + }); + await _run(); + } + + Future _open(MessageHit hit) async { + final peer = widget.peer; + if (peer != null) { + // The chat page jumps to the picked message. + Navigator.pop(context, hit.message.sentAt); + return; + } + final user = _users[hit.conversationId]; + if (user == null) { + return; + } + await Navigator.of(context) + .push(stepRoute(ChatPage(user, jumpTo: hit.message.sentAt))); + } + + String _displayName(String conversationId) { + final user = _users[conversationId]; + if (user == null || user.username.isEmpty) { + return '?'; + } + return user.username; + } + + Widget _typeSelector() { + return DropdownButton( + value: _type, + underline: const SizedBox.shrink(), + borderRadius: BorderRadius.circular(12), + hint: Text('anyType'.tr()), + items: [ + DropdownMenuItem(value: null, child: Text('anyType'.tr())), + DropdownMenuItem( + value: MessageSearchQuery.textType, child: Text('textOnly'.tr())), + for (final type in [ + MediaType.image, + MediaType.video, + MediaType.voice, + MediaType.file, + MediaType.gif, + ]) + DropdownMenuItem( + value: type.name, child: Text('media${_typeLabel(type)}'.tr())), + ], + onChanged: (value) async { + setState(() { + _type = value; + }); + await _run(); + }, + ); + } + + /// Suffix of the existing media label keys (mediaPhoto, mediaVideo, ...). + String _typeLabel(MediaType type) { + switch (type) { + case MediaType.image: + return 'Photo'; + case MediaType.video: + return 'Video'; + case MediaType.voice: + return 'Voice'; + case MediaType.file: + return 'File'; + case MediaType.gif: + return 'Gif'; + } + } + + Widget _senderSelector() { + return DropdownButton( + value: _conversationId, + underline: const SizedBox.shrink(), + borderRadius: BorderRadius.circular(12), + hint: Text('anySender'.tr()), + items: [ + DropdownMenuItem(value: null, child: Text('anySender'.tr())), + for (final user in _conversations) + DropdownMenuItem( + value: user.id, + child: SizedBox( + width: 140, + child: Text( + user.username.isEmpty ? '?' : user.username, + overflow: TextOverflow.ellipsis, + ), + ), + ), + ], + onChanged: (value) async { + setState(() { + _conversationId = value; + }); + await _run(); + }, + ); + } + + Widget _filters() { + final label = _range == null + ? 'anyDate'.tr() + : '${DateFormat.MMMd().format(_range!.start)}' + ' – ${DateFormat.MMMd().format(_range!.end)}'; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + _typeSelector(), + FilterChip( + label: Text(label), + selected: _range != null, + avatar: const Icon(Icons.date_range, size: 18), + onSelected: (_) => _pickRange(), + ), + if (_global && _conversations.isNotEmpty) _senderSelector(), + ], + ), + ); + } + + /// A result line with the found text highlighted. + Widget _snippetText(String text, {int? maxLines}) { + final scheme = Theme.of(context).colorScheme; + return Text.rich( + TextSpan( + children: [ + for (final part in highlightParts( + snippet(text, _controller.text), _controller.text)) + TextSpan( + text: part.text, + style: part.match + ? TextStyle( + fontWeight: FontWeight.bold, + color: scheme.onPrimaryContainer, + backgroundColor: + scheme.primaryContainer.withValues(alpha: 0.8), + ) + : null, + ), + ], + ), + maxLines: maxLines, + overflow: maxLines == null ? null : TextOverflow.ellipsis, + ); + } + + Widget _resultTile(MessageHit hit) { + final message = hit.message; + final user = _users[hit.conversationId]; + final time = DateFormat.MMMd().add_Hm().format(message.sentAt.toLocal()); + final text = message.preview; + return ListTile( + leading: _global + ? CircleAvatar( + radius: 20, + backgroundColor: + user?.avatarColor ?? Theme.of(context).colorScheme.primary, + child: Text( + _displayName(hit.conversationId)[0].toUpperCase(), + style: TextStyle( + fontSize: 16, + color: user?.avatarTextColor ?? Colors.white, + ), + ), + ) + : null, + title: _global + ? Text(_displayName(hit.conversationId)) + : _snippetText(text, maxLines: 2), + subtitle: _global ? _snippetText(text, maxLines: 2) : null, + trailing: Text( + time, + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.onSurfaceVariant), + ), + onTap: () => _open(hit), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text(_global ? 'searchMessages'.tr() : widget.peer!.username), + ), + body: SafeArea( + child: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 4), + child: TextField( + controller: _controller, + autofocus: true, + textInputAction: TextInputAction.search, + onChanged: _onTextChanged, + onSubmitted: (_) => _run(), + decoration: InputDecoration( + hintText: 'searchHint'.tr(), + prefixIcon: const Icon(Icons.search), + suffixIcon: _controller.text.isEmpty + ? null + : IconButton( + icon: const Icon(Icons.clear), + tooltip: 'cancel'.tr(), + onPressed: () { + _controller.clear(); + _run(); + }, + ), + filled: true, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(24), + borderSide: BorderSide.none, + ), + ), + ), + ), + _filters(), + if (_loading) const LinearProgressIndicator(), + Expanded(child: _body()), + ], + ), + ), + ); + } + + Widget _body() { + if (!_searched) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + 'searchEmptyHint'.tr(), + textAlign: TextAlign.center, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant), + ), + ), + ); + } + if (_hits.isEmpty) { + return Center(child: Text('noSearchResults'.tr())); + } + return ListView.builder( + itemCount: _hits.length, + itemBuilder: (context, index) => _resultTile(_hits[index]), + ); + } +} diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 123a175..9f3024d 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -14,6 +14,7 @@ import '../models/user.dart'; import 'color_utils.dart'; import 'crypto_utils.dart'; import 'media_utils.dart'; +import 'message_search.dart'; import 'singleton.dart'; import 'utils.dart'; @@ -779,6 +780,27 @@ class CacheUtils { return counts; } + /// Searches the stored conversations, newest hit first. + /// + /// The message box holds decrypted text, so this is a local scan: the query + /// never reaches the server. + static Future> searchMessages( + MessageSearchQuery query) async { + final box = await _openPrivateMessagesBox(); + final hits = []; + for (final key in box.keys.whereType()) { + final conversationId = conversationOfKey(key); + if (conversationId == null) { + continue; + } + final value = box.get(key); + if (value is PrivateMessage) { + hits.add(MessageHit(conversationId, value)); + } + } + return filterMessages(hits, query); + } + /// Oldest unread message of a conversation: the anchor of the "new messages" /// divider, taken before the chat marks everything read. static Future firstUnreadSentAt(String userId) async { diff --git a/lib/utils/message_search.dart b/lib/utils/message_search.dart new file mode 100644 index 0000000..20c6d3b --- /dev/null +++ b/lib/utils/message_search.dart @@ -0,0 +1,164 @@ +import '../models/private_message.dart'; + +/// One stored message that matched a search, with the conversation it belongs +/// to (the other side's user id, not the sender: an archived message we sent +/// lives in the peer's conversation). +class MessageHit { + const MessageHit(this.conversationId, this.message); + + final String conversationId; + final PrivateMessage message; +} + +/// What to look for in the local message store. +/// +/// The store holds decrypted text, so a search is a local scan: nothing leaves +/// the device and no server round-trip happens. +class MessageSearchQuery { + const MessageSearchQuery({ + this.text = '', + this.conversationId, + this.from, + this.to, + this.type, + }); + + /// Case-insensitive substring of the message text (or of an attachment name). + final String text; + + /// Restricts the search to one conversation. + final String? conversationId; + + /// Inclusive start of the date range. + final DateTime? from; + + /// Inclusive end of the date range: the whole [to] day counts. + final DateTime? to; + + /// `text`, or a [MediaType.name]; null matches everything. + final String? type; + + /// Value of [type] for messages without an attachment. + static const String textType = 'text'; + + /// Whether this query filters anything out at all. + bool get isEmpty => + text.trim().isEmpty && + type == null && + from == null && + to == null && + conversationId == null; + + bool matches(MessageHit hit) { + final message = hit.message; + if (conversationId != null && hit.conversationId != conversationId) { + return false; + } + if (!_matchesType(message)) { + return false; + } + final time = message.sentAt; + if (from != null && time.isBefore(from!)) { + return false; + } + if (to != null) { + final endOfDay = DateTime(to!.year, to!.month, to!.day, 23, 59, 59, 999); + if (time.isAfter(endOfDay)) { + return false; + } + } + final needle = text.trim().toLowerCase(); + if (needle.isEmpty) { + return true; + } + // An attachment without a caption is still findable by its file name. + return message.message.toLowerCase().contains(needle) || + (message.fileName ?? '').toLowerCase().contains(needle); + } + + bool _matchesType(PrivateMessage message) { + final wanted = type; + if (wanted == null) { + return true; + } + if (wanted == textType) { + return !message.isMedia; + } + if (message.mediaTypeStr == wanted) { + return true; + } + // An album matches when any of its attachments has the type. + return message.album.any((item) => item.type == wanted); + } +} + +/// How many hits a search returns. A single letter must not walk the whole +/// history into a list. +const int searchResultLimit = 300; + +/// Applies [query] to [hits] and returns the newest first. +List filterMessages( + Iterable hits, MessageSearchQuery query) { + final matched = hits.where(query.matches).toList() + ..sort((a, b) => b.message.sentAt.compareTo(a.message.sentAt)); + return matched.length > searchResultLimit + ? matched.sublist(0, searchResultLimit) + : matched; +} + +/// A window of [text] around the first occurrence of [needle], for the result +/// list. Returns [text] when the needle is not in it. +String snippet(String text, String needle, {int radius = 40}) { + final trimmed = needle.trim(); + if (trimmed.isEmpty) { + return text.length <= radius * 2 + ? text + : '${text.substring(0, radius * 2)}…'; + } + final at = text.toLowerCase().indexOf(trimmed.toLowerCase()); + if (at < 0) { + return text.length <= radius * 2 + ? text + : '${text.substring(0, radius * 2)}…'; + } + var start = at - radius; + var end = at + trimmed.length + radius; + if (start < 0) { + start = 0; + } + if (end > text.length) { + end = text.length; + } + final prefix = start > 0 ? '…' : ''; + final suffix = end < text.length ? '…' : ''; + return '$prefix${text.substring(start, end)}$suffix'; +} + +/// Splits [text] into alternating plain and matched runs, so a result can show +/// what it found. Case-insensitive; every occurrence is marked. +List<({String text, bool match})> highlightParts(String text, String needle) { + final plain = [(text: text, match: false)]; + final trimmed = needle.trim(); + if (trimmed.isEmpty || text.isEmpty) { + return plain; + } + final lowered = text.toLowerCase(); + final target = trimmed.toLowerCase(); + final parts = <({String text, bool match})>[]; + var index = 0; + while (true) { + final at = lowered.indexOf(target, index); + if (at < 0) { + if (index < text.length) { + parts.add((text: text.substring(index), match: false)); + } + break; + } + if (at > index) { + parts.add((text: text.substring(index, at), match: false)); + } + parts.add((text: text.substring(at, at + target.length), match: true)); + index = at + target.length; + } + return parts.isEmpty ? plain : parts; +} diff --git a/lib/utils/nav_transitions.dart b/lib/utils/nav_transitions.dart index e0c7e59..cf1ecbc 100644 --- a/lib/utils/nav_transitions.dart +++ b/lib/utils/nav_transitions.dart @@ -33,8 +33,8 @@ Route fadeRoute(Widget child) { /// Opens the next step of a flow (forwarding, onboarding): it comes in from /// the side, the way a form usually does. -Route stepRoute(Widget child) { - return PageTransition( +Route stepRoute(Widget child) { + return PageTransition( type: PageTransitionType.rightToLeft, child: child, duration: navDuration, diff --git a/test/message_search_test.dart b/test/message_search_test.dart new file mode 100644 index 0000000..fc3807f --- /dev/null +++ b/test/message_search_test.dart @@ -0,0 +1,160 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/message_search.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +PrivateMessage text(String body, DateTime sentAt, {String? fileName}) { + return PrivateMessage('peer', body, sentAt, sentAt, true, fileName: fileName); +} + +PrivateMessage media(String type, DateTime sentAt) { + return PrivateMessage('peer', '', sentAt, sentAt, true, mediaTypeStr: type); +} + +PrivateMessage album(List types, DateTime sentAt) { + final message = PrivateMessage('peer', '', sentAt, sentAt, true); + message.setAlbum([ + for (var i = 0; i < types.length; i++) + AlbumItem(mediaId: '$i', type: types[i], size: 1), + ]); + return message; +} + +MessageHit hit(String conversation, PrivateMessage message) => + MessageHit(conversation, message); + +/// Renders a highlighted line back to text, marking matches in brackets, so a +/// test can assert on the split without inspecting styles. +String marked(String text, String needle) => highlightParts(text, needle) + .map((part) => part.match ? '[${part.text}]' : part.text) + .join(); + +void main() { + final base = DateTime(2026, 6, 1, 12); + + group('text matching', () { + test('is case-insensitive and matches inside a word', () { + final query = MessageSearchQuery(text: 'AHOJ'); + expect(query.matches(hit('a', text('tak ahoj tam', base))), isTrue); + expect(query.matches(hit('a', text('nic', base))), isFalse); + }); + + test('an empty query matches everything', () { + const query = MessageSearchQuery(); + expect(query.isEmpty, isTrue); + expect(query.matches(hit('a', text('cokoli', base))), isTrue); + }); + + test('an attachment is findable by its file name', () { + final query = MessageSearchQuery(text: 'smlouva'); + final message = media(MediaType.file.name, base) + ..fileName = 'Smlouva-2026.pdf'; + expect(query.matches(hit('a', message)), isTrue); + }); + + test('the conversation filter scopes the search', () { + final query = MessageSearchQuery(text: 'ahoj', conversationId: 'b'); + expect(query.matches(hit('a', text('ahoj', base))), isFalse); + expect(query.matches(hit('b', text('ahoj', base))), isTrue); + }); + }); + + group('date range', () { + test('both ends are inclusive', () { + final query = MessageSearchQuery( + from: DateTime(2026, 6, 1), + to: DateTime(2026, 6, 1), + ); + expect(query.matches(hit('a', text('x', DateTime(2026, 6, 1)))), isTrue); + expect(query.matches(hit('a', text('x', DateTime(2026, 6, 1, 23, 59)))), + isTrue); + expect(query.matches(hit('a', text('x', DateTime(2026, 6, 2)))), isFalse); + expect( + query.matches(hit('a', text('x', DateTime(2026, 5, 31)))), isFalse); + }); + }); + + group('type filter', () { + test('text means no attachment', () { + final query = MessageSearchQuery(type: MessageSearchQuery.textType); + expect(query.matches(hit('a', text('ahoj', base))), isTrue); + expect( + query.matches(hit('a', media(MediaType.image.name, base))), isFalse); + }); + + test('a media type matches its messages', () { + final query = MessageSearchQuery(type: MediaType.image.name); + expect( + query.matches(hit('a', media(MediaType.image.name, base))), isTrue); + expect( + query.matches(hit('a', media(MediaType.video.name, base))), isFalse); + }); + + test('an album matches when any attachment has the type', () { + final query = MessageSearchQuery(type: MediaType.video.name); + expect( + query.matches(hit( + 'a', album([MediaType.image.name, MediaType.video.name], base))), + isTrue); + expect( + query.matches(hit( + 'a', album([MediaType.image.name, MediaType.gif.name], base))), + isFalse); + }); + }); + + group('result ordering', () { + test('newest first and capped', () { + final hits = [ + for (var i = 0; i < searchResultLimit + 5; i++) + hit('a', text('ahoj', base.add(Duration(minutes: i)))), + ]; + final result = + filterMessages(hits, const MessageSearchQuery(text: 'ahoj')); + expect(result.length, searchResultLimit); + expect(result.first.message.sentAt.isAfter(result.last.message.sentAt), + isTrue); + }); + }); + + group('snippet', () { + test('short text is returned as it is', () { + expect(snippet('ahoj', 'ahoj'), 'ahoj'); + }); + + test('long text is cut around the match', () { + final long = '${'a' * 100} hledané ${'b' * 100}'; + final value = snippet(long, 'hledané', radius: 10); + expect(value.startsWith('…'), isTrue); + expect(value.endsWith('…'), isTrue); + expect(value, contains('hledané')); + expect(value.length, lessThan(long.length)); + }); + + test('a missing needle still returns a short window', () { + final value = snippet('a' * 200, 'nic'); + expect(value.endsWith('…'), isTrue); + expect(value.length, 81); + }); + }); + + group('highlighting', () { + test('no needle is a single plain run', () { + expect(highlightParts('ahoj', '').single.match, isFalse); + }); + + test('every occurrence is marked, case-insensitively', () { + expect(marked('Ahoj ahoj AHoj', 'ahoj'), '[Ahoj] [ahoj] [AHoj]'); + }); + + test('the text around the matches is preserved', () { + expect(marked('tak ahoj tam', 'ahoj'), 'tak [ahoj] tam'); + }); + + test('a needle that is not there changes nothing', () { + final parts = highlightParts('tak ahoj tam', 'nic'); + expect(parts.single.text, 'tak ahoj tam'); + expect(parts.single.match, isFalse); + }); + }); +} From fe3f2dfcba54112673bdd8a8aae3ad477eaccab8 Mon Sep 17 00:00:00 2001 From: Josef Date: Tue, 17 Nov 2026 23:25:35 +0100 Subject: [PATCH 078/181] refactor(search): search only inside a conversation Scoped search page reached from the chat info page, text and file-name matching only; global entry, type/date/sender filters and the chat menu removed. --- assets/translations/cs.json | 7 +- assets/translations/en.json | 7 +- lib/pages/chat_info_page.dart | 21 +++ lib/pages/chat_page.dart | 59 ++------ lib/pages/home_page.dart | 10 -- lib/pages/search_page.dart | 254 +++------------------------------- lib/utils/message_search.dart | 61 +------- test/message_search_test.dart | 61 +------- 8 files changed, 57 insertions(+), 423 deletions(-) diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 77987c6..0ed9858 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -144,15 +144,10 @@ "selectedCount": "Vybráno: %d", "moreActions": "Další akce", "jumpToLatest": "Skočit na nejnovější", - "searchMessages": "Hledat zprávy", "searchInChat": "Hledat v tomto chatu", "searchHint": "Hledat v lokální historii", - "searchEmptyHint": "Napiš text nebo zvol filtr. Zprávy se hledají jen v tomto zařízení.", + "searchEmptyHint": "Napiš text. Hledá se jen v této konverzaci a jen v tomto zařízení.", "noSearchResults": "Nic nenalezeno", - "anyType": "Jakýkoli typ", - "textOnly": "Text", - "anyDate": "Kdykoli", - "anySender": "Kdokoli", "jumpToDate": "Skočit na datum", "noMessagesOnDate": "Žádné zprávy od toho dne", "allChats": "Vše", diff --git a/assets/translations/en.json b/assets/translations/en.json index 5f61ad8..aae946a 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -144,15 +144,10 @@ "selectedCount": "%d selected", "moreActions": "More actions", "jumpToLatest": "Jump to latest", - "searchMessages": "Search messages", "searchInChat": "Search in this chat", "searchHint": "Search the local history", - "searchEmptyHint": "Type something, or pick a filter. Messages are searched on this device only.", + "searchEmptyHint": "Type to search this conversation. Messages are searched on this device only.", "noSearchResults": "Nothing found", - "anyType": "Any type", - "textOnly": "Text", - "anyDate": "Any date", - "anySender": "Anyone", "jumpToDate": "Jump to date", "noMessagesOnDate": "No messages from that day or later", "allChats": "All", diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 4ce7d01..13a8f48 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -14,6 +14,7 @@ import '../widgets/media_bubble.dart'; import '../widgets/settings_tile.dart'; import 'home_page.dart'; import 'media_viewer_page.dart'; +import 'search_page.dart'; class ChatInfoPage extends StatefulWidget { const ChatInfoPage(this.userId, {super.key}); @@ -98,6 +99,20 @@ class _ChatInfoPageState extends State { ); } + /// Search this conversation. A picked hit is handed back to the chat page, + /// which jumps to it. + Future _openSearch() async { + final user = await CacheUtils.getUserById(widget.userId); + if (user == null || !mounted) { + return; + } + final picked = await Navigator.of(context) + .push(stepRoute(MessageSearchPage(user))); + if (picked != null && mounted) { + Navigator.pop(context, picked); + } + } + @override Widget build(BuildContext context) { return Theme( @@ -112,6 +127,12 @@ class _ChatInfoPageState extends State { SliverToBoxAdapter( child: Column( children: [ + // Search in this conversation + SettingsTile( + icon: Icons.search, + label: 'searchInChat'.tr(), + onPressed: _openSearch, + ), // Chat theme SettingsTile( icon: Icons.palette, diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index a8cf050..8e96389 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -24,15 +24,11 @@ import '../widgets/attachment_confirm_sheet.dart'; import '../widgets/chat_bubble.dart'; import 'chat_info_page.dart'; import 'forward_page.dart'; -import 'search_page.dart'; class ChatPage extends StatefulWidget { - const ChatPage(this.user, {this.jumpTo, super.key}); + const ChatPage(this.user, {super.key}); final User user; - /// Opens the conversation at this message instead of the newest one. - final DateTime? jumpTo; - @override State createState() => _ChatPageState(); } @@ -127,10 +123,6 @@ class _ChatPageState extends State { await _loadMessages(); // Then top the conversation up from the server archive _loadHistory(); - final jumpTo = widget.jumpTo; - if (jumpTo != null) { - await _jumpToMessage(jumpTo); - } } /// Keeps the newest message on screen when the keyboard opens. @@ -385,18 +377,14 @@ class _ChatPageState extends State { } Future _openChatInfo() async { - await Navigator.of(context).push(stepRoute(ChatInfoPage(widget.user.id))); + // The info page hands back a timestamp when a search hit was picked there. + final jumpTo = await Navigator.of(context) + .push(stepRoute(ChatInfoPage(widget.user.id))); // The theme (and possibly the user) may have changed while it was open. await _loadChatTheme(); await _loadMessages(); - } - - /// Search this conversation; the picked result is jumped to. - Future _openSearch() async { - final picked = await Navigator.of(context) - .push(stepRoute(MessageSearchPage(peer: widget.user))); - if (picked != null && mounted) { - await _jumpToMessage(picked); + if (jumpTo != null && mounted) { + await _jumpToMessage(jumpTo); } } @@ -1380,37 +1368,10 @@ class _ChatPageState extends State { ), // Action buttons actions: [ - PopupMenuButton( - tooltip: 'moreActions'.tr(), - onSelected: (value) { - if (value == 'search') { - _openSearch(); - } else { - _jumpToDate(); - } - }, - itemBuilder: (context) => [ - PopupMenuItem( - value: 'search', - child: Row( - children: [ - const Icon(Icons.search), - const SizedBox(width: 12), - Text('searchInChat'.tr()), - ], - ), - ), - PopupMenuItem( - value: 'jumpDate', - child: Row( - children: [ - const Icon(Icons.event), - const SizedBox(width: 12), - Text('jumpToDate'.tr()), - ], - ), - ), - ], + IconButton( + icon: const Icon(Icons.event), + tooltip: 'jumpToDate'.tr(), + onPressed: _jumpToDate, ), IconButton( icon: const Icon(Icons.info), diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 4408e59..c99393e 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -17,7 +17,6 @@ import '../utils/message_notifier.dart'; import '../utils/notification_service.dart'; import 'search_user_page.dart'; import 'settings_page.dart'; -import 'search_page.dart'; import '../utils/dialog_utils.dart'; import '../widgets/invite_list_item.dart'; import 'package:whisper_openapi_client_dart/api.dart'; @@ -484,15 +483,6 @@ class _HomePageState extends State title: Text('msgPage'.tr()), // Action buttons actions: [ - // Search across every locally stored conversation - IconButton( - icon: const Icon(Icons.search), - tooltip: 'searchMessages'.tr(), - onPressed: () { - Navigator.of(context) - .push(stepRoute(const MessageSearchPage())); - }, - ), // Settings IconButton( icon: const Icon(Icons.settings), diff --git a/lib/pages/search_page.dart b/lib/pages/search_page.dart index c3a1629..03b2240 100644 --- a/lib/pages/search_page.dart +++ b/lib/pages/search_page.dart @@ -2,25 +2,20 @@ import 'dart:async'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/user.dart'; import '../utils/cache_utils.dart'; -import '../utils/message_notifier.dart'; import '../utils/message_search.dart'; -import '../utils/nav_transitions.dart'; -import 'chat_page.dart'; -/// Searches the local message store. Messages are stored decrypted, so this is -/// a local scan: nothing is sent anywhere. +/// Searches one conversation's local history. Messages are stored decrypted, +/// so this is a local scan: nothing is sent anywhere. /// -/// With [peer] the search is scoped to that conversation and the picked -/// message is returned as a timestamp (the caller jumps to it). Without [peer] -/// the results span every conversation and open the chat at the hit. +/// The page returns the timestamp of the picked message; the chat it belongs to +/// jumps there. class MessageSearchPage extends StatefulWidget { - const MessageSearchPage({this.peer, super.key}); + const MessageSearchPage(this.peer, {super.key}); - final User? peer; + final User peer; @override State createState() => _MessageSearchPageState(); @@ -33,25 +28,6 @@ class _MessageSearchPageState extends State { bool _loading = false; bool _searched = false; - /// Media type name, or [MessageSearchQuery.textType]; null matches any. - String? _type; - DateTimeRange? _range; - - /// Sender (conversation) filter, only offered in the global search. - String? _conversationId; - List _conversations = []; - final Map _users = {}; - - bool get _global => widget.peer == null; - - @override - void initState() { - super.initState(); - if (_global) { - _loadConversations(); - } - } - @override void dispose() { _debounce?.cancel(); @@ -59,31 +35,16 @@ class _MessageSearchPageState extends State { super.dispose(); } - Future _loadConversations() async { - final chats = await MessageNotifier().getLatestPrivateMessages(); - if (!mounted) { - return; - } - setState(() { - _conversations = chats.keys.toList(); - }); - } - - MessageSearchQuery get _query => MessageSearchQuery( - text: _controller.text, - conversationId: widget.peer?.id ?? _conversationId, - from: _range?.start, - to: _range?.end, - type: _type, - ); - void _onTextChanged(String _) { _debounce?.cancel(); _debounce = Timer(const Duration(milliseconds: 250), _run); } Future _run() async { - final query = _query; + final query = MessageSearchQuery( + text: _controller.text, + conversationId: widget.peer.id, + ); if (query.isEmpty) { setState(() { _hits = []; @@ -98,16 +59,6 @@ class _MessageSearchPageState extends State { if (!mounted) { return; } - for (final hit in hits) { - if (_users.containsKey(hit.conversationId)) { - continue; - } - _users[hit.conversationId] = - await CacheUtils.getUserById(hit.conversationId); - } - if (!mounted) { - return; - } setState(() { _hits = hits; _loading = false; @@ -115,161 +66,14 @@ class _MessageSearchPageState extends State { }); } - Future _pickRange() async { - // Tapping the active chip clears it, which is the only way back to "any - // date" without reopening the picker. - if (_range != null) { - setState(() { - _range = null; - }); - await _run(); - return; - } - final now = DateTime.now(); - final picked = await showDateRangePicker( - context: context, - firstDate: DateTime(now.year - 10), - lastDate: now, - ); - if (picked == null || !mounted) { - return; - } - setState(() { - _range = picked; - }); - await _run(); - } - - Future _open(MessageHit hit) async { - final peer = widget.peer; - if (peer != null) { - // The chat page jumps to the picked message. - Navigator.pop(context, hit.message.sentAt); - return; - } - final user = _users[hit.conversationId]; - if (user == null) { - return; - } - await Navigator.of(context) - .push(stepRoute(ChatPage(user, jumpTo: hit.message.sentAt))); - } - - String _displayName(String conversationId) { - final user = _users[conversationId]; - if (user == null || user.username.isEmpty) { - return '?'; - } - return user.username; - } - - Widget _typeSelector() { - return DropdownButton( - value: _type, - underline: const SizedBox.shrink(), - borderRadius: BorderRadius.circular(12), - hint: Text('anyType'.tr()), - items: [ - DropdownMenuItem(value: null, child: Text('anyType'.tr())), - DropdownMenuItem( - value: MessageSearchQuery.textType, child: Text('textOnly'.tr())), - for (final type in [ - MediaType.image, - MediaType.video, - MediaType.voice, - MediaType.file, - MediaType.gif, - ]) - DropdownMenuItem( - value: type.name, child: Text('media${_typeLabel(type)}'.tr())), - ], - onChanged: (value) async { - setState(() { - _type = value; - }); - await _run(); - }, - ); - } - - /// Suffix of the existing media label keys (mediaPhoto, mediaVideo, ...). - String _typeLabel(MediaType type) { - switch (type) { - case MediaType.image: - return 'Photo'; - case MediaType.video: - return 'Video'; - case MediaType.voice: - return 'Voice'; - case MediaType.file: - return 'File'; - case MediaType.gif: - return 'Gif'; - } - } - - Widget _senderSelector() { - return DropdownButton( - value: _conversationId, - underline: const SizedBox.shrink(), - borderRadius: BorderRadius.circular(12), - hint: Text('anySender'.tr()), - items: [ - DropdownMenuItem(value: null, child: Text('anySender'.tr())), - for (final user in _conversations) - DropdownMenuItem( - value: user.id, - child: SizedBox( - width: 140, - child: Text( - user.username.isEmpty ? '?' : user.username, - overflow: TextOverflow.ellipsis, - ), - ), - ), - ], - onChanged: (value) async { - setState(() { - _conversationId = value; - }); - await _run(); - }, - ); - } - - Widget _filters() { - final label = _range == null - ? 'anyDate'.tr() - : '${DateFormat.MMMd().format(_range!.start)}' - ' – ${DateFormat.MMMd().format(_range!.end)}'; - return Padding( - padding: const EdgeInsets.symmetric(horizontal: 12), - child: Wrap( - spacing: 8, - runSpacing: 4, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - _typeSelector(), - FilterChip( - label: Text(label), - selected: _range != null, - avatar: const Icon(Icons.date_range, size: 18), - onSelected: (_) => _pickRange(), - ), - if (_global && _conversations.isNotEmpty) _senderSelector(), - ], - ), - ); - } - /// A result line with the found text highlighted. - Widget _snippetText(String text, {int? maxLines}) { + Widget _snippetText(String text) { final scheme = Theme.of(context).colorScheme; + final needle = _controller.text; return Text.rich( TextSpan( children: [ - for (final part in highlightParts( - snippet(text, _controller.text), _controller.text)) + for (final part in highlightParts(snippet(text, needle), needle)) TextSpan( text: part.text, style: part.match @@ -283,51 +87,30 @@ class _MessageSearchPageState extends State { ), ], ), - maxLines: maxLines, - overflow: maxLines == null ? null : TextOverflow.ellipsis, + maxLines: 2, + overflow: TextOverflow.ellipsis, ); } Widget _resultTile(MessageHit hit) { final message = hit.message; - final user = _users[hit.conversationId]; final time = DateFormat.MMMd().add_Hm().format(message.sentAt.toLocal()); - final text = message.preview; return ListTile( - leading: _global - ? CircleAvatar( - radius: 20, - backgroundColor: - user?.avatarColor ?? Theme.of(context).colorScheme.primary, - child: Text( - _displayName(hit.conversationId)[0].toUpperCase(), - style: TextStyle( - fontSize: 16, - color: user?.avatarTextColor ?? Colors.white, - ), - ), - ) - : null, - title: _global - ? Text(_displayName(hit.conversationId)) - : _snippetText(text, maxLines: 2), - subtitle: _global ? _snippetText(text, maxLines: 2) : null, + title: _snippetText(message.preview), trailing: Text( time, style: TextStyle( fontSize: 12, color: Theme.of(context).colorScheme.onSurfaceVariant), ), - onTap: () => _open(hit), + onTap: () => Navigator.pop(context, message.sentAt), ); } @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: Text(_global ? 'searchMessages'.tr() : widget.peer!.username), - ), + appBar: AppBar(title: Text('searchInChat'.tr())), body: SafeArea( child: Column( children: [ @@ -360,7 +143,6 @@ class _MessageSearchPageState extends State { ), ), ), - _filters(), if (_loading) const LinearProgressIndicator(), Expanded(child: _body()), ], diff --git a/lib/utils/message_search.dart b/lib/utils/message_search.dart index 20c6d3b..3420843 100644 --- a/lib/utils/message_search.dart +++ b/lib/utils/message_search.dart @@ -10,86 +10,35 @@ class MessageHit { final PrivateMessage message; } -/// What to look for in the local message store. +/// What to look for in one conversation's local history. /// /// The store holds decrypted text, so a search is a local scan: nothing leaves /// the device and no server round-trip happens. class MessageSearchQuery { - const MessageSearchQuery({ - this.text = '', - this.conversationId, - this.from, - this.to, - this.type, - }); + const MessageSearchQuery({this.text = '', this.conversationId}); - /// Case-insensitive substring of the message text (or of an attachment name). + /// Case-insensitive substring of the message text (or of a file name). final String text; /// Restricts the search to one conversation. final String? conversationId; - /// Inclusive start of the date range. - final DateTime? from; - - /// Inclusive end of the date range: the whole [to] day counts. - final DateTime? to; - - /// `text`, or a [MediaType.name]; null matches everything. - final String? type; - - /// Value of [type] for messages without an attachment. - static const String textType = 'text'; - /// Whether this query filters anything out at all. - bool get isEmpty => - text.trim().isEmpty && - type == null && - from == null && - to == null && - conversationId == null; + bool get isEmpty => text.trim().isEmpty; bool matches(MessageHit hit) { - final message = hit.message; if (conversationId != null && hit.conversationId != conversationId) { return false; } - if (!_matchesType(message)) { - return false; - } - final time = message.sentAt; - if (from != null && time.isBefore(from!)) { - return false; - } - if (to != null) { - final endOfDay = DateTime(to!.year, to!.month, to!.day, 23, 59, 59, 999); - if (time.isAfter(endOfDay)) { - return false; - } - } final needle = text.trim().toLowerCase(); if (needle.isEmpty) { return true; } + final message = hit.message; // An attachment without a caption is still findable by its file name. return message.message.toLowerCase().contains(needle) || (message.fileName ?? '').toLowerCase().contains(needle); } - - bool _matchesType(PrivateMessage message) { - final wanted = type; - if (wanted == null) { - return true; - } - if (wanted == textType) { - return !message.isMedia; - } - if (message.mediaTypeStr == wanted) { - return true; - } - // An album matches when any of its attachments has the type. - return message.album.any((item) => item.type == wanted); - } } /// How many hits a search returns. A single letter must not walk the whole diff --git a/test/message_search_test.dart b/test/message_search_test.dart index fc3807f..3909b60 100644 --- a/test/message_search_test.dart +++ b/test/message_search_test.dart @@ -1,25 +1,11 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:whisper/models/private_message.dart'; import 'package:whisper/utils/message_search.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; PrivateMessage text(String body, DateTime sentAt, {String? fileName}) { return PrivateMessage('peer', body, sentAt, sentAt, true, fileName: fileName); } -PrivateMessage media(String type, DateTime sentAt) { - return PrivateMessage('peer', '', sentAt, sentAt, true, mediaTypeStr: type); -} - -PrivateMessage album(List types, DateTime sentAt) { - final message = PrivateMessage('peer', '', sentAt, sentAt, true); - message.setAlbum([ - for (var i = 0; i < types.length; i++) - AlbumItem(mediaId: '$i', type: types[i], size: 1), - ]); - return message; -} - MessageHit hit(String conversation, PrivateMessage message) => MessageHit(conversation, message); @@ -47,8 +33,7 @@ void main() { test('an attachment is findable by its file name', () { final query = MessageSearchQuery(text: 'smlouva'); - final message = media(MediaType.file.name, base) - ..fileName = 'Smlouva-2026.pdf'; + final message = text('', base, fileName: 'Smlouva-2026.pdf'); expect(query.matches(hit('a', message)), isTrue); }); @@ -59,50 +44,6 @@ void main() { }); }); - group('date range', () { - test('both ends are inclusive', () { - final query = MessageSearchQuery( - from: DateTime(2026, 6, 1), - to: DateTime(2026, 6, 1), - ); - expect(query.matches(hit('a', text('x', DateTime(2026, 6, 1)))), isTrue); - expect(query.matches(hit('a', text('x', DateTime(2026, 6, 1, 23, 59)))), - isTrue); - expect(query.matches(hit('a', text('x', DateTime(2026, 6, 2)))), isFalse); - expect( - query.matches(hit('a', text('x', DateTime(2026, 5, 31)))), isFalse); - }); - }); - - group('type filter', () { - test('text means no attachment', () { - final query = MessageSearchQuery(type: MessageSearchQuery.textType); - expect(query.matches(hit('a', text('ahoj', base))), isTrue); - expect( - query.matches(hit('a', media(MediaType.image.name, base))), isFalse); - }); - - test('a media type matches its messages', () { - final query = MessageSearchQuery(type: MediaType.image.name); - expect( - query.matches(hit('a', media(MediaType.image.name, base))), isTrue); - expect( - query.matches(hit('a', media(MediaType.video.name, base))), isFalse); - }); - - test('an album matches when any attachment has the type', () { - final query = MessageSearchQuery(type: MediaType.video.name); - expect( - query.matches(hit( - 'a', album([MediaType.image.name, MediaType.video.name], base))), - isTrue); - expect( - query.matches(hit( - 'a', album([MediaType.image.name, MediaType.gif.name], base))), - isFalse); - }); - }); - group('result ordering', () { test('newest first and capped', () { final hits = [ From 48509cc5abc17228d1db185e5c524f7c50784acd Mon Sep 17 00:00:00 2001 From: Josef Date: Tue, 17 Nov 2026 23:31:37 +0100 Subject: [PATCH 079/181] fix(chat): keep the header to the info button Jump to date moves to the chat info page next to search; both hand a timestamp back to the chat page. --- lib/pages/chat_info_page.dart | 21 +++++++++++++++++ lib/pages/chat_page.dart | 44 +++++++++++------------------------ 2 files changed, 34 insertions(+), 31 deletions(-) diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 13a8f48..a18c31c 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -99,6 +99,21 @@ class _ChatInfoPageState extends State { ); } + /// Pick a day and hand it back to the chat page, which jumps to the first + /// message of that day (or the first one after it). + Future _jumpToDate() async { + final now = DateTime.now(); + final picked = await showDatePicker( + context: context, + initialDate: now, + firstDate: DateTime(now.year - 10), + lastDate: now, + ); + if (picked != null && mounted) { + Navigator.pop(context, picked); + } + } + /// Search this conversation. A picked hit is handed back to the chat page, /// which jumps to it. Future _openSearch() async { @@ -133,6 +148,12 @@ class _ChatInfoPageState extends State { label: 'searchInChat'.tr(), onPressed: _openSearch, ), + // Jump to a day + SettingsTile( + icon: Icons.event, + label: 'jumpToDate'.tr(), + onPressed: _jumpToDate, + ), // Chat theme SettingsTile( icon: Icons.palette, diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 8e96389..f759370 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -377,47 +377,34 @@ class _ChatPageState extends State { } Future _openChatInfo() async { - // The info page hands back a timestamp when a search hit was picked there. - final jumpTo = await Navigator.of(context) + // The info page hands back a timestamp when a search hit or a date was + // picked there. + final target = await Navigator.of(context) .push(stepRoute(ChatInfoPage(widget.user.id))); // The theme (and possibly the user) may have changed while it was open. await _loadChatTheme(); await _loadMessages(); - if (jumpTo != null && mounted) { - await _jumpToMessage(jumpTo); + if (target != null && mounted) { + await _jumpTo(target); } } - /// Jump to the first message of a picked day (or the first one after it). - Future _jumpToDate() async { + /// Jumps to [target], or to the first message after it: a search hit is an + /// exact instant, a picked day is midnight. + Future _jumpTo(DateTime target) async { if (_messages.isEmpty) { return; } - final oldest = _messages.first.sentAt.toLocal(); - final firstDay = DateTime(oldest.year, oldest.month, oldest.day); - final now = DateTime.now(); - final picked = await showDatePicker( - context: context, - initialDate: now, - firstDate: firstDay.isBefore(DateTime(2000)) ? DateTime(2000) : firstDay, - lastDate: now, - ); - if (picked == null || !mounted) { - return; - } - DateTime? target; - for (final message in _messages) { - if (!message.sentAt.isBefore(picked)) { - target = message.sentAt; - break; - } + var index = _messages.indexWhere((message) => message.sentAt == target); + if (index < 0) { + index = _messages.indexWhere((message) => message.sentAt.isAfter(target)); } - if (target == null) { + if (index < 0) { await Fluttertoast.showToast( msg: 'noMessagesOnDate'.tr(), backgroundColor: Colors.orange); return; } - await _jumpToMessage(target); + await _jumpToMessage(_messages[index].sentAt); } // --------------------------------------------------------------------------- @@ -1368,11 +1355,6 @@ class _ChatPageState extends State { ), // Action buttons actions: [ - IconButton( - icon: const Icon(Icons.event), - tooltip: 'jumpToDate'.tr(), - onPressed: _jumpToDate, - ), IconButton( icon: const Icon(Icons.info), tooltip: 'infoButton'.tr(), From fe8281e5c1ce4c07aa42c241fd74fda518a593de Mon Sep 17 00:00:00 2001 From: Josef Date: Tue, 17 Nov 2026 23:41:13 +0100 Subject: [PATCH 080/181] feat(search): avatar and a language-aware date on each hit Result rows lead with the peer avatar and use the shared chat date label; intl date data is initialized for en/cs and Intl.defaultLocale follows the selected language. --- lib/main.dart | 9 +++++++ lib/pages/search_page.dart | 31 ++++++++++++++++++++---- lib/pages/whisper_page.dart | 6 +++++ lib/utils/chat_date.dart | 36 +++++++++++++++++++++++++++ lib/widgets/chat_list_item.dart | 36 +++++---------------------- test/chat_date_test.dart | 43 +++++++++++++++++++++++++++++++++ 6 files changed, 126 insertions(+), 35 deletions(-) create mode 100644 lib/utils/chat_date.dart create mode 100644 test/chat_date_test.dart diff --git a/lib/main.dart b/lib/main.dart index 852b033..09a4d2a 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,6 +1,10 @@ import 'dart:io'; import 'package:easy_localization/easy_localization.dart'; +// intl is pinned through easy_localization; declaring it a second time would +// only duplicate that pin. +// ignore: depend_on_referenced_packages +import 'package:intl/date_symbol_data_local.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; @@ -48,6 +52,11 @@ void main() async { // Load locale (the notification service needs it for the channel texts) await EasyLocalization.ensureInitialized(); + // Date patterns and month names for the languages the app ships with. Without + // them DateFormat falls back to English for everything. + for (final locale in ['en', 'cs']) { + await initializeDateFormatting(locale); + } // Local notifications. A failure here must not block the app. try { diff --git a/lib/pages/search_page.dart b/lib/pages/search_page.dart index 03b2240..7d749aa 100644 --- a/lib/pages/search_page.dart +++ b/lib/pages/search_page.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import '../models/user.dart'; import '../utils/cache_utils.dart'; +import '../utils/chat_date.dart'; import '../utils/message_search.dart'; /// Searches one conversation's local history. Messages are stored decrypted, @@ -94,14 +95,34 @@ class _MessageSearchPageState extends State { Widget _resultTile(MessageHit hit) { final message = hit.message; - final time = DateFormat.MMMd().add_Hm().format(message.sentAt.toLocal()); return ListTile( + leading: CircleAvatar( + radius: 20, + backgroundColor: widget.peer.avatarColor, + child: Text( + widget.peer.username.isNotEmpty + ? widget.peer.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 16, + color: widget.peer.avatarTextColor, + ), + ), + ), title: _snippetText(message.preview), - trailing: Text( - time, - style: TextStyle( + subtitle: Padding( + padding: const EdgeInsets.only(top: 2), + child: Text( + chatDateLabel( + message.sentAt, + todayLabel: 'todayText'.tr(), + yesterdayLabel: 'yesterdayText'.tr(), + ), + style: TextStyle( fontSize: 12, - color: Theme.of(context).colorScheme.onSurfaceVariant), + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), ), onTap: () => Navigator.pop(context, message.sentAt), ); diff --git a/lib/pages/whisper_page.dart b/lib/pages/whisper_page.dart index 443e658..58a9d13 100644 --- a/lib/pages/whisper_page.dart +++ b/lib/pages/whisper_page.dart @@ -54,6 +54,12 @@ class WhisperPage extends StatelessWidget { return MaterialApp( navigatorObservers: [PageNavigatorObserver()], debugShowCheckedModeBanner: true, + // Every DateFormat in the app (chat rows, bubbles, day headers, search) + // follows the selected language instead of the platform default. + builder: (context, child) { + Intl.defaultLocale = context.locale.toString(); + return child ?? const SizedBox.shrink(); + }, // Light theme theme: ThemeData.from( colorScheme: ColorScheme.fromSeed( diff --git a/lib/utils/chat_date.dart b/lib/utils/chat_date.dart new file mode 100644 index 0000000..768a8e0 --- /dev/null +++ b/lib/utils/chat_date.dart @@ -0,0 +1,36 @@ +import 'package:easy_localization/easy_localization.dart'; + +/// Date label of a conversation row and of a search result: today and +/// yesterday by name, then the weekday for the last week, then the date. +/// +/// [todayLabel] and [yesterdayLabel] are passed in because a pure helper +/// cannot reach the localization; [now] is injectable for tests. Patterns and +/// month names follow `Intl.defaultLocale`, which the app keeps in sync with +/// the selected language. +String chatDateLabel( + DateTime when, { + required String todayLabel, + required String yesterdayLabel, + DateTime? now, +}) { + final current = (now ?? DateTime.now()).toLocal(); + final date = when.toLocal(); + final time = DateFormat.Hm().format(date); + final days = DateTime(date.year, date.month, date.day) + .difference(DateTime(current.year, current.month, current.day)) + .inDays; + + if (days == 0) { + return '$todayLabel $time'; + } + if (days == -1) { + return '$yesterdayLabel $time'; + } + if (days >= -7) { + return '${DateFormat.EEEE().format(date)} $time'; + } + if (date.year == current.year) { + return DateFormat.MMMMd().format(date); + } + return DateFormat.yMMMMd().format(date); +} diff --git a/lib/widgets/chat_list_item.dart b/lib/widgets/chat_list_item.dart index 87c5269..f548b95 100644 --- a/lib/widgets/chat_list_item.dart +++ b/lib/widgets/chat_list_item.dart @@ -2,6 +2,7 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import '../models/private_message.dart'; import '../models/user.dart'; +import '../utils/chat_date.dart'; class ChatListItem extends StatefulWidget { const ChatListItem(this.user, this.lastMessage, this.onPressed, @@ -22,35 +23,6 @@ class ChatListItem extends StatefulWidget { } class _ChatListItemState extends State { - String formatDate() { - final DateTime now = DateTime.now().toLocal(); - final DateTime messageDate = widget.lastMessage.receivedAt.toLocal(); - final int daysDifference = messageDate.difference(now).inDays; - - // Today - if (messageDate.day == now.day && - messageDate.month == now.month && - messageDate.year == now.year) { - return '${'todayText'.tr()} ${DateFormat.Hm().format(messageDate)}'; - } - // Yesterday - else if (daysDifference == -1) { - return '${'yesterdayText'.tr()} ${DateFormat.Hm().format(messageDate)}'; - } - // Last week - else if (daysDifference >= -7) { - return '${DateFormat.EEEE().format(messageDate)} ${DateFormat.Hm().format(messageDate)}'; - } - // This year - else if (messageDate.year == now.year) { - return DateFormat.MMMMd().format(messageDate); - } - // Different year - else { - return DateFormat.yMMMMd().format(messageDate); - } - } - /// Rounded counter, capped the way every messenger does it. Widget _unreadBadge() { final scheme = Theme.of(context).colorScheme; @@ -133,7 +105,11 @@ class _ChatListItemState extends State { mainAxisSize: MainAxisSize.min, children: [ Text( - formatDate(), + chatDateLabel( + widget.lastMessage.receivedAt, + todayLabel: 'todayText'.tr(), + yesterdayLabel: 'yesterdayText'.tr(), + ), style: unread ? TextStyle( fontWeight: FontWeight.bold, diff --git a/test/chat_date_test.dart b/test/chat_date_test.dart new file mode 100644 index 0000000..14928ee --- /dev/null +++ b/test/chat_date_test.dart @@ -0,0 +1,43 @@ +import 'package:easy_localization/easy_localization.dart'; +// intl is pinned through easy_localization; same import as the app itself. +// ignore: depend_on_referenced_packages +import 'package:intl/date_symbol_data_local.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/chat_date.dart'; + +void main() { + final now = DateTime(2026, 6, 10, 12); + + setUpAll(() async { + await initializeDateFormatting('en'); + Intl.defaultLocale = 'en'; + }); + + String label(DateTime when) => chatDateLabel(when, + todayLabel: 'Today', yesterdayLabel: 'Yesterday', now: now); + + test('today carries the localized label and the time', () { + expect(label(DateTime(2026, 6, 10, 9, 5)), 'Today 09:05'); + }); + + test('yesterday carries its own label', () { + expect(label(DateTime(2026, 6, 9, 23, 59)), 'Yesterday 23:59'); + }); + + test('the last week shows the weekday name', () { + final when = DateTime(2026, 6, 7, 8, 30); + expect(label(when), '${DateFormat.EEEE().format(when)} 08:30'); + }); + + test('an older message this year shows the date without the year', () { + final when = DateTime(2026, 5, 3, 8); + expect(label(when), DateFormat.MMMMd().format(when)); + expect(label(when).contains('2026'), isFalse); + }); + + test('a message from another year shows the year', () { + final when = DateTime(2025, 12, 31, 8); + expect(label(when), DateFormat.yMMMMd().format(when)); + expect(label(when).contains('2025'), isTrue); + }); +} From 029c06584e01c6f08ef590b6f5ae05e569876a35 Mon Sep 17 00:00:00 2001 From: Josef Date: Tue, 17 Nov 2026 23:48:58 +0100 Subject: [PATCH 081/181] fix(chat): make a search hit actually scroll into view Cut the rendered window down to the target and jump to the top of it; walk up a viewport at a time when the target sits inside a large window. Adds chat_scroll helpers with tests. --- lib/pages/chat_page.dart | 90 +++++++++++++++++++++++++++----------- lib/utils/chat_scroll.dart | 23 ++++++++++ test/chat_scroll_test.dart | 37 ++++++++++++++++ 3 files changed, 124 insertions(+), 26 deletions(-) create mode 100644 lib/utils/chat_scroll.dart create mode 100644 test/chat_scroll_test.dart diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index f759370..94a300a 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -12,6 +12,7 @@ import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../models/user.dart'; import '../utils/cache_utils.dart'; +import '../utils/chat_scroll.dart'; import '../utils/chat_sender.dart'; import '../utils/media_utils.dart'; import '../utils/message_actions.dart'; @@ -57,6 +58,8 @@ class _ChatPageState extends State { bool _historyLoading = false; // Guards against overlapping "grow the window upwards" passes bool _growing = false; + // A jump walks the list itself; window growth would move the offset under it + bool _jumping = false; // Whether the newest archive page was already asked for bool _historyLoaded = false; // Cursor for the next (older) archive page, null when the archive ends @@ -250,7 +253,7 @@ class _ChatPageState extends State { /// Extend the rendered window when the user scrolls towards older messages. void _onScroll() { - if (!_scrollController.hasClients) { + if (_jumping || !_scrollController.hasClients) { return; } final position = _scrollController.position; @@ -480,33 +483,68 @@ class _ChatPageState extends State { }); } - /// Scrolls to the message a reply quotes, widening the window when it is - /// older than what is rendered. + /// Scrolls to [sentAt], used by the reply quote, the search hits and the + /// date jump. + /// + /// Widening the rendered window is not enough: a list only builds what is + /// near the viewport, so growing the tail never builds an old message. The + /// fast path therefore cuts the window down to the target, which puts it one + /// screen from the top, and `jumpTo(0)` lands on it. The slow path walks up a + /// viewport at a time for a target already inside a large window but far + /// below the screen. Future _jumpToMessage(DateTime sentAt) async { final micros = sentAt.microsecondsSinceEpoch; - final context = _messageKeys[micros]?.currentContext; - if (context != null) { - await Scrollable.ensureVisible(context, - alignment: 0.3, duration: const Duration(milliseconds: 250)); - return; - } - // Not rendered: open the window up to it, then try once more. - final index = _messages.indexWhere((message) => message.sentAt == sentAt); - if (index < 0) { - return; - } - final needed = _messages.length - index + 5; - if (needed > _visibleCount) { - await _growWindow(needed - _visibleCount); - } - await WidgetsBinding.instance.endOfFrame; - if (!mounted) { - return; - } - final retry = _messageKeys[micros]?.currentContext; - if (retry != null && retry.mounted) { - await Scrollable.ensureVisible(retry, - alignment: 0.3, duration: const Duration(milliseconds: 250)); + _jumping = true; + try { + final index = _messages.indexWhere((message) => message.sentAt == sentAt); + if (index < 0) { + return; + } + final needed = windowForAddition(_messages.length, index); + if (needed > _visibleCount) { + setState(() { + _visibleCount = needed; + }); + await WidgetsBinding.instance.endOfFrame; + if (!mounted || !_scrollController.hasClients) { + return; + } + _scrollController.jumpTo(0); + await WidgetsBinding.instance.endOfFrame; + if (!mounted) { + return; + } + } + final context = _messageKeys[micros]?.currentContext; + if (context != null && context.mounted) { + await Scrollable.ensureVisible(context, + alignment: 0.2, duration: const Duration(milliseconds: 250)); + return; + } + for (var attempt = 0; attempt < 50; attempt++) { + if (!_scrollController.hasClients) { + return; + } + final position = _scrollController.position; + final next = + nextJumpOffset(position.pixels, position.viewportDimension); + if (next == position.pixels) { + return; + } + _scrollController.jumpTo(next); + await WidgetsBinding.instance.endOfFrame; + if (!mounted) { + return; + } + final reached = _messageKeys[micros]?.currentContext; + if (reached != null && reached.mounted) { + await Scrollable.ensureVisible(reached, + alignment: 0.3, duration: const Duration(milliseconds: 250)); + return; + } + } + } finally { + _jumping = false; } } diff --git a/lib/utils/chat_scroll.dart b/lib/utils/chat_scroll.dart new file mode 100644 index 0000000..07d828f --- /dev/null +++ b/lib/utils/chat_scroll.dart @@ -0,0 +1,23 @@ +/// How many of the newest messages must be rendered for the message at +/// [index] to exist in the list at all. +/// +/// The rendered window is a slice of the tail, so reaching an older message +/// always means widening that slice. [margin] leaves a few messages above the +/// target, so it does not sit alone on the first line. +int windowForAddition(int messageCount, int index, {int margin = 5}) { + final needed = messageCount - index + margin; + if (needed < 1) { + return 1; + } + return needed > messageCount ? messageCount : needed; +} + +/// Next scroll offset while walking up the list towards a message that is not +/// built yet: one viewport at a time, never below the top. +double nextJumpOffset(double pixels, double viewport) { + final next = pixels - viewport; + if (next < 0) { + return 0; + } + return next > pixels ? pixels : next; +} diff --git a/test/chat_scroll_test.dart b/test/chat_scroll_test.dart new file mode 100644 index 0000000..d8c3112 --- /dev/null +++ b/test/chat_scroll_test.dart @@ -0,0 +1,37 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/chat_scroll.dart'; + +void main() { + group('windowForAddition', () { + test('includes the target plus a margin of newer messages', () { + // 100 messages, target at 40, 5 above it: 100 - 40 + 5. + expect(windowForAddition(100, 40), 65); + }); + + test('the newest message needs only the margin', () { + expect(windowForAddition(100, 99), 6); + }); + + test('the oldest message needs the whole conversation', () { + expect(windowForAddition(100, 0), 100); + }); + + test('never asks for more than there is', () { + expect(windowForAddition(3, 0), 3); + }); + }); + + group('nextJumpOffset', () { + test('moves one viewport up', () { + expect(nextJumpOffset(1000, 600), 400); + }); + + test('stops at the top instead of going negative', () { + expect(nextJumpOffset(200, 600), 0); + }); + + test('returns the same offset when already at the top', () { + expect(nextJumpOffset(0, 600), 0); + }); + }); +} From 8ff3fffc04dd9a53f2db7fb8cf22a535bb9a7c7a Mon Sep 17 00:00:00 2001 From: Josef Date: Tue, 17 Nov 2026 23:57:09 +0100 Subject: [PATCH 082/181] fix(chat): let an attachment fill its bubble Media bubbles drop the accent padding/background and clip the attachment to the corners; the selection border moves to foregroundDecoration. --- lib/widgets/chat_bubble.dart | 37 ++++++++++++++++++++++++++---------- test/chat_bubble_test.dart | 25 ++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 10 deletions(-) diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 6bf6257..af6e414 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -289,21 +289,38 @@ class _ChatBubbleState extends State { ], ); - // Emoji-only messages drop the bubble chrome and read large. + // Emoji-only messages drop the bubble chrome and read large; an attachment + // is the bubble, so it is clipped to the corners instead of sitting inside + // a coloured frame. + final isMedia = widget.message.isMedia; final bubbleBox = Container( decoration: BoxDecoration( - color: _isLargeEmoji ? null : bubbleBackground(), + // A reply needs a surface for its quote; the attachment below fills the + // rest of the bubble. + color: isMedia + ? (widget.message.isReply ? bubbleBackground() : null) + : (_isLargeEmoji ? null : bubbleBackground()), borderRadius: BorderRadius.circular(20), - border: widget.selected - ? Border.all( + ), + // Above the child: a border in the decoration would sit under an + // attachment that fills the bubble. + foregroundDecoration: widget.selected + ? BoxDecoration( + borderRadius: BorderRadius.circular(20), + border: Border.all( color: Theme.of(context).colorScheme.primary, width: 2, - ) - : null, - ), - padding: _isLargeEmoji - ? EdgeInsets.zero - : const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + ), + ) + : null, + clipBehavior: isMedia ? Clip.antiAlias : Clip.none, + padding: isMedia + ? (widget.message.isReply + ? const EdgeInsets.fromLTRB(8, 8, 8, 0) + : EdgeInsets.zero) + : (_isLargeEmoji + ? EdgeInsets.zero + : const EdgeInsets.symmetric(horizontal: 16, vertical: 10)), child: bubble, ); diff --git a/test/chat_bubble_test.dart b/test/chat_bubble_test.dart index 2d7bf24..07ee74b 100644 --- a/test/chat_bubble_test.dart +++ b/test/chat_bubble_test.dart @@ -10,6 +10,8 @@ import 'package:whisper/models/user.dart'; import 'package:whisper/utils/singleton.dart'; import 'package:whisper/utils/text_envelope.dart'; import 'package:whisper/widgets/chat_bubble.dart'; +import 'package:whisper/widgets/media_bubble.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; /// Plain text of everything the bubble rendered, spans included. String renderedText(WidgetTester tester) => tester @@ -168,5 +170,28 @@ void main() { TextDecorationStyle.solid, reason: tappable); } + + // An attachment is the bubble: no coloured frame or padding around it. + await show(ChatBubble( + null, + PrivateMessage( + '2', + '', + DateTime(2026), + DateTime(2026), + true, + mediaTypeStr: MediaType.image.name, + downloadStatus: MediaDownloadStatus.failed, + ), + null, + peer, + accentColor: Colors.blue, + )); + final mediaFrame = tester.widget(find + .ancestor( + of: find.byType(MediaBubble), matching: find.byType(Container)) + .first); + expect(mediaFrame.padding, EdgeInsets.zero); + expect((mediaFrame.decoration as BoxDecoration?)?.color, isNull); }); } From 61190f6f6b8a8db0d1802fb628810ef21b9629b1 Mon Sep 17 00:00:00 2001 From: Josef Date: Wed, 18 Nov 2026 00:11:02 +0100 Subject: [PATCH 083/181] fix(media): stop re-downloading attachments the device already holds Guard downloadMediaMessage on a local file and render from the file whatever the stale status says. --- lib/utils/cache_utils.dart | 27 ++++++++++++ lib/utils/message_notifier.dart | 7 ++++ lib/widgets/media_bubble.dart | 41 +++++++++--------- test/media_guard_test.dart | 74 +++++++++++++++++++++++++++++++++ 4 files changed, 130 insertions(+), 19 deletions(-) create mode 100644 test/media_guard_test.dart diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 9f3024d..c8ff56e 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -801,6 +801,33 @@ class CacheUtils { return filterMessages(hits, query); } + /// Whether the attachment [mediaId] already sits on this device, either as a + /// single attachment or as one item of an album. + /// + /// The server deletes its copy once delivery is confirmed, so downloading a + /// media that is already here can only fail with 404 and would overwrite a + /// healthy attachment with an error state. A history page or a sync + /// redelivers messages that are already stored, which is exactly when this + /// check matters. + static Future hasMediaLocally(String userId, String mediaId) async { + final box = await _openPrivateMessagesBox(); + for (final key in _conversationKeys(box, userId)) { + final value = box.get(key); + if (value is! PrivateMessage) { + continue; + } + if (value.mediaId == mediaId && value.localPath != null) { + return true; + } + for (final item in value.album) { + if (item.mediaId == mediaId && item.localPath != null) { + return true; + } + } + } + return false; + } + /// Oldest unread message of a conversation: the anchor of the "new messages" /// divider, taken before the chat marks everything read. static Future firstUnreadSentAt(String userId) async { diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index 1826181..a589018 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -87,6 +87,13 @@ class MessageNotifier extends ChangeNotifier { /// thus deleted); on failure the message is marked as failed for retry. Future downloadMediaMessage( String conversationUserId, MediaReference reference) async { + // A redelivery (history page, sync, reconnect) must not re-fetch an + // attachment we already hold: the server deleted its copy on confirm, so + // the attempt would 404 and mark a working attachment as failed. + if (await CacheUtils.hasMediaLocally( + conversationUserId, reference.mediaId)) { + return; + } _pendingMediaRefs[reference.mediaId] = reference; try { final blob = await Utils.callApi( diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 42fe702..f7eabce 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -137,25 +137,10 @@ class _MediaBubbleState extends State { final insideBubble = type == MediaType.voice || type == MediaType.file; Widget media; - if (insideBubble && - widget.message.downloadStatus == MediaDownloadStatus.pending) { - media = type == MediaType.voice - ? SizedBox( - width: 220, - height: 48, - child: Center( - child: CircularProgressIndicator(color: widget.textColor), - ), - ) - : _fileWidget(); - } else if (widget.message.downloadStatus == MediaDownloadStatus.pending) { - media = _placeholder(child: const CircularProgressIndicator()); - } else if (widget.message.downloadStatus == MediaDownloadStatus.failed || - widget.message.downloadStatus == MediaDownloadStatus.expired) { - media = _failed(); - } else if (widget.message.localPath == null) { - media = _placeholder(child: const CircularProgressIndicator()); - } else { + if (widget.message.localPath != null) { + // The file on disk is the truth. A failed/expired status can be stale: a + // redelivered message used to re-try a download the server had already + // confirmed, which flipped a working attachment to expired. switch (type) { case MediaType.image: case MediaType.gif: @@ -173,6 +158,24 @@ class _MediaBubbleState extends State { case null: media = _placeholder(child: const Icon(Icons.broken_image)); } + } else if (insideBubble && + widget.message.downloadStatus == MediaDownloadStatus.pending) { + media = type == MediaType.voice + ? SizedBox( + width: 220, + height: 48, + child: Center( + child: CircularProgressIndicator(color: widget.textColor), + ), + ) + : _fileWidget(); + } else if (widget.message.downloadStatus == MediaDownloadStatus.pending) { + media = _placeholder(child: const CircularProgressIndicator()); + } else if (widget.message.downloadStatus == MediaDownloadStatus.failed || + widget.message.downloadStatus == MediaDownloadStatus.expired) { + media = _failed(); + } else { + media = _placeholder(child: const CircularProgressIndicator()); } // Voice and file messages live inside the coloured bubble. diff --git a/test/media_guard_test.dart b/test/media_guard_test.dart new file mode 100644 index 0000000..ae93427 --- /dev/null +++ b/test/media_guard_test.dart @@ -0,0 +1,74 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +PrivateMessage media(DateTime sentAt, + {String? mediaId, String? localPath, String? albumItemPath}) { + final message = PrivateMessage('peer', '', sentAt, sentAt, true, + mediaId: mediaId, + mediaTypeStr: albumItemPath == null ? MediaType.image.name : null, + localPath: localPath); + if (albumItemPath != null) { + message.setAlbum([ + AlbumItem( + mediaId: mediaId!, + type: MediaType.image.name, + size: 1, + localPath: albumItemPath), + ]); + } + return message; +} + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_media_guard_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + final base = DateTime(2026, 6, 1, 12); + + test('a downloaded attachment counts as local', () async { + await CacheUtils.addPrivateMessages( + 'peer', [media(base, mediaId: 'm1', localPath: '/tmp/a.bin')]); + expect(await CacheUtils.hasMediaLocally('peer', 'm1'), isTrue); + }); + + test('a placeholder waiting for download does not', () async { + await CacheUtils.addPrivateMessages('peer', [media(base, mediaId: 'm2')]); + expect(await CacheUtils.hasMediaLocally('peer', 'm2'), isFalse); + }); + + test('an album item counts when it has a local file', () async { + await CacheUtils.addPrivateMessages( + 'peer', [media(base, mediaId: 'm3', albumItemPath: '/tmp/a.bin')]); + expect(await CacheUtils.hasMediaLocally('peer', 'm3'), isTrue); + }); + + test('another conversation does not count', () async { + await CacheUtils.addPrivateMessages( + 'peer', [media(base, mediaId: 'm4', localPath: '/tmp/a.bin')]); + expect(await CacheUtils.hasMediaLocally('other', 'm4'), isFalse); + }); + + test('an empty store reports nothing local', () async { + expect(await CacheUtils.hasMediaLocally('peer', 'nope'), isFalse); + }); +} From 76d56f2c38d188f76388905856d5932a7c782fc0 Mon Sep 17 00:00:00 2001 From: Josef Date: Wed, 18 Nov 2026 00:18:58 +0100 Subject: [PATCH 084/181] fix(voice): keep the track centred while the speed label is shown Reserve the speed line's height above the track so the playback line stays centred on the play button. --- lib/widgets/voice_player.dart | 37 +++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/lib/widgets/voice_player.dart b/lib/widgets/voice_player.dart index b979352..cecfb33 100644 --- a/lib/widgets/voice_player.dart +++ b/lib/widgets/voice_player.dart @@ -191,12 +191,16 @@ class _VoicePlayerState extends State with WidgetsBindingObserver { final completed = stateSnapshot.data?.processingState == ProcessingState.completed; // The speed control appears with playback and is gone - // again once the message finished. + // again once the message finished. It sits under the time, + // so the track gets an equal spacer above it to stay + // centred on the play button instead of drifting up. final started = position > Duration.zero && !completed; + const double speedLine = 16; return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + if (started) const SizedBox(height: speedLine), Row( children: [ Expanded( @@ -234,20 +238,23 @@ class _VoicePlayerState extends State with WidgetsBindingObserver { ], ), if (started) - Align( - alignment: Alignment.centerRight, - child: Semantics( - button: true, - child: InkWell( - onTap: _cycleSpeed, - child: Padding( - padding: const EdgeInsets.only(right: 4), - child: Text( - speedLabel(_speed), - style: TextStyle( - fontSize: 11, - fontWeight: FontWeight.w600, - color: widget.color, + SizedBox( + height: speedLine, + child: Align( + alignment: Alignment.centerRight, + child: Semantics( + button: true, + child: InkWell( + onTap: _cycleSpeed, + child: Padding( + padding: const EdgeInsets.only(right: 4), + child: Text( + speedLabel(_speed), + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: widget.color, + ), ), ), ), From 82003ee870303e088935b4ffa3b79f96f4c9e7e6 Mon Sep 17 00:00:00 2001 From: Josef Date: Wed, 18 Nov 2026 00:28:58 +0100 Subject: [PATCH 085/181] fix(media): open the attachment that was tapped viewableMedia judges by the local file instead of a stale status flag, so the viewer and the shared-media grid list what the bubbles show; the viewer no longer falls back to the newest item. --- lib/pages/media_viewer_page.dart | 4 +++- lib/utils/message_notifier.dart | 17 +++++++------- test/chat_info_media_test.dart | 38 +++++++++++++++++++++++++++++--- 3 files changed, 47 insertions(+), 12 deletions(-) diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index 82ee077..f728d90 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -83,7 +83,9 @@ class _MediaViewerPageState extends State { return; } setState(() { - _media = media.isEmpty ? [widget.message] : media; + // Never fall back to the first page when the tapped attachment is not in + // the list: that opens a different attachment than the one clicked. + _media = index < 0 ? [widget.message] : media; _index = index < 0 ? 0 : index; _controller = PageController(initialPage: _index); }); diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index a589018..709a918 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -27,22 +27,23 @@ class MessageNotifier extends ChangeNotifier { /// items are expanded into one entry per attachment. static List viewableMedia(List messages) { final media = []; + // A local file is what makes an attachment viewable, not its status: a + // stale failed/expired flag (an old redelivery) used to hide attachments + // that the bubbles and the viewer can still open. + bool viewable(PrivateMessage message) => + message.localPath != null && + message.mediaType != null && + message.mediaType != MediaType.voice; for (final message in messages) { if (message.isAlbum) { for (final item in albumMedia(message)) { - if (item.localPath != null && - item.mediaType != null && - item.mediaType != MediaType.voice && - item.downloadStatus == MediaDownloadStatus.ready) { + if (viewable(item)) { media.add(item); } } continue; } - if (message.localPath != null && - message.mediaType != null && - message.mediaType != MediaType.voice && - message.downloadStatus == MediaDownloadStatus.ready) { + if (viewable(message)) { media.add(message); } } diff --git a/test/chat_info_media_test.dart b/test/chat_info_media_test.dart index e888c2c..f1b79f3 100644 --- a/test/chat_info_media_test.dart +++ b/test/chat_info_media_test.dart @@ -1,6 +1,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:whisper/models/private_message.dart'; import 'package:whisper/utils/message_notifier.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; PrivateMessage message(String? type, String? path, DateTime sentAt, {int? downloadStatus}) { @@ -10,8 +11,22 @@ PrivateMessage message(String? type, String? path, DateTime sentAt, downloadStatus: downloadStatus ?? MediaDownloadStatus.ready); } +PrivateMessage album(DateTime sentAt, String path, MediaType type, + {int status = MediaDownloadStatus.ready}) { + final result = PrivateMessage('1', '', sentAt, sentAt, false); + result.setAlbum([ + AlbumItem( + mediaId: 'a', + type: type.name, + size: 1, + localPath: path, + status: status), + ]); + return result; +} + void main() { - test('shared media keeps only ready, viewable media with a local file', () { + test('shared media needs a local file, whatever the status says', () { final now = DateTime(2026, 11, 12, 12); final media = MessageNotifier.viewableMedia([ message('image', '/tmp/a.jpg', now), @@ -21,12 +36,29 @@ void main() { // Not downloaded yet message('image', null, now.subtract(const Duration(minutes: 3))), // Still downloading - message('image', '/tmp/d.jpg', now.subtract(const Duration(minutes: 4)), + message('image', null, now.subtract(const Duration(minutes: 4)), downloadStatus: MediaDownloadStatus.pending), + // A stale failure flag must not hide a file that is right there + message('image', '/tmp/e.jpg', now.subtract(const Duration(minutes: 5)), + downloadStatus: MediaDownloadStatus.expired), // Plain text - message(null, null, now.subtract(const Duration(minutes: 5))), + message(null, null, now.subtract(const Duration(minutes: 6))), + ]); + + expect(media.map((m) => m.localPath), + ['/tmp/a.jpg', '/tmp/b.mp4', '/tmp/e.jpg']); + }); + + test('an album contributes each of its attachments', () { + final now = DateTime(2026, 11, 12, 12); + final media = MessageNotifier.viewableMedia([ + album(now, '/tmp/a.jpg', MediaType.image), + album(now.subtract(const Duration(minutes: 1)), '/tmp/b.mp4', + MediaType.video, + status: MediaDownloadStatus.failed), ]); expect(media.map((m) => m.localPath), ['/tmp/a.jpg', '/tmp/b.mp4']); + expect(media.first.mediaType, MediaType.image); }); } From 10434850c8ca733058da2b4a0c5bdba3f35044a4 Mon Sep 17 00:00:00 2001 From: Josef Date: Wed, 18 Nov 2026 00:46:13 +0100 Subject: [PATCH 086/181] fix(ui): keep content out from under the translucent app bar Home chips and the chat conversation start below the bar; the list's automatic MediaQuery padding is off so the gap is not counted twice. --- lib/pages/chat_page.dart | 8 ++++++++ lib/pages/home_page.dart | 13 +++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 94a300a..9d64851 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1227,6 +1227,14 @@ class _ChatPageState extends State { parent: AlwaysScrollableScrollPhysics(), ), slivers: [ + // The body sits behind the translucent app bar, so the conversation + // has to start below it: without this the avatar header and the first + // day separator are painted under the bar. + SliverToBoxAdapter( + child: SizedBox( + height: MediaQuery.viewPaddingOf(context).top + kToolbarHeight, + ), + ), SliverToBoxAdapter( child: hasOlder ? const Padding( diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index c99393e..5951ed3 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -399,6 +399,9 @@ class _HomePageState extends State physics: const BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics(), ), + // The chips already clear the app bar; a scroll view's automatic + // MediaQuery padding would add a second gap above the first row. + padding: EdgeInsets.zero, itemCount: chats.length, itemBuilder: (context, index) { // Indexed access: `Map.entries.elementAt` is O(n) and made the list @@ -543,8 +546,14 @@ class _HomePageState extends State // Messages Column( children: [ - SizedBox(height: 10), - _filterChips(), + // The body sits behind the translucent app bar; the chips do not + // scroll, so they start below it. + Padding( + padding: EdgeInsets.only( + top: MediaQuery.viewPaddingOf(context).top + kToolbarHeight, + ), + child: _filterChips(), + ), // Messages and avatar list Expanded( child: _firstLoad From eddb74e62d3ccfb2827c70d044ea2f1a37de5842 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Wed, 18 Nov 2026 04:02:12 +0100 Subject: [PATCH 087/181] chore: drop a stale TODO in main --- lib/main.dart | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index 09a4d2a..9f72e3a 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -26,8 +26,6 @@ import 'utils/singleton.dart'; import 'utils/theme_notifier.dart'; import 'utils/utils.dart'; -// TODO tor? - void main() async { // Initialize Flutter widgets WidgetsFlutterBinding.ensureInitialized(); From 76e39d340e4116df176934d52029b6fd49100398 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Wed, 18 Nov 2026 04:02:12 +0100 Subject: [PATCH 088/181] fix(chat): land on the newest message when the chat opens The first jump targets the lazy list's estimated extent, so the real end sat screens further down; jump again until the content stops growing. History pages and message reloads share one pin flag instead of always compensating the scroll offset, and a change arriving mid-read gets one extra pass instead of being dropped. Our own read notifies on purpose (it marks messages read), so it is filtered to keep that from looping. --- lib/pages/chat_page.dart | 79 +++++++++++++++++++++++++++++++++++----- 1 file changed, 70 insertions(+), 9 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 9d64851..e1af5ea 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -54,6 +54,10 @@ class _ChatPageState extends State { bool _firstLoad = true; // Guards against overlapping cache reads bool _loading = false; + // A change arrived mid-read: run one more pass when it ends + bool _reloadRequested = false; + // True only around our own read, which notifies on purpose (home list row) + bool _selfRead = false; // Guards against overlapping history requests bool _historyLoading = false; // Guards against overlapping "grow the window upwards" passes @@ -133,9 +137,19 @@ class _ChatPageState extends State { /// Reload the conversation from the cache when messages or media state change. void _onMessagesChanged() { + // Our own read notifies too (it marks messages read); do not re-enter. + if (_selfRead) { + return; + } _loadMessages(); } + /// Whether the viewport follows the newest message, so a history page landing + /// above it does not leave the view stuck one page up. + /// shortcut: only message and history events re-take the bottom; growth with + /// neither (a voice bubble opening) is not followed. + bool _pinned = true; + /// Whether the viewport sits at the newest message. bool get _atBottom { if (!_scrollController.hasClients) { @@ -147,14 +161,26 @@ class _ChatPageState extends State { /// Load the conversation once per change instead of once per build. Future _loadMessages() async { - if (_loading || !mounted) { + if (_loading) { + // Reading the cache already; the running pass may predate this change. + _reloadRequested = true; + return; + } + if (!mounted) { return; } _loading = true; final first = _firstLoad; final wasAtBottom = _atBottom; try { - final messages = await MessageNotifier().getMessages(widget.user.id); + // The read notifies as a side effect; keep that out of the listener. + final List messages; + _selfRead = true; + try { + messages = await MessageNotifier().getMessages(widget.user.id); + } finally { + _selfRead = false; + } if (!mounted) { return; } @@ -185,17 +211,19 @@ class _ChatPageState extends State { _firstLoad = false; }); if (first || wasAtBottom) { - await WidgetsBinding.instance.endOfFrame; - if (!mounted) { - return; - } - _jumpToBottom(); + await _settleAtBottom(); if (first) { await _jumpToFirstUnread(); } } } finally { _loading = false; + if (_reloadRequested) { + _reloadRequested = false; + if (mounted) { + await _loadMessages(); + } + } } } @@ -223,6 +251,7 @@ class _ChatPageState extends State { if (!_scrollController.hasClients) { return; } + _pinned = true; final target = _scrollController.position.maxScrollExtent; if (animate) { _scrollController.animateTo(target, @@ -237,6 +266,28 @@ class _ChatPageState extends State { } } + /// Takes the bottom over a few frames. + /// + /// The first jump targets an estimate: a lazy list only knows the height of + /// the items it laid out, so the real end sits further down. Jump again until + /// the content stops growing, then leave it alone. + Future _settleAtBottom() async { + for (var pass = 0; pass < 5; pass++) { + if (!_scrollController.hasClients) { + return; + } + final before = _scrollController.position.maxScrollExtent; + _jumpToBottom(); + await WidgetsBinding.instance.endOfFrame; + if (!mounted || !_scrollController.hasClients) { + return; + } + if ((_scrollController.position.maxScrollExtent - before).abs() < 1) { + return; + } + } + } + /// Opens the chat on the first message the user has not read yet. Future _jumpToFirstUnread() async { if (_unreadAnchor == null) { @@ -247,13 +298,19 @@ class _ChatPageState extends State { if (context == null || !context.mounted) { return; } + // The divider is above the newest messages: stop following them. + _pinned = false; await Scrollable.ensureVisible(context, alignment: 0.15, duration: const Duration(milliseconds: 250)); } /// Extend the rendered window when the user scrolls towards older messages. void _onScroll() { - if (_jumping || !_scrollController.hasClients) { + if (!_scrollController.hasClients) { + return; + } + _pinned = _atBottom; + if (_jumping) { return; } final position = _scrollController.position; @@ -349,7 +406,11 @@ class _ChatPageState extends State { return; } final delta = _scrollController.position.maxScrollExtent - before; - if (delta > 0) { + // Older messages land above the viewport: keep what is on screen there, + // unless the user is following the newest message. + if (_pinned) { + await _settleAtBottom(); + } else if (delta > 0) { _scrollController.jumpTo(_scrollController.offset + delta); } } finally { From 4525b1ac709ea43f8d8ff469b197bbbcf73d5d5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Wed, 18 Nov 2026 14:40:03 +0100 Subject: [PATCH 089/181] Commitni a pushni --- lib/pages/chat_page.dart | 156 +++++++++++++++---------------------- lib/utils/chat_scroll.dart | 4 +- test/chat_scroll_test.dart | 6 +- 3 files changed, 69 insertions(+), 97 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index e1af5ea..46d2686 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -144,19 +144,13 @@ class _ChatPageState extends State { _loadMessages(); } - /// Whether the viewport follows the newest message, so a history page landing - /// above it does not leave the view stuck one page up. - /// shortcut: only message and history events re-take the bottom; growth with - /// neither (a voice bubble opening) is not followed. - bool _pinned = true; - - /// Whether the viewport sits at the newest message. + /// Whether the viewport sits at the newest message. The list is reversed, so + /// the newest message is at offset zero and older ones have larger offsets. bool get _atBottom { if (!_scrollController.hasClients) { return true; } - final position = _scrollController.position; - return position.pixels >= position.maxScrollExtent - 40; + return _scrollController.position.pixels <= 40; } /// Load the conversation once per change instead of once per build. @@ -211,7 +205,11 @@ class _ChatPageState extends State { _firstLoad = false; }); if (first || wasAtBottom) { - await _settleAtBottom(); + await WidgetsBinding.instance.endOfFrame; + if (!mounted) { + return; + } + _jumpToBottom(); if (first) { await _jumpToFirstUnread(); } @@ -251,13 +249,12 @@ class _ChatPageState extends State { if (!_scrollController.hasClients) { return; } - _pinned = true; - final target = _scrollController.position.maxScrollExtent; + // Reversed list: the newest message is at offset zero. if (animate) { - _scrollController.animateTo(target, + _scrollController.animateTo(0, duration: const Duration(milliseconds: 250), curve: Curves.easeOut); } else { - _scrollController.jumpTo(target); + _scrollController.jumpTo(0); } if (_unseenCount != 0) { setState(() { @@ -266,18 +263,15 @@ class _ChatPageState extends State { } } - /// Takes the bottom over a few frames. - /// - /// The first jump targets an estimate: a lazy list only knows the height of - /// the items it laid out, so the real end sits further down. Jump again until - /// the content stops growing, then leave it alone. - Future _settleAtBottom() async { + /// Takes the oldest end over a few frames: the first jump only reaches the + /// estimated extent, and the list lays out the real end further on. + Future _settleAtOldest() async { for (var pass = 0; pass < 5; pass++) { if (!_scrollController.hasClients) { return; } final before = _scrollController.position.maxScrollExtent; - _jumpToBottom(); + _scrollController.jumpTo(before); await WidgetsBinding.instance.endOfFrame; if (!mounted || !_scrollController.hasClients) { return; @@ -298,29 +292,23 @@ class _ChatPageState extends State { if (context == null || !context.mounted) { return; } - // The divider is above the newest messages: stop following them. - _pinned = false; await Scrollable.ensureVisible(context, alignment: 0.15, duration: const Duration(milliseconds: 250)); } /// Extend the rendered window when the user scrolls towards older messages. void _onScroll() { - if (!_scrollController.hasClients) { - return; - } - _pinned = _atBottom; - if (_jumping) { + if (_jumping || !_scrollController.hasClients) { return; } final position = _scrollController.position; - if (position.pixels >= position.maxScrollExtent - 40 && _unseenCount != 0) { + if (_atBottom && _unseenCount != 0) { setState(() { _unseenCount = 0; }); } - // Older messages are above: the window grows near the top of the list. - if (position.pixels > 200) { + // Reversed list: older messages are at the far end of the scroll extent. + if (position.pixels < position.maxScrollExtent - 200) { return; } if (_visibleCount < _messages.length) { @@ -332,28 +320,18 @@ class _ChatPageState extends State { } /// Renders more messages above the viewport without moving what is on screen. + /// + /// The list is reversed, so the extra messages are appended past the current + /// end of the scroll extent and the viewport does not need any compensation. Future _growWindow(int by) async { if (_growing || !mounted) { return; } _growing = true; - final before = _scrollController.hasClients - ? _scrollController.position.maxScrollExtent - : 0.0; setState(() { _visibleCount += by; }); await WidgetsBinding.instance.endOfFrame; - if (!mounted) { - _growing = false; - return; - } - if (_scrollController.hasClients) { - final delta = _scrollController.position.maxScrollExtent - before; - if (delta > 0) { - _scrollController.jumpTo(_scrollController.offset + delta); - } - } _growing = false; } @@ -373,9 +351,6 @@ class _ChatPageState extends State { return; } _historyLoading = true; - final before = _scrollController.hasClients - ? _scrollController.position.maxScrollExtent - : 0.0; try { final page = await utils.Utils.callApi( () => Singleton().messagesApi.getHistory(widget.user.id, @@ -398,21 +373,11 @@ class _ChatPageState extends State { return; } // Show the page that just arrived without making the user scroll again. + // Reversed list: the page is appended past the current end, so the + // viewport stays where the user left it. setState(() { _visibleCount += page.messages.length; }); - await WidgetsBinding.instance.endOfFrame; - if (!mounted || !_scrollController.hasClients) { - return; - } - final delta = _scrollController.position.maxScrollExtent - before; - // Older messages land above the viewport: keep what is on screen there, - // unless the user is following the newest message. - if (_pinned) { - await _settleAtBottom(); - } else if (delta > 0) { - _scrollController.jumpTo(_scrollController.offset + delta); - } } finally { _historyLoading = false; } @@ -550,9 +515,9 @@ class _ChatPageState extends State { /// Widening the rendered window is not enough: a list only builds what is /// near the viewport, so growing the tail never builds an old message. The /// fast path therefore cuts the window down to the target, which puts it one - /// screen from the top, and `jumpTo(0)` lands on it. The slow path walks up a - /// viewport at a time for a target already inside a large window but far - /// below the screen. + /// screen from the oldest end, and jumping to that end lands on it. The slow + /// path walks a viewport at a time towards older messages for a target + /// already inside a large window but far from the screen. Future _jumpToMessage(DateTime sentAt) async { final micros = sentAt.microsecondsSinceEpoch; _jumping = true; @@ -570,8 +535,8 @@ class _ChatPageState extends State { if (!mounted || !_scrollController.hasClients) { return; } - _scrollController.jumpTo(0); - await WidgetsBinding.instance.endOfFrame; + // Reversed list: the target sits at the far end of the window. + await _settleAtOldest(); if (!mounted) { return; } @@ -1282,20 +1247,41 @@ class _ChatPageState extends State { } final orderedDays = days.keys.toList()..sort(); + // The scroll view is reversed: the first sliver is painted at the bottom + // of the screen, so the days and their messages go newest first. Offset + // zero is the newest message, which is why opening the chat needs no jump + // and older pages cannot move what the user is reading. return CustomScrollView( controller: _scrollController, + reverse: true, physics: const BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics(), ), slivers: [ - // The body sits behind the translucent app bar, so the conversation - // has to start below it: without this the avatar header and the first - // day separator are painted under the bar. - SliverToBoxAdapter( - child: SizedBox( - height: MediaQuery.viewPaddingOf(context).top + kToolbarHeight, + for (final day in orderedDays.reversed) ...[ + SliverList.builder( + itemCount: days[day]!.length, + itemBuilder: (context, index) { + final position = days[day]![days[day]!.length - 1 - index]; + final message = visible[position]; + return _buildBubble( + message, + position > 0 ? visible[position - 1] : null, + position < visible.length - 1 ? visible[position + 1] : null, + ); + }, ), - ), + SliverPersistentHeader( + // A pinned header would stick to the bottom edge in a reversed + // view, so day separators scroll with their messages instead. + pinned: false, + delegate: _DayHeader( + label: _dayLabel(day), + textColor: Theme.of(context).colorScheme.onSurfaceVariant, + background: chatBackground(tintAlpha: 0.35), + ), + ), + ], SliverToBoxAdapter( child: hasOlder ? const Padding( @@ -1310,28 +1296,14 @@ class _ChatPageState extends State { ) : _buildHeader(), ), - for (final day in orderedDays) ...[ - SliverPersistentHeader( - pinned: true, - delegate: _DayHeader( - label: _dayLabel(day), - textColor: Theme.of(context).colorScheme.onSurfaceVariant, - background: chatBackground(tintAlpha: 0.35), - ), - ), - SliverList.builder( - itemCount: days[day]!.length, - itemBuilder: (context, index) { - final position = days[day]![index]; - final message = visible[position]; - return _buildBubble( - message, - position > 0 ? visible[position - 1] : null, - position < visible.length - 1 ? visible[position + 1] : null, - ); - }, + // The body sits behind the translucent app bar, so the conversation + // has to start below it: without this the avatar header and the first + // day separator are painted under the bar. + SliverToBoxAdapter( + child: SizedBox( + height: MediaQuery.viewPaddingOf(context).top + kToolbarHeight, ), - ], + ), ], ); } diff --git a/lib/utils/chat_scroll.dart b/lib/utils/chat_scroll.dart index 07d828f..d4faa2d 100644 --- a/lib/utils/chat_scroll.dart +++ b/lib/utils/chat_scroll.dart @@ -12,8 +12,8 @@ int windowForAddition(int messageCount, int index, {int margin = 5}) { return needed > messageCount ? messageCount : needed; } -/// Next scroll offset while walking up the list towards a message that is not -/// built yet: one viewport at a time, never below the top. +/// Next scroll offset while walking back towards newer messages that are not +/// built yet: one viewport at a time, never past the newest message. double nextJumpOffset(double pixels, double viewport) { final next = pixels - viewport; if (next < 0) { diff --git a/test/chat_scroll_test.dart b/test/chat_scroll_test.dart index d8c3112..3106b9a 100644 --- a/test/chat_scroll_test.dart +++ b/test/chat_scroll_test.dart @@ -22,15 +22,15 @@ void main() { }); group('nextJumpOffset', () { - test('moves one viewport up', () { + test('moves one viewport towards newer messages', () { expect(nextJumpOffset(1000, 600), 400); }); - test('stops at the top instead of going negative', () { + test('stops at the newest message instead of going negative', () { expect(nextJumpOffset(200, 600), 0); }); - test('returns the same offset when already at the top', () { + test('returns the same offset when already at the newest message', () { expect(nextJumpOffset(0, 600), 0); }); }); From ad9bace54f10d417ab9e12934aeabced6a37eab5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Wed, 18 Nov 2026 18:01:03 +0100 Subject: [PATCH 090/181] feat(chat): delete a chat or a message for the whole account Deleting a chat used to wipe the device only, and the server, which never heard about it, handed the conversation back with the next archive page. - deleteChat calls the server first and wipes locally only on success, so a failed call no longer hides a chat that still exists. - The cut comes back as clearedAt and is stored per conversation; opening the chat on another device drops what is older. - Messages carry the archive id (Hive field 19) so a delete can name them. - Own message: "delete for everyone" (ciphertext erased, tombstone left) or "delete for me"; the peer's message only "delete for me". - A tombstone in a page removes the local copy instead of storing an undecryptable placeholder. --- assets/translations/cs.json | 7 ++- assets/translations/en.json | 7 ++- lib/models/private_message.dart | 6 +++ lib/models/private_message.g.dart | 8 +-- lib/pages/chat_info_page.dart | 13 ++++- lib/pages/chat_page.dart | 7 +++ lib/pages/home_page.dart | 7 ++- lib/utils/cache_utils.dart | 56 ++++++++++++++++++++ lib/utils/message_actions.dart | 69 ++++++++++++++++++++++--- lib/utils/message_notifier.dart | 17 +++++- lib/utils/utils.dart | 25 ++++++--- pubspec.lock | 16 +++--- test/attachment_confirm_sheet_test.dart | 3 +- test/media_album_test.dart | 16 +++--- test/token_expiry_test.dart | 21 ++++---- 15 files changed, 229 insertions(+), 49 deletions(-) diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 0ed9858..62eb13a 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -131,8 +131,13 @@ "forwardMessage": "Přeposlat", "saveAttachment": "Uložit přílohu", "deleteMessageForMe": "Smazat pro mě", + "deleteMessageForEveryone": "Smazat pro všechny", "deleteMessageConfirm": "Smazat zprávu", - "deleteMessageConfirmText": "Zpráva se smaže jen z tohoto zařízení. Druhá strana si ji nechá.", + "deleteMessageConfirmText": "Zpráva se smaže ze všech tvých zařízení. Druhá strana si ji nechá.", + "deleteMessageForEveryoneConfirm": "Smazat pro všechny", + "deleteMessageForEveryoneConfirmText": "Zpráva se smaže na serveru a druhá strana o ni přijde. Co už měla stažené, jí zůstane.", + "deleteMessageForEveryoneFailed": "Pro všechny lze smazat jen zprávu, která je v archivu", + "deleteChatFailed": "Smazání chatu se nepovedlo", "copiedText": "Zkopírováno", "attachmentSaved": "Příloha uložena", "attachmentSaveFailed": "Uložení přílohy se nepovedlo", diff --git a/assets/translations/en.json b/assets/translations/en.json index aae946a..6f46293 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -131,8 +131,13 @@ "forwardMessage": "Forward", "saveAttachment": "Save attachment", "deleteMessageForMe": "Delete for me", + "deleteMessageForEveryone": "Delete for everyone", "deleteMessageConfirm": "Delete message", - "deleteMessageConfirmText": "The message will be deleted only from this device. The other side keeps it.", + "deleteMessageConfirmText": "The message will be deleted from all your devices. The other side keeps it.", + "deleteMessageForEveryoneConfirm": "Delete for everyone", + "deleteMessageForEveryoneConfirmText": "The message will be erased on the server and the other side loses it. Anything they already downloaded stays with them.", + "deleteMessageForEveryoneFailed": "Only an archived message can be deleted for everyone", + "deleteChatFailed": "Deleting the chat failed", "copiedText": "Copied", "attachmentSaved": "Attachment saved", "attachmentSaveFailed": "Saving the attachment failed", diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index 8d091bf..ec58aa6 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -176,6 +176,12 @@ class PrivateMessage extends HiveObject { @HiveField(18) String? replyToPreview; + /// Archive id from the server, null for a message this device only ever sent + /// and for rows stored before the id was kept. Deleting on the server needs + /// it. + @HiveField(19) + String? id; + /// Cache for [album], keyed by the [albumJson] it was decoded from. String? _albumCacheJson; List? _albumCache; diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index a8cc2a3..44bbb4d 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -36,13 +36,13 @@ class PrivateMessageAdapter extends TypeAdapter { replyToSenderId: fields[16] as String?, replyToSentAt: fields[17] as DateTime?, replyToPreview: fields[18] as String?, - ); + )..id = fields[19] as String?; } @override void write(BinaryWriter writer, PrivateMessage obj) { writer - ..writeByte(19) + ..writeByte(20) ..writeByte(0) ..write(obj.senderId) ..writeByte(1) @@ -80,7 +80,9 @@ class PrivateMessageAdapter extends TypeAdapter { ..writeByte(17) ..write(obj.replyToSentAt) ..writeByte(18) - ..write(obj.replyToPreview); + ..write(obj.replyToPreview) + ..writeByte(19) + ..write(obj.id); } @override diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index a18c31c..7f9a7a5 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -1,6 +1,7 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; import '../utils/nav_transitions.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; @@ -231,7 +232,17 @@ class _ChatInfoPageState extends State { context, 'deleteChatConfirm'.tr(), 'deleteChatConfirmText'.tr(), () async { - MessageNotifier().deleteChat(widget.userId); + final deleted = + await MessageNotifier().deleteChat(widget.userId); + if (!deleted) { + Fluttertoast.showToast( + msg: 'deleteChatFailed'.tr(), + backgroundColor: Colors.red); + return; + } + if (!context.mounted) { + return; + } // Redirect to home page and clear navigation stack Navigator.pushAndRemoveUntil( context, diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 46d2686..1f78f7d 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -361,6 +361,13 @@ class _ChatPageState extends State { } _historyLoaded = true; _historyCursor = page.nextCursor; + // The account may have cleared this chat on another device: drop what + // this one still holds before the page is written back. + if (page.clearedAt != null) { + await CacheUtils.applyConversationClearedAt( + widget.user.id, page.clearedAt!.toLocal()); + MessageNotifier().notify(); + } for (final peer in page.peers) { await CacheUtils.addUser( User(peer.id, peer.username, peer.publicKey, peer.admin)); diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 5951ed3..15307b3 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -229,7 +229,12 @@ class _HomePageState extends State DialogUtils.yesNoDialog( context, 'deleteChatConfirm'.tr(), 'deleteChatConfirmText'.tr(), () async { - await MessageNotifier().deleteChat(user.id); + final deleted = await MessageNotifier().deleteChat(user.id); + if (!deleted) { + Fluttertoast.showToast( + msg: 'deleteChatFailed'.tr(), backgroundColor: Colors.red); + } + await _getConversations(); }); } diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index c8ff56e..d9575b9 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -482,6 +482,23 @@ class CacheUtils { } } + /// Deletes one stored message by its timestamp. Used for a server tombstone: + /// the other side deleted the message for everyone. + static Future deletePrivateMessageAt( + String userId, DateTime sentAt) async { + final box = await _openPrivateMessagesBox(); + await _migrateLegacyConversation(box, userId); + final key = messageKey(userId, sentAt); + final value = box.get(key); + if (value is PrivateMessage) { + for (final path in value.localPaths) { + await MediaUtils.deleteLocalFile(path); + } + } + await _deletePendingSend(userId, sentAt); + await box.delete(key); + } + /// Delete user messages static Future deletePrivateMessagesWithUser(String userId) async { Box messageBox = await _openPrivateMessagesBox(); @@ -753,6 +770,45 @@ class CacheUtils { } } + /// Instant up to which the account deleted this conversation, null when it + /// never did. Everything at or before it is gone for good. + static Future conversationClearedAt(String userId) async { + final box = await _openConversationsBox(); + final raw = _metaOf(box, userId)['clearedAt']; + return raw is int ? DateTime.fromMillisecondsSinceEpoch(raw) : null; + } + + /// Remembers the server's cut and drops what this device still holds of it. + /// The later of the two instants wins, so a stale page cannot undo a delete. + static Future applyConversationClearedAt( + String userId, DateTime clearedAt) async { + final box = await _openConversationsBox(); + final stored = await conversationClearedAt(userId); + final cut = + stored != null && stored.isAfter(clearedAt) ? stored : clearedAt; + final meta = _metaOf(box, userId); + meta['clearedAt'] = cut.millisecondsSinceEpoch; + await box.put(userId, meta); + await purgeConversationUpTo(userId, cut); + } + + /// Deletes the stored messages sent at or before [cut], media included. + static Future purgeConversationUpTo(String userId, DateTime cut) async { + final box = await _openPrivateMessagesBox(); + await _migrateLegacyConversation(box, userId); + for (final key in _conversationKeys(box, userId).toList()) { + final value = box.get(key); + if (value is! PrivateMessage || value.sentAt.isAfter(cut)) { + continue; + } + for (final path in value.localPaths) { + await MediaUtils.deleteLocalFile(path); + } + await _deletePendingSend(userId, value.sentAt); + await box.delete(key); + } + } + /// Ids of the pinned conversations. static Future> getPinnedConversations() async { final box = await _openConversationsBox(); diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index af387fb..05c84b6 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -11,6 +11,8 @@ import 'chat_sender.dart'; import 'dialog_utils.dart'; import 'media_utils.dart'; import 'message_notifier.dart'; +import 'singleton.dart'; +import 'utils.dart'; import '../utils/nav_transitions.dart'; /// Actions for a single message, offered by the bubble long-press sheet and by @@ -75,6 +77,16 @@ class MessageActions { save(message); }, ), + if (message.isMe && (message.id?.isNotEmpty ?? false)) + ListTile( + leading: const Icon(deleteIcon), + title: Text('deleteMessageForEveryone'.tr()), + onTap: () { + Navigator.pop(ctx); + deleteForEveryone(context, message, conversationUserId, + onDeleted: onDeleted); + }, + ), ListTile( leading: const Icon(deleteIcon), title: Text('deleteMessageForMe'.tr()), @@ -128,16 +140,59 @@ class MessageActions { await Navigator.of(context).push(stepRoute(ForwardPage(messages))); } - /// Delete the message only on this device, after a confirmation. + /// Delete the message for this account on every device, after a + /// confirmation. The other side keeps its copy. static void delete( BuildContext context, PrivateMessage message, String conversationUserId, {VoidCallback? onDeleted}) { DialogUtils.yesNoDialog( - context, 'deleteMessageConfirm'.tr(), 'deleteMessageConfirmText'.tr(), - () async { - await CacheUtils.deletePrivateMessage(conversationUserId, message); - MessageNotifier().notify(); - onDeleted?.call(); - }); + context, + 'deleteMessageConfirm'.tr(), + 'deleteMessageConfirmText'.tr(), + () => _delete(context, message, conversationUserId, + forEveryone: false, onDeleted: onDeleted)); + } + + /// Delete an own message for everyone, after a confirmation: the server + /// erases the ciphertext, so the other side loses it from the archive. + static void deleteForEveryone( + BuildContext context, PrivateMessage message, String conversationUserId, + {VoidCallback? onDeleted}) { + DialogUtils.yesNoDialog( + context, + 'deleteMessageForEveryoneConfirm'.tr(), + 'deleteMessageForEveryoneConfirmText'.tr(), + () => _delete(context, message, conversationUserId, + forEveryone: true, onDeleted: onDeleted)); + } + + /// Removes [message] on the server first, then locally. A failed server call + /// leaves the message alone: a local delete on its own would come back with + /// the next history page. + static Future _delete( + BuildContext context, PrivateMessage message, String conversationUserId, + {required bool forEveryone, VoidCallback? onDeleted}) async { + // A message that never reached the archive has nothing to delete on the + // server; only this device holds it. + final id = message.id; + if (id != null && id.isNotEmpty) { + try { + await Utils.callApi( + () => forEveryone + ? Singleton().messagesApi.deleteMessage(id) + : Singleton().messagesApi.hideMessage(id), + rethrowErr: true); + } catch (_) { + return; + } + } else if (forEveryone) { + await Fluttertoast.showToast( + msg: 'deleteMessageForEveryoneFailed'.tr(), + backgroundColor: Colors.red); + return; + } + await CacheUtils.deletePrivateMessage(conversationUserId, message); + MessageNotifier().notify(); + onDeleted?.call(); } } diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index 709a918..f601b02 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -221,9 +221,24 @@ class MessageNotifier extends ChangeNotifier { } /// Delete chat by user ID - Future deleteChat(String userId) async { + /// Deletes the conversation for this account on every device: the server + /// stops returning it, then this device drops what it holds. A failed call + /// leaves everything in place, because a local wipe alone would come back + /// with the next archive page. + /// + /// @return bool whether the server confirmed the delete + Future deleteChat(String userId) async { + final cleared = await Utils.callApi( + () => Singleton().messagesApi.clearConversation(userId), + showError: true); + final cut = cleared?.clearedAt; + if (cut == null) { + return false; + } await CacheUtils.deletePrivateMessagesWithUser(userId); + await CacheUtils.applyConversationClearedAt(userId, cut.toLocal()); notifyListeners(); + return true; } void notify() { diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 36a0d96..c2e00de 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -429,15 +429,19 @@ class Utils { // an archived message we sent has our own id as the sender. final byPeer = >{}; final peerOfMessage = {}; + final idOfMessage = {}; for (final message in messages) { - peerOfMessage[ - '${message.senderId}|${message.sentAt.toUtc().toIso8601String()}'] = - message.peerId; + final key = + '${message.senderId}|${message.sentAt.toUtc().toIso8601String()}'; + peerOfMessage[key] = message.peerId; + idOfMessage[key] = message.id; } for (final message in decryptedMessages) { - final peer = peerOfMessage[ - '${message.senderId}|${message.sentAt.toUtc().toIso8601String()}'] ?? - message.senderId; + final key = + '${message.senderId}|${message.sentAt.toUtc().toIso8601String()}'; + // The archive id is what a delete on the server needs. + message.id ??= idOfMessage[key]; + final peer = peerOfMessage[key] ?? message.senderId; byPeer.putIfAbsent(peer, () => []).add(message); } for (final entry in byPeer.entries) { @@ -559,6 +563,15 @@ class Utils { if (messages.isEmpty) { return; } + // A tombstone carries no ciphertext (the sender deleted it for everyone): + // drop the local copy instead of storing an undecryptable placeholder. + for (final dead in messages.where((message) => message.deletedAt != null)) { + await CacheUtils.deletePrivateMessageAt(dead.peerId, dead.sentAt); + } + messages = messages.where((message) => message.deletedAt == null).toList(); + if (messages.isEmpty) { + return; + } final wire = messages .map((message) => PrivateMessage.fromJson({ 'id': message.id, diff --git a/pubspec.lock b/pubspec.lock index f81726e..30987dc 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1780,20 +1780,16 @@ packages: whisper_openapi_client_dart: dependency: "direct main" description: - path: "." - ref: "v0.1.0" - resolved-ref: "6e97e025fa4408ae0b93c90ce500b4d83b1694e1" - url: "https://github.com/jsfraz/whisper_openapi_client_dart.git" - source: git + path: "../whisper_openapi_client_dart" + relative: true + source: path version: "0.1.0" whisper_websocket_client_dart: dependency: "direct main" description: - path: "." - ref: "v0.1.0" - resolved-ref: e590c319d5074442ae4a5ee7d0891a4bf358982f - url: "https://github.com/jsfraz/whisper_websocket_client_dart.git" - source: git + path: "../whisper_websocket_client_dart" + relative: true + source: path version: "0.1.0" win32: dependency: transitive diff --git a/test/attachment_confirm_sheet_test.dart b/test/attachment_confirm_sheet_test.dart index 191bd01..45b3d02 100644 --- a/test/attachment_confirm_sheet_test.dart +++ b/test/attachment_confirm_sheet_test.dart @@ -13,7 +13,8 @@ void main() { await EasyLocalization.ensureInitialized(); }); - testWidgets('cancel returns null and send returns the caption', (tester) async { + testWidgets('cancel returns null and send returns the caption', + (tester) async { String? result = 'unset'; await tester.pumpWidget(EasyLocalization( path: 'assets/translations', diff --git a/test/media_album_test.dart b/test/media_album_test.dart index db6f823..2d04f0e 100644 --- a/test/media_album_test.dart +++ b/test/media_album_test.dart @@ -76,8 +76,8 @@ void main() { group('album items', () { test('serialize and deserialize', () { - final message = PrivateMessage('1', 'cap', DateTime(2026), DateTime(2026), - true); + final message = + PrivateMessage('1', 'cap', DateTime(2026), DateTime(2026), true); message.setAlbum([ AlbumItem( mediaId: 'a', @@ -110,8 +110,8 @@ void main() { }); test('expands into one entry per attachment for the viewer', () { - final message = PrivateMessage('1', 'cap', DateTime(2026), DateTime(2026), - true); + final message = + PrivateMessage('1', 'cap', DateTime(2026), DateTime(2026), true); message.setAlbum([ AlbumItem( mediaId: 'a', @@ -153,8 +153,8 @@ void main() { }); test('updating one album attachment keeps the others untouched', () async { - final message = PrivateMessage('1', 'cap', DateTime(2026, 1, 1), - DateTime(2026, 1, 1), true, + final message = PrivateMessage( + '1', 'cap', DateTime(2026, 1, 1), DateTime(2026, 1, 1), true, downloadStatus: MediaDownloadStatus.pending); message.setAlbum([ AlbumItem( @@ -189,8 +189,8 @@ void main() { }); test('send status is stored on the message', () async { - final message = PrivateMessage('1', 'hi', DateTime(2026, 2, 1), - DateTime(2026, 2, 1), true, + final message = PrivateMessage( + '1', 'hi', DateTime(2026, 2, 1), DateTime(2026, 2, 1), true, sendStatus: SendStatus.sending); await CacheUtils.addPrivateMessages('1', [message]); await CacheUtils.updateStoredMessage('1', message, (stored) { diff --git a/test/token_expiry_test.dart b/test/token_expiry_test.dart index d447053..41e7212 100644 --- a/test/token_expiry_test.dart +++ b/test/token_expiry_test.dart @@ -6,7 +6,10 @@ import 'package:whisper/utils/utils.dart'; String _token(Map payload) { String encode(Map value) => base64Url.encode(utf8.encode(jsonEncode(value))).replaceAll('=', ''); - return '${encode({'alg': 'HS256', 'typ': 'JWT'})}.${encode(payload)}.signature'; + return '${encode({ + 'alg': 'HS256', + 'typ': 'JWT' + })}.${encode(payload)}.signature'; } void main() { @@ -15,8 +18,8 @@ void main() { final expired = _token({ 'sub': 'user', 'exp': DateTime.now() - .subtract(const Duration(minutes: 1)) - .millisecondsSinceEpoch ~/ + .subtract(const Duration(minutes: 1)) + .millisecondsSinceEpoch ~/ 1000, }); expect(Utils.isTokenExpired(expired), isTrue); @@ -26,8 +29,8 @@ void main() { final live = _token({ 'sub': 'user', 'exp': DateTime.now() - .add(const Duration(minutes: 5)) - .millisecondsSinceEpoch ~/ + .add(const Duration(minutes: 5)) + .millisecondsSinceEpoch ~/ 1000, }); expect(Utils.isTokenExpired(live), isFalse); @@ -39,8 +42,8 @@ void main() { final legacy = _token({ 'sub': 'user', 'exp': DateTime.now() - .add(const Duration(minutes: 5)) - .millisecondsSinceEpoch ~/ + .add(const Duration(minutes: 5)) + .millisecondsSinceEpoch ~/ 1000, }); expect(Utils.isTokenExpired(legacy), isFalse); @@ -52,8 +55,8 @@ void main() { 'sub': 'user', 'typ': 'access', 'exp': DateTime.now() - .add(const Duration(minutes: 5)) - .millisecondsSinceEpoch ~/ + .add(const Duration(minutes: 5)) + .millisecondsSinceEpoch ~/ 1000, }); expect(Utils.isTokenUsable(typed), isTrue); From 668dd65cffe629d965400762b583f8a874e9b1f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Wed, 18 Nov 2026 18:21:34 +0100 Subject: [PATCH 091/181] fix(chat): delete an own message right after sending The delivery ack carries the archive id and seq, but only the receiver id and timestamp were kept, so a just-sent bubble had no id until the next sync brought one. "Delete for everyone" is offered only for a message that has an id, which left the fresh message with the local-only delete. - confirmSent/markMessageSent take the acked id and store it. - In the debug self-chat the peer is you, so "for everyone" would mean the same as "for me"; it is hidden there. --- lib/utils/cache_utils.dart | 7 +++++-- lib/utils/chat_sender.dart | 5 +++-- lib/utils/message_actions.dart | 6 +++++- lib/utils/utils.dart | 2 +- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index d9575b9..eb4ea02 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -654,8 +654,8 @@ class CacheUtils { /// /// [receiverId] and [sentAt] are the values the server echoes back; the pair /// identifies the stored message without keeping a client message id. - static Future markMessageSent( - String receiverId, DateTime sentAt) async { + static Future markMessageSent(String receiverId, DateTime sentAt, + {String? id}) async { Box box = await _openPrivateMessagesBox(); await _migrateLegacyConversation(box, receiverId); final key = messageKey(receiverId, sentAt); @@ -664,6 +664,9 @@ class CacheUtils { return; } stored.sendStatus = SendStatus.sent; + // The ack carries the archive id: without it the bubble could only be + // deleted for this device until the next sync handed the id over. + stored.id ??= id; await box.put(key, stored); await _deletePendingSend(receiverId, sentAt); } diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index c56a17f..baee615 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -316,8 +316,9 @@ class ChatSender { } /// Mark a message as sent after the server acknowledged it. - static Future confirmSent(String receiverId, DateTime sentAt) async { - await CacheUtils.markMessageSent(receiverId, sentAt); + static Future confirmSent(String receiverId, DateTime sentAt, + {String? id}) async { + await CacheUtils.markMessageSent(receiverId, sentAt, id: id); _outgoingReferences.remove(CacheUtils.messageKey(receiverId, sentAt)); MessageNotifier().notify(); } diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 05c84b6..b1c5727 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -77,7 +77,11 @@ class MessageActions { save(message); }, ), - if (message.isMe && (message.id?.isNotEmpty ?? false)) + // In the debug self-chat the other side is you, so "for + // everyone" would mean exactly the same as "for me". + if (message.isMe && + conversationUserId != Singleton().profile.user.id && + (message.id?.isNotEmpty ?? false)) ListTile( leading: const Icon(deleteIcon), title: Text('deleteMessageForEveryone'.tr()), diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index c2e00de..88fc462 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -542,7 +542,7 @@ class Utils { // Delivery acknowledgement of one of our outgoing messages case WsResponseType.ack: final ack = wsResponse.payload as DeliveryAck; - await ChatSender.confirmSent(ack.receiverId, ack.sentAt); + await ChatSender.confirmSent(ack.receiverId, ack.sentAt, id: ack.id); break; // Error From 69bd1745750ae6586c12875dd2f33aa243651af0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 19 Nov 2026 17:44:27 +0100 Subject: [PATCH 092/181] feat(chat): edit, react and pin messages Long-press now opens the action sheet (multi-select moved into it), which carries a reaction row, an edit dialog for own text messages and a shared pin. Edits, deletions, reactions and pins arrive as live frames and are replayed by sync behind a second cursor, cleared chats empty a device that was offline, and an unknown frame type is ignored instead of erroring. Clients are pinned to v0.2.0 of the regenerated contract. --- assets/translations/cs.json | 9 +- assets/translations/en.json | 9 +- integration_test/app_e2e_test.dart | 8 +- lib/models/private_message.dart | 18 +++ lib/models/private_message.g.dart | 10 +- lib/pages/chat_info_page.dart | 73 +++++++++++ lib/pages/chat_page.dart | 105 +++++++++++++++ lib/utils/cache_utils.dart | 114 ++++++++++++++++ lib/utils/message_actions.dart | 203 ++++++++++++++++++++++++++++- lib/utils/utils.dart | 136 +++++++++++++++++-- lib/utils/version.dart | 2 +- lib/widgets/chat_bubble.dart | 54 +++++++- pubspec.lock | 4 +- pubspec.yaml | 6 +- test/message_actions_test.dart | 25 ++++ test/message_lifecycle_test.dart | 98 ++++++++++++++ 16 files changed, 850 insertions(+), 24 deletions(-) create mode 100644 test/message_lifecycle_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 62eb13a..fd6f886 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -241,5 +241,12 @@ "invalidRetention": "Nepodporovaná hodnota retence.", "invalidCursor": "Neplatný požadavek na historii.", "confirm": "Potvrdit", - "newLoginTitle": "Nové přihlášení" + "newLoginTitle": "Nové přihlášení", + "editMessage": "Upravit zprávu", + "pinMessage": "Připnout", + "unpinMessage": "Odepnout", + "selectMessage": "Vybrat", + "messageEdited": "upraveno", + "pinnedMessages": "Připnuté zprávy", + "noPinnedMessages": "Zatím žádná připnutá zpráva" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 6f46293..a461a7e 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -241,5 +241,12 @@ "invalidRetention": "Unsupported retention value.", "invalidCursor": "The history request was invalid.", "confirm": "Confirm", - "newLoginTitle": "New login" + "newLoginTitle": "New login", + "editMessage": "Edit message", + "pinMessage": "Pin", + "unpinMessage": "Unpin", + "selectMessage": "Select", + "messageEdited": "edited", + "pinnedMessages": "Pinned messages", + "noPinnedMessages": "No pinned messages yet" } diff --git a/integration_test/app_e2e_test.dart b/integration_test/app_e2e_test.dart index fad9c39..a42199b 100644 --- a/integration_test/app_e2e_test.dart +++ b/integration_test/app_e2e_test.dart @@ -124,10 +124,10 @@ void main() { expect(message.senderId, '2'); final plaintext = await CryptoUtils.decryptMessageData( - message.content, - message.key, - message.nonce, - message.mac, + message.content!, + message.key!, + message.nonce!, + message.mac!, keys.privateKey as RSAPrivateKey, ); expect(utf8.decode(plaintext), 'hello over websocket'); diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index ec58aa6..8041d35 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -182,6 +182,15 @@ class PrivateMessage extends HiveObject { @HiveField(19) String? id; + /// Instant the sender last edited the text, null when it was never edited. + @HiveField(20) + DateTime? editedAt; + + /// Emoji reaction of each participant, keyed by user id. Null when nobody + /// reacted. + @HiveField(21) + Map? reactions; + /// Cache for [album], keyed by the [albumJson] it was decoded from. String? _albumCacheJson; List? _albumCache; @@ -206,8 +215,17 @@ class PrivateMessage extends HiveObject { this.replyToSenderId, this.replyToSentAt, this.replyToPreview, + this.editedAt, + this.reactions, }); + /// Whether the sender edited the text after sending it. + bool get isEdited => editedAt != null; + + /// Distinct reaction emoji, sorted so the chips do not jump around. + List get reactionEmojis => + (reactions?.values.toSet().toList() ?? [])..sort(); + /// The quoted message, or null when this message is not a reply. ReplyRef? get replyTo { final senderId = replyToSenderId; diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index 44bbb4d..b42740a 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -36,13 +36,15 @@ class PrivateMessageAdapter extends TypeAdapter { replyToSenderId: fields[16] as String?, replyToSentAt: fields[17] as DateTime?, replyToPreview: fields[18] as String?, + editedAt: fields[20] as DateTime?, + reactions: (fields[21] as Map?)?.cast(), )..id = fields[19] as String?; } @override void write(BinaryWriter writer, PrivateMessage obj) { writer - ..writeByte(20) + ..writeByte(22) ..writeByte(0) ..write(obj.senderId) ..writeByte(1) @@ -82,7 +84,11 @@ class PrivateMessageAdapter extends TypeAdapter { ..writeByte(18) ..write(obj.replyToPreview) ..writeByte(19) - ..write(obj.id); + ..write(obj.id) + ..writeByte(20) + ..write(obj.editedAt) + ..writeByte(21) + ..write(obj.reactions); } @override diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 7f9a7a5..d1caade 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -6,6 +6,7 @@ import '../utils/nav_transitions.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../utils/cache_utils.dart'; +import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; import '../utils/dialog_utils.dart'; import '../utils/media_utils.dart'; @@ -28,12 +29,72 @@ class ChatInfoPage extends StatefulWidget { class _ChatInfoPageState extends State { Color? _chatThemeColor; List _media = []; + Map _pins = {}; @override void initState() { super.initState(); _loadChatTheme(); _loadMedia(); + _loadPins(); + } + + Future _loadPins() async { + final pins = await CacheUtils.getPinnedMessages(widget.userId); + if (mounted) { + setState(() { + _pins = pins; + }); + } + } + + /// Pinned messages of this chat, newest pin first, with an unpin per row. + Future _openPinned() async { + final messages = await CacheUtils.getPrivateMessages(widget.userId); + final pins = await CacheUtils.getPinnedMessages(widget.userId); + final pinned = messages + .where((message) => message.id != null && pins.containsKey(message.id)) + .toList() + ..sort((a, b) => pins[b.id]!.compareTo(pins[a.id]!)); + if (!mounted) { + return; + } + await showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (ctx) => SafeArea( + child: ListView( + shrinkWrap: true, + children: [ + if (pinned.isEmpty) ListTile(title: Text('noPinnedMessages'.tr())), + for (final message in pinned) + ListTile( + leading: const Icon(Icons.push_pin), + title: Text( + message.preview.isEmpty ? 'mediaPhoto'.tr() : message.preview, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + subtitle: Text(DateFormat.yMMMd() + .add_Hm() + .format(message.sentAt.toLocal())), + trailing: IconButton( + icon: const Icon(Icons.close), + tooltip: 'unpinMessage'.tr(), + onPressed: () async { + await MessageActions.togglePin(message, widget.userId, + pinned: true); + if (ctx.mounted) { + Navigator.pop(ctx); + } + await _loadPins(); + }, + ), + ), + ], + ), + ), + ); } Future _loadChatTheme() async { @@ -155,6 +216,18 @@ class _ChatInfoPageState extends State { label: 'jumpToDate'.tr(), onPressed: _jumpToDate, ), + // Pinned messages, shared with the other participant + SettingsTile( + icon: Icons.push_pin, + label: 'pinnedMessages'.tr(), + onPressed: _openPinned, + extra: _pins.isEmpty + ? null + : Padding( + padding: const EdgeInsets.only(left: 10), + child: Text('${_pins.length}'), + ), + ), // Chat theme SettingsTile( icon: Icons.palette, diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 1f78f7d..7fc54c0 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -93,6 +93,9 @@ class _ChatPageState extends State { /// Bubble keys by client timestamp, for jumping to a quoted message. final Map _messageKeys = {}; + /// Pinned message ids of this chat with the instant of the pin. + Map _pins = {}; + /// Newest message the viewport has already shown at the bottom; anything /// after it while scrolled up counts as unseen. int _newestSeenSentAt = 0; @@ -188,8 +191,13 @@ class _ChatPageState extends State { } final newest = messages.isEmpty ? 0 : messages.last.sentAt.microsecondsSinceEpoch; + final pins = await CacheUtils.getPinnedMessages(widget.user.id); + if (!mounted) { + return; + } setState(() { _messages = messages; + _pins = pins; if (!first) { if (wasAtBottom) { _unseenCount = 0; @@ -368,6 +376,17 @@ class _ChatPageState extends State { widget.user.id, page.clearedAt!.toLocal()); MessageNotifier().notify(); } + // Pins are shared and the page always carries the whole set, so this is + // also how an unpin that happened on another device lands here. + final pins = { + for (final pin in page.pins) pin.messageId: pin.pinnedAt.toLocal(), + }; + await CacheUtils.replacePinnedMessages(widget.user.id, pins); + if (mounted) { + setState(() { + _pins = pins; + }); + } for (final peer in page.peers) { await CacheUtils.addUser( User(peer.id, peer.username, peer.publicKey, peer.admin)); @@ -390,6 +409,90 @@ class _ChatPageState extends State { } } + /// Opens the long-press sheet for one message. The pin state of the sheet is + /// the one this device knows, so the entry reads "unpin" when it applies. + void _openMessageActions(PrivateMessage message) { + final id = message.id; + MessageActions.showSheet( + context, + message, + widget.user.id, + pinned: id != null && _pins.containsKey(id), + onSelect: () => _toggleSelected(message), + ); + } + + /// The newest pinned message this device still holds, null when none is left. + PrivateMessage? get _newestPin { + PrivateMessage? newest; + DateTime? newestAt; + for (final message in _messages) { + final id = message.id; + if (id == null) { + continue; + } + final at = _pins[id]; + if (at == null) { + continue; + } + if (newestAt == null || at.isAfter(newestAt)) { + newest = message; + newestAt = at; + } + } + return newest; + } + + /// Narrow bar above the composer: the newest pin, tap to jump, cross to unpin. + Widget _buildPinBar() { + final pinned = _newestPin; + if (pinned == null) { + return const SizedBox.shrink(); + } + final preview = pinned.preview; + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Material( + color: Theme.of(context).colorScheme.surfaceContainerHigh, + borderRadius: BorderRadius.circular(12), + child: InkWell( + borderRadius: BorderRadius.circular(12), + onTap: () => _jumpToMessage(pinned.sentAt), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + child: Row( + children: [ + const Icon(Icons.push_pin, size: 16), + const SizedBox(width: 8), + Expanded( + child: Text( + preview.isEmpty ? 'mediaPhoto'.tr() : preview, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 12), + ), + ), + if (_pins.length > 1) + Padding( + padding: const EdgeInsets.only(left: 8), + child: Text('+${_pins.length - 1}', + style: const TextStyle(fontSize: 11)), + ), + IconButton( + icon: const Icon(Icons.close, size: 16), + tooltip: 'unpinMessage'.tr(), + onPressed: () => MessageActions.togglePin( + pinned, widget.user.id, + pinned: true), + ), + ], + ), + ), + ), + ), + ); + } + /// Load the draft message saved when leaving the chat. Future getConceptMessage() async { String? conceptMsg = await CacheUtils.getMessageConcept(widget.user.id); @@ -1225,6 +1328,7 @@ class _ChatPageState extends State { selectionMode: _selectionMode, selected: _selected.contains(micros), onSelect: () => _toggleSelected(message), + onActions: () => _openMessageActions(message), onReply: () => _startReply(message), onTapQuote: message.isReply ? () => _jumpToMessage(message.replyTo!.sentAt) @@ -1530,6 +1634,7 @@ class _ChatPageState extends State { child: Column( mainAxisSize: MainAxisSize.min, children: [ + _buildPinBar(), if (_replyTo != null) _buildReplyBar(), Stack( alignment: Alignment.center, diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index eb4ea02..a03d8b1 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -33,6 +33,7 @@ class CacheUtils { static const String _saltStorageKey = 'whisper_pbkdf2_salt'; static const String _deviceIdKey = 'whisper_device_id'; static const String _syncSeqKey = 'syncSeq'; + static const String _syncEventSeqKey = 'syncEventSeq'; static const FlutterSecureStorage _secureStorage = FlutterSecureStorage(); static const _chatThemeKeyPrefix = 'chatTheme:'; @@ -90,6 +91,23 @@ class CacheUtils { } } + /// Highest mutation-log `eventSeq` stored on this device. Edits, deletions, + /// reactions and pins only reach a device that was offline through this + /// cursor. + static Future getSyncEventSeq() async { + Box box = await Hive.openBox(_settingsKey); + return box.get(_syncEventSeqKey) as int? ?? 0; + } + + /// Advances the mutation cursor; like [setSyncSeq] it never moves backwards. + static Future setSyncEventSeq(int seq) async { + Box box = await Hive.openBox(_settingsKey); + final stored = box.get(_syncEventSeqKey) as int? ?? 0; + if (seq > stored) { + await box.put(_syncEventSeqKey, seq); + } + } + /// Opens box with password hash static Future _openPasswordHashBox() async { return Hive.openBox(_hashBoxKey); @@ -494,11 +512,46 @@ class CacheUtils { for (final path in value.localPaths) { await MediaUtils.deleteLocalFile(path); } + await setMessagePinned(userId, value.id, null); } await _deletePendingSend(userId, sentAt); await box.delete(key); } + /// Stores the newest text of an edited message, or drops the edit when the + /// message is not on this device. + static Future markMessageEdited( + String userId, DateTime sentAt, String text, DateTime editedAt) async { + final box = await _openPrivateMessagesBox(); + final key = messageKey(userId, sentAt); + final value = box.get(key); + if (value is! PrivateMessage) { + return; + } + value.message = text; + value.editedAt = editedAt; + await box.put(key, value); + } + + /// Sets or clears one participant's reaction on a stored message. + static Future setMessageReaction( + String userId, DateTime sentAt, String reactorId, String? emoji) async { + final box = await _openPrivateMessagesBox(); + final key = messageKey(userId, sentAt); + final value = box.get(key); + if (value is! PrivateMessage) { + return; + } + final reactions = Map.from(value.reactions ?? const {}); + if (emoji == null) { + reactions.remove(reactorId); + } else { + reactions[reactorId] = emoji; + } + value.reactions = reactions.isEmpty ? null : reactions; + await box.put(key, value); + } + /// Delete user messages static Future deletePrivateMessagesWithUser(String userId) async { Box messageBox = await _openPrivateMessagesBox(); @@ -773,6 +826,66 @@ class CacheUtils { } } + /// Pinned message ids of one chat, with the instant each was pinned. + static Future> getPinnedMessages(String userId) async { + final box = await _openConversationsBox(); + final raw = _metaOf(box, userId)['pins']; + if (raw is! Map) { + return {}; + } + return { + for (final entry in raw.entries) + if (entry.key is String && entry.value is int) + entry.key as String: + DateTime.fromMillisecondsSinceEpoch(entry.value as int), + }; + } + + /// Pins or unpins one message of a chat. Pins are shared between both + /// participants, so this is written from a pin event or a history page. + static Future setMessagePinned( + String userId, String? messageId, DateTime? pinnedAt) async { + if (messageId == null || messageId.isEmpty) { + return; + } + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + final pins = Map.from( + meta['pins'] is Map ? meta['pins'] as Map : const {}); + if (pinnedAt == null) { + pins.remove(messageId); + } else { + pins[messageId] = pinnedAt.millisecondsSinceEpoch; + } + await _putPins(box, userId, meta, pins); + } + + /// Replaces the pins of a chat with a server answer, so an unpin that happened + /// on another device does not survive on a stale local entry. + static Future replacePinnedMessages( + String userId, Map pins) async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + await _putPins(box, userId, meta, { + for (final entry in pins.entries) + entry.key: entry.value.millisecondsSinceEpoch, + }); + } + + static Future _putPins( + Box box, String userId, Map meta, Map pins) async { + if (pins.isEmpty) { + meta.remove('pins'); + } else { + meta['pins'] = pins; + } + if (meta.isEmpty) { + await box.delete(userId); + } else { + await box.put(userId, meta); + } + } + /// Instant up to which the account deleted this conversation, null when it /// never did. Everything at or before it is gone for good. static Future conversationClearedAt(String userId) async { @@ -808,6 +921,7 @@ class CacheUtils { await MediaUtils.deleteLocalFile(path); } await _deletePendingSend(userId, value.sentAt); + await setMessagePinned(userId, value.id, null); await box.delete(key); } } diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index b1c5727..2ba6176 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -1,17 +1,23 @@ +import 'dart:convert'; + +import 'package:basic_utils/basic_utils.dart' as bu; import 'package:easy_localization/easy_localization.dart'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; +import 'package:whisper_openapi_client_dart/api.dart'; import '../models/private_message.dart'; import '../pages/forward_page.dart'; import 'cache_utils.dart'; import 'chat_sender.dart'; +import 'crypto_utils.dart'; import 'dialog_utils.dart'; import 'media_utils.dart'; import 'message_notifier.dart'; import 'singleton.dart'; +import 'text_envelope.dart'; import 'utils.dart'; import '../utils/nav_transitions.dart'; @@ -25,6 +31,21 @@ class MessageActions { static const IconData saveIcon = Icons.download; static const IconData deleteIcon = Icons.delete; static const IconData resendIcon = Icons.refresh; + static const IconData editIcon = Icons.edit; + static const IconData pinIcon = Icons.push_pin_outlined; + static const IconData unpinIcon = Icons.push_pin; + static const IconData selectIcon = Icons.checklist; + + /// Emoji offered by the reaction row. A short fixed set keeps reacting one + /// tap instead of opening a picker. + static const List reactionEmojis = [ + '👍', + '❤️', + '😂', + '😮', + '😢', + '🙏' + ]; /// Whether [message] can be saved or forwarded (the file must be on disk). static bool canSave(PrivateMessage message) => @@ -34,14 +55,65 @@ class MessageActions { /// [conversationUserId] is the other side of the conversation. static Future showSheet( BuildContext context, PrivateMessage message, String conversationUserId, - {VoidCallback? onDeleted}) { + {VoidCallback? onDeleted, bool pinned = false, VoidCallback? onSelect}) { return showModalBottomSheet( context: context, showDragHandle: true, builder: (ctx) { + final canAddress = + message.id?.isNotEmpty ?? false; // needs the archive id return SafeArea( child: Wrap( children: [ + // Reactions first: one tap, and the same emoji again removes it. + if (canAddress) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + for (final emoji in reactionEmojis) + IconButton( + onPressed: () { + Navigator.pop(ctx); + react(message, conversationUserId, emoji); + }, + icon: + Text(emoji, style: const TextStyle(fontSize: 22)), + ), + ], + ), + ), + if (message.isMe && + !message.isMedia && + !message.isUndecryptable && + canAddress) + ListTile( + leading: const Icon(editIcon), + title: Text('editMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + edit(context, message, conversationUserId); + }, + ), + if (canAddress) + ListTile( + leading: Icon(pinned ? unpinIcon : pinIcon), + title: Text(pinned ? 'unpinMessage'.tr() : 'pinMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + togglePin(message, conversationUserId, pinned: pinned); + }, + ), + if (onSelect != null) + ListTile( + leading: const Icon(selectIcon), + title: Text('selectMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + onSelect(); + }, + ), if (message.isMe && message.sendStatus == SendStatus.failed) ListTile( leading: const Icon(resendIcon), @@ -113,6 +185,135 @@ class MessageActions { Fluttertoast.showToast(msg: 'copiedText'.tr()); } + /// Sets the caller's reaction, or removes it when the same emoji is picked + /// again. The emoji travels encrypted like the message body. + static Future react( + PrivateMessage message, String conversationUserId, String emoji) async { + final id = message.id; + if (id == null || id.isEmpty) { + return; + } + final me = Singleton().profile.user.id; + final removing = message.reactions?[me] == emoji; + try { + if (removing) { + await Utils.callApi(() => Singleton().messagesApi.removeReaction(id), + rethrowErr: true); + } else { + final peer = await CacheUtils.getUserById(conversationUserId); + if (peer == null) { + return; + } + final data = await CryptoUtils.encryptMessageData( + Uint8List.fromList(utf8.encode(emoji)), + bu.CryptoUtils.rsaPublicKeyFromPem(peer.publicKey)); + await Utils.callApi( + () => Singleton().messagesApi.setReaction( + id, + setReactionInput: SetReactionInput( + content: data['encryptedData']!, + key: data['encryptedKey']!, + nonce: data['nonce']!, + mac: data['mac']!, + ), + ), + rethrowErr: true); + } + await CacheUtils.setMessageReaction( + conversationUserId, message.sentAt, me, removing ? null : emoji); + MessageNotifier().notify(); + } catch (_) { + // The server refused; nothing changed locally either. + } + } + + /// Pins or unpins the message for both participants. + static Future togglePin( + PrivateMessage message, String conversationUserId, + {required bool pinned}) async { + final id = message.id; + if (id == null || id.isEmpty) { + return; + } + try { + await Utils.callApi( + () => pinned + ? Singleton().messagesApi.unpinMessage(id) + : Singleton().messagesApi.pinMessage(id), + rethrowErr: true); + await CacheUtils.setMessagePinned( + conversationUserId, id, pinned ? null : DateTime.now()); + MessageNotifier().notify(); + } catch (_) { + // Left as it was. + } + } + + /// Rewrites the text of an own message: new ciphertext, server stamp, same + /// bubble. + static Future edit(BuildContext context, PrivateMessage message, + String conversationUserId) async { + final id = message.id; + if (id == null || id.isEmpty) { + return; + } + final controller = TextEditingController(text: message.message); + final text = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: Text('editMessage'.tr()), + content: TextField( + controller: controller, + autofocus: true, + maxLines: null, + minLines: 1, + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx), + child: Text('cancel'.tr()), + ), + TextButton( + onPressed: () => Navigator.pop(ctx, controller.text), + child: Text('okText'.tr()), + ), + ], + ), + ); + controller.dispose(); + if (text == null || text.trim().isEmpty || text == message.message) { + return; + } + try { + final peer = await CacheUtils.getUserById(conversationUserId); + if (peer == null) { + return; + } + // A reply keeps its quote; only the body changes. + final reply = message.replyTo; + final plaintext = + reply == null ? utf8.encode(text) : buildTextEnvelope(text, reply); + final data = await CryptoUtils.encryptMessageData( + plaintext, bu.CryptoUtils.rsaPublicKeyFromPem(peer.publicKey)); + final response = await Utils.callApi( + () => Singleton().messagesApi.editMessage( + id, + editMessageInput: EditMessageInput( + content: data['encryptedData']!, + key: data['encryptedKey']!, + nonce: data['nonce']!, + mac: data['mac']!, + ), + ), + rethrowErr: true); + await CacheUtils.markMessageEdited(conversationUserId, message.sentAt, + text, (response?.editedAt ?? DateTime.now()).toLocal()); + MessageNotifier().notify(); + } catch (_) { + // The old text stays in place. + } + } + /// Save the decrypted attachment wherever the user picks. static Future save(PrivateMessage message) async { final path = message.localPath; diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 88fc462..6697aa0 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -13,6 +13,7 @@ import '../pages/chat_page.dart'; import 'package:whisper_openapi_client_dart/api.dart'; import 'package:basic_utils/basic_utils.dart' as bu; import 'package:whisper_websocket_client_dart/models/delivery_ack.dart'; +import 'package:whisper_websocket_client_dart/models/message_event.dart'; import 'package:whisper_websocket_client_dart/models/synced.dart'; import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import 'package:whisper_websocket_client_dart/models/private_message.dart'; @@ -279,6 +280,19 @@ class Utils { /// older echoes are dropped; history from a sync is stored silently. static Future _storeMessages(List messages, {required bool notify, bool advanceCursor = false}) async { + // A tombstone (deleted for everyone) has no ciphertext left. The caller + // drops the local copy; storing it here would only create an undecryptable + // placeholder. + messages = messages + .where((message) => + message.content != null && + message.key != null && + message.nonce != null && + message.mac != null) + .toList(); + if (messages.isEmpty) { + return; + } messages.sort((a, b) => a.sentAt.compareTo(b.sentAt)); List decryptedMessages = []; // Media references of each conversation that still need a download. @@ -292,10 +306,10 @@ class Utils { decryptedBatch = await CryptoUtils.decryptMessageBatch( messages .map((message) => { - 'data': message.content, - 'key': message.key, - 'nonce': message.nonce, - 'mac': message.mac, + 'data': message.content!, + 'key': message.key!, + 'nonce': message.nonce!, + 'mac': message.mac!, }) .toList(), Singleton().profile.privateKey); @@ -430,17 +444,20 @@ class Utils { final byPeer = >{}; final peerOfMessage = {}; final idOfMessage = {}; + final editedOfMessage = {}; for (final message in messages) { final key = '${message.senderId}|${message.sentAt.toUtc().toIso8601String()}'; peerOfMessage[key] = message.peerId; idOfMessage[key] = message.id; + editedOfMessage[key] = message.editedAt; } for (final message in decryptedMessages) { final key = '${message.senderId}|${message.sentAt.toUtc().toIso8601String()}'; // The archive id is what a delete on the server needs. message.id ??= idOfMessage[key]; + message.editedAt ??= editedOfMessage[key]; final peer = peerOfMessage[key] ?? message.senderId; byPeer.putIfAbsent(peer, () => []).add(message); } @@ -518,19 +535,44 @@ class Utils { await CacheUtils.addUser( User(peer.id, peer.username, peer.publicKey, false)); } + // A tombstone carries no ciphertext: drop the local copy instead of + // storing an undecryptable placeholder. + for (final dead + in synced.messages.where((message) => message.deletedAt != null)) { + await CacheUtils.deletePrivateMessageAt(dead.peerId, dead.sentAt); + } if (synced.messages.isNotEmpty) { // History is silent: a week offline must not ring once per old // message. await _storeMessages(synced.messages, notify: false); } + for (final cleared in synced.cleared) { + await CacheUtils.applyConversationClearedAt( + cleared.peerId, cleared.clearedAt.toLocal()); + } + // Events come after the messages they talk about, which is what the + // server's cursor ordering guarantees. + for (final event in synced.events) { + await applyEvent(event); + } // Only after the batch is stored: a cursor ahead of the local messages // would drop them for good. await CacheUtils.setSyncSeq(synced.syncedThrough); + await CacheUtils.setSyncEventSeq(synced.eventsThrough); if (synced.hasMore && Singleton().wsClient.isConnected) { - Singleton().wsClient.sendSync(synced.syncedThrough); + Singleton().wsClient.sendSync(synced.syncedThrough, + sinceEventSeq: synced.eventsThrough); } break; + // One live mutation of an archived message + case WsResponseType.edit: + case WsResponseType.delete: + case WsResponseType.reaction: + case WsResponseType.pin: + await applyEvent(wsResponse.payload as MessageEvent); + break; + // Delete account case WsResponseType.deleteAccount: await CacheUtils.deleteCache(); @@ -551,6 +593,81 @@ class Utils { await Fluttertoast.showToast( msg: Utils.serverErrorText(error), backgroundColor: Colors.red); break; + + // A frame from a newer server. Ignoring it keeps this build usable. + case WsResponseType.unknown: + break; + } + } + + /// Applies one entry of the mutation log: an edit, a deletion, a reaction or + /// a pin of a message this device already has. The same code serves a live + /// frame and a replayed sync page, so a reconnect converges on the same + /// state. + static Future applyEvent(MessageEvent event) async { + switch (event.kind) { + case MessageEventKind.delete: + await CacheUtils.deletePrivateMessageAt(event.peerId, event.sentAt); + await CacheUtils.setMessagePinned(event.peerId, event.messageId, null); + break; + + case MessageEventKind.edit: + final content = event.content; + if (content == null) { + return; + } + final plain = await _decryptSmall(event); + if (plain == null) { + return; + } + final body = tryParseTextEnvelope(plain)?.body ?? utf8.decode(plain); + await CacheUtils.markMessageEdited( + event.peerId, event.sentAt, body, event.createdAt.toLocal()); + break; + + case MessageEventKind.reaction: + // My own reaction ciphertext is wrapped for the other side, so this + // device keeps the emoji it set locally. + if (event.actorId == Singleton().profile.user.id) { + return; + } + String? emoji; + if (event.content != null) { + final plain = await _decryptSmall(event); + if (plain == null) { + return; + } + emoji = utf8.decode(plain); + } + await CacheUtils.setMessageReaction( + event.peerId, event.sentAt, event.actorId, emoji); + break; + + case MessageEventKind.pin: + await CacheUtils.setMessagePinned(event.peerId, event.messageId, + event.pinned == true ? event.createdAt.toLocal() : null); + break; + } + MessageNotifier().notify(); + } + + /// Decrypts the small payload of an edit or a reaction, null when it cannot + /// be opened. + static Future _decryptSmall(MessageEvent event) async { + final content = event.content; + final key = event.key; + final nonce = event.nonce; + final mac = event.mac; + if (content == null || key == null || nonce == null || mac == null) { + return null; + } + try { + final decrypted = await CryptoUtils.decryptMessageBatch([ + {'data': content, 'key': key, 'nonce': nonce, 'mac': mac} + ], Singleton().profile.privateKey); + return decrypted.single; + } catch (_) { + return null; } } @@ -583,20 +700,23 @@ class Utils { 'nonce': message.nonce, 'mac': message.mac, 'sentAt': message.sentAt.toIso8601String(), + 'editedAt': message.editedAt?.toIso8601String(), 'recipientOnline': false, })) .toList(); await _storeMessages(wire, notify: false); } - /// Ask the server for the archive delta above the cursor stored on this - /// device. Nothing is pushed on connect, so this is what catches a client up. + /// Ask the server for the archive delta and the mutation log above the + /// cursors stored on this device. Nothing is pushed on connect, so this is + /// what catches a client up. static Future syncArchive() async { if (!Singleton().wsClient.isConnected) { return; } try { - Singleton().wsClient.sendSync(await CacheUtils.getSyncSeq()); + Singleton().wsClient.sendSync(await CacheUtils.getSyncSeq(), + sinceEventSeq: await CacheUtils.getSyncEventSeq()); } catch (e) { if (kDebugMode) { debugPrint('sync request failed: $e'); diff --git a/lib/utils/version.dart b/lib/utils/version.dart index c156336..8ed168e 100644 --- a/lib/utils/version.dart +++ b/lib/utils/version.dart @@ -1,3 +1,3 @@ /// Version of this app build, sent as `X-Client-Version`. The server refuses a /// login below its `minClientVersion` with a code we can translate. -const String appVersion = '0.1.0'; +const String appVersion = '0.2.0'; diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index af6e414..845742e 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -30,6 +30,9 @@ class ChatBubble extends StatefulWidget { /// Toggles this bubble in the selection (tap and long-press). final VoidCallback? onSelect; + /// Opens the action sheet (long-press). Falls back to [onSelect] when unset. + final VoidCallback? onActions; + /// Quotes this message in the composer (double-tap and swipe). final VoidCallback? onReply; @@ -42,6 +45,7 @@ class ChatBubble extends StatefulWidget { this.selectionMode = false, this.selected = false, this.onSelect, + this.onActions, this.onReply, this.onTapQuote, super.key}); @@ -70,6 +74,23 @@ class _ChatBubbleState extends State { isEmojiOnly(widget.message.message) && emojiCount(widget.message.message) <= 3; + /// One reaction chip: the emoji, plus how many participants picked it. + Widget _reactionChip(String emoji) { + final count = + widget.message.reactions?.values.where((v) => v == emoji).length ?? 0; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surfaceContainerHigh, + borderRadius: BorderRadius.circular(10), + ), + child: Text( + count > 1 ? '$emoji $count' : emoji, + style: const TextStyle(fontSize: 12), + ), + ); + } + @override Widget build(BuildContext context) { bool showAvatar() { @@ -162,7 +183,7 @@ class _ChatBubbleState extends State { if (widget.selectionMode) { return; } - widget.onSelect?.call(); + (widget.onActions ?? widget.onSelect)?.call(); } Widget content() { @@ -286,6 +307,18 @@ class _ChatBubbleState extends State { children: [ if (widget.message.isReply) quoteBlock(), content(), + if (widget.message.isEdited) + Padding( + padding: const EdgeInsets.only(top: 2), + child: Text( + 'messageEdited'.tr(), + style: TextStyle( + color: bubbleTextColor().withValues(alpha: 0.7), + fontSize: 11, + fontStyle: FontStyle.italic, + ), + ), + ), ], ); @@ -419,6 +452,25 @@ class _ChatBubbleState extends State { ) else bubbleBox, + // Reactions sit just outside the bubble, the + // way they do in the other messengers. + if (widget.message.reactionEmojis.isNotEmpty) + GestureDetector( + onTap: () => + (widget.onActions ?? widget.onSelect) + ?.call(), + child: Padding( + padding: const EdgeInsets.only(top: 2), + child: Wrap( + spacing: 4, + children: [ + for (final emoji + in widget.message.reactionEmojis) + _reactionChip(emoji), + ], + ), + ), + ), // Outgoing messages show a clock while they are // being sent and an error when the send failed. if (widget.message.isMe && diff --git a/pubspec.lock b/pubspec.lock index 30987dc..e465cb3 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1783,14 +1783,14 @@ packages: path: "../whisper_openapi_client_dart" relative: true source: path - version: "0.1.0" + version: "0.2.0" whisper_websocket_client_dart: dependency: "direct main" description: path: "../whisper_websocket_client_dart" relative: true source: path - version: "0.1.0" + version: "0.2.0" win32: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index f6c2dd6..c66312a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,7 +3,7 @@ description: "Secure private self-hosted end-to-end encryption messaging app." publish_to: 'none' # Remove this line if you wish to publish to pub.dev # Bump before every release; the release workflow tags v and fails if # that tag already exists. The build number after + must only ever grow. -version: 0.1.0+3 +version: 0.2.0+4 environment: sdk: '>=3.4.3 <4.0.0' @@ -51,11 +51,11 @@ dependencies: whisper_openapi_client_dart: git: url: https://github.com/jsfraz/whisper_openapi_client_dart.git - ref: v0.1.0 + ref: v0.2.0 whisper_websocket_client_dart: git: url: https://github.com/jsfraz/whisper_websocket_client_dart.git - ref: v0.1.0 + ref: v0.2.0 dev_dependencies: flutter_test: diff --git a/test/message_actions_test.dart b/test/message_actions_test.dart index 0ec905c..b42c443 100644 --- a/test/message_actions_test.dart +++ b/test/message_actions_test.dart @@ -93,5 +93,30 @@ void main() { await tester.tap(find.text('open')); await tester.pumpAndSettle(); expect(find.text('Send again'), findsNothing); + + // Close the sheet + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + // An archived message gains the reaction row and the pin entry; only an own + // text message can be edited. + message = PrivateMessage('2', 'hello', DateTime(2026), DateTime(2026), true) + ..id = '00000000-0000-4000-8000-000000000000'; + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('👍'), findsOneWidget); + expect(find.text('Pin'), findsOneWidget); + expect(find.text('Edit message'), findsNothing); + + // Close the sheet + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + message = PrivateMessage('1', 'hello', DateTime(2026), DateTime(2026), true) + ..id = '00000000-0000-4000-8000-000000000000'; + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('Edit message'), findsOneWidget); + expect(find.text('Unpin'), findsNothing); }); } diff --git a/test/message_lifecycle_test.dart b/test/message_lifecycle_test.dart new file mode 100644 index 0000000..27ae135 --- /dev/null +++ b/test/message_lifecycle_test.dart @@ -0,0 +1,98 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; + +/// The local side of the lifecycle: an edit rewrites the stored text, a +/// reaction is a per-user map, a pin lives on the chat, and the mutation cursor +/// only moves forward. All four are what sync and live frames write into. +void main() { + late Directory dir; + const peer = 'peer-id'; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_lifecycle_test'); + Hive.init(dir.path); + if (!Hive.isAdapterRegistered(3)) { + Hive.registerAdapter(PrivateMessageAdapter()); + } + }); + + setUp(() async { + for (final box in ['privateMessages', 'conversations', 'settings']) { + await Hive.openBox(box); + await Hive.box(box).clear(); + } + final sentAt = DateTime(2026, 11, 19, 12); + await CacheUtils.addPrivateMessages(peer, [ + PrivateMessage(peer, 'before', sentAt, sentAt, true)..id = 'message-id', + ]); + }); + + tearDownAll(() async { + await Hive.deleteFromDisk(); + await dir.delete(recursive: true); + }); + + test('an edit replaces the text and marks the message', () async { + final editedAt = DateTime(2026, 11, 19, 12, 5); + await CacheUtils.markMessageEdited( + peer, DateTime(2026, 11, 19, 12), 'after', editedAt); + + final message = (await CacheUtils.getPrivateMessages(peer)).single; + expect(message.message, 'after'); + expect(message.isEdited, isTrue); + expect(message.editedAt, editedAt); + }); + + test('a reaction is set per user, replaced and removed', () async { + final sentAt = DateTime(2026, 11, 19, 12); + await CacheUtils.setMessageReaction(peer, sentAt, 'me', '👍'); + await CacheUtils.setMessageReaction(peer, sentAt, 'peer-id', '❤️'); + + var message = (await CacheUtils.getPrivateMessages(peer)).single; + expect(message.reactions, {'me': '👍', 'peer-id': '❤️'}); + expect(message.reactionEmojis, ['❤️', '👍']); + + // The same user reacting again replaces the emoji instead of adding one. + await CacheUtils.setMessageReaction(peer, sentAt, 'me', '😂'); + message = (await CacheUtils.getPrivateMessages(peer)).single; + expect(message.reactions, {'me': '😂', 'peer-id': '❤️'}); + + await CacheUtils.setMessageReaction(peer, sentAt, 'me', null); + message = (await CacheUtils.getPrivateMessages(peer)).single; + expect(message.reactions, {'peer-id': '❤️'}); + + await CacheUtils.setMessageReaction(peer, sentAt, 'peer-id', null); + message = (await CacheUtils.getPrivateMessages(peer)).single; + expect(message.reactions, isNull); + }); + + test('pins are shared state of the chat and can be replaced', () async { + await CacheUtils.setConversationPinned(peer, true); + await CacheUtils.setMessagePinned( + peer, 'message-id', DateTime(2026, 11, 19, 12, 6)); + + var pins = await CacheUtils.getPinnedMessages(peer); + expect(pins.keys, ['message-id']); + // The chat being pinned to the top of the list is a different flag and must + // survive. + expect(await CacheUtils.isConversationPinned(peer), isTrue); + + // A server page is authoritative: anything missing was unpinned elsewhere. + await CacheUtils.replacePinnedMessages(peer, {}); + pins = await CacheUtils.getPinnedMessages(peer); + expect(pins, isEmpty); + + await CacheUtils.setMessagePinned(peer, 'message-id', null); + expect(await CacheUtils.getPinnedMessages(peer), isEmpty); + }); + + test('the mutation cursor never moves backwards', () async { + await CacheUtils.setSyncEventSeq(5); + await CacheUtils.setSyncEventSeq(3); + expect(await CacheUtils.getSyncEventSeq(), 5); + }); +} From f4fe5ab974afe690d79e755fb24d14bf179dc4fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 19 Nov 2026 18:13:56 +0100 Subject: [PATCH 093/181] feat(chat): forwarded label, read receipts and seen ticks Forwarding now marks the message so the receiver sees "Forwarded"; the flag rides as an optional key in the existing v3/media envelopes, so an older reader still opens the body. Read receipts are one per-chat switch, off by default: on publishes this account's read cursor (time only, the server never learns which message was read) and shows the peer's, turning the sent tick into a read tick. Clients pinned to v0.3.0. --- assets/translations/cs.json | 6 +++- assets/translations/en.json | 6 +++- lib/models/private_message.dart | 6 ++++ lib/models/private_message.g.dart | 7 +++-- lib/pages/chat_info_page.dart | 36 ++++++++++++++++++++++++ lib/pages/chat_page.dart | 42 ++++++++++++++++++++++++++++ lib/pages/forward_page.dart | 6 ++-- lib/pages/password_page.dart | 6 ++-- lib/utils/cache_utils.dart | 46 +++++++++++++++++++++++++++++++ lib/utils/chat_sender.dart | 31 +++++++++++++-------- lib/utils/media_utils.dart | 22 +++++++++++---- lib/utils/singleton.dart | 2 ++ lib/utils/text_envelope.dart | 22 +++++++++++---- lib/utils/utils.dart | 35 ++++++++++++++++++++++- lib/utils/version.dart | 2 +- lib/widgets/chat_bubble.dart | 45 ++++++++++++++++++++++++++++++ pubspec.lock | 4 +-- pubspec.yaml | 6 ++-- test/chat_bubble_test.dart | 36 ++++++++++++++++++++++++ test/message_lifecycle_test.dart | 19 +++++++++++++ test/text_envelope_test.dart | 20 ++++++++++++++ 21 files changed, 366 insertions(+), 39 deletions(-) diff --git a/assets/translations/cs.json b/assets/translations/cs.json index fd6f886..fa35d80 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -248,5 +248,9 @@ "selectMessage": "Vybrat", "messageEdited": "upraveno", "pinnedMessages": "Připnuté zprávy", - "noPinnedMessages": "Zatím žádná připnutá zpráva" + "noPinnedMessages": "Zatím žádná připnutá zpráva", + "forwardedMessage": "Přeposláno", + "readReceipts": "Potvrzení o přečtení", + "messageDelivered": "Doručeno", + "messageRead": "Přečteno" } diff --git a/assets/translations/en.json b/assets/translations/en.json index a461a7e..15a0dd8 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -248,5 +248,9 @@ "selectMessage": "Select", "messageEdited": "edited", "pinnedMessages": "Pinned messages", - "noPinnedMessages": "No pinned messages yet" + "noPinnedMessages": "No pinned messages yet", + "forwardedMessage": "Forwarded", + "readReceipts": "Read receipts", + "messageDelivered": "Delivered", + "messageRead": "Read" } diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index 8041d35..a5a5ac8 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -191,6 +191,11 @@ class PrivateMessage extends HiveObject { @HiveField(21) Map? reactions; + /// Whether the message was forwarded: the sender passed on somebody else's + /// text instead of writing it. + @HiveField(22, defaultValue: false) + bool forwarded; + /// Cache for [album], keyed by the [albumJson] it was decoded from. String? _albumCacheJson; List? _albumCache; @@ -217,6 +222,7 @@ class PrivateMessage extends HiveObject { this.replyToPreview, this.editedAt, this.reactions, + this.forwarded = false, }); /// Whether the sender edited the text after sending it. diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index b42740a..ed2fad0 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -38,13 +38,14 @@ class PrivateMessageAdapter extends TypeAdapter { replyToPreview: fields[18] as String?, editedAt: fields[20] as DateTime?, reactions: (fields[21] as Map?)?.cast(), + forwarded: fields[22] == null ? false : fields[22] as bool, )..id = fields[19] as String?; } @override void write(BinaryWriter writer, PrivateMessage obj) { writer - ..writeByte(22) + ..writeByte(23) ..writeByte(0) ..write(obj.senderId) ..writeByte(1) @@ -88,7 +89,9 @@ class PrivateMessageAdapter extends TypeAdapter { ..writeByte(20) ..write(obj.editedAt) ..writeByte(21) - ..write(obj.reactions); + ..write(obj.reactions) + ..writeByte(22) + ..write(obj.forwarded); } @override diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index d1caade..a800cce 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -11,6 +11,7 @@ import '../utils/message_notifier.dart'; import '../utils/dialog_utils.dart'; import '../utils/media_utils.dart'; import '../utils/singleton.dart'; +import '../utils/utils.dart'; import '../utils/theme_utils.dart'; import '../widgets/media_bubble.dart'; import '../widgets/settings_tile.dart'; @@ -30,6 +31,7 @@ class _ChatInfoPageState extends State { Color? _chatThemeColor; List _media = []; Map _pins = {}; + bool _readReceipts = false; @override void initState() { @@ -37,6 +39,30 @@ class _ChatInfoPageState extends State { _loadChatTheme(); _loadMedia(); _loadPins(); + _loadReadReceipts(); + } + + Future _loadReadReceipts() async { + final enabled = await CacheUtils.isReadReceiptsEnabled(widget.userId); + if (mounted) { + setState(() { + _readReceipts = enabled; + }); + } + } + + /// Turns receipts of this chat on or off. Turning them on publishes the + /// current cursor right away, so the peer's ticks catch up without waiting + /// for the next message. + Future _toggleReadReceipts(bool enabled) async { + await CacheUtils.setReadReceiptsEnabled(widget.userId, enabled); + if (enabled) { + final messages = await CacheUtils.getPrivateMessages(widget.userId); + if (messages.isNotEmpty) { + await Utils.sendReadCursor(widget.userId, messages.last.sentAt); + } + } + await _loadReadReceipts(); } Future _loadPins() async { @@ -216,6 +242,16 @@ class _ChatInfoPageState extends State { label: 'jumpToDate'.tr(), onPressed: _jumpToDate, ), + // Read receipts: off by default, one switch for both + // directions of this chat + SettingsTile( + icon: Icons.done_all, + label: 'readReceipts'.tr(), + trailing: Switch( + value: _readReceipts, + onChanged: _toggleReadReceipts, + ), + ), // Pinned messages, shared with the other participant SettingsTile( icon: Icons.push_pin, diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 7fc54c0..f0c9d47 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -96,6 +96,17 @@ class _ChatPageState extends State { /// Pinned message ids of this chat with the instant of the pin. Map _pins = {}; + /// Whether this chat publishes and shows read receipts. + bool _readReceipts = false; + + /// Instant up to which the other participant has read this chat. + DateTime? _peerReadAt; + + /// Instant this device already told the server about, so an idle re-render + /// does not send the same cursor again. + DateTime? _publishedReadAt; + Timer? _readPublish; + /// Newest message the viewport has already shown at the bottom; anything /// after it while scrolled up counts as unseen. int _newestSeenSentAt = 0; @@ -192,12 +203,17 @@ class _ChatPageState extends State { final newest = messages.isEmpty ? 0 : messages.last.sentAt.microsecondsSinceEpoch; final pins = await CacheUtils.getPinnedMessages(widget.user.id); + final peerReadAt = await CacheUtils.getPeerReadAt(widget.user.id); + final readReceipts = + await CacheUtils.isReadReceiptsEnabled(widget.user.id); if (!mounted) { return; } setState(() { _messages = messages; _pins = pins; + _peerReadAt = peerReadAt; + _readReceipts = readReceipts; if (!first) { if (wasAtBottom) { _unseenCount = 0; @@ -222,6 +238,8 @@ class _ChatPageState extends State { await _jumpToFirstUnread(); } } + // Reading the chat is what moves the cursor; the peer's ticks follow. + _publishReadCursor(); } finally { _loading = false; if (_reloadRequested) { @@ -493,6 +511,28 @@ class _ChatPageState extends State { ); } + /// Publishes how far this chat was read, debounced: scrolling through a burst + /// of messages should cost one request, not one per message. + void _publishReadCursor() { + if (!_readReceipts || _messages.isEmpty) { + return; + } + final newest = _messages.last.sentAt; + if (_publishedReadAt != null && !newest.isAfter(_publishedReadAt!)) { + return; + } + _readPublish?.cancel(); + _readPublish = Timer(const Duration(seconds: 1), () async { + final at = _messages.isEmpty ? null : _messages.last.sentAt; + if (at == null) { + return; + } + if (await utils.Utils.sendReadCursor(widget.user.id, at) && mounted) { + _publishedReadAt = at; + } + }); + } + /// Load the draft message saved when leaving the chat. Future getConceptMessage() async { String? conceptMsg = await CacheUtils.getMessageConcept(widget.user.id); @@ -1327,6 +1367,7 @@ class _ChatPageState extends State { accentColor: _chatThemeColor ?? Singleton().appTheme.color, selectionMode: _selectionMode, selected: _selected.contains(micros), + readAt: _peerReadAt, onSelect: () => _toggleSelected(message), onActions: () => _openMessageActions(message), onReply: () => _startReply(message), @@ -1425,6 +1466,7 @@ class _ChatPageState extends State { _scrollController.removeListener(_onScroll); WidgetsBinding.instance.removeObserver(_metricsObserver); _recordTimer?.cancel(); + _readPublish?.cancel(); _recorderController?.dispose(); _controllerMessage.dispose(); _scrollController.dispose(); diff --git a/lib/pages/forward_page.dart b/lib/pages/forward_page.dart index 3ca1bf4..150d309 100644 --- a/lib/pages/forward_page.dart +++ b/lib/pages/forward_page.dart @@ -65,9 +65,11 @@ class _ForwardPageState extends State { width: message.width, height: message.height, durationMs: message.durationMs, - fileName: message.fileName); + fileName: message.fileName, + forwarded: true); } else { - sent = await ChatSender.sendText(to, message.message); + sent = + await ChatSender.sendText(to, message.message, forwarded: true); } allSent = allSent && sent; } diff --git a/lib/pages/password_page.dart b/lib/pages/password_page.dart index 935f758..02a7ed4 100644 --- a/lib/pages/password_page.dart +++ b/lib/pages/password_page.dart @@ -58,8 +58,7 @@ class _PasswordPageState extends State { // Load profile Singleton().profile = await CacheUtils.getProfile(); // OpenAPI client - Singleton().api = - Singleton.createApiClient(Singleton().profile.url); + Singleton().api = Singleton.createApiClient(Singleton().profile.url); // Check tokens await Utils.authCheck(); // WebSocket client @@ -147,8 +146,7 @@ class _PasswordPageState extends State { // Add profile to singleton Singleton().profile = await CacheUtils.getProfile(); // OpenAPI client - Singleton().api = - Singleton.createApiClient(Singleton().profile.url); + Singleton().api = Singleton.createApiClient(Singleton().profile.url); // Kontrola tokenů await Utils.authCheck(); diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index a03d8b1..bf32486 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -886,6 +886,52 @@ class CacheUtils { } } + /// Whether this chat sends and shows read receipts. Off by default; one + /// switch governs both directions, so ticks only appear when both sides opted + /// in (a side that is off never publishes its cursor). + static Future isReadReceiptsEnabled(String userId) async { + final box = await _openConversationsBox(); + return _metaOf(box, userId)['readReceipts'] == true; + } + + /// Turns read receipts of one chat on or off. + static Future setReadReceiptsEnabled( + String userId, bool enabled) async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + if (enabled) { + meta['readReceipts'] = true; + } else { + meta.remove('readReceipts'); + } + if (meta.isEmpty) { + await box.delete(userId); + } else { + await box.put(userId, meta); + } + } + + /// Instant up to which the other participant has read this chat, null when + /// they never published one. + static Future getPeerReadAt(String userId) async { + final box = await _openConversationsBox(); + final raw = _metaOf(box, userId)['peerReadAt']; + return raw is int ? DateTime.fromMillisecondsSinceEpoch(raw) : null; + } + + /// Remembers the peer's read cursor. It only moves forward, so a frame that + /// arrives out of order cannot take the tick back. + static Future setPeerReadAt(String userId, DateTime readAt) async { + final stored = await getPeerReadAt(userId); + if (stored != null && !readAt.isAfter(stored)) { + return; + } + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + meta['peerReadAt'] = readAt.millisecondsSinceEpoch; + await box.put(userId, meta); + } + /// Instant up to which the account deleted this conversation, null when it /// never did. Everything at or before it is gone for good. static Future conversationClearedAt(String userId) async { diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index baee615..e27b708 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -57,13 +57,14 @@ class ChatSender { /// upgrade by persisting the transport key inside the encrypted profile box. static final Map> _outgoingReferences = {}; - /// Send a text message to [recipient], optionally quoting [reply]. + /// Send a text message to [recipient], optionally quoting [reply] or marked + /// as forwarded. static Future sendText(User recipient, String text, - {ReplyRef? reply}) async { + {ReplyRef? reply, bool forwarded = false}) async { final now = DateTime.now(); final message = PrivateMessage( Singleton().profile.user.id, text, now, now, true, - sendStatus: SendStatus.sending) + sendStatus: SendStatus.sending, forwarded: forwarded) ..setReplyTo(reply); try { await _persist(recipient, [message]); @@ -86,7 +87,8 @@ class ChatSender { int? width, int? height, int? durationMs, - String? fileName}) async { + String? fileName, + bool forwarded = false}) async { if (!MediaUtils.uploadFits(bytes.length)) { _toastTooLarge(); return false; @@ -110,6 +112,7 @@ class ChatSender { downloadStatus: MediaDownloadStatus.ready, fileName: fileName, sendStatus: SendStatus.sending, + forwarded: forwarded, ); try { await _persist(recipient, [message]); @@ -128,7 +131,8 @@ class ChatSender { } _outgoingReferences[CacheUtils.messageKey(recipient.id, message.sentAt)] = [reference]; - final envelope = MediaUtils.buildMediaEnvelope(reference, caption); + final envelope = MediaUtils.buildMediaEnvelope(reference, caption, + forwarded: forwarded); await _sendEnvelope(recipient, envelope, message.sentAt); await CacheUtils.updateStoredMessage(recipient.id, message, (stored) { stored.mediaId = reference.mediaId; @@ -144,7 +148,7 @@ class ChatSender { /// envelope carrying all references, one WebSocket message. static Future sendAlbum( User recipient, List attachments, - {String caption = ''}) async { + {String caption = '', bool forwarded = false}) async { if (attachments.isEmpty) { return false; } @@ -169,6 +173,7 @@ class ChatSender { true, downloadStatus: MediaDownloadStatus.ready, sendStatus: SendStatus.sending, + forwarded: forwarded, ); message.setAlbum([ for (var i = 0; i < attachments.length; i++) @@ -210,7 +215,8 @@ class ChatSender { _outgoingReferences[CacheUtils.messageKey(recipient.id, message.sentAt)] = references; - final envelope = MediaUtils.buildAlbumEnvelope(references, caption); + final envelope = MediaUtils.buildAlbumEnvelope(references, caption, + forwarded: forwarded); await _sendEnvelope(recipient, envelope, message.sentAt); await CacheUtils.updateStoredMessage(recipient.id, message, (stored) { final items = stored.album; @@ -342,8 +348,10 @@ class ChatSender { } _outgoingReferences[key] = references; final envelope = message.isAlbum - ? MediaUtils.buildAlbumEnvelope(references, message.message) - : MediaUtils.buildMediaEnvelope(references.first, message.message); + ? MediaUtils.buildAlbumEnvelope(references, message.message, + forwarded: message.forwarded) + : MediaUtils.buildMediaEnvelope(references.first, message.message, + forwarded: message.forwarded); await _sendEnvelope(recipient, envelope, message.sentAt); } @@ -402,9 +410,10 @@ class ChatSender { // A reply needs the quote next to the body; everything else stays raw text // so an older client can still read it. final reply = message.replyTo; - final plaintext = reply == null + final plaintext = reply == null && !message.forwarded ? utf8.encode(message.message) - : buildTextEnvelope(message.message, reply); + : buildTextEnvelope(message.message, reply, + forwarded: message.forwarded); final data = await CryptoUtils.encryptMessageData( plaintext, bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); Singleton().wsClient.sendMessage(WsMessage.privateMessage(NewPrivateMessage( diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 23d9bd0..3af0b89 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -501,13 +501,14 @@ class MediaUtils { /// Build the plaintext (pre-encryption) bytes for a media message: a JSON /// envelope wrapping the [reference] and optional [caption]. - static Uint8List buildMediaEnvelope( - MediaReference reference, String caption) { + static Uint8List buildMediaEnvelope(MediaReference reference, String caption, + {bool forwarded = false}) { final map = { 'whisperMsg': envelopeVersion, 'kind': 'media', 'caption': caption, 'media': reference.toJson(), + if (forwarded) 'forwarded': true, }; return Uint8List.fromList(utf8.encode(jsonEncode(map))); } @@ -515,12 +516,14 @@ class MediaUtils { /// Build the plaintext (pre-encryption) bytes for an album message: a JSON /// envelope wrapping [references] and an optional [caption]. static Uint8List buildAlbumEnvelope( - List references, String caption) { + List references, String caption, + {bool forwarded = false}) { final map = { 'whisperMsg': envelopeVersionAlbum, 'kind': 'media', 'caption': caption, 'media': references.map((reference) => reference.toJson()).toList(), + if (forwarded) 'forwarded': true, }; return Uint8List.fromList(utf8.encode(jsonEncode(map))); } @@ -532,11 +535,13 @@ class MediaUtils { final decoded = jsonDecode(utf8.decode(plaintext)); if (decoded is Map && decoded['kind'] == 'media') { final caption = (decoded['caption'] as String?) ?? ''; + final forwarded = decoded['forwarded'] == true; if (decoded['whisperMsg'] == envelopeVersion && decoded['media'] is Map) { final reference = MediaReference.fromJson( Map.from(decoded['media'] as Map)); - return ParsedMediaEnvelope([reference], caption); + return ParsedMediaEnvelope([reference], caption, + forwarded: forwarded); } if (decoded['whisperMsg'] == envelopeVersionAlbum && decoded['media'] is List) { @@ -546,7 +551,8 @@ class MediaUtils { MediaReference.fromJson(Map.from(item))) .toList(); if (references.isNotEmpty) { - return ParsedMediaEnvelope(references, caption); + return ParsedMediaEnvelope(references, caption, + forwarded: forwarded); } } } @@ -618,7 +624,11 @@ class ParsedMediaEnvelope { final List references; final String caption; - const ParsedMediaEnvelope(this.references, this.caption); + /// The sender passed on somebody else's attachment instead of writing it. + final bool forwarded; + + const ParsedMediaEnvelope(this.references, this.caption, + {this.forwarded = false}); } /// Thin wrapper around the [AudioRecorder] for hold-to-record voice messages. diff --git a/lib/utils/singleton.dart b/lib/utils/singleton.dart index 8baf1cb..da125b1 100644 --- a/lib/utils/singleton.dart +++ b/lib/utils/singleton.dart @@ -91,5 +91,7 @@ class Singleton { MessagesApi get messagesApi => MessagesApi(_api); + ChatsApi get chatsApi => ChatsApi(_api); + bool get offlineMode => _offlineMode; } diff --git a/lib/utils/text_envelope.dart b/lib/utils/text_envelope.dart index 81bad79..79013e1 100644 --- a/lib/utils/text_envelope.dart +++ b/lib/utils/text_envelope.dart @@ -53,10 +53,13 @@ class ReplyRef { /// Payload of a text message that quotes another one. class ParsedTextEnvelope { - const ParsedTextEnvelope(this.body, this.reply); + const ParsedTextEnvelope(this.body, this.reply, {this.forwarded = false}); final String body; final ReplyRef? reply; + + /// The sender passed on somebody else's text instead of writing it. + final bool forwarded; } /// Envelope version of a text message carrying a quote. Versions 1 and 2 are @@ -64,13 +67,18 @@ class ParsedTextEnvelope { /// quotes anything keeps writing what every older client can open. const int textEnvelopeVersion = 3; -/// Plaintext (pre-encryption) bytes of a reply. -Uint8List buildTextEnvelope(String body, ReplyRef reply) { +/// Plaintext (pre-encryption) bytes of a reply or a forwarded message. +/// +/// The envelope stays version 3 and the flags are optional keys, so a reader +/// that predates them still shows the body instead of raw JSON. +Uint8List buildTextEnvelope(String body, ReplyRef? reply, + {bool forwarded = false}) { final map = { 'whisperMsg': textEnvelopeVersion, 'kind': 'text', 'body': body, - 'replyTo': reply.toJson(), + if (reply != null) 'replyTo': reply.toJson(), + if (forwarded) 'forwarded': true, }; return Uint8List.fromList(utf8.encode(jsonEncode(map))); } @@ -87,7 +95,11 @@ ParsedTextEnvelope? tryParseTextEnvelope(Uint8List plaintext) { if (body is! String) { return null; } - return ParsedTextEnvelope(body, ReplyRef.fromJson(decoded['replyTo'])); + return ParsedTextEnvelope( + body, + ReplyRef.fromJson(decoded['replyTo']), + forwarded: decoded['forwarded'] == true, + ); } } catch (_) { // Not JSON / not a text envelope -> plain text. diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 6697aa0..19aa6f9 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -14,6 +14,7 @@ import 'package:whisper_openapi_client_dart/api.dart'; import 'package:basic_utils/basic_utils.dart' as bu; import 'package:whisper_websocket_client_dart/models/delivery_ack.dart'; import 'package:whisper_websocket_client_dart/models/message_event.dart'; +import 'package:whisper_websocket_client_dart/models/read_receipt.dart'; import 'package:whisper_websocket_client_dart/models/synced.dart'; import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import 'package:whisper_websocket_client_dart/models/private_message.dart'; @@ -339,6 +340,7 @@ class Utils { DateTime.now(), false, downloadStatus: pm.MediaDownloadStatus.pending, + forwarded: envelope.forwarded, ); albumMsg.setAlbum(envelope.references .map((ref) => pm.AlbumItem( @@ -369,6 +371,7 @@ class Utils { durationMs: ref.durationMs, fileName: ref.fileName, downloadStatus: pm.MediaDownloadStatus.pending, + forwarded: envelope.forwarded, ); return (mediaMsg, [ref], message.peerId); } @@ -380,7 +383,8 @@ class Utils { textEnvelope?.body ?? utf8.decode(decryptedMessage), message.sentAt, DateTime.now(), - false) + false, + forwarded: textEnvelope?.forwarded ?? false) ..setReplyTo(textEnvelope?.reply); return (textMsg, const [], message.peerId); } catch (e) { @@ -555,6 +559,10 @@ class Utils { for (final event in synced.events) { await applyEvent(event); } + for (final receipt in synced.reads) { + await CacheUtils.setPeerReadAt( + receipt.peerId, receipt.readAt.toLocal()); + } // Only after the batch is stored: a cursor ahead of the local messages // would drop them for good. await CacheUtils.setSyncSeq(synced.syncedThrough); @@ -573,6 +581,14 @@ class Utils { await applyEvent(wsResponse.payload as MessageEvent); break; + // The other participant moved their read cursor + case WsResponseType.read: + final receipt = wsResponse.payload as ReadReceipt; + await CacheUtils.setPeerReadAt( + receipt.peerId, receipt.readAt.toLocal()); + MessageNotifier().notify(); + break; + // Delete account case WsResponseType.deleteAccount: await CacheUtils.deleteCache(); @@ -724,6 +740,23 @@ class Utils { } } + /// Publishes how far the account has read [peerId]'s chat. Returns false when + /// the server refused, so the caller can retry on the next message. + static Future sendReadCursor(String peerId, DateTime readAt) async { + try { + await callApi( + () => Singleton().chatsApi.setReadCursor( + peerId, + setReadCursorInput: SetReadCursorInput(readAt: readAt.toUtc()), + ), + rethrowErr: true, + showError: false); + return true; + } catch (_) { + return false; + } + } + /// Invoked after a successful connect, e.g. to push a pending Firebase id /// without polling. static Future Function()? onConnected; diff --git a/lib/utils/version.dart b/lib/utils/version.dart index 8ed168e..6bd8c79 100644 --- a/lib/utils/version.dart +++ b/lib/utils/version.dart @@ -1,3 +1,3 @@ /// Version of this app build, sent as `X-Client-Version`. The server refuses a /// login below its `minClientVersion` with a code we can translate. -const String appVersion = '0.2.0'; +const String appVersion = '0.3.0'; diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 845742e..22504c4 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -27,6 +27,10 @@ class ChatBubble extends StatefulWidget { /// Whether this bubble is part of the current selection. final bool selected; + /// Instant up to which the peer read the chat; null when they never + /// published one (receipts off or nothing read yet). + final DateTime? readAt; + /// Toggles this bubble in the selection (tap and long-press). final VoidCallback? onSelect; @@ -44,6 +48,7 @@ class ChatBubble extends StatefulWidget { {required this.accentColor, this.selectionMode = false, this.selected = false, + this.readAt, this.onSelect, this.onActions, this.onReply, @@ -305,6 +310,18 @@ class _ChatBubbleState extends State { : CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ + if (widget.message.forwarded) + Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Text( + 'forwardedMessage'.tr(), + style: TextStyle( + color: bubbleTextColor().withValues(alpha: 0.8), + fontSize: 11, + fontStyle: FontStyle.italic, + ), + ), + ), if (widget.message.isReply) quoteBlock(), content(), if (widget.message.isEdited) @@ -495,6 +512,28 @@ class _ChatBubbleState extends State { ), ), ), + // Sent messages carry ticks: one for the ack + // (the server stored it), two when the peer's + // read cursor passed it. + if (widget.message.isMe && + widget.message.sendStatus == SendStatus.sent) + Padding( + padding: const EdgeInsets.only(top: 2), + child: Tooltip( + message: _readByPeer + ? 'messageRead'.tr() + : 'messageDelivered'.tr(), + child: Icon( + _readByPeer ? Icons.done_all : Icons.done, + size: 13, + color: _readByPeer + ? Theme.of(context) + .colorScheme + .primary + : Colors.grey, + ), + ), + ), ], ), ), @@ -510,6 +549,12 @@ class _ChatBubbleState extends State { ); } + /// Whether the peer's read cursor already covers this message. + bool get _readByPeer { + final readAt = widget.readAt; + return readAt != null && !widget.message.sentAt.isAfter(readAt); + } + Widget _swipeBackground(Alignment alignment, Color color) { return Container( alignment: alignment, diff --git a/pubspec.lock b/pubspec.lock index e465cb3..0210697 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1783,14 +1783,14 @@ packages: path: "../whisper_openapi_client_dart" relative: true source: path - version: "0.2.0" + version: "0.3.0" whisper_websocket_client_dart: dependency: "direct main" description: path: "../whisper_websocket_client_dart" relative: true source: path - version: "0.2.0" + version: "0.3.0" win32: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index c66312a..b9cce94 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,7 +3,7 @@ description: "Secure private self-hosted end-to-end encryption messaging app." publish_to: 'none' # Remove this line if you wish to publish to pub.dev # Bump before every release; the release workflow tags v and fails if # that tag already exists. The build number after + must only ever grow. -version: 0.2.0+4 +version: 0.3.0+5 environment: sdk: '>=3.4.3 <4.0.0' @@ -51,11 +51,11 @@ dependencies: whisper_openapi_client_dart: git: url: https://github.com/jsfraz/whisper_openapi_client_dart.git - ref: v0.2.0 + ref: v0.3.0 whisper_websocket_client_dart: git: url: https://github.com/jsfraz/whisper_websocket_client_dart.git - ref: v0.2.0 + ref: v0.3.0 dev_dependencies: flutter_test: diff --git a/test/chat_bubble_test.dart b/test/chat_bubble_test.dart index 07ee74b..72d9c96 100644 --- a/test/chat_bubble_test.dart +++ b/test/chat_bubble_test.dart @@ -153,6 +153,42 @@ void main() { await tester.pumpAndSettle(); expect(find.text('Show less'), findsOneWidget); + // A forwarded message says so above its body. + await show(ChatBubble( + null, + PrivateMessage( + '2', 'přeposlaný text', DateTime(2026), DateTime(2026), true) + ..forwarded = true, + null, + peer, + accentColor: Colors.blue, + )); + expect(find.text('Forwarded'), findsOneWidget); + expect(renderedText(tester), contains('přeposlaný text')); + + // Own messages carry one tick once the server stored them; the peer's read + // cursor covering the message turns it into two. + final sent = DateTime(2026, 11, 19, 12); + await show(ChatBubble( + null, + PrivateMessage('1', 'odesláno', sent, sent, true), + null, + peer, + accentColor: Colors.blue, + )); + expect(find.byIcon(Icons.done), findsOneWidget); + expect(find.byIcon(Icons.done_all), findsNothing); + + await show(ChatBubble( + null, + PrivateMessage('1', 'přečteno', sent, sent, true), + null, + peer, + accentColor: Colors.blue, + readAt: sent, + )); + expect(find.byIcon(Icons.done_all), findsOneWidget); + // Phone numbers and e-mails are underlined like a link. await show(ChatBubble( null, diff --git a/test/message_lifecycle_test.dart b/test/message_lifecycle_test.dart index 27ae135..b11fa92 100644 --- a/test/message_lifecycle_test.dart +++ b/test/message_lifecycle_test.dart @@ -90,6 +90,25 @@ void main() { expect(await CacheUtils.getPinnedMessages(peer), isEmpty); }); + test('read receipts are off by default and the peer cursor only moves on', + () async { + const peer = 'peer-id'; + expect(await CacheUtils.isReadReceiptsEnabled(peer), isFalse); + + await CacheUtils.setReadReceiptsEnabled(peer, true); + expect(await CacheUtils.isReadReceiptsEnabled(peer), isTrue); + + await CacheUtils.setPeerReadAt(peer, DateTime(2026, 11, 19, 12, 5)); + expect(await CacheUtils.getPeerReadAt(peer), DateTime(2026, 11, 19, 12, 5)); + + // Out of order frames must not take the tick back. + await CacheUtils.setPeerReadAt(peer, DateTime(2026, 11, 19, 12, 1)); + expect(await CacheUtils.getPeerReadAt(peer), DateTime(2026, 11, 19, 12, 5)); + + await CacheUtils.setReadReceiptsEnabled(peer, false); + expect(await CacheUtils.isReadReceiptsEnabled(peer), isFalse); + }); + test('the mutation cursor never moves backwards', () async { await CacheUtils.setSyncEventSeq(5); await CacheUtils.setSyncEventSeq(3); diff --git a/test/text_envelope_test.dart b/test/text_envelope_test.dart index d595b0d..c19a7b6 100644 --- a/test/text_envelope_test.dart +++ b/test/text_envelope_test.dart @@ -33,6 +33,26 @@ void main() { expect(decoded['whisperMsg'], textEnvelopeVersion); }); + test('a forwarded message survives the round trip without a quote', () { + final envelope = buildTextEnvelope('přeposláno', null, forwarded: true); + + final parsed = tryParseTextEnvelope(envelope); + expect(parsed, isNotNull); + expect(parsed!.body, 'přeposláno'); + expect(parsed.forwarded, isTrue); + expect(parsed.reply, isNull); + // The version stays 3: an older reader still opens the body instead of + // showing raw JSON. + final decoded = jsonDecode(utf8.decode(envelope)) as Map; + expect(decoded['whisperMsg'], textEnvelopeVersion); + }); + + test('an envelope without the flag is not a forward', () { + final parsed = tryParseTextEnvelope(buildTextEnvelope( + 'x', ReplyRef(senderId: 'a', sentAt: DateTime(2026), preview: 'y'))); + expect(parsed!.forwarded, isFalse); + }); + test('plain text is not an envelope', () { expect(tryParseTextEnvelope(bytes('ahoj')), isNull); }); From f126e2c087fbe234caf55cf8a69fa0edf23cd5f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 19 Nov 2026 23:19:56 +0100 Subject: [PATCH 094/181] fix(chat): let the edit dialog own its controller Disposing the controller right after showDialog returned raced the route's exit animation: the TextField was still mounted and the dialog's inherited elements deactivated with a live dependent, tripping InheritedElement.debugDeactivated on Android (red screen after a successful edit). Desktop happened to survive it. --- lib/utils/message_actions.dart | 71 ++++++++++++++++++++++++---------- test/edit_dialog_test.dart | 67 ++++++++++++++++++++++++++++++++ 2 files changed, 117 insertions(+), 21 deletions(-) create mode 100644 test/edit_dialog_test.dart diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 2ba6176..48401b5 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -257,30 +257,10 @@ class MessageActions { if (id == null || id.isEmpty) { return; } - final controller = TextEditingController(text: message.message); final text = await showDialog( context: context, - builder: (ctx) => AlertDialog( - title: Text('editMessage'.tr()), - content: TextField( - controller: controller, - autofocus: true, - maxLines: null, - minLines: 1, - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(ctx), - child: Text('cancel'.tr()), - ), - TextButton( - onPressed: () => Navigator.pop(ctx, controller.text), - child: Text('okText'.tr()), - ), - ], - ), + builder: (_) => _EditMessageDialog(initial: message.message), ); - controller.dispose(); if (text == null || text.trim().isEmpty || text == message.message) { return; } @@ -401,3 +381,52 @@ class MessageActions { onDeleted?.call(); } } + +/// Edit dialog that owns its controller. +/// +/// Disposing a controller right after `showDialog` returns races the route's +/// exit animation: the `TextField` is still mounted and the dialog's inherited +/// elements deactivate with a live dependent, which trips +/// `InheritedElement.debugDeactivated` on a phone. +class _EditMessageDialog extends StatefulWidget { + const _EditMessageDialog({required this.initial}); + + final String initial; + + @override + State<_EditMessageDialog> createState() => _EditMessageDialogState(); +} + +class _EditMessageDialogState extends State<_EditMessageDialog> { + late final TextEditingController _controller = + TextEditingController(text: widget.initial); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text('editMessage'.tr()), + content: TextField( + controller: _controller, + autofocus: true, + maxLines: null, + minLines: 1, + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text('cancel'.tr()), + ), + TextButton( + onPressed: () => Navigator.pop(context, _controller.text), + child: Text('okText'.tr()), + ), + ], + ); + } +} diff --git a/test/edit_dialog_test.dart b/test/edit_dialog_test.dart new file mode 100644 index 0000000..026cf45 --- /dev/null +++ b/test/edit_dialog_test.dart @@ -0,0 +1,67 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/models/profile.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/message_actions.dart'; +import 'package:whisper/utils/singleton.dart'; + +/// Closing the edit dialog used to dispose its controller while the route was +/// still animating out; that trips `InheritedElement.debugDeactivated` on a +/// device (red screen after a successful edit). The dialog now owns its +/// controller, and this test locks the close path in. +void main() { + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + testWidgets('the edit dialog opens and closes without a framework assert', + (tester) async { + final message = + PrivateMessage('1', 'hello', DateTime(2026), DateTime(2026), true) + ..id = '00000000-0000-4000-8000-000000000000'; + + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Scaffold( + body: Center( + child: Builder(builder: (inner) { + return ElevatedButton( + onPressed: () => MessageActions.edit(inner, message, '5'), + child: const Text('edit'), + ); + }), + ), + ), + ); + }), + )); + await tester.pumpAndSettle(); + + await tester.tap(find.text('edit')); + await tester.pumpAndSettle(); + expect(find.text('Edit message'), findsOneWidget); + + // Typing then cancelling is the same teardown path as confirming. + await tester.enterText(find.byType(TextField), 'hello again'); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.text('Edit message'), findsNothing); + }); +} From 73cc68622c5d85f25b5bb79c1e964b7be3b57eb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 19 Nov 2026 23:36:41 +0100 Subject: [PATCH 095/181] feat(chat): pin reactions to the bubble as one bottom badge The chips sat under the bubble with a gap and on the bubble's own side. They are now a single pill hanging on the bubble's bottom edge, on the opposite side, with the emoji adjacent (a count appears only when the same emoji came from several participants). --- lib/widgets/chat_bubble.dart | 122 +++++++++++++++++++++-------------- test/chat_bubble_test.dart | 21 ++++++ 2 files changed, 95 insertions(+), 48 deletions(-) diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 22504c4..1ad8029 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -79,19 +79,34 @@ class _ChatBubbleState extends State { isEmojiOnly(widget.message.message) && emojiCount(widget.message.message) <= 3; - /// One reaction chip: the emoji, plus how many participants picked it. - Widget _reactionChip(String emoji) { - final count = - widget.message.reactions?.values.where((v) => v == emoji).length ?? 0; + /// One badge for all reactions of the bubble: the emoji sit in a single pill + /// with no gap between them, and a count only when the same emoji came from + /// more than one participant. + Widget _reactionBadge() { + final emojis = widget.message.reactionEmojis; + final counts = {}; + for (final emoji in widget.message.reactions?.values ?? const []) { + counts[emoji] = (counts[emoji] ?? 0) + 1; + } return Container( - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1), decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceContainerHigh, borderRadius: BorderRadius.circular(10), ), - child: Text( - count > 1 ? '$emoji $count' : emoji, - style: const TextStyle(fontSize: 12), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + for (var i = 0; i < emojis.length; i++) ...[ + if (i > 0) const SizedBox(width: 1), + Text( + (counts[emojis[i]] ?? 1) > 1 + ? '${emojis[i]}${counts[emojis[i]]}' + : emojis[i], + style: const TextStyle(fontSize: 12), + ), + ], + ], ), ); } @@ -374,6 +389,26 @@ class _ChatBubbleState extends State { child: bubble, ); + // The reactions hang on the bubble's bottom edge as one badge, on the side + // opposite the bubble's own side, the way a messenger pins them there. + final bubbleWithBadge = widget.message.reactionEmojis.isEmpty + ? bubbleBox + : Stack( + clipBehavior: Clip.none, + children: [ + bubbleBox, + Positioned( + bottom: -8, + left: widget.message.isMe ? 8 : null, + right: widget.message.isMe ? null : 8, + child: GestureDetector( + onTap: () => (widget.onActions ?? widget.onSelect)?.call(), + child: _reactionBadge(), + ), + ), + ], + ); + return Padding( padding: EdgeInsets.only( left: widget.message.isMe ? 96 : 16, @@ -448,46 +483,37 @@ class _ChatBubbleState extends State { ? CrossAxisAlignment.end : CrossAxisAlignment.start, children: [ - if (widget.onReply != null && - !widget.selectionMode) - Dismissible( - key: ValueKey( - 'reply|${widget.message.senderId}' - '|${widget.message.sentAt.microsecondsSinceEpoch}'), - direction: DismissDirection.horizontal, - // The swipe is an action, not a delete: the - // bubble always springs back. - confirmDismiss: (_) async { - widget.onReply?.call(); - return false; - }, - background: _swipeBackground( - Alignment.centerLeft, bubbleTextColor()), - secondaryBackground: _swipeBackground( - Alignment.centerRight, bubbleTextColor()), - child: bubbleBox, - ) - else - bubbleBox, - // Reactions sit just outside the bubble, the - // way they do in the other messengers. - if (widget.message.reactionEmojis.isNotEmpty) - GestureDetector( - onTap: () => - (widget.onActions ?? widget.onSelect) - ?.call(), - child: Padding( - padding: const EdgeInsets.only(top: 2), - child: Wrap( - spacing: 4, - children: [ - for (final emoji - in widget.message.reactionEmojis) - _reactionChip(emoji), - ], - ), - ), - ), + Padding( + // Room for the reaction badge hanging under + // the bubble. + padding: EdgeInsets.only( + bottom: + widget.message.reactionEmojis.isEmpty + ? 0 + : 10), + child: widget.onReply != null && + !widget.selectionMode + ? Dismissible( + key: ValueKey( + 'reply|${widget.message.senderId}' + '|${widget.message.sentAt.microsecondsSinceEpoch}'), + direction: DismissDirection.horizontal, + // The swipe is an action, not a + // delete: the bubble springs back. + confirmDismiss: (_) async { + widget.onReply?.call(); + return false; + }, + background: _swipeBackground( + Alignment.centerLeft, + bubbleTextColor()), + secondaryBackground: _swipeBackground( + Alignment.centerRight, + bubbleTextColor()), + child: bubbleWithBadge, + ) + : bubbleWithBadge, + ), // Outgoing messages show a clock while they are // being sent and an error when the send failed. if (widget.message.isMe && diff --git a/test/chat_bubble_test.dart b/test/chat_bubble_test.dart index 72d9c96..4aeaff4 100644 --- a/test/chat_bubble_test.dart +++ b/test/chat_bubble_test.dart @@ -189,6 +189,27 @@ void main() { )); expect(find.byIcon(Icons.done_all), findsOneWidget); + // Reactions are one badge hanging on the bubble's bottom edge: no gap + // between the emoji and none between the badge and the bubble. + final sentAt = DateTime(2026, 11, 19, 12); + await show(ChatBubble( + null, + PrivateMessage('1', 'reaguj', sentAt, sentAt, true) + ..reactions = {'1': '❤️', '2': '😂'}, + null, + peer, + accentColor: Colors.blue, + )); + expect(find.text('❤️'), findsOneWidget); + expect(find.text('😂'), findsOneWidget); + final body = tester.getRect(find.text('reaguj')); + final heart = tester.getRect(find.text('❤️')); + final laugh = tester.getRect(find.text('😂')); + // Overlapping the bubble instead of sitting below it. + expect(heart.top, lessThan(body.bottom + 5)); + // The two emoji are one badge, not two chips with a gap. + expect(laugh.left - heart.right, lessThan(8)); + // Phone numbers and e-mails are underlined like a link. await show(ChatBubble( null, From 4029483a303cb8d9a7d55665b3f2cb512cd916ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 19 Nov 2026 23:40:30 +0100 Subject: [PATCH 096/181] feat(chat): double-tap reacts instead of quoting Double-tap now toggles the quick reaction (heart) on the message; swipe still quotes it. The bubble badge also sits a bit lower, hanging further past the bubble's bottom edge. --- lib/pages/chat_page.dart | 2 ++ lib/utils/message_actions.dart | 3 +++ lib/widgets/chat_bubble.dart | 15 +++++++++++---- test/chat_bubble_test.dart | 7 +++++-- 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index f0c9d47..25d2719 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1370,6 +1370,8 @@ class _ChatPageState extends State { readAt: _peerReadAt, onSelect: () => _toggleSelected(message), onActions: () => _openMessageActions(message), + onQuickReact: () => MessageActions.react( + message, widget.user.id, MessageActions.quickReaction), onReply: () => _startReply(message), onTapQuote: message.isReply ? () => _jumpToMessage(message.replyTo!.sentAt) diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 48401b5..392a291 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -36,6 +36,9 @@ class MessageActions { static const IconData unpinIcon = Icons.push_pin; static const IconData selectIcon = Icons.checklist; + /// Reaction a double-tap adds, toggled off by a second double-tap. + static const String quickReaction = '❤️'; + /// Emoji offered by the reaction row. A short fixed set keeps reacting one /// tap instead of opening a picker. static const List reactionEmojis = [ diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 1ad8029..3eb14ff 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -37,9 +37,13 @@ class ChatBubble extends StatefulWidget { /// Opens the action sheet (long-press). Falls back to [onSelect] when unset. final VoidCallback? onActions; - /// Quotes this message in the composer (double-tap and swipe). + /// Quotes this message in the composer (swipe, and double-tap when no quick + /// reaction is wired). final VoidCallback? onReply; + /// Double-tap: adds the quick reaction to this message. + final VoidCallback? onQuickReact; + /// Jumps to the quoted message. final VoidCallback? onTapQuote; @@ -52,6 +56,7 @@ class ChatBubble extends StatefulWidget { this.onSelect, this.onActions, this.onReply, + this.onQuickReact, this.onTapQuote, super.key}); @@ -398,7 +403,7 @@ class _ChatBubbleState extends State { children: [ bubbleBox, Positioned( - bottom: -8, + bottom: -12, left: widget.message.isMe ? 8 : null, right: widget.message.isMe ? null : 8, child: GestureDetector( @@ -443,7 +448,9 @@ class _ChatBubbleState extends State { GestureDetector( onTap: onTap, onLongPress: onLongPress, - onDoubleTap: widget.onReply, + onDoubleTap: widget.selectionMode + ? null + : (widget.onQuickReact ?? widget.onReply), child: Align( alignment: widget.message.isMe ? Alignment.centerRight @@ -490,7 +497,7 @@ class _ChatBubbleState extends State { bottom: widget.message.reactionEmojis.isEmpty ? 0 - : 10), + : 14), child: widget.onReply != null && !widget.selectionMode ? Dismissible( diff --git a/test/chat_bubble_test.dart b/test/chat_bubble_test.dart index 4aeaff4..078b21c 100644 --- a/test/chat_bubble_test.dart +++ b/test/chat_bubble_test.dart @@ -124,7 +124,8 @@ void main() { )); expect(find.byIcon(Icons.check_circle), findsOneWidget); - // Double tap quotes the message in the composer. + // Double tap adds the quick reaction instead of quoting. + var reacted = false; var replied = false; await show(ChatBubble( null, @@ -133,12 +134,14 @@ void main() { peer, accentColor: Colors.blue, onReply: () => replied = true, + onQuickReact: () => reacted = true, )); await tester.tap(find.text('ahoj')); await tester.pump(const Duration(milliseconds: 50)); await tester.tap(find.text('ahoj')); await tester.pumpAndSettle(); - expect(replied, isTrue); + expect(reacted, isTrue); + expect(replied, isFalse); // A long message can be unfolded. await show(ChatBubble( From 0065f7560ffd4f0630944d320a93442aa17a27e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 19 Nov 2026 23:57:00 +0100 Subject: [PATCH 097/181] feat(chat): edit an attachment caption, badge on the media corner An own attachment now offers "Edit message" for its caption: the new text goes into a rebuilt media (or album) envelope, so the attachment survives. The reference is kept on the row from now on, the upload cache and a re-upload of the local copy cover older rows, and an archive page backfills the reference for messages stored before it was kept. The reaction badge of an attachment sits on the media's bottom corner instead of hanging at the caption's level. --- assets/translations/cs.json | 3 +- assets/translations/en.json | 3 +- lib/models/private_message.dart | 49 +++++++++++++++++++++++++++++++ lib/models/private_message.g.dart | 7 +++-- lib/utils/cache_utils.dart | 9 +++++- lib/utils/chat_sender.dart | 22 ++++++++++++++ lib/utils/message_actions.dart | 34 +++++++++++++++------ lib/utils/utils.dart | 2 ++ lib/widgets/chat_bubble.dart | 12 ++++++-- lib/widgets/media_bubble.dart | 23 +++++++++++++-- test/message_actions_test.dart | 14 +++++++++ test/message_lifecycle_test.dart | 48 ++++++++++++++++++++++++++++++ 12 files changed, 207 insertions(+), 19 deletions(-) diff --git a/assets/translations/cs.json b/assets/translations/cs.json index fa35d80..2f78539 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -252,5 +252,6 @@ "forwardedMessage": "Přeposláno", "readReceipts": "Potvrzení o přečtení", "messageDelivered": "Doručeno", - "messageRead": "Přečteno" + "messageRead": "Přečteno", + "attachmentCaptionUneditable": "Tetó příloze nelze upravit popisek" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 15a0dd8..43e5dbd 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -252,5 +252,6 @@ "forwardedMessage": "Forwarded", "readReceipts": "Read receipts", "messageDelivered": "Delivered", - "messageRead": "Read" + "messageRead": "Read", + "attachmentCaptionUneditable": "This attachment's caption can't be edited" } diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index a5a5ac8..80c3a4d 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import 'package:easy_localization/easy_localization.dart'; import 'package:hive/hive.dart'; +import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../utils/singleton.dart'; @@ -49,6 +50,7 @@ class AlbumItem { this.height, this.durationMs, this.fileName, + this.keyB64, this.localPath, this.status = MediaDownloadStatus.ready, }); @@ -63,6 +65,11 @@ class AlbumItem { int? durationMs; String? fileName; + /// Base64 of the transport key of the attachment, kept so a caption can be + /// re-encrypted into a new envelope later. Null on rows stored before it was + /// kept. + String? keyB64; + /// Encrypted-at-rest file on this device, null until downloaded/sent. String? localPath; int status; @@ -85,6 +92,7 @@ class AlbumItem { if (height != null) 'height': height, if (durationMs != null) 'durationMs': durationMs, if (fileName != null) 'fileName': fileName, + if (keyB64 != null) 'keyB64': keyB64, if (localPath != null) 'localPath': localPath, 'status': status, }; @@ -97,6 +105,7 @@ class AlbumItem { height: (json['height'] as num?)?.toInt(), durationMs: (json['durationMs'] as num?)?.toInt(), fileName: json['fileName'] as String?, + keyB64: json['keyB64'] as String?, localPath: json['localPath'] as String?, status: (json['status'] as num?)?.toInt() ?? MediaDownloadStatus.ready, ); @@ -196,6 +205,12 @@ class PrivateMessage extends HiveObject { @HiveField(22, defaultValue: false) bool forwarded; + /// JSON of the media reference (id, key, type, size, metadata) for a single + /// attachment. Kept so editing the caption can build a new envelope without + /// the original upload; null on rows stored before it was kept. + @HiveField(23) + String? mediaRefJson; + /// Cache for [album], keyed by the [albumJson] it was decoded from. String? _albumCacheJson; List? _albumCache; @@ -223,8 +238,42 @@ class PrivateMessage extends HiveObject { this.editedAt, this.reactions, this.forwarded = false, + this.mediaRefJson, }); + /// References needed to re-encrypt this message with a new caption, null for + /// text messages and when their key was never kept. + List? get mediaReferences { + if (isAlbum) { + final refs = []; + for (final item in album) { + final key = item.keyB64 == null ? null : base64Decode(item.keyB64!); + final type = item.mediaType; + if (key == null || type == null) { + return null; + } + refs.add(MediaReference(item.mediaId, key, type, item.size, + width: item.width, + height: item.height, + durationMs: item.durationMs, + fileName: item.fileName)); + } + return refs.isEmpty ? null : refs; + } + final raw = mediaRefJson; + if (raw == null || raw.isEmpty) { + return null; + } + try { + return [ + MediaReference.fromJson( + Map.from(jsonDecode(raw) as Map)) + ]; + } catch (_) { + return null; + } + } + /// Whether the sender edited the text after sending it. bool get isEdited => editedAt != null; diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index ed2fad0..b208ed2 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -39,13 +39,14 @@ class PrivateMessageAdapter extends TypeAdapter { editedAt: fields[20] as DateTime?, reactions: (fields[21] as Map?)?.cast(), forwarded: fields[22] == null ? false : fields[22] as bool, + mediaRefJson: fields[23] as String?, )..id = fields[19] as String?; } @override void write(BinaryWriter writer, PrivateMessage obj) { writer - ..writeByte(23) + ..writeByte(24) ..writeByte(0) ..write(obj.senderId) ..writeByte(1) @@ -91,7 +92,9 @@ class PrivateMessageAdapter extends TypeAdapter { ..writeByte(21) ..write(obj.reactions) ..writeByte(22) - ..write(obj.forwarded); + ..write(obj.forwarded) + ..writeByte(23) + ..write(obj.mediaRefJson); } @override diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index bf32486..81f4367 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -455,7 +455,14 @@ class CacheUtils { await _migrateLegacyConversation(box, userId); for (final message in messages) { final key = messageKey(userId, message.sentAt); - if (box.containsKey(key)) { + final stored = box.get(key); + if (stored is PrivateMessage) { + // Rows written before the transport key was kept cannot edit their + // caption; the archive page brings the reference back, so fill it in. + if (stored.mediaRefJson == null && message.mediaRefJson != null) { + stored.mediaRefJson = message.mediaRefJson; + await box.put(key, stored); + } continue; } await box.put(key, message); diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index e27b708..494f5a4 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -136,6 +136,9 @@ class ChatSender { await _sendEnvelope(recipient, envelope, message.sentAt); await CacheUtils.updateStoredMessage(recipient.id, message, (stored) { stored.mediaId = reference.mediaId; + // Keep the reference (with its transport key) so the caption can be + // edited later without the original upload. + stored.mediaRefJson = jsonEncode(reference.toJson()); }); return true; } catch (e) { @@ -222,6 +225,7 @@ class ChatSender { final items = stored.album; for (var i = 0; i < items.length && i < references.length; i++) { items[i].mediaId = references[i].mediaId; + items[i].keyB64 = base64Encode(references[i].key); } stored.setAlbum(items); }); @@ -232,6 +236,24 @@ class ChatSender { } } + /// Media references of an already stored message, for re-encrypting it with a + /// new caption. Prefers what the row kept, then the upload cache, and only + /// re-uploads the local copies when neither has it (a message from a build + /// that did not keep the key yet). + static Future?> mediaReferencesFor( + User recipient, PrivateMessage message) async { + final kept = message.mediaReferences; + if (kept != null && kept.isNotEmpty) { + return kept; + } + final cached = _outgoingReferences[ + CacheUtils.messageKey(recipient.id, message.sentAt)]; + if (cached != null && cached.isNotEmpty) { + return cached; + } + return _uploadLocalCopies(recipient, message); + } + /// Resend every message that never received a delivery ack. /// /// Called after a WebSocket reconnect: the server deduplicates by diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 392a291..d4341da 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -87,10 +87,7 @@ class MessageActions { ], ), ), - if (message.isMe && - !message.isMedia && - !message.isUndecryptable && - canAddress) + if (message.isMe && !message.isUndecryptable && canAddress) ListTile( leading: const Icon(editIcon), title: Text('editMessage'.tr()), @@ -264,7 +261,9 @@ class MessageActions { context: context, builder: (_) => _EditMessageDialog(initial: message.message), ); - if (text == null || text.trim().isEmpty || text == message.message) { + // A plain message cannot become empty; a caption can be cleared. + final unchanged = text == null || text == message.message; + if (unchanged || (text.trim().isEmpty && !message.isMedia)) { return; } try { @@ -272,10 +271,27 @@ class MessageActions { if (peer == null) { return; } - // A reply keeps its quote; only the body changes. - final reply = message.replyTo; - final plaintext = - reply == null ? utf8.encode(text) : buildTextEnvelope(text, reply); + // A reply keeps its quote and an attachment keeps its media reference, so + // only the body of the envelope changes. + final Uint8List plaintext; + if (message.isMedia) { + final references = await ChatSender.mediaReferencesFor(peer, message); + if (references == null || references.isEmpty) { + await Fluttertoast.showToast( + msg: 'attachmentCaptionUneditable'.tr(), + backgroundColor: Colors.red); + return; + } + plaintext = message.isAlbum + ? MediaUtils.buildAlbumEnvelope(references, text, + forwarded: message.forwarded) + : MediaUtils.buildMediaEnvelope(references.first, text, + forwarded: message.forwarded); + } else { + final reply = message.replyTo; + plaintext = + reply == null ? utf8.encode(text) : buildTextEnvelope(text, reply); + } final data = await CryptoUtils.encryptMessageData( plaintext, bu.CryptoUtils.rsaPublicKeyFromPem(peer.publicKey)); final response = await Utils.callApi( diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 19aa6f9..1ef9d9e 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -351,6 +351,7 @@ class Utils { height: ref.height, durationMs: ref.durationMs, fileName: ref.fileName, + keyB64: base64Encode(ref.key), status: pm.MediaDownloadStatus.pending, )) .toList()); @@ -372,6 +373,7 @@ class Utils { fileName: ref.fileName, downloadStatus: pm.MediaDownloadStatus.pending, forwarded: envelope.forwarded, + mediaRefJson: jsonEncode(ref.toJson()), ); return (mediaMsg, [ref], message.peerId); } diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 3eb14ff..6c3082d 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -215,6 +215,12 @@ class _ChatBubbleState extends State { if (widget.message.isMedia) { return MediaBubble( message: widget.message, + badge: widget.message.reactionEmojis.isEmpty + ? null + : GestureDetector( + onTap: () => (widget.onActions ?? widget.onSelect)?.call(), + child: _reactionBadge(), + ), conversationUserId: widget.user.id, bubbleColor: bubbleBackground(), textColor: bubbleTextColor(), @@ -396,7 +402,8 @@ class _ChatBubbleState extends State { // The reactions hang on the bubble's bottom edge as one badge, on the side // opposite the bubble's own side, the way a messenger pins them there. - final bubbleWithBadge = widget.message.reactionEmojis.isEmpty + final bubbleWithBadge = widget.message.reactionEmojis.isEmpty || + widget.message.isMedia ? bubbleBox : Stack( clipBehavior: Clip.none, @@ -495,7 +502,8 @@ class _ChatBubbleState extends State { // the bubble. padding: EdgeInsets.only( bottom: - widget.message.reactionEmojis.isEmpty + widget.message.reactionEmojis.isEmpty || + widget.message.isMedia ? 0 : 14), child: widget.onReply != null && diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index f7eabce..0bace09 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -24,6 +24,9 @@ class MediaBubble extends StatefulWidget { final bool canRetry; final String conversationUserId; + /// Reaction badge drawn on the attachment's bottom corner. + final Widget? badge; + const MediaBubble({ required this.message, required this.bubbleColor, @@ -31,6 +34,7 @@ class MediaBubble extends StatefulWidget { required this.onRetry, required this.canRetry, required this.conversationUserId, + this.badge, super.key, }); @@ -237,9 +241,22 @@ class _MediaBubbleState extends State { : CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ - ClipRRect( - borderRadius: BorderRadius.circular(16), - child: media, + Stack( + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(16), + child: media, + ), + // On the attachment itself: the corner of the media, not the level + // of the caption below it. + if (widget.badge != null) + Positioned( + bottom: 6, + left: widget.message.isMe ? 6 : null, + right: widget.message.isMe ? null : 6, + child: widget.badge!, + ), + ], ), if (hasCaption) Container( diff --git a/test/message_actions_test.dart b/test/message_actions_test.dart index b42c443..881d87f 100644 --- a/test/message_actions_test.dart +++ b/test/message_actions_test.dart @@ -118,5 +118,19 @@ void main() { await tester.pumpAndSettle(); expect(find.text('Edit message'), findsOneWidget); expect(find.text('Unpin'), findsNothing); + + // Close the sheet + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + // An own attachment offers the caption edit too. + message = PrivateMessage( + '1', 'caption', DateTime(2026), DateTime(2026), true, + localPath: '/tmp/whisper_media_test', mediaTypeStr: 'image') + ..id = '00000000-0000-4000-8000-000000000000'; + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('Edit message'), findsOneWidget); + expect(find.text('Save attachment'), findsOneWidget); }); } diff --git a/test/message_lifecycle_test.dart b/test/message_lifecycle_test.dart index b11fa92..3f80419 100644 --- a/test/message_lifecycle_test.dart +++ b/test/message_lifecycle_test.dart @@ -1,9 +1,13 @@ +import 'dart:convert'; import 'dart:io'; +import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; import 'package:whisper/models/private_message.dart'; import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper_websocket_client_dart/models/media_reference.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; /// The local side of the lifecycle: an edit rewrites the stored text, a /// reaction is a per-user map, a pin lives on the chat, and the mutation cursor @@ -109,6 +113,50 @@ void main() { expect(await CacheUtils.isReadReceiptsEnabled(peer), isFalse); }); + test('a stored media reference rebuilds the envelope for a caption edit', + () async { + final key = Uint8List.fromList([1, 2, 3, 4]); + final reference = MediaReference('media-id', key, MediaType.image, 100, + width: 640, height: 480); + final message = + PrivateMessage(peer, 'caption', DateTime(2026), DateTime(2026), true) + ..mediaId = 'media-id' + ..mediaTypeStr = 'image' + ..mediaRefJson = jsonEncode(reference.toJson()); + + final rebuilt = message.mediaReferences; + expect(rebuilt, isNotNull); + expect(rebuilt!.single.mediaId, 'media-id'); + expect(rebuilt.single.key, key); + expect(rebuilt.single.width, 640); + + // An album is rebuilt from the per-item keys instead. + final album = + PrivateMessage(peer, 'album', DateTime(2026), DateTime(2026), true) + ..setAlbum([ + AlbumItem( + mediaId: 'a', + type: 'image', + size: 10, + keyB64: base64Encode(key), + ), + AlbumItem( + mediaId: 'b', + type: 'image', + size: 20, + keyB64: base64Encode(key), + ), + ]); + expect(album.mediaReferences, hasLength(2)); + expect(album.mediaReferences!.first.mediaId, 'a'); + + // Without the key there is nothing to re-encrypt, so editing is refused. + final legacy = + PrivateMessage(peer, 'legacy', DateTime(2026), DateTime(2026), true) + ..mediaTypeStr = 'image'; + expect(legacy.mediaReferences, isNull); + }); + test('the mutation cursor never moves backwards', () async { await CacheUtils.setSyncEventSeq(5); await CacheUtils.setSyncEventSeq(3); From b4a5d56bcb921125a42049cd382815b2dc96ee05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Thu, 19 Nov 2026 23:58:27 +0100 Subject: [PATCH 098/181] fix(chat): keep the attachment reaction badge off the corner curve At 6 px the pill straddled the rounded corner, where the media is transparent, so half of it hung over the edge. 12 px keeps it on the attachment. --- lib/widgets/media_bubble.dart | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 0bace09..0badcb0 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -251,9 +251,11 @@ class _MediaBubbleState extends State { // of the caption below it. if (widget.badge != null) Positioned( - bottom: 6, - left: widget.message.isMe ? 6 : null, - right: widget.message.isMe ? null : 6, + // Clear of the rounded corner: right at the corner the media + // is transparent and the badge would hang over the edge. + bottom: 12, + left: widget.message.isMe ? 12 : null, + right: widget.message.isMe ? null : 12, child: widget.badge!, ), ], From 181ed5963dc15f2035c62128fd838212f46eea75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 00:02:31 +0100 Subject: [PATCH 099/181] fix(chat): drop the attachment badge to the bottom edge 4 px from the bottom, 16 px from the corner, so it reads as a badge on the attachment without the rounded corner cutting it. --- lib/widgets/media_bubble.dart | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 0badcb0..a107528 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -251,11 +251,11 @@ class _MediaBubbleState extends State { // of the caption below it. if (widget.badge != null) Positioned( - // Clear of the rounded corner: right at the corner the media - // is transparent and the badge would hang over the edge. - bottom: 12, - left: widget.message.isMe ? 12 : null, - right: widget.message.isMe ? null : 12, + // Low on the attachment, but far enough from the corner that + // the rounded edge (transparent there) does not cut it. + bottom: 4, + left: widget.message.isMe ? 16 : null, + right: widget.message.isMe ? null : 16, child: widget.badge!, ), ], From 1c04daaca8f86d1152e477f20341776720470e0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 00:04:56 +0100 Subject: [PATCH 100/181] fix(chat): let the attachment badge straddle the media's bottom edge The media stack clipped its overflow, so the badge was cut in half at the edge. Stack now does not clip and the badge sits 10 px past the edge, half on the attachment. --- lib/widgets/chat_bubble.dart | 6 +++++- lib/widgets/media_bubble.dart | 9 ++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 6c3082d..cbe97b1 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -389,7 +389,11 @@ class _ChatBubbleState extends State { ), ) : null, - clipBehavior: isMedia ? Clip.antiAlias : Clip.none, + // An attachment clips its own media; the bubble must stay unclipped when + // a reaction badge hangs over its bottom edge. + clipBehavior: isMedia && widget.message.reactionEmojis.isEmpty + ? Clip.antiAlias + : Clip.none, padding: isMedia ? (widget.message.isReply ? const EdgeInsets.fromLTRB(8, 8, 8, 0) diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index a107528..b234258 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -242,6 +242,8 @@ class _MediaBubbleState extends State { mainAxisSize: MainAxisSize.min, children: [ Stack( + // The badge hangs over the bottom edge, so the stack must not clip. + clipBehavior: Clip.none, children: [ ClipRRect( borderRadius: BorderRadius.circular(16), @@ -251,9 +253,10 @@ class _MediaBubbleState extends State { // of the caption below it. if (widget.badge != null) Positioned( - // Low on the attachment, but far enough from the corner that - // the rounded edge (transparent there) does not cut it. - bottom: 4, + // On the attachment's bottom edge: half of the pill hangs over + // the edge, the way a badge is pinned to it. Far enough from + // the corner that the rounded side does not cut it. + bottom: -10, left: widget.message.isMe ? 16 : null, right: widget.message.isMe ? null : 16, child: widget.badge!, From c0a20efc8c0af58b7e4a9e3b872b692f603c2c5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 00:07:30 +0100 Subject: [PATCH 101/181] fix(chat): keep the caption off the hanging badge With a caption the badge's overhanging half was painted over by the caption strip. The media layer now reserves 12 px for it when a caption follows. --- lib/widgets/media_bubble.dart | 46 ++++++++++++++++++++--------------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index b234258..f5c78b0 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -241,27 +241,33 @@ class _MediaBubbleState extends State { : CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ - Stack( - // The badge hangs over the bottom edge, so the stack must not clip. - clipBehavior: Clip.none, - children: [ - ClipRRect( - borderRadius: BorderRadius.circular(16), - child: media, - ), - // On the attachment itself: the corner of the media, not the level - // of the caption below it. - if (widget.badge != null) - Positioned( - // On the attachment's bottom edge: half of the pill hangs over - // the edge, the way a badge is pinned to it. Far enough from - // the corner that the rounded side does not cut it. - bottom: -10, - left: widget.message.isMe ? 16 : null, - right: widget.message.isMe ? null : 16, - child: widget.badge!, + // The caption below would paint over the half of the badge that hangs + // past the media, so the media layer reserves room for it. + Padding( + padding: EdgeInsets.only( + bottom: hasCaption && widget.badge != null ? 12 : 0), + child: Stack( + // The badge hangs over the bottom edge, so the stack must not clip. + clipBehavior: Clip.none, + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(16), + child: media, ), - ], + // On the attachment itself: the corner of the media, not the + // level of the caption below it. + if (widget.badge != null) + Positioned( + // On the attachment's bottom edge: half of the pill hangs + // over the edge, the way a badge is pinned to it. Far enough + // from the corner that the rounded side does not cut it. + bottom: -10, + left: widget.message.isMe ? 16 : null, + right: widget.message.isMe ? null : 16, + child: widget.badge!, + ), + ], + ), ), if (hasCaption) Container( From 03128c9583334d98ed8f84d2621e3c589626023e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 00:18:41 +0100 Subject: [PATCH 102/181] feat(chat): attach inside the input, messages under the composer The + moved into the field's prefix, mirroring the mic on the suffix. The composer is now a bottom bar the message list runs behind (extendBody with the measured height reserved at the bottom), so a tall bubble is not cut at the input's edge and the newest message rests above it. --- lib/pages/chat_page.dart | 243 ++++++++++++++++++++++----------------- 1 file changed, 136 insertions(+), 107 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 25d2719..7aefbb4 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -107,6 +107,11 @@ class _ChatPageState extends State { DateTime? _publishedReadAt; Timer? _readPublish; + /// The composer floats over the message list, so the list reserves its + /// measured height at the bottom and slides behind the bar above it. + final GlobalKey _composerKey = GlobalKey(); + double _composerHeight = 0; + /// Newest message the viewport has already shown at the bottom; anything /// after it while scrolled up counts as unseen. int _newestSeenSentAt = 0; @@ -1075,96 +1080,90 @@ class _ChatPageState extends State { return '$minutes:$seconds'; } - /// Default message input bar (attach + text field + mic/send). + /// Default message input bar: attach inside the field on the left, mic or + /// send on the right. Widget _buildInputBar() { - return Row( - children: [ - IconButton( - icon: const Icon(Icons.add), - tooltip: 'attachButton'.tr(), - onPressed: _isSending ? null : _showAttachSheet, + return Padding( + padding: const EdgeInsets.only(right: 5, left: 5), + child: TextField( + controller: _controllerMessage, + minLines: 1, + maxLines: 5, + textInputAction: TextInputAction.newline, + contentInsertionConfiguration: ContentInsertionConfiguration( + allowedMimeTypes: const ['image/gif', 'image/webp'], + onContentInserted: _onKeyboardContentInserted, ), - Expanded( - child: Padding( - padding: const EdgeInsets.only(right: 5, left: 5), - child: TextField( - controller: _controllerMessage, - minLines: 1, - maxLines: 5, - textInputAction: TextInputAction.newline, - contentInsertionConfiguration: ContentInsertionConfiguration( - allowedMimeTypes: const ['image/gif', 'image/webp'], - onContentInserted: _onKeyboardContentInserted, - ), - decoration: InputDecoration( - hintText: 'yourMessage'.tr(), - filled: true, - fillColor: chatTheme.brightness == Brightness.dark - ? chatTheme.colorScheme.surfaceBright - : chatTheme.colorScheme.surfaceDim, - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(30), - borderSide: BorderSide.none, - ), - suffixIcon: ValueListenableBuilder( - valueListenable: _controllerMessage, - builder: (context, value, _) { - final hasText = value.text.trim().isNotEmpty; - if (hasText) { - return IconButton( - onPressed: _isSending ? null : _sendMessage, - icon: _isSending - ? const SizedBox( - width: 18, - height: 18, - child: - CircularProgressIndicator(strokeWidth: 2), - ) - : const Icon(Icons.send), - ); - } - // Hold-to-record voice message. The bar is overlaid while - // recording, so this detector stays mounted and its - // long-press end still fires. - return GestureDetector( - onLongPressStart: (_) { - if (!_isSending) { - _startRecording(); - } - }, - onLongPressMoveUpdate: (details) { - final shouldCancel = - details.localOffsetFromOrigin.dx < -80; - if (shouldCancel != _cancelRecording) { - setState(() { - _cancelRecording = shouldCancel; - }); - } - }, - onLongPressEnd: (_) { - if (_isRecording) { - _stopRecording(); - } else { - _stopRequested = true; - } - }, - child: IconButton( - onPressed: _isSending - ? null - : () async { - await Fluttertoast.showToast( - msg: 'holdToRecord'.tr()); - }, - icon: const Icon(Icons.mic), - ), - ); - }, + decoration: InputDecoration( + hintText: 'yourMessage'.tr(), + // The attach button lives inside the field, mirroring the mic. + prefixIcon: IconButton( + icon: const Icon(Icons.add), + tooltip: 'attachButton'.tr(), + onPressed: _isSending ? null : _showAttachSheet, + ), + filled: true, + fillColor: chatTheme.brightness == Brightness.dark + ? chatTheme.colorScheme.surfaceBright + : chatTheme.colorScheme.surfaceDim, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(30), + borderSide: BorderSide.none, + ), + suffixIcon: ValueListenableBuilder( + valueListenable: _controllerMessage, + builder: (context, value, _) { + final hasText = value.text.trim().isNotEmpty; + if (hasText) { + return IconButton( + onPressed: _isSending ? null : _sendMessage, + icon: _isSending + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.send), + ); + } + // Hold-to-record voice message. The bar is overlaid while + // recording, so this detector stays mounted and its + // long-press end still fires. + return GestureDetector( + onLongPressStart: (_) { + if (!_isSending) { + _startRecording(); + } + }, + onLongPressMoveUpdate: (details) { + final shouldCancel = details.localOffsetFromOrigin.dx < -80; + if (shouldCancel != _cancelRecording) { + setState(() { + _cancelRecording = shouldCancel; + }); + } + }, + onLongPressEnd: (_) { + if (_isRecording) { + _stopRecording(); + } else { + _stopRequested = true; + } + }, + child: IconButton( + onPressed: _isSending + ? null + : () async { + await Fluttertoast.showToast( + msg: 'holdToRecord'.tr()); + }, + icon: const Icon(Icons.mic), ), - ), - ), + ); + }, ), ), - ], + ), ); } @@ -1412,6 +1411,9 @@ class _ChatPageState extends State { parent: AlwaysScrollableScrollPhysics(), ), slivers: [ + // Reversed list: the first sliver sits at the visual bottom, so this + // spacer keeps the newest message above the composer bar. + SliverToBoxAdapter(child: SizedBox(height: _composerHeight)), for (final day in orderedDays.reversed) ...[ SliverList.builder( itemCount: days[day]!.length, @@ -1598,8 +1600,25 @@ class _ChatPageState extends State { ); } + /// Measures the composer so the list can reserve exactly its height. + void _measureComposer() { + final render = _composerKey.currentContext?.findRenderObject(); + if (render is! RenderBox || !render.hasSize) { + return; + } + final height = render.size.height; + if ((height - _composerHeight).abs() > 0.5) { + setState(() => _composerHeight = height); + } + } + @override Widget build(BuildContext context) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _measureComposer(); + } + }); return PopScope( onPopInvokedWithResult: (didPop, _) async { if (didPop && _messages.isNotEmpty) { @@ -1628,6 +1647,37 @@ class _ChatPageState extends State { ), ), ), + // The message list runs behind the composer bar, so a tall bubble is + // never cut off at the input's edge. + extendBody: true, + bottomNavigationBar: Container( + key: _composerKey, + decoration: BoxDecoration( + color: chatBackground(), + image: chatPattern(), + ), + child: SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _buildPinBar(), + if (_replyTo != null) _buildReplyBar(), + Stack( + alignment: Alignment.center, + children: [ + _buildInputBar(), + if (_isRecording) + Positioned.fill(child: _buildRecordingBar()), + ], + ), + ], + ), + ), + ), + ), body: Container( decoration: BoxDecoration(image: chatPattern()), child: Column( @@ -1649,7 +1699,7 @@ class _ChatPageState extends State { if (!_firstLoad && _unseenCount > 0) Positioned( right: 16, - bottom: 16, + bottom: _composerHeight + 16, child: FloatingActionButton.small( heroTag: 'jumpToBottom', tooltip: 'jumpToLatest'.tr(), @@ -1671,27 +1721,6 @@ class _ChatPageState extends State { ], ), ), - SafeArea( - top: false, - child: Padding( - padding: const EdgeInsets.all(8.0), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - _buildPinBar(), - if (_replyTo != null) _buildReplyBar(), - Stack( - alignment: Alignment.center, - children: [ - _buildInputBar(), - if (_isRecording) - Positioned.fill(child: _buildRecordingBar()), - ], - ), - ], - ), - ), - ), ], ), ), From 57cc09b01678f82e536bbeb17a84381188b3c810 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 00:21:31 +0100 Subject: [PATCH 103/181] fix(chat): transparent composer bar The bar painted its own copy of the chat background, so it showed as a filled band with a second pattern layer. It is transparent now: the chat background and the messages continue behind the floating input. --- lib/pages/chat_page.dart | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 7aefbb4..c2801a3 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1650,12 +1650,10 @@ class _ChatPageState extends State { // The message list runs behind the composer bar, so a tall bubble is // never cut off at the input's edge. extendBody: true, + // Transparent on purpose: the chat background and the messages + // slide under the composer instead of a filled band behind it. bottomNavigationBar: Container( key: _composerKey, - decoration: BoxDecoration( - color: chatBackground(), - image: chatPattern(), - ), child: SafeArea( top: false, child: Padding( From c3421cadd5a60a44830740057e3597eeeb817542 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 00:41:21 +0100 Subject: [PATCH 104/181] fix(chat): repaint read ticks without a new message Three gaps kept the sender on a stale tick: a cursor that arrived with a sync page was written without notifying the open chat, the notify from storing that page ran before the cursors were written, and leaving the chat inside the debounce window dropped the cursor entirely. The sync branch now notifies after the cursors, dispose flushes a pending cursor, and the per-chat metadata map is written through a lock so a pin or an archive page cannot clobber the cursor. Ticks follow the agreed rule: only the newest own message, only when the peer's cursor covers it, and only with receipts enabled in that chat. --- lib/pages/chat_page.dart | 23 ++++++- lib/utils/cache_utils.dart | 116 +++++++++++++++++++++-------------- lib/utils/utils.dart | 3 + lib/widgets/chat_bubble.dart | 24 +++----- test/chat_bubble_test.dart | 6 +- test/read_receipt_test.dart | 86 ++++++++++++++++++++++++++ 6 files changed, 193 insertions(+), 65 deletions(-) create mode 100644 test/read_receipt_test.dart diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index c2801a3..b2b4c6e 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -102,6 +102,10 @@ class _ChatPageState extends State { /// Instant up to which the other participant has read this chat. DateTime? _peerReadAt; + /// Client timestamp of the newest own message: only that one carries the + /// read tick. + int? _lastOwnMicros; + /// Instant this device already told the server about, so an idle re-render /// does not send the same cursor again. DateTime? _publishedReadAt; @@ -214,11 +218,19 @@ class _ChatPageState extends State { if (!mounted) { return; } + var lastOwn = 0; + for (final message in messages.reversed) { + if (message.isMe) { + lastOwn = message.sentAt.microsecondsSinceEpoch; + break; + } + } setState(() { _messages = messages; _pins = pins; _peerReadAt = peerReadAt; _readReceipts = readReceipts; + _lastOwnMicros = lastOwn == 0 ? null : lastOwn; if (!first) { if (wasAtBottom) { _unseenCount = 0; @@ -1366,7 +1378,7 @@ class _ChatPageState extends State { accentColor: _chatThemeColor ?? Singleton().appTheme.color, selectionMode: _selectionMode, selected: _selected.contains(micros), - readAt: _peerReadAt, + readAt: micros == _lastOwnMicros && _readReceipts ? _peerReadAt : null, onSelect: () => _toggleSelected(message), onActions: () => _openMessageActions(message), onQuickReact: () => MessageActions.react( @@ -1470,6 +1482,15 @@ class _ChatPageState extends State { _scrollController.removeListener(_onScroll); WidgetsBinding.instance.removeObserver(_metricsObserver); _recordTimer?.cancel(); + if (_readPublish?.isActive ?? false) { + // Leaving within the debounce window used to drop the cursor; send it + // now, fire and forget (dispose cannot await). + _readPublish!.cancel(); + if (_readReceipts && _messages.isNotEmpty) { + unawaited( + utils.Utils.sendReadCursor(widget.user.id, _messages.last.sentAt)); + } + } _readPublish?.cancel(); _recorderController?.dispose(); _controllerMessage.dispose(); diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 81f4367..a1c5fad 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -805,6 +805,16 @@ class CacheUtils { return Hive.openBox(_conversationsKey); } + /// Serializes the read-modify-write of the per-chat metadata map, so a pin, + /// an archive page and a read cursor cannot overwrite each other. + static Future _metaLock = Future.value(); + + static Future _serializedMeta(Future Function() action) { + final result = _metaLock.then((_) => action()); + _metaLock = result.then((_) {}, onError: (_) {}); + return result; + } + static Map _metaOf(Box box, String userId) { final stored = box.get(userId); return stored is Map ? Map.from(stored) : {}; @@ -818,19 +828,21 @@ class CacheUtils { /// Pins or unpins a conversation. The entry is dropped once it is empty, so /// the box only holds chats that differ from the default. - static Future setConversationPinned(String userId, bool pinned) async { - final box = await _openConversationsBox(); - final meta = _metaOf(box, userId); - if (pinned) { - meta['pinned'] = true; - } else { - meta.remove('pinned'); - } - if (meta.isEmpty) { - await box.delete(userId); - } else { - await box.put(userId, meta); - } + static Future setConversationPinned(String userId, bool pinned) { + return _serializedMeta(() async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + if (pinned) { + meta['pinned'] = true; + } else { + meta.remove('pinned'); + } + if (meta.isEmpty) { + await box.delete(userId); + } else { + await box.put(userId, meta); + } + }); } /// Pinned message ids of one chat, with the instant each was pinned. @@ -851,31 +863,35 @@ class CacheUtils { /// Pins or unpins one message of a chat. Pins are shared between both /// participants, so this is written from a pin event or a history page. static Future setMessagePinned( - String userId, String? messageId, DateTime? pinnedAt) async { + String userId, String? messageId, DateTime? pinnedAt) { if (messageId == null || messageId.isEmpty) { - return; - } - final box = await _openConversationsBox(); - final meta = _metaOf(box, userId); - final pins = Map.from( - meta['pins'] is Map ? meta['pins'] as Map : const {}); - if (pinnedAt == null) { - pins.remove(messageId); - } else { - pins[messageId] = pinnedAt.millisecondsSinceEpoch; + return Future.value(); } - await _putPins(box, userId, meta, pins); + return _serializedMeta(() async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + final pins = Map.from( + meta['pins'] is Map ? meta['pins'] as Map : const {}); + if (pinnedAt == null) { + pins.remove(messageId); + } else { + pins[messageId] = pinnedAt.millisecondsSinceEpoch; + } + await _putPins(box, userId, meta, pins); + }); } /// Replaces the pins of a chat with a server answer, so an unpin that happened /// on another device does not survive on a stale local entry. static Future replacePinnedMessages( - String userId, Map pins) async { - final box = await _openConversationsBox(); - final meta = _metaOf(box, userId); - await _putPins(box, userId, meta, { - for (final entry in pins.entries) - entry.key: entry.value.millisecondsSinceEpoch, + String userId, Map pins) { + return _serializedMeta(() async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + await _putPins(box, userId, meta, { + for (final entry in pins.entries) + entry.key: entry.value.millisecondsSinceEpoch, + }); }); } @@ -928,15 +944,17 @@ class CacheUtils { /// Remembers the peer's read cursor. It only moves forward, so a frame that /// arrives out of order cannot take the tick back. - static Future setPeerReadAt(String userId, DateTime readAt) async { - final stored = await getPeerReadAt(userId); - if (stored != null && !readAt.isAfter(stored)) { - return; - } - final box = await _openConversationsBox(); - final meta = _metaOf(box, userId); - meta['peerReadAt'] = readAt.millisecondsSinceEpoch; - await box.put(userId, meta); + static Future setPeerReadAt(String userId, DateTime readAt) { + return _serializedMeta(() async { + final stored = await getPeerReadAt(userId); + if (stored != null && !readAt.isAfter(stored)) { + return; + } + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + meta['peerReadAt'] = readAt.millisecondsSinceEpoch; + await box.put(userId, meta); + }); } /// Instant up to which the account deleted this conversation, null when it @@ -951,13 +969,17 @@ class CacheUtils { /// The later of the two instants wins, so a stale page cannot undo a delete. static Future applyConversationClearedAt( String userId, DateTime clearedAt) async { - final box = await _openConversationsBox(); - final stored = await conversationClearedAt(userId); - final cut = - stored != null && stored.isAfter(clearedAt) ? stored : clearedAt; - final meta = _metaOf(box, userId); - meta['clearedAt'] = cut.millisecondsSinceEpoch; - await box.put(userId, meta); + final cut = await _serializedMeta(() async { + final box = await _openConversationsBox(); + final stored = await conversationClearedAt(userId); + final cut = + stored != null && stored.isAfter(clearedAt) ? stored : clearedAt; + final meta = _metaOf(box, userId); + meta['clearedAt'] = cut.millisecondsSinceEpoch; + await box.put(userId, meta); + return cut; + }); + // Outside the lock: purging calls setMessagePinned, which takes it. await purgeConversationUpTo(userId, cut); } diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 1ef9d9e..47cca81 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -565,6 +565,9 @@ class Utils { await CacheUtils.setPeerReadAt( receipt.peerId, receipt.readAt.toLocal()); } + // After the cursors are stored: the reload kicked off earlier (when the + // messages were written) read the old value. + MessageNotifier().notify(); // Only after the batch is stored: a cursor ahead of the local messages // would drop them for good. await CacheUtils.setSyncSeq(synced.syncedThrough); diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index cbe97b1..5367104 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -557,25 +557,21 @@ class _ChatBubbleState extends State { ), ), ), - // Sent messages carry ticks: one for the ack - // (the server stored it), two when the peer's - // read cursor passed it. - if (widget.message.isMe && - widget.message.sendStatus == SendStatus.sent) + // Only the newest own message carries a tick, and + // only when the peer's cursor covers it: a single + // "delivered" tick would be a claim this build + // cannot back, because the peer's receipt switch + // is their business. + if (widget.message.isMe && _readByPeer) Padding( padding: const EdgeInsets.only(top: 2), child: Tooltip( - message: _readByPeer - ? 'messageRead'.tr() - : 'messageDelivered'.tr(), + message: 'messageRead'.tr(), child: Icon( - _readByPeer ? Icons.done_all : Icons.done, + Icons.done_all, size: 13, - color: _readByPeer - ? Theme.of(context) - .colorScheme - .primary - : Colors.grey, + color: + Theme.of(context).colorScheme.primary, ), ), ), diff --git a/test/chat_bubble_test.dart b/test/chat_bubble_test.dart index 078b21c..2d4fb77 100644 --- a/test/chat_bubble_test.dart +++ b/test/chat_bubble_test.dart @@ -169,8 +169,8 @@ void main() { expect(find.text('Forwarded'), findsOneWidget); expect(renderedText(tester), contains('přeposlaný text')); - // Own messages carry one tick once the server stored them; the peer's read - // cursor covering the message turns it into two. + // Only the peer's cursor covering the message shows a tick; there is no + // single "delivered" tick any more. final sent = DateTime(2026, 11, 19, 12); await show(ChatBubble( null, @@ -179,7 +179,7 @@ void main() { peer, accentColor: Colors.blue, )); - expect(find.byIcon(Icons.done), findsOneWidget); + expect(find.byIcon(Icons.done), findsNothing); expect(find.byIcon(Icons.done_all), findsNothing); await show(ChatBubble( diff --git a/test/read_receipt_test.dart b/test/read_receipt_test.dart new file mode 100644 index 0000000..d558a29 --- /dev/null +++ b/test/read_receipt_test.dart @@ -0,0 +1,86 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper/utils/message_notifier.dart'; +import 'package:whisper/utils/utils.dart'; +import 'package:whisper_websocket_client_dart/models/ws_response.dart'; + +Uint8List frame(Map json) => + Uint8List.fromList(utf8.encode(jsonEncode(json))); + +/// A cursor that arrives with a sync page used to land in Hive without any +/// listener hearing about it, so the ticks of an open chat stayed stale until +/// the next message repainted them. +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_read_receipt_test'); + Hive.init(dir.path); + if (!Hive.isAdapterRegistered(3)) { + Hive.registerAdapter(PrivateMessageAdapter()); + } + }); + + setUp(() async { + for (final box in [ + 'privateMessages', + 'conversations', + 'settings', + 'user' + ]) { + await Hive.openBox(box); + await Hive.box(box).clear(); + } + }); + + tearDownAll(() async { + await Hive.deleteFromDisk(); + await dir.delete(recursive: true); + }); + + test('a cursor from a sync page reaches the cache and the UI', () async { + var notified = 0; + void listener() => notified++; + MessageNotifier().addListener(listener); + addTearDown(() => MessageNotifier().removeListener(listener)); + + final readAt = DateTime.utc(2026, 11, 20, 10, 30); + final response = WsResponse.fromUint8List(frame({ + 'type': 'synced', + 'payload': { + 'messages': [], + 'peers': [], + 'events': [], + 'cleared': [], + 'reads': [ + {'v': 1, 'peerId': 'peer-id', 'readAt': readAt.toIso8601String()} + ], + 'syncedThrough': 0, + 'eventsThrough': 0, + 'hasMore': false, + }, + })); + + await Utils.onWsMessageReceived(response); + + expect(notified, greaterThan(0)); + expect(await CacheUtils.getPeerReadAt('peer-id'), readAt.toLocal()); + }); + + test('the cursor only moves forward and is keyed per peer', () async { + final later = DateTime(2026, 11, 20, 11); + await CacheUtils.setPeerReadAt('a', later); + await CacheUtils.setPeerReadAt( + 'a', later.subtract(const Duration(hours: 1))); + await CacheUtils.setPeerReadAt('b', later); + + expect(await CacheUtils.getPeerReadAt('a'), later); + expect(await CacheUtils.getPeerReadAt('b'), later); + }); +} From 75343b8ba1513d0f0a6532254e54f6030b250aaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 00:48:18 +0100 Subject: [PATCH 105/181] fix(chat): keep the read receipts row enabled and un-spammable The row had no press handler, so TextButton rendered its icon and label in the disabled colour. Tapping the row now toggles too, and a toggle in flight disables the switch until the server call and the cache write are done. --- lib/pages/chat_info_page.dart | 36 ++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index a800cce..1ee581f 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -33,6 +33,10 @@ class _ChatInfoPageState extends State { Map _pins = {}; bool _readReceipts = false; + /// A toggle in flight: the switch stays disabled until the server call and + /// the cache write are done, so it cannot be flipped back and forth. + bool _readReceiptsBusy = false; + @override void initState() { super.initState(); @@ -55,14 +59,27 @@ class _ChatInfoPageState extends State { /// current cursor right away, so the peer's ticks catch up without waiting /// for the next message. Future _toggleReadReceipts(bool enabled) async { - await CacheUtils.setReadReceiptsEnabled(widget.userId, enabled); - if (enabled) { - final messages = await CacheUtils.getPrivateMessages(widget.userId); - if (messages.isNotEmpty) { - await Utils.sendReadCursor(widget.userId, messages.last.sentAt); + if (_readReceiptsBusy) { + return; + } + setState(() { + _readReceiptsBusy = true; + _readReceipts = enabled; + }); + try { + await CacheUtils.setReadReceiptsEnabled(widget.userId, enabled); + if (enabled) { + final messages = await CacheUtils.getPrivateMessages(widget.userId); + if (messages.isNotEmpty) { + await Utils.sendReadCursor(widget.userId, messages.last.sentAt); + } + } + await _loadReadReceipts(); + } finally { + if (mounted) { + setState(() => _readReceiptsBusy = false); } } - await _loadReadReceipts(); } Future _loadPins() async { @@ -247,9 +264,14 @@ class _ChatInfoPageState extends State { SettingsTile( icon: Icons.done_all, label: 'readReceipts'.tr(), + // Tap on the row toggles too; a non-null handler keeps + // the row in the enabled colours (a disabled TextButton + // greys out its icon and label). + onPressed: () => _toggleReadReceipts(!_readReceipts), trailing: Switch( value: _readReceipts, - onChanged: _toggleReadReceipts, + onChanged: + _readReceiptsBusy ? null : _toggleReadReceipts, ), ), // Pinned messages, shared with the other participant From 49cb0ff118919b51d5b567edb22171e07568053b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 00:53:20 +0100 Subject: [PATCH 106/181] feat(chat): move the pin strip under the header and slim it down The pinned message is a single-line strip attached to the header (pin, preview, count, unpin) instead of a card above the composer, so the composer is only the input again. --- lib/pages/chat_page.dart | 161 +++++++++++++++++++++------------------ 1 file changed, 87 insertions(+), 74 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index b2b4c6e..f7eee7d 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -478,50 +478,50 @@ class _ChatPageState extends State { return newest; } - /// Narrow bar above the composer: the newest pin, tap to jump, cross to unpin. + /// Slim strip under the header: the newest pin, tap to jump, cross to unpin. Widget _buildPinBar() { final pinned = _newestPin; if (pinned == null) { return const SizedBox.shrink(); } final preview = pinned.preview; - return Padding( - padding: const EdgeInsets.only(bottom: 6), - child: Material( - color: Theme.of(context).colorScheme.surfaceContainerHigh, - borderRadius: BorderRadius.circular(12), - child: InkWell( - borderRadius: BorderRadius.circular(12), - onTap: () => _jumpToMessage(pinned.sentAt), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), - child: Row( - children: [ - const Icon(Icons.push_pin, size: 16), - const SizedBox(width: 8), - Expanded( - child: Text( - preview.isEmpty ? 'mediaPhoto'.tr() : preview, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: const TextStyle(fontSize: 12), - ), + return Material( + // Opaque in the header's tint: the strip sits over the message list, so a + // translucent fill would let bubbles show through it. + color: chatBackground(tintAlpha: 0.32), + child: InkWell( + onTap: () => _jumpToMessage(pinned.sentAt), + child: Padding( + padding: const EdgeInsets.only(left: 12, right: 4), + child: Row( + children: [ + const Icon(Icons.push_pin, size: 13), + const SizedBox(width: 6), + Expanded( + child: Text( + preview.isEmpty ? 'mediaPhoto'.tr() : preview, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11), ), - if (_pins.length > 1) - Padding( - padding: const EdgeInsets.only(left: 8), - child: Text('+${_pins.length - 1}', - style: const TextStyle(fontSize: 11)), - ), - IconButton( - icon: const Icon(Icons.close, size: 16), - tooltip: 'unpinMessage'.tr(), - onPressed: () => MessageActions.togglePin( - pinned, widget.user.id, - pinned: true), + ), + if (_pins.length > 1) + Padding( + padding: const EdgeInsets.only(left: 6), + child: Text('+${_pins.length - 1}', + style: const TextStyle(fontSize: 10)), ), - ], - ), + IconButton( + icon: const Icon(Icons.close, size: 14), + tooltip: 'unpinMessage'.tr(), + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 28, minHeight: 26), + onPressed: () => MessageActions.togglePin( + pinned, widget.user.id, + pinned: true), + ), + ], ), ), ), @@ -1682,7 +1682,6 @@ class _ChatPageState extends State { child: Column( mainAxisSize: MainAxisSize.min, children: [ - _buildPinBar(), if (_replyTo != null) _buildReplyBar(), Stack( alignment: Alignment.center, @@ -1699,47 +1698,61 @@ class _ChatPageState extends State { ), body: Container( decoration: BoxDecoration(image: chatPattern()), - child: Column( + child: Stack( children: [ - // Messages and avatar list - Expanded( - child: Stack( - children: [ - _firstLoad - ? Center( - child: Transform.scale( - scale: 1.5, - child: CircularProgressIndicator(), - ), - ) - : _getContent(_messages), - // Floating "down" button with the count of messages that - // arrived while the user was reading further up. - if (!_firstLoad && _unseenCount > 0) - Positioned( - right: 16, - bottom: _composerHeight + 16, - child: FloatingActionButton.small( - heroTag: 'jumpToBottom', - tooltip: 'jumpToLatest'.tr(), - onPressed: () => _jumpToBottom(animate: true), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.arrow_downward, size: 16), - if (_unseenCount > 1) - Padding( - padding: const EdgeInsets.only(left: 2), - child: Text('$_unseenCount', - style: const TextStyle(fontSize: 11)), + Column( + children: [ + // Messages and avatar list + Expanded( + child: Stack( + children: [ + _firstLoad + ? Center( + child: Transform.scale( + scale: 1.5, + child: CircularProgressIndicator(), ), - ], + ) + : _getContent(_messages), + // Floating "down" button with the count of messages that + // arrived while the user was reading further up. + if (!_firstLoad && _unseenCount > 0) + Positioned( + right: 16, + bottom: _composerHeight + 16, + child: FloatingActionButton.small( + heroTag: 'jumpToBottom', + tooltip: 'jumpToLatest'.tr(), + onPressed: () => _jumpToBottom(animate: true), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.arrow_downward, size: 16), + if (_unseenCount > 1) + Padding( + padding: const EdgeInsets.only(left: 2), + child: Text('$_unseenCount', + style: + const TextStyle(fontSize: 11)), + ), + ], + ), + ), ), - ), - ), - ], - ), + ], + ), + ), + ], ), + // Right under the header, over the list: the pin is where the + // eye looks first and the composer stays clean. + if (_newestPin != null) + Positioned( + top: kToolbarHeight + MediaQuery.of(context).padding.top, + left: 0, + right: 0, + child: _buildPinBar(), + ), ], ), ), From 184e891731b1eb69beedcaaab0d7f379e54ab278 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 16:07:19 +0100 Subject: [PATCH 107/181] fix(chat): keep the read cursor in microseconds A cursor is the sentAt of the newest message the peer read, and sentAt has microseconds. Storing the cursor in milliseconds made it a little older than that message, so the tick only appeared once something newer arrived. Values below the bound written by older builds still read as milliseconds. --- lib/utils/cache_utils.dart | 13 +++++++++++-- test/read_receipt_test.dart | 15 +++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index a1c5fad..23e4d41 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -939,7 +939,16 @@ class CacheUtils { static Future getPeerReadAt(String userId) async { final box = await _openConversationsBox(); final raw = _metaOf(box, userId)['peerReadAt']; - return raw is int ? DateTime.fromMillisecondsSinceEpoch(raw) : null; + if (raw is! int) { + return null; + } + // A cursor carries the sentAt of the newest message the peer read, and + // sentAt has microseconds: rounding it to milliseconds made the cursor a + // little older than the message, so the tick only appeared once the peer + // sent something newer. Values below this bound are the old encoding. + return raw < 100000000000000 + ? DateTime.fromMillisecondsSinceEpoch(raw) + : DateTime.fromMicrosecondsSinceEpoch(raw); } /// Remembers the peer's read cursor. It only moves forward, so a frame that @@ -952,7 +961,7 @@ class CacheUtils { } final box = await _openConversationsBox(); final meta = _metaOf(box, userId); - meta['peerReadAt'] = readAt.millisecondsSinceEpoch; + meta['peerReadAt'] = readAt.microsecondsSinceEpoch; await box.put(userId, meta); }); } diff --git a/test/read_receipt_test.dart b/test/read_receipt_test.dart index d558a29..909c68b 100644 --- a/test/read_receipt_test.dart +++ b/test/read_receipt_test.dart @@ -73,6 +73,21 @@ void main() { expect(await CacheUtils.getPeerReadAt('peer-id'), readAt.toLocal()); }); + test('the cursor keeps the microseconds of a message sentAt', () async { + // A read cursor equals the sentAt of the newest message read; rounding it + // to milliseconds made the message look unread. + final readAt = DateTime(2026, 11, 20, 10, 30, 0, 123, 456); + await CacheUtils.setPeerReadAt('a', readAt); + expect(await CacheUtils.getPeerReadAt('a'), readAt); + }); + + test('a cursor stored in milliseconds still reads', () async { + final readAt = DateTime(2026, 11, 20, 10, 30, 0, 123); + final box = await Hive.openBox('conversations'); + await box.put('a', {'peerReadAt': readAt.millisecondsSinceEpoch}); + expect(await CacheUtils.getPeerReadAt('a'), readAt); + }); + test('the cursor only moves forward and is keyed per peer', () async { final later = DateTime(2026, 11, 20, 11); await CacheUtils.setPeerReadAt('a', later); From 08f42abf5b3ddfc6813675b3bc7c6058db3aebd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 16:07:19 +0100 Subject: [PATCH 108/181] fix(chat): lift the composer above the keyboard A bottomNavigationBar is anchored to the screen bottom, not to the IME. With edge-to-edge the window is no longer resized for the keyboard, so the field ended up behind it; the bar now carries the inset itself and the list reserves its measured height. --- lib/pages/chat_page.dart | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index f7eee7d..e5a077b 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1640,6 +1640,12 @@ class _ChatPageState extends State { _measureComposer(); } }); + // A bottomNavigationBar is anchored to the screen bottom, not to the + // keyboard: with edge-to-edge the window is no longer resized for the IME, + // so the bar has to carry the inset itself or the field hides behind the + // keyboard. It stays inside the measured composer, so the list reserves + // the room. + final keyboardInset = MediaQuery.viewInsetsOf(context).bottom; return PopScope( onPopInvokedWithResult: (didPop, _) async { if (didPop && _messages.isNotEmpty) { @@ -1675,6 +1681,7 @@ class _ChatPageState extends State { // slide under the composer instead of a filled band behind it. bottomNavigationBar: Container( key: _composerKey, + padding: EdgeInsets.only(bottom: keyboardInset), child: SafeArea( top: false, child: Padding( From 304bb3aac54cd5e66b4825a54e311b84632eabaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 16:14:37 +0100 Subject: [PATCH 109/181] feat(chat): show the peer's read tick in the chat list The last own message in a row now carries the same done_all tick the bubble does, so a delivered message no longer looks like a read one until the chat is opened. The cursors of every chat with receipts on are read in one pass instead of one box read per row. --- lib/pages/home_page.dart | 6 ++++ lib/utils/cache_utils.dart | 31 ++++++++++++++++---- lib/widgets/chat_list_item.dart | 35 ++++++++++++++++++++--- test/chat_list_item_test.dart | 49 ++++++++++++++++++++++++++++++++ test/conversation_meta_test.dart | 9 ++++++ 5 files changed, 120 insertions(+), 10 deletions(-) create mode 100644 test/chat_list_item_test.dart diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 15307b3..17a199c 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -53,6 +53,9 @@ class _HomePageState extends State /// Conversation ids pinned to the top of the list. Set _pinnedChats = {}; + /// Read cursors of the chats that publish receipts, for the seen ticks. + Map _peerReadAts = {}; + /// Which rows the list shows; folders without extra storage. _ChatFilter _filter = _ChatFilter.all; bool _firstLoad = true; @@ -201,6 +204,7 @@ class _HomePageState extends State final chats = await CacheUtils.getLatestPrivateMessages(); final unread = await CacheUtils.getUnreadCounts(); final pinned = await CacheUtils.getPinnedConversations(); + final peerReadAts = await CacheUtils.peerReadAts(); if (!mounted) { return; } @@ -208,6 +212,7 @@ class _HomePageState extends State _chatEntries = chats.entries.toList(); _unreadCounts = unread; _pinnedChats = pinned; + _peerReadAts = peerReadAts; _firstLoad = false; }); } @@ -441,6 +446,7 @@ class _HomePageState extends State }, unreadCount: _unreadCounts[chat.key.id] ?? 0, pinned: _pinnedChats.contains(chat.key.id), + peerReadAt: _peerReadAts[chat.key.id], ), ), ); diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 23e4d41..72278df 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -939,13 +939,32 @@ class CacheUtils { static Future getPeerReadAt(String userId) async { final box = await _openConversationsBox(); final raw = _metaOf(box, userId)['peerReadAt']; - if (raw is! int) { - return null; + return raw is int ? _decodePeerReadAt(raw) : null; + } + + /// Read cursors of every chat that publishes receipts, keyed by peer id: one + /// box read for the whole chat list instead of one per row. + static Future> peerReadAts() async { + final box = await _openConversationsBox(); + final cursors = {}; + for (final entry in box.toMap().entries) { + final meta = entry.value; + if (meta is! Map || meta['readReceipts'] != true) { + continue; + } + final raw = meta['peerReadAt']; + if (raw is int) { + cursors[entry.key as String] = _decodePeerReadAt(raw); + } } - // A cursor carries the sentAt of the newest message the peer read, and - // sentAt has microseconds: rounding it to milliseconds made the cursor a - // little older than the message, so the tick only appeared once the peer - // sent something newer. Values below this bound are the old encoding. + return cursors; + } + + /// A cursor carries the sentAt of the newest message the peer read, and + /// sentAt has microseconds: rounding it to milliseconds made the cursor a + /// little older than the message, so the tick only appeared once the peer + /// sent something newer. Values below this bound are the old encoding. + static DateTime _decodePeerReadAt(int raw) { return raw < 100000000000000 ? DateTime.fromMillisecondsSinceEpoch(raw) : DateTime.fromMicrosecondsSinceEpoch(raw); diff --git a/lib/widgets/chat_list_item.dart b/lib/widgets/chat_list_item.dart index f548b95..4442b3c 100644 --- a/lib/widgets/chat_list_item.dart +++ b/lib/widgets/chat_list_item.dart @@ -6,7 +6,7 @@ import '../utils/chat_date.dart'; class ChatListItem extends StatefulWidget { const ChatListItem(this.user, this.lastMessage, this.onPressed, - {this.unreadCount = 0, this.pinned = false, super.key}); + {this.unreadCount = 0, this.pinned = false, this.peerReadAt, super.key}); final User user; final PrivateMessage lastMessage; @@ -18,6 +18,10 @@ class ChatListItem extends StatefulWidget { /// Whether the conversation is pinned to the top of the list. final bool pinned; + /// Instant up to which the peer read this chat; null when the chat does not + /// publish receipts or they never read it. + final DateTime? peerReadAt; + @override State createState() => _ChatListItemState(); } @@ -56,6 +60,10 @@ class _ChatListItemState extends State { } final bool unread = widget.unreadCount > 0 || !widget.lastMessage.read; + // Same rule as the bubble's tick, so the row and the chat cannot disagree. + final bool seenByPeer = widget.lastMessage.isMe && + widget.peerReadAt != null && + !widget.lastMessage.sentAt.isAfter(widget.peerReadAt!); return ListTile( onTap: widget.onPressed, @@ -95,9 +103,28 @@ class _ChatListItemState extends State { ), ], ), - subtitle: Text( - getTitle(), - style: unread ? const TextStyle(fontWeight: FontWeight.bold) : null, + subtitle: Row( + children: [ + // The last own message carries the peer's tick, the way the bubble + // does; a row that hides it makes "delivered" and "read" look alike. + if (seenByPeer) + Padding( + padding: const EdgeInsets.only(right: 4), + child: Icon( + Icons.done_all, + size: 14, + color: Theme.of(context).colorScheme.primary, + ), + ), + Expanded( + child: Text( + getTitle(), + overflow: TextOverflow.ellipsis, + style: + unread ? const TextStyle(fontWeight: FontWeight.bold) : null, + ), + ), + ], ), trailing: Column( mainAxisAlignment: MainAxisAlignment.center, diff --git a/test/chat_list_item_test.dart b/test/chat_list_item_test.dart new file mode 100644 index 0000000..2be1bc6 --- /dev/null +++ b/test/chat_list_item_test.dart @@ -0,0 +1,49 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/models/profile.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/singleton.dart'; +import 'package:whisper/widgets/chat_list_item.dart'; + +Widget app(PrivateMessage last, {DateTime? peerReadAt}) { + return MaterialApp( + home: Scaffold( + body: ChatListItem(User('1', 'peer', 'key', false), last, () {}, + peerReadAt: peerReadAt), + ), + ); +} + +void main() { + setUp(() { + Singleton().profile = Profile('http://localhost', + User('me', 'me', 'key', false), 'key', 'private-key', '', '', true); + }); + + final sentAt = DateTime(2026, 5, 1, 12); + PrivateMessage own() => PrivateMessage('me', 'text', sentAt, sentAt, false); + PrivateMessage theirs() => PrivateMessage('1', 'text', sentAt, sentAt, false); + + testWidgets('an own message carries the tick once the cursor covers it', + (tester) async { + await tester.pumpWidget(app(own(), peerReadAt: sentAt)); + expect(find.byIcon(Icons.done_all), findsOneWidget); + }); + + testWidgets('no tick while the cursor is behind the message', (tester) async { + await tester.pumpWidget( + app(own(), peerReadAt: sentAt.subtract(const Duration(seconds: 1)))); + expect(find.byIcon(Icons.done_all), findsNothing); + }); + + testWidgets('an incoming message never carries the tick', (tester) async { + await tester.pumpWidget(app(theirs(), peerReadAt: sentAt)); + expect(find.byIcon(Icons.done_all), findsNothing); + }); + + testWidgets('receipts off means no tick', (tester) async { + await tester.pumpWidget(app(own())); + expect(find.byIcon(Icons.done_all), findsNothing); + }); +} diff --git a/test/conversation_meta_test.dart b/test/conversation_meta_test.dart index b1e2dac..7142043 100644 --- a/test/conversation_meta_test.dart +++ b/test/conversation_meta_test.dart @@ -88,4 +88,13 @@ void main() { expect(await CacheUtils.getPinnedConversations(), isEmpty); }); + + test('the chat list gets cursors only from chats with receipts on', () async { + final readAt = DateTime(2026, 5, 1, 12, 0, 0, 123, 456); + await CacheUtils.setPeerReadAt('on', readAt); + await CacheUtils.setReadReceiptsEnabled('on', true); + await CacheUtils.setPeerReadAt('off', readAt); + + expect(await CacheUtils.peerReadAts(), {'on': readAt}); + }); } From 81aa6421eb26db215afb1c87beb3883786e904fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 16:18:29 +0100 Subject: [PATCH 110/181] fix(chat): draw the reaction badge on voice and file bubbles Those bubbles render inside a plain container that dropped the badge, so a quick react on a voice message was saved but never shown. The badge now hangs over the bubble's bottom edge like it does on a visual attachment. --- lib/widgets/media_bubble.dart | 20 +++++++++++++++++++- test/chat_bubble_test.dart | 14 ++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index f5c78b0..f1d7365 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -184,7 +184,7 @@ class _MediaBubbleState extends State { // Voice and file messages live inside the coloured bubble. if (insideBubble) { - return Container( + final box = Container( decoration: BoxDecoration( color: widget.bubbleColor, borderRadius: BorderRadius.circular(20), @@ -192,6 +192,24 @@ class _MediaBubbleState extends State { padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: media, ); + if (widget.badge == null) { + return box; + } + // The reaction hangs over the bubble's bottom edge, the way it does on a + // visual attachment. Dropping it here made a reaction on a voice message + // look like it never happened. + return Stack( + clipBehavior: Clip.none, + children: [ + box, + Positioned( + bottom: -10, + left: widget.message.isMe ? 16 : null, + right: widget.message.isMe ? null : 16, + child: widget.badge!, + ), + ], + ); } // Visual media: rounded thumbnail with optional caption underneath. diff --git a/test/chat_bubble_test.dart b/test/chat_bubble_test.dart index 2d4fb77..43f841b 100644 --- a/test/chat_bubble_test.dart +++ b/test/chat_bubble_test.dart @@ -253,5 +253,19 @@ void main() { .first); expect(mediaFrame.padding, EdgeInsets.zero); expect((mediaFrame.decoration as BoxDecoration?)?.color, isNull); + + // A voice message shows the reaction it carries: the badge sits inside the + // bubble's edge, so a quick react there is not a silent no-op. + await show(ChatBubble( + null, + PrivateMessage('2', '', DateTime(2026), DateTime(2026), true, + mediaTypeStr: MediaType.voice.name, + downloadStatus: MediaDownloadStatus.failed) + ..reactions = {'2': '👍'}, + null, + peer, + accentColor: Colors.blue, + )); + expect(find.text('👍'), findsOneWidget); }); } From 17f5285a9c03c70e3f4b6bd6f54f3f1332a72b71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 16:23:54 +0100 Subject: [PATCH 111/181] fix(chat): reach a pin that is far from the viewport, and walk the pins Jumping to a pinned message only worked when its bubble was already built: the fallback walk started from the current offset and only ever moved towards newer messages, so from the bottom it stopped immediately. It now takes the oldest end of the window and walks down until the target is built, which covers both directions. The strip showed only the newest pin and a bare '+N'. It now shows 'n/N' with a chevron; tapping it steps to the next pinned message and jumps to it. --- lib/pages/chat_page.dart | 99 +++++++++++++++++++++++----------------- 1 file changed, 56 insertions(+), 43 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index e5a077b..b81da40 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -96,6 +96,9 @@ class _ChatPageState extends State { /// Pinned message ids of this chat with the instant of the pin. Map _pins = {}; + /// Which pin the strip shows; the list is newest pin first. + int _pinIndex = 0; + /// Whether this chat publishes and shows read receipts. bool _readReceipts = false; @@ -457,33 +460,36 @@ class _ChatPageState extends State { ); } - /// The newest pinned message this device still holds, null when none is left. - PrivateMessage? get _newestPin { - PrivateMessage? newest; - DateTime? newestAt; + /// Pinned messages this device holds, newest pin first: the strip walks them. + List get _pinnedInOrder { + final pinned = []; for (final message in _messages) { final id = message.id; - if (id == null) { - continue; - } - final at = _pins[id]; - if (at == null) { - continue; - } - if (newestAt == null || at.isAfter(newestAt)) { - newest = message; - newestAt = at; + if (id != null && _pins.containsKey(id)) { + pinned.add(message); } } - return newest; + pinned.sort((a, b) => _pins[b.id]!.compareTo(_pins[a.id]!)); + return pinned; + } + + /// Steps the strip to the next pinned message and jumps to it. + Future _cyclePin(List pins) async { + final next = (_pinIndex + 1) % pins.length; + setState(() { + _pinIndex = next; + }); + await _jumpToMessage(pins[next].sentAt); } - /// Slim strip under the header: the newest pin, tap to jump, cross to unpin. + /// Slim strip under the header: one pin, tap to jump, cross to unpin, the + /// counter to walk the rest. Widget _buildPinBar() { - final pinned = _newestPin; - if (pinned == null) { + final pins = _pinnedInOrder; + if (pins.isEmpty) { return const SizedBox.shrink(); } + final pinned = pins[_pinIndex % pins.length]; final preview = pinned.preview; return Material( // Opaque in the header's tint: the strip sits over the message list, so a @@ -505,11 +511,25 @@ class _ChatPageState extends State { style: const TextStyle(fontSize: 11), ), ), - if (_pins.length > 1) - Padding( - padding: const EdgeInsets.only(left: 6), - child: Text('+${_pins.length - 1}', - style: const TextStyle(fontSize: 10)), + if (pins.length > 1) + // Without this the strip only ever showed the newest pin and + // the others were unreachable. + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => _cyclePin(pins), + child: Padding( + padding: const EdgeInsets.only(left: 6), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '${_pinIndex % pins.length + 1}/${pins.length}', + style: const TextStyle(fontSize: 10), + ), + const Icon(Icons.expand_more, size: 14), + ], + ), + ), ), IconButton( icon: const Icon(Icons.close, size: 14), @@ -681,10 +701,10 @@ class _ChatPageState extends State { /// /// Widening the rendered window is not enough: a list only builds what is /// near the viewport, so growing the tail never builds an old message. The - /// fast path therefore cuts the window down to the target, which puts it one - /// screen from the oldest end, and jumping to that end lands on it. The slow - /// path walks a viewport at a time towards older messages for a target - /// already inside a large window but far from the screen. + /// window is therefore cut down to the target first, then the oldest end is + /// taken and the viewport walks towards newer messages until the target is + /// built. Walking back from the oldest end covers both a target above the + /// viewport and one below it. Future _jumpToMessage(DateTime sentAt) async { final micros = sentAt.microsecondsSinceEpoch; _jumping = true; @@ -702,11 +722,6 @@ class _ChatPageState extends State { if (!mounted || !_scrollController.hasClients) { return; } - // Reversed list: the target sits at the far end of the window. - await _settleAtOldest(); - if (!mounted) { - return; - } } final context = _messageKeys[micros]?.currentContext; if (context != null && context.mounted) { @@ -714,8 +729,15 @@ class _ChatPageState extends State { alignment: 0.2, duration: const Duration(milliseconds: 250)); return; } + await _settleAtOldest(); for (var attempt = 0; attempt < 50; attempt++) { - if (!_scrollController.hasClients) { + if (!mounted || !_scrollController.hasClients) { + return; + } + final reached = _messageKeys[micros]?.currentContext; + if (reached != null && reached.mounted) { + await Scrollable.ensureVisible(reached, + alignment: 0.3, duration: const Duration(milliseconds: 250)); return; } final position = _scrollController.position; @@ -726,15 +748,6 @@ class _ChatPageState extends State { } _scrollController.jumpTo(next); await WidgetsBinding.instance.endOfFrame; - if (!mounted) { - return; - } - final reached = _messageKeys[micros]?.currentContext; - if (reached != null && reached.mounted) { - await Scrollable.ensureVisible(reached, - alignment: 0.3, duration: const Duration(milliseconds: 250)); - return; - } } } finally { _jumping = false; @@ -1753,7 +1766,7 @@ class _ChatPageState extends State { ), // Right under the header, over the list: the pin is where the // eye looks first and the composer stays clean. - if (_newestPin != null) + if (_pinnedInOrder.isNotEmpty) Positioned( top: kToolbarHeight + MediaQuery.of(context).padding.top, left: 0, From 0753340a73248b574cca3e840897dd1f5e68f26c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 16:30:19 +0100 Subject: [PATCH 112/181] feat(chat): jump to a pinned message from chat info, and flash the target Tapping a row in the pinned list only closed the sheet; it now hands the instant back to the chat, which scrolls to it. Every jump ends by lighting the target bubble for a moment and fading the frame out, so a message that looks like its neighbours is still obvious. --- lib/pages/chat_info_page.dart | 6 ++++++ lib/pages/chat_page.dart | 21 +++++++++++++++++++++ lib/widgets/chat_bubble.dart | 12 ++++++++++-- test/chat_bubble_test.dart | 26 ++++++++++++++++++++++++++ 4 files changed, 63 insertions(+), 2 deletions(-) diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 1ee581f..fb610a3 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -121,6 +121,12 @@ class _ChatInfoPageState extends State { subtitle: Text(DateFormat.yMMMd() .add_Hm() .format(message.sentAt.toLocal())), + // Hands the instant back to the chat, which scrolls to it and + // flashes the bubble. + onTap: () { + Navigator.pop(ctx); + Navigator.pop(context, message.sentAt); + }, trailing: IconButton( icon: const Icon(Icons.close), tooltip: 'unpinMessage'.tr(), diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index b81da40..2d5d18a 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -99,6 +99,11 @@ class _ChatPageState extends State { /// Which pin the strip shows; the list is newest pin first. int _pinIndex = 0; + /// Message the last jump landed on, flashing so the user sees which one it + /// was; cleared by [_highlightTimer]. + int? _highlightMicros; + Timer? _highlightTimer; + /// Whether this chat publishes and shows read receipts. bool _readReceipts = false; @@ -696,6 +701,18 @@ class _ChatPageState extends State { }); } + /// Flashes the bubble a jump landed on, so the target is obvious even when + /// the message itself looks like its neighbours. + void _flashMessage(int micros) { + _highlightTimer?.cancel(); + setState(() => _highlightMicros = micros); + _highlightTimer = Timer(const Duration(milliseconds: 1200), () { + if (mounted) { + setState(() => _highlightMicros = null); + } + }); + } + /// Scrolls to [sentAt], used by the reply quote, the search hits and the /// date jump. /// @@ -727,6 +744,7 @@ class _ChatPageState extends State { if (context != null && context.mounted) { await Scrollable.ensureVisible(context, alignment: 0.2, duration: const Duration(milliseconds: 250)); + _flashMessage(micros); return; } await _settleAtOldest(); @@ -738,6 +756,7 @@ class _ChatPageState extends State { if (reached != null && reached.mounted) { await Scrollable.ensureVisible(reached, alignment: 0.3, duration: const Duration(milliseconds: 250)); + _flashMessage(micros); return; } final position = _scrollController.position; @@ -1391,6 +1410,7 @@ class _ChatPageState extends State { accentColor: _chatThemeColor ?? Singleton().appTheme.color, selectionMode: _selectionMode, selected: _selected.contains(micros), + highlight: _highlightMicros == micros, readAt: micros == _lastOwnMicros && _readReceipts ? _peerReadAt : null, onSelect: () => _toggleSelected(message), onActions: () => _openMessageActions(message), @@ -1495,6 +1515,7 @@ class _ChatPageState extends State { _scrollController.removeListener(_onScroll); WidgetsBinding.instance.removeObserver(_metricsObserver); _recordTimer?.cancel(); + _highlightTimer?.cancel(); if (_readPublish?.isActive ?? false) { // Leaving within the debounce window used to drop the cursor; send it // now, fire and forget (dispose cannot await). diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 5367104..fe73c5c 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -27,6 +27,10 @@ class ChatBubble extends StatefulWidget { /// Whether this bubble is part of the current selection. final bool selected; + /// Flashes the bubble after a jump, so the user can see which message the + /// jump landed on. + final bool highlight; + /// Instant up to which the peer read the chat; null when they never /// published one (receipts off or nothing read yet). final DateTime? readAt; @@ -52,6 +56,7 @@ class ChatBubble extends StatefulWidget { {required this.accentColor, this.selectionMode = false, this.selected = false, + this.highlight = false, this.readAt, this.onSelect, this.onActions, @@ -369,7 +374,10 @@ class _ChatBubbleState extends State { // is the bubble, so it is clipped to the corners instead of sitting inside // a coloured frame. final isMedia = widget.message.isMedia; - final bubbleBox = Container( + // Animated so a jump flashes in and fades out instead of popping. + final bubbleBox = AnimatedContainer( + duration: const Duration(milliseconds: 250), + curve: Curves.easeOut, decoration: BoxDecoration( // A reply needs a surface for its quote; the attachment below fills the // rest of the bubble. @@ -380,7 +388,7 @@ class _ChatBubbleState extends State { ), // Above the child: a border in the decoration would sit under an // attachment that fills the bubble. - foregroundDecoration: widget.selected + foregroundDecoration: (widget.selected || widget.highlight) ? BoxDecoration( borderRadius: BorderRadius.circular(20), border: Border.all( diff --git a/test/chat_bubble_test.dart b/test/chat_bubble_test.dart index 43f841b..ef09168 100644 --- a/test/chat_bubble_test.dart +++ b/test/chat_bubble_test.dart @@ -267,5 +267,31 @@ void main() { accentColor: Colors.blue, )); expect(find.text('👍'), findsOneWidget); + + // A jump lights the target bubble and drops the frame again afterwards. + Future frame(ChatBubble bubble) async { + await show(bubble); + return tester + .widget(find + .ancestor( + of: find.text('cíl'), + matching: find.byType(AnimatedContainer)) + .first) + .foregroundDecoration; + } + + ChatBubble target({required bool highlight, bool selected = false}) => + ChatBubble( + null, + PrivateMessage('2', 'cíl', DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + highlight: highlight, + selected: selected, + ); + expect(await frame(target(highlight: false)), isNull); + expect(await frame(target(highlight: true)), isNotNull); + expect(await frame(target(highlight: true, selected: true)), isNotNull); }); } From 45adaf3f2981565f0f42b96aa155128f7f444e35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 16:35:26 +0100 Subject: [PATCH 113/181] perf(media): stop re-decrypting attachments and decode them tile-sized Scrolling a chat or the media grid kept showing a spinner because every row that left the viewport was disposed, and coming back decrypted the same file again - queued behind the two-decrypt throttle. Decrypted bytes now stay in a bounded in-memory cache (24 files / 64 MB), cleared whenever the media files are wiped. The thumbnails also decoded the camera's full resolution into a bubble or a 100 px tile: Image.memory is now given a cacheWidth for the box it fills. --- lib/pages/chat_info_page.dart | 9 +++++- lib/utils/media_utils.dart | 51 ++++++++++++++++++++++++++++++++-- lib/widgets/media_bubble.dart | 7 ++++- test/media_cache_test.dart | 52 +++++++++++++++++++++++++++++++++++ 4 files changed, 114 insertions(+), 5 deletions(-) create mode 100644 test/media_cache_test.dart diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index fb610a3..054bc01 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -447,6 +447,9 @@ class _MediaTileState extends State<_MediaTile> { } } + /// One tile of the three-column grid, gaps and padding taken off. + double get _tileWidth => (MediaQuery.sizeOf(context).width - 24) / 3; + @override Widget build(BuildContext context) { final isVideo = widget.message.mediaType == MediaType.video; @@ -458,7 +461,11 @@ class _MediaTileState extends State<_MediaTile> { child: isVideo ? _videoTile() : _bytes != null - ? Image.memory(_bytes!, fit: BoxFit.cover) + ? Image.memory(_bytes!, + fit: BoxFit.cover, + // Tile-sized decode: a full-resolution photo per square is + // 40+ MB of bitmap and a visible hitch while scrolling. + cacheWidth: MediaUtils.decodeWidth(context, _tileWidth)) : Center( child: _error ? const Icon(Icons.broken_image, size: 24) diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 3af0b89..60de5a9 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -6,7 +6,7 @@ import 'dart:ui' as ui; import 'package:cryptography/cryptography.dart' as cryptography; import 'package:file_picker/file_picker.dart'; import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart' show IconData, Icons; +import 'package:flutter/material.dart' show BuildContext, IconData, Icons, MediaQuery; import 'package:image_picker/image_picker.dart'; import 'package:mime/mime.dart'; import 'package:path_provider/path_provider.dart'; @@ -143,15 +143,59 @@ class MediaUtils { /// Decrypt an at-rest file written by [encryptAtRest]. /// /// Throttled: decrypting spawns an isolate per call, so a chat full of - /// attachments would otherwise spawn one burst per scroll. + /// attachments would otherwise spawn one burst per scroll. Decrypted bytes + /// are kept for the most recently shown attachments: a list disposes its + /// rows when they leave the viewport, and decrypting the same photo again + /// every time it scrolls back is what kept the spinner up. static Future decryptAtRest(String path) async { + final cached = _mediaCache.remove(path); + if (cached != null) { + _mediaCache[path] = cached; + return cached; + } return _withDecryptSlot(() async { final blob = await File(path).readAsBytes(); final key = Uint8List.fromList(Singleton().boxCollectionKey); - return compute(_gcmDecrypt, _GcmArgs(blob, key)); + final plain = await compute(_gcmDecrypt, _GcmArgs(blob, key)); + _cacheBytes(path, plain); + return plain; }); } + /// Decoded media kept in memory, oldest first. + static final Map _mediaCache = {}; + static const int _maxCachedMedia = 24; + static const int _maxCachedBytes = 64 << 20; + static int _cachedBytes = 0; + + static void _cacheBytes(String path, Uint8List bytes) { + final previous = _mediaCache.remove(path); + if (previous != null) { + _cachedBytes -= previous.length; + } + if (bytes.length > _maxCachedBytes) { + return; + } + _mediaCache[path] = bytes; + _cachedBytes += bytes.length; + while (_mediaCache.length > _maxCachedMedia || + _cachedBytes > _maxCachedBytes) { + _cachedBytes -= _mediaCache.remove(_mediaCache.keys.first)!.length; + } + } + + /// Drops the plaintext attachments held in memory, e.g. when the local media + /// files are deleted. + static void clearDecryptCache() { + _mediaCache.clear(); + _cachedBytes = 0; + } + + /// Decode width for [Image.memory]: a camera photo must not be decoded at its + /// full resolution for a thumbnail-sized box. + static int decodeWidth(BuildContext context, double logicalWidth) => + (logicalWidth * MediaQuery.devicePixelRatioOf(context)).round(); + static const int _maxConcurrentDecrypts = 2; static int _activeDecrypts = 0; static final List> _decryptWaiters = []; @@ -313,6 +357,7 @@ class MediaUtils { /// Remove every locally stored media file (used on full cache wipe). static Future clearMediaDir() async { + clearDecryptCache(); try { final dir = Directory('${await Utils.getCacheDir()}/media'); if (await dir.exists()) { diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index f1d7365..2fd5de4 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -363,6 +363,7 @@ class _MediaBubbleState extends State { width: size.width, height: size.height, fit: BoxFit.cover, + cacheWidth: MediaUtils.decodeWidth(context, size.width), ); }, ), @@ -597,7 +598,11 @@ class _AlbumTileState extends State { if (!snapshot.hasData) { return const Center(child: Icon(Icons.broken_image)); } - return Image.memory(snapshot.data!, fit: BoxFit.cover); + // Album tiles are 110 wide (see _albumWidget); decoding the full + // photo for one of them is what made a grid of attachments crawl. + return Image.memory(snapshot.data!, + fit: BoxFit.cover, + cacheWidth: MediaUtils.decodeWidth(context, 110)); }, ); case MediaType.video: diff --git a/test/media_cache_test.dart b/test/media_cache_test.dart new file mode 100644 index 0000000..385e09e --- /dev/null +++ b/test/media_cache_test.dart @@ -0,0 +1,52 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/media_utils.dart'; +import 'package:whisper/utils/singleton.dart'; + +/// A chat list disposes the rows that leave the viewport, so a photo scrolling +/// back into view used to be decrypted again from disk: the spinner stayed up +/// for as long as the queue behind it. +void main() { + final key = List.generate(32, (i) => i + 1); + final plain = Uint8List.fromList(List.generate(2048, (i) => i % 251)); + late Directory dir; + + setUpAll(() { + dir = Directory.systemTemp.createTempSync('whisper_media_cache_test'); + Singleton().boxCollectionKey = key; + }); + + tearDownAll(() async { + MediaUtils.clearDecryptCache(); + await dir.delete(recursive: true); + }); + + Future stored(String name) async { + final path = '${dir.path}/$name'; + await File(path).writeAsBytes(await MediaUtils.encryptWith(plain, key)); + return path; + } + + test('a decrypted attachment is served from memory the second time', + () async { + final path = await stored('one'); + expect(await MediaUtils.decryptAtRest(path), plain); + + // The file is gone, so only the cache can answer this one. + await File(path).delete(); + expect(await MediaUtils.decryptAtRest(path), plain); + }); + + test('clearing the cache sends the next read back to the file', () async { + final path = await stored('two'); + await MediaUtils.decryptAtRest(path); + + MediaUtils.clearDecryptCache(); + await File(path).delete(); + + await expectLater( + MediaUtils.decryptAtRest(path), throwsA(isA())); + }); +} From 54bcc488d210ca3d3b6a0c6f809294b3e90ea5e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 17:08:05 +0100 Subject: [PATCH 114/181] fix(chat): stop a reaction from re-mounting the attachment The bubble clipped itself only while it carried no reaction, and a Container adds or drops its clip widget with that flag: the attachment below changed depth, was mounted again, and its decoded frame went away until the photo was decrypted and decoded once more - the white flash. The clip wrapper is now always there and only switches between clipping and passing through. --- lib/widgets/chat_bubble.dart | 24 ++++++--- test/reaction_rebuild_test.dart | 87 +++++++++++++++++++++++++++++++++ 2 files changed, 104 insertions(+), 7 deletions(-) create mode 100644 test/reaction_rebuild_test.dart diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index fe73c5c..88a3f19 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -397,11 +397,6 @@ class _ChatBubbleState extends State { ), ) : null, - // An attachment clips its own media; the bubble must stay unclipped when - // a reaction badge hangs over its bottom edge. - clipBehavior: isMedia && widget.message.reactionEmojis.isEmpty - ? Clip.antiAlias - : Clip.none, padding: isMedia ? (widget.message.isReply ? const EdgeInsets.fromLTRB(8, 8, 8, 0) @@ -412,15 +407,30 @@ class _ChatBubbleState extends State { child: bubble, ); + // An attachment clips its own media; the bubble must stay unclipped when a + // reaction badge hangs over its bottom edge. The wrapper is always there and + // only stops clipping: toggling Container.clipBehavior adds or drops its + // clip widget, which re-mounts the attachment and throws the decoded image + // away - the white flash when a reaction was added. + final clippedBox = isMedia + ? ClipRRect( + borderRadius: BorderRadius.circular(20), + clipBehavior: widget.message.reactionEmojis.isEmpty + ? Clip.antiAlias + : Clip.none, + child: bubbleBox, + ) + : bubbleBox; + // The reactions hang on the bubble's bottom edge as one badge, on the side // opposite the bubble's own side, the way a messenger pins them there. final bubbleWithBadge = widget.message.reactionEmojis.isEmpty || widget.message.isMedia - ? bubbleBox + ? clippedBox : Stack( clipBehavior: Clip.none, children: [ - bubbleBox, + clippedBox, Positioned( bottom: -12, left: widget.message.isMe ? 8 : null, diff --git a/test/reaction_rebuild_test.dart b/test/reaction_rebuild_test.dart new file mode 100644 index 0000000..bb42c3c --- /dev/null +++ b/test/reaction_rebuild_test.dart @@ -0,0 +1,87 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/models/profile.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/media_utils.dart'; +import 'package:whisper/utils/singleton.dart'; +import 'package:whisper/widgets/chat_bubble.dart'; +import 'package:whisper/widgets/media_bubble.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +/// A reaction is toggled on an attachment all the time. When the bubble's clip +/// wrapper came and went with it, the attachment was mounted again from +/// scratch: the decoded frame went away and the photo blinked white before it +/// came back. +void main() { + final png = base64Decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFAAH/q842iQAAAABJRU5ErkJggg=='); + final key = List.generate(32, (i) => i + 1); + final peer = User('2', 'peer', '', false); + late Directory dir; + + setUpAll(() { + dir = Directory.systemTemp.createTempSync('whisper_reaction_rebuild'); + Singleton().boxCollectionKey = key; + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + tearDownAll(() async { + MediaUtils.clearDecryptCache(); + await dir.delete(recursive: true); + }); + + Widget app(PrivateMessage message) => MaterialApp( + home: Scaffold( + body: Center( + child: + ChatBubble(null, message, null, peer, accentColor: Colors.blue), + ), + ), + ); + + testWidgets('reacting to an attachment keeps its image mounted', + (tester) async { + final path = '${dir.path}/photo'; + await tester.runAsync(() async { + await File(path).writeAsBytes( + await MediaUtils.encryptWith(Uint8List.fromList(png), key)); + }); + final message = PrivateMessage( + '2', + '', + DateTime(2026), + DateTime(2026), + true, + mediaId: 'media-1', + mediaTypeStr: MediaType.image.name, + localPath: path, + width: 100, + height: 100, + ); + + await tester.pumpWidget(app(message)); + for (var i = 0; i < 20; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 20))); + await tester.pump(const Duration(milliseconds: 16)); + } + expect(find.byType(Image), findsOneWidget); + final before = tester.state(find.byType(MediaBubble)); + + // What CacheUtils.setMessageReaction does: same object, a new badge. + message.reactions = {'1': '👍'}; + await tester.pumpWidget(app(message)); + await tester.pump(const Duration(milliseconds: 16)); + + expect(identical(tester.state(find.byType(MediaBubble)), before), isTrue, + reason: 'the attachment must not be re-mounted by a reaction'); + expect(find.text('👍'), findsOneWidget); + expect(find.byType(Image), findsOneWidget); + }); +} From 3b95ec7d44d9c817e5002bd9a5842690869aea3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 17:50:44 +0100 Subject: [PATCH 115/181] feat(settings): redesign the theme dialog The dialog was a dropdown, a button that opened a second dialog, and a Material 3 switch, in a box a quarter of the screen wide. It now shows a live sample of the picked seed and mode, switches the mode with a segmented control, and offers twelve seed swatches plus a custom tile that opens the color wheel. The wheel dialog gained a hex field and a swatch of the color it holds. Material 3 is no longer a setting: the app is Material 3, so the field, its adapter entry, its translation key and the switch are gone. --- assets/translations/cs.json | 4 +- assets/translations/en.json | 4 +- lib/main.dart | 2 +- lib/models/app_theme.dart | 9 +- lib/models/app_theme.g.dart | 7 +- lib/pages/whisper_page.dart | 6 +- lib/utils/dialog_utils.dart | 386 ++++++++++++++++++++++++++---------- lib/utils/theme_utils.dart | 3 +- test/theme_dialog_test.dart | 77 +++++++ 9 files changed, 372 insertions(+), 126 deletions(-) create mode 100644 test/theme_dialog_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 2f78539..89b2501 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -81,8 +81,10 @@ "lightText": "Světlý", "darkText": "Tmavý", "themeColor": "Barva motivu", + "themePreviewPeer": "Ahoj, jak to vypadá?", + "themePreviewOwn": "Takto bude vypadat tvůj chat", + "themePreviewButton": "Odeslat", "chooseColor": "Vybrat barvu", - "useMat3": "Material Design 3", "pickColor": "Vyberte barvu", "newMessagesTitle": "Nové zprávy", "newMessagesBody": "Máte nové zprávy v chatu", diff --git a/assets/translations/en.json b/assets/translations/en.json index 43e5dbd..12a081a 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -81,8 +81,10 @@ "lightText": "Light", "darkText": "Dark", "themeColor": "Theme color", + "themePreviewPeer": "Hi, how does it look?", + "themePreviewOwn": "Your chat will look like this", + "themePreviewButton": "Send", "chooseColor": "Choose color", - "useMat3": "Material Design 3", "pickColor": "Pick color", "newMessagesTitle": "New messages", "newMessagesBody": "You have new messages in chat", diff --git a/lib/main.dart b/lib/main.dart index 9f72e3a..643a0b9 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -82,7 +82,7 @@ void main() async { // Default theme Singleton().appTheme = await CacheUtils.getTheme() ?? - AppTheme.fromValues(ThemeMode.system, Colors.blue, true); + AppTheme.fromValues(ThemeMode.system, Colors.blue); // Save theme await CacheUtils.setTheme(Singleton().appTheme); diff --git a/lib/models/app_theme.dart b/lib/models/app_theme.dart index b56e7bd..eca44bd 100644 --- a/lib/models/app_theme.dart +++ b/lib/models/app_theme.dart @@ -7,19 +7,16 @@ part 'app_theme.g.dart'; @HiveType(typeId: 2) class AppTheme { /// Constructor for Hive - AppTheme(this.themeModeStr, this.colorHex, this.useMaterial3); + AppTheme(this.themeModeStr, this.colorHex); @HiveField(0) String themeModeStr; // String of ThemeMode enum @HiveField(1) String colorHex; // Color hex - @HiveField(2) - bool useMaterial3; /// Factory constructor for user friendly usage - factory AppTheme.fromValues( - ThemeMode themeMode, Color color, bool material3) { - return AppTheme(themeMode.name, ColorUtils.colorToHex(color), material3); + factory AppTheme.fromValues(ThemeMode themeMode, Color color) { + return AppTheme(themeMode.name, ColorUtils.colorToHex(color)); } /// Get ThemeMode from themeModeStr diff --git a/lib/models/app_theme.g.dart b/lib/models/app_theme.g.dart index cd3c92a..75f40c0 100644 --- a/lib/models/app_theme.g.dart +++ b/lib/models/app_theme.g.dart @@ -19,20 +19,17 @@ class AppThemeAdapter extends TypeAdapter { return AppTheme( fields[0] as String, fields[1] as String, - fields[2] as bool, ); } @override void write(BinaryWriter writer, AppTheme obj) { writer - ..writeByte(3) + ..writeByte(2) ..writeByte(0) ..write(obj.themeModeStr) ..writeByte(1) - ..write(obj.colorHex) - ..writeByte(2) - ..write(obj.useMaterial3); + ..write(obj.colorHex); } @override diff --git a/lib/pages/whisper_page.dart b/lib/pages/whisper_page.dart index 58a9d13..765221a 100644 --- a/lib/pages/whisper_page.dart +++ b/lib/pages/whisper_page.dart @@ -65,16 +65,14 @@ class WhisperPage extends StatelessWidget { colorScheme: ColorScheme.fromSeed( seedColor: Provider.of(context).appTheme.color, brightness: Brightness.light), - useMaterial3: - Provider.of(context).appTheme.useMaterial3) + useMaterial3: true) .copyWith(pageTransitionsTheme: _pageTransitionsTheme), // Dark theme darkTheme: ThemeData.from( colorScheme: ColorScheme.fromSeed( seedColor: Provider.of(context).appTheme.color, brightness: Brightness.dark), - useMaterial3: - Provider.of(context).appTheme.useMaterial3) + useMaterial3: true) .copyWith(pageTransitionsTheme: _pageTransitionsTheme), // Light / Dark / System themeMode: Provider.of(context).appTheme.themeMode, diff --git a/lib/utils/dialog_utils.dart b/lib/utils/dialog_utils.dart index a05b6cf..c08940f 100644 --- a/lib/utils/dialog_utils.dart +++ b/lib/utils/dialog_utils.dart @@ -7,6 +7,7 @@ import 'package:flutter_colorpicker/flutter_colorpicker.dart'; import 'package:provider/provider.dart'; import '../utils/cache_utils.dart'; import 'package:whisper_openapi_client_dart/api.dart'; +import 'color_utils.dart'; import 'singleton.dart'; import 'theme_notifier.dart'; import 'utils.dart'; @@ -85,102 +86,137 @@ class DialogUtils { }); } + /// Seed colors offered as swatches in the theme dialog. + static const List themeSeeds = [ + Colors.blue, + Colors.indigo, + Colors.deepPurple, + Colors.pink, + Colors.red, + Colors.orange, + Colors.amber, + Colors.green, + Colors.teal, + Colors.cyan, + Colors.brown, + Colors.blueGrey, + ]; + /// Returns theme dialog static Widget themeDialog(BuildContext context) { /// Change theme via notifier - changeTheme() { + void changeTheme() { Provider.of(context, listen: false) .changeTheme(Singleton().appTheme); } + /// Applies a change live: the preview and the page behind the dialog move + /// with it, so there is no apply button to forget. + Future apply(VoidCallback mutate) async { + mutate(); + changeTheme(); + await CacheUtils.setTheme(Singleton().appTheme); + } + return StatefulBuilder(builder: (context, setState) { - /// Open color picker dialog/// Open color picker dialog + /// Open the color wheel; the palette covers the common cases. Future openColorPickerDialog() async { - await showDialog( - context: context, - builder: (context) => - colorPickerDialog(context, Singleton().appTheme.color)) - .then((value) async { - if (value != null) { - setState(() { - Singleton().appTheme.color = value; - changeTheme(); - }); - await CacheUtils.setTheme(Singleton().appTheme); - } - }); + final value = await showDialog( + context: context, + builder: (context) => + colorPickerDialog(context, Singleton().appTheme.color)); + if (value != null) { + setState(() { + Singleton().appTheme.color = value; + }); + await apply(() {}); + } } + final theme = Singleton().appTheme; + final seed = theme.color; + final inPalette = themeSeeds.any((color) => color == seed); + return BackdropFilter( filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10), child: AlertDialog( + // The dialog had a quarter of the screen; a seed palette and a + // preview need the width, and 380 keeps it readable on a tablet. + constraints: const BoxConstraints(maxWidth: 380), title: Text('themeSettings'.tr()), content: SizedBox( - width: MediaQuery.of(context).size.width / 4, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - // Theme mode - Row( - children: [ - Text( - 'themeMode'.tr(), - style: TextStyle(fontSize: 16), - ), - Spacer(), - DropdownButton( - value: Singleton().appTheme.themeMode, - items: ThemeMode.values.map((ThemeMode mode) { - return DropdownMenuItem( - value: mode, - child: Text('${mode.name}Text'.tr()), - ); - }).toList(), - onChanged: (ThemeMode? value) async { + width: double.maxFinite, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _themePreview(context, seed), + const SizedBox(height: 16), + Center( + child: SegmentedButton( + showSelectedIcon: false, + segments: [ + for (final mode in ThemeMode.values) + ButtonSegment( + value: mode, + icon: Icon( + switch (mode) { + ThemeMode.system => Icons.brightness_auto, + ThemeMode.light => Icons.light_mode, + ThemeMode.dark => Icons.dark_mode, + }, + // The icons carry the label for the screen reader; + // three labels would not fit next to each other. + semanticLabel: '${mode.name}Text'.tr(), + ), + ), + ], + selected: {theme.themeMode}, + onSelectionChanged: (selection) async { setState(() { - Singleton().appTheme.themeMode = value!; - changeTheme(); + theme.themeMode = selection.first; }); - await CacheUtils.setTheme(Singleton().appTheme); + await apply(() {}); }, - ) - ], - ), - // Theme color - Row( - children: [ - Text( - 'themeColor'.tr(), - style: TextStyle(fontSize: 16), - ), - Spacer(), - ElevatedButton( - onPressed: openColorPickerDialog, - child: Text('chooseColor'.tr()), - ), - ], - ), - // Use material 3 - Row( - children: [ - Text( - 'useMat3'.tr(), - style: TextStyle(fontSize: 16), ), - Spacer(), - Switch( - value: Singleton().appTheme.useMaterial3, - onChanged: (_) { - setState(() { - Singleton().appTheme.useMaterial3 = - !Singleton().appTheme.useMaterial3; - changeTheme(); - CacheUtils.setTheme(Singleton().appTheme); - }); - }) - ], - ) - ], + ), + const SizedBox(height: 20), + Text('themeColor'.tr(), + style: Theme.of(context).textTheme.labelLarge), + const SizedBox(height: 8), + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + for (var i = 0; i < themeSeeds.length; i++) + _colorSwatch( + context, + key: ValueKey('themeSwatch-$i'), + color: themeSeeds[i], + selected: themeSeeds[i] == seed, + onTap: () async { + setState(() { + theme.color = themeSeeds[i]; + }); + await apply(() {}); + }, + ), + // The custom color is a tile of its own: a hand picked + // seed is not in the palette, and it still has to show as + // the current choice. + _colorSwatch( + context, + key: const ValueKey('themeSwatch-custom'), + color: inPalette ? null : seed, + selected: !inPalette, + icon: inPalette ? Icons.colorize : null, + onTap: openColorPickerDialog, + ), + ], + ), + ], + ), ), ), actionsAlignment: MainAxisAlignment.center, @@ -197,7 +233,8 @@ class DialogUtils { onPressed: Navigator.of(context).pop, child: Text( 'okText'.tr(), - style: TextStyle(color: Theme.of(context).colorScheme.surface), + style: + TextStyle(color: Theme.of(context).colorScheme.onPrimary), ), ), ], @@ -206,42 +243,179 @@ class DialogUtils { }); } + /// Live sample of the theme: what the picked seed and mode look like on a + /// bubble, on the surface and on a filled button. + static Widget _themePreview(BuildContext context, Color seed) { + final scheme = ColorScheme.fromSeed( + seedColor: seed, brightness: Theme.of(context).brightness); + Widget bubble(String text, {required bool mine}) { + return Align( + alignment: mine ? Alignment.centerRight : Alignment.centerLeft, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: mine ? scheme.primary : scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(16), + ), + child: Text( + text, + style: TextStyle( + fontSize: 13, + color: mine ? scheme.onPrimary : scheme.onSurface), + ), + ), + ); + } + + return Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: scheme.surfaceContainerLow, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: scheme.outlineVariant), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + bubble('themePreviewPeer'.tr(), mine: false), + const SizedBox(height: 6), + bubble('themePreviewOwn'.tr(), mine: true), + const SizedBox(height: 10), + FilledButton( + onPressed: () {}, + child: Text('themePreviewButton'.tr()), + ), + ], + ), + ); + } + + /// One round seed swatch of the theme palette, with a check when it is the + /// one in use. + static Widget _colorSwatch( + BuildContext context, { + required Key key, + required Color? color, + required bool selected, + required VoidCallback onTap, + IconData? icon, + }) { + final scheme = Theme.of(context).colorScheme; + return InkWell( + key: key, + onTap: onTap, + customBorder: const CircleBorder(), + child: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + border: Border.all( + color: color == null ? scheme.outline : scheme.outlineVariant, + ), + ), + child: Icon( + selected ? Icons.check : icon, + size: 20, + color: color == null + ? scheme.onSurfaceVariant + : ThemeData.estimateBrightnessForColor(color) == Brightness.dark + ? Colors.white + : Colors.black, + ), + ), + ); + } + /// Returns color picker dialog static Widget colorPickerDialog(BuildContext context, Color initialColor) { Color pickerColor = initialColor; + String hexOf(Color color) => '#' + '${color.toARGB32().toRadixString(16).padLeft(8, '0').substring(2).toUpperCase()}'; + final hexController = TextEditingController(text: hexOf(initialColor)); - return BackdropFilter( - filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10), - child: AlertDialog( - title: Text('pickColor'.tr()), - content: Column( - mainAxisSize: MainAxisSize.min, - children: [ - ColorPicker( - enableAlpha: false, - labelTypes: [], - pickerColor: initialColor, - onColorChanged: (color) => pickerColor = color, - ), - ], - ), - actionsAlignment: MainAxisAlignment.center, - actions: [ - ElevatedButton( - onPressed: () => Navigator.of(context).pop(pickerColor), - style: ButtonStyle( - backgroundColor: WidgetStateProperty.all( - Theme.of(context).colorScheme.primary), - shape: WidgetStateProperty.all( - RoundedRectangleBorder(borderRadius: BorderRadius.circular(35)), + return StatefulBuilder(builder: (context, setState) { + void pick(Color color) { + setState(() { + pickerColor = color; + hexController.text = hexOf(color); + }); + } + + return BackdropFilter( + filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10), + child: AlertDialog( + constraints: const BoxConstraints(maxWidth: 380), + title: Text('pickColor'.tr()), + content: SizedBox( + width: double.maxFinite, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // What the wheel currently holds, before the hex field: the + // wheel alone does not say which color is selected. + Container( + height: 36, + decoration: BoxDecoration( + color: pickerColor, + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: Theme.of(context).colorScheme.outlineVariant), + ), + ), + const SizedBox(height: 8), + TextField( + controller: hexController, + decoration: const InputDecoration( + isDense: true, + hintText: '#RRGGBB', + prefixIcon: Icon(Icons.tag, size: 18), + ), + onChanged: (value) { + try { + final parsed = ColorUtils.colorFromHex(value); + setState(() { + pickerColor = parsed; + }); + } catch (_) { + // Half-typed hex: keep the last valid color. + } + }, + ), + const SizedBox(height: 8), + ColorPicker( + enableAlpha: false, + labelTypes: const [], + displayThumbColor: true, + pickerColor: pickerColor, + onColorChanged: pick, + ), + ], ), ), - child: Text('okText'.tr(), - style: TextStyle(color: Theme.of(context).colorScheme.surface)), ), - ], - ), - ); + actionsAlignment: MainAxisAlignment.center, + actions: [ + ElevatedButton( + onPressed: () => Navigator.of(context).pop(pickerColor), + style: ButtonStyle( + backgroundColor: WidgetStateProperty.all( + Theme.of(context).colorScheme.primary), + shape: WidgetStateProperty.all( + RoundedRectangleBorder( + borderRadius: BorderRadius.circular(35)), + ), + ), + child: Text('okText'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.onPrimary)), + ), + ], + ), + ); + }); } /// Returns yes/no dialog diff --git a/lib/utils/theme_utils.dart b/lib/utils/theme_utils.dart index 117ca38..6309b1c 100644 --- a/lib/utils/theme_utils.dart +++ b/lib/utils/theme_utils.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; -import 'singleton.dart'; class ThemeUtils { /// Theme seeded with the per-chat color, or the inherited theme without an override. @@ -16,7 +15,7 @@ class ThemeUtils { return _chatThemes[key] ??= ThemeData.from( colorScheme: ColorScheme.fromSeed(seedColor: seed, brightness: brightness), - useMaterial3: Singleton().appTheme.useMaterial3); + useMaterial3: true); } static final Map _chatThemes = {}; diff --git a/test/theme_dialog_test.dart b/test/theme_dialog_test.dart new file mode 100644 index 0000000..6170634 --- /dev/null +++ b/test/theme_dialog_test.dart @@ -0,0 +1,77 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:provider/provider.dart'; +import 'package:whisper/models/app_theme.dart'; +import 'package:whisper/utils/dialog_utils.dart'; +import 'package:whisper/utils/singleton.dart'; +import 'package:whisper/utils/theme_notifier.dart'; + +/// The theme dialog applies on tap, so picking a swatch has to move the seed +/// the whole app is seeded with - and show which one is in use. +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_theme_dialog_test'); + Hive.init(dir.path); + if (!Hive.isAdapterRegistered(2)) { + Hive.registerAdapter(AppThemeAdapter()); + } + }); + + setUp(() async { + await Hive.openBox('theme'); + await Hive.box('theme').clear(); + Singleton().appTheme = AppTheme.fromValues(ThemeMode.system, Colors.blue); + }); + + tearDownAll(() async { + await dir.delete(recursive: true); + }); + + Future open(WidgetTester tester) async { + final theme = ThemeNotifier(Singleton().appTheme); + await tester.pumpWidget(ChangeNotifierProvider.value( + value: theme, + child: MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => showDialog( + context: context, builder: DialogUtils.themeDialog), + child: const Text('open'), + ), + ), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + } + + testWidgets('a swatch becomes the seed and is marked as picked', + (tester) async { + await open(tester); + expect(find.byIcon(Icons.check), findsOneWidget, reason: 'blue is picked'); + + await tester.tap(find.byKey(const ValueKey('themeSwatch-8'))); + await tester.pumpAndSettle(); + // Let the fire-and-forget Hive write finish before the test tears down. + await tester + .runAsync(() => Future.delayed(const Duration(milliseconds: 50))); + + // getMaterialColor builds a fresh MaterialColor, so compare values. + expect(Singleton().appTheme.color.toARGB32(), Colors.teal.toARGB32()); + expect(find.byIcon(Icons.check), findsOneWidget); + final swatch = tester.widget(find + .descendant( + of: find.byKey(const ValueKey('themeSwatch-8')), + matching: find.byType(Container)) + .first); + expect((swatch.decoration as BoxDecoration?)?.color?.toARGB32(), + Colors.teal.toARGB32()); + }); +} From 0f84cf7671035044e2c47d96f52c8f93071c9826 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 18:14:02 +0100 Subject: [PATCH 116/181] feat(chat): give the chat theme the same picker as the app theme The chat theme opened the bare color wheel from a settings row, with a second row to drop the override, so the two places that pick a seed color shared nothing. The palette, the preview and the custom tile now live in one widget used by both dialogs; the chat dialog adds a tile for the global color, which replaces the separate row, and applies live like the app dialog does. The swatch check compares colors by value: the stored seed is re-built from its hex, so an identity check left the mark on the custom tile forever. --- lib/pages/chat_info_page.dart | 37 +++--- lib/utils/dialog_utils.dart | 220 +++++++++++++------------------ lib/widgets/theme_palette.dart | 202 ++++++++++++++++++++++++++++ test/chat_theme_dialog_test.dart | 41 ++++++ test/theme_dialog_test.dart | 9 +- 5 files changed, 360 insertions(+), 149 deletions(-) create mode 100644 lib/widgets/theme_palette.dart create mode 100644 test/chat_theme_dialog_test.dart diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 054bc01..9c3da8c 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -10,7 +10,6 @@ import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; import '../utils/dialog_utils.dart'; import '../utils/media_utils.dart'; -import '../utils/singleton.dart'; import '../utils/utils.dart'; import '../utils/theme_utils.dart'; import '../widgets/media_bubble.dart'; @@ -165,29 +164,31 @@ class _ChatInfoPageState extends State { } } - /// Pick a per-chat theme color. The dialog uses the chat color too. + /// Open the chat theme dialog: the same palette as the app theme, applied + /// live. The dialog is themed with the chat color, so it previews itself. Future _pickChatTheme() async { - Color? color = await showDialog( + await showDialog( context: context, builder: (dialogContext) => Theme( data: ThemeUtils.chatTheme(context, _chatThemeColor), child: Builder( - builder: (themedContext) => DialogUtils.colorPickerDialog( - themedContext, - _chatThemeColor ?? Singleton().appTheme.color), + builder: (themedContext) => DialogUtils.chatThemeDialog( + themedContext, + current: _chatThemeColor, + onChanged: _applyChatTheme, + ), ), )); - if (color == null || !mounted) { - return; - } - await CacheUtils.setChatTheme(widget.userId, color); await _loadChatTheme(); } - /// Drop the per-chat theme and fall back to the global one - Future _clearChatTheme() async { - await CacheUtils.clearChatTheme(widget.userId); - await _loadChatTheme(); + /// Stores the picked chat color; null falls back to the global theme. + Future _applyChatTheme(Color? color) async { + if (color == null) { + await CacheUtils.clearChatTheme(widget.userId); + } else { + await CacheUtils.setChatTheme(widget.userId, color); + } } void _openMedia(PrivateMessage message) { @@ -311,14 +312,6 @@ class _ChatInfoPageState extends State { ), ), ), - // Drop the override - if (_chatThemeColor != null) - SettingsTile( - icon: Icons.restart_alt, - label: 'useGlobalTheme'.tr(), - onPressed: _clearChatTheme, - ), - Divider(thickness: 1, indent: 10, endIndent: 10), ], ), diff --git a/lib/utils/dialog_utils.dart b/lib/utils/dialog_utils.dart index c08940f..a0f9025 100644 --- a/lib/utils/dialog_utils.dart +++ b/lib/utils/dialog_utils.dart @@ -7,6 +7,7 @@ import 'package:flutter_colorpicker/flutter_colorpicker.dart'; import 'package:provider/provider.dart'; import '../utils/cache_utils.dart'; import 'package:whisper_openapi_client_dart/api.dart'; +import '../widgets/theme_palette.dart'; import 'color_utils.dart'; import 'singleton.dart'; import 'theme_notifier.dart'; @@ -86,22 +87,6 @@ class DialogUtils { }); } - /// Seed colors offered as swatches in the theme dialog. - static const List themeSeeds = [ - Colors.blue, - Colors.indigo, - Colors.deepPurple, - Colors.pink, - Colors.red, - Colors.orange, - Colors.amber, - Colors.green, - Colors.teal, - Colors.cyan, - Colors.brown, - Colors.blueGrey, - ]; - /// Returns theme dialog static Widget themeDialog(BuildContext context) { /// Change theme via notifier @@ -135,7 +120,6 @@ class DialogUtils { final theme = Singleton().appTheme; final seed = theme.color; - final inPalette = themeSeeds.any((color) => color == seed); return BackdropFilter( filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10), @@ -151,7 +135,7 @@ class DialogUtils { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - _themePreview(context, seed), + ThemePreview(seed: seed), const SizedBox(height: 16), Center( child: SegmentedButton( @@ -185,35 +169,15 @@ class DialogUtils { Text('themeColor'.tr(), style: Theme.of(context).textTheme.labelLarge), const SizedBox(height: 8), - Wrap( - spacing: 8, - runSpacing: 8, - children: [ - for (var i = 0; i < themeSeeds.length; i++) - _colorSwatch( - context, - key: ValueKey('themeSwatch-$i'), - color: themeSeeds[i], - selected: themeSeeds[i] == seed, - onTap: () async { - setState(() { - theme.color = themeSeeds[i]; - }); - await apply(() {}); - }, - ), - // The custom color is a tile of its own: a hand picked - // seed is not in the palette, and it still has to show as - // the current choice. - _colorSwatch( - context, - key: const ValueKey('themeSwatch-custom'), - color: inPalette ? null : seed, - selected: !inPalette, - icon: inPalette ? Icons.colorize : null, - onTap: openColorPickerDialog, - ), - ], + ThemePalette( + selected: seed, + onPicked: (color) async { + setState(() { + theme.color = color; + }); + await apply(() {}); + }, + onCustom: openColorPickerDialog, ), ], ), @@ -243,89 +207,93 @@ class DialogUtils { }); } - /// Live sample of the theme: what the picked seed and mode look like on a - /// bubble, on the surface and on a filled button. - static Widget _themePreview(BuildContext context, Color seed) { - final scheme = ColorScheme.fromSeed( - seedColor: seed, brightness: Theme.of(context).brightness); - Widget bubble(String text, {required bool mine}) { - return Align( - alignment: mine ? Alignment.centerRight : Alignment.centerLeft, - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), - decoration: BoxDecoration( - color: mine ? scheme.primary : scheme.surfaceContainerHighest, - borderRadius: BorderRadius.circular(16), - ), - child: Text( - text, - style: TextStyle( - fontSize: 13, - color: mine ? scheme.onPrimary : scheme.onSurface), - ), - ), - ); - } - - return Container( - padding: const EdgeInsets.all(12), - decoration: BoxDecoration( - color: scheme.surfaceContainerLow, - borderRadius: BorderRadius.circular(16), - border: Border.all(color: scheme.outlineVariant), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - bubble('themePreviewPeer'.tr(), mine: false), - const SizedBox(height: 6), - bubble('themePreviewOwn'.tr(), mine: true), - const SizedBox(height: 10), - FilledButton( - onPressed: () {}, - child: Text('themePreviewButton'.tr()), - ), - ], - ), - ); - } - - /// One round seed swatch of the theme palette, with a check when it is the - /// one in use. - static Widget _colorSwatch( + /// Returns the per-chat theme dialog: the same palette and preview as the app + /// theme, plus a tile that hands the chat back to the global color. Mode and + /// Material version stay global, so they are not offered here. + /// + /// [onChanged] receives the picked color, or null for "use the global theme", + /// and is awaited before the next tap, so the page can persist it. + static Widget chatThemeDialog( BuildContext context, { - required Key key, - required Color? color, - required bool selected, - required VoidCallback onTap, - IconData? icon, + required Color? current, + required Future Function(Color? color) onChanged, }) { - final scheme = Theme.of(context).colorScheme; - return InkWell( - key: key, - onTap: onTap, - customBorder: const CircleBorder(), - child: Container( - width: 40, - height: 40, - decoration: BoxDecoration( - color: color, - shape: BoxShape.circle, - border: Border.all( - color: color == null ? scheme.outline : scheme.outlineVariant, + return StatefulBuilder(builder: (context, setState) { + // The dialog applies on tap, so it keeps its own copy: the page reloads + // from the cache asynchronously. + Color? picked = current; + + Future openColorPickerDialog() async { + final value = await showDialog( + context: context, + builder: (context) => colorPickerDialog( + context, picked ?? Singleton().appTheme.color)); + if (value != null) { + setState(() { + picked = value; + }); + await onChanged(value); + } + } + + return BackdropFilter( + filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10), + child: AlertDialog( + constraints: const BoxConstraints(maxWidth: 380), + title: Text('chatTheme'.tr()), + content: SizedBox( + width: double.maxFinite, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ThemePreview(seed: picked), + const SizedBox(height: 20), + Text('themeColor'.tr(), + style: Theme.of(context).textTheme.labelLarge), + const SizedBox(height: 8), + ThemePalette( + selected: picked, + inheritSelected: picked == null, + onInherit: () async { + setState(() { + picked = null; + }); + await onChanged(null); + }, + onPicked: (color) async { + setState(() { + picked = color; + }); + await onChanged(color); + }, + onCustom: openColorPickerDialog, + ), + ], + ), + ), ), + actionsAlignment: MainAxisAlignment.center, + actions: [ + TextButton( + style: ButtonStyle( + backgroundColor: WidgetStateProperty.all( + Theme.of(context).colorScheme.primary), + shape: WidgetStateProperty.all( + RoundedRectangleBorder( + borderRadius: BorderRadius.circular(35)), + ), + ), + onPressed: Navigator.of(context).pop, + child: Text('okText'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.onPrimary)), + ), + ], ), - child: Icon( - selected ? Icons.check : icon, - size: 20, - color: color == null - ? scheme.onSurfaceVariant - : ThemeData.estimateBrightnessForColor(color) == Brightness.dark - ? Colors.white - : Colors.black, - ), - ), - ); + ); + }); } /// Returns color picker dialog diff --git a/lib/widgets/theme_palette.dart b/lib/widgets/theme_palette.dart new file mode 100644 index 0000000..3d53f19 --- /dev/null +++ b/lib/widgets/theme_palette.dart @@ -0,0 +1,202 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +/// Seed colors offered as swatches: the app theme and the per-chat theme draw +/// from the same list, so a color picked in one place exists in the other. +const List themeSeeds = [ + Colors.blue, + Colors.indigo, + Colors.deepPurple, + Colors.pink, + Colors.red, + Colors.orange, + Colors.amber, + Colors.green, + Colors.teal, + Colors.cyan, + Colors.brown, + Colors.blueGrey, +]; + +/// Whether [color] is one of [themeSeeds]. Compared by value: a stored theme +/// rebuilds its MaterialColor, so identity never matches. +bool isSeedColor(Color? color) { + if (color == null) { + return false; + } + return themeSeeds.any((seed) => seed.toARGB32() == color.toARGB32()); +} + +/// Live sample of a theme: a bubble of each side and a filled button. +/// +/// [seed] is the color the sample is tinted with, the global app color when +/// null. +class ThemePreview extends StatelessWidget { + const ThemePreview({super.key, required this.seed}); + + final Color? seed; + + @override + Widget build(BuildContext context) { + final scheme = ColorScheme.fromSeed( + seedColor: seed ?? Theme.of(context).colorScheme.primary, + brightness: Theme.of(context).brightness, + ); + + Widget bubble(String text, {required bool mine}) { + return Align( + alignment: mine ? Alignment.centerRight : Alignment.centerLeft, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: mine ? scheme.primary : scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(16), + ), + child: Text( + text, + style: TextStyle( + fontSize: 13, + color: mine ? scheme.onPrimary : scheme.onSurface, + ), + ), + ), + ); + } + + return Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: scheme.surfaceContainerLow, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: scheme.outlineVariant), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + bubble('themePreviewPeer'.tr(), mine: false), + const SizedBox(height: 6), + bubble('themePreviewOwn'.tr(), mine: true), + const SizedBox(height: 10), + FilledButton( + onPressed: () {}, + child: Text('themePreviewButton'.tr()), + ), + ], + ), + ); + } +} + +/// Round seed swatches with the controls that sit next to them in a theme +/// dialog: a custom color and, when a chat may inherit, the global one. +class ThemePalette extends StatelessWidget { + const ThemePalette({ + super.key, + required this.selected, + this.onPicked, + this.onCustom, + this.onInherit, + this.inheritSelected = false, + }); + + /// The seed in use, null when the theme inherits the global color. + final Color? selected; + + final ValueChanged? onPicked; + final VoidCallback? onCustom; + + /// Present when "use the global theme" is a choice of its own. + final VoidCallback? onInherit; + final bool inheritSelected; + + @override + Widget build(BuildContext context) { + return Wrap( + spacing: 8, + runSpacing: 8, + children: [ + if (onInherit != null) + _Swatch( + key: const ValueKey('themeSwatch-global'), + color: null, + selected: inheritSelected, + icon: Icons.public, + tooltip: 'useGlobalTheme'.tr(), + onTap: onInherit, + ), + for (var i = 0; i < themeSeeds.length; i++) + _Swatch( + key: ValueKey('themeSwatch-$i'), + color: themeSeeds[i], + selected: selected?.toARGB32() == themeSeeds[i].toARGB32(), + onTap: onPicked == null ? null : () => onPicked!(themeSeeds[i]), + ), + // A hand picked color is not in the palette, and it still has to show + // as the current choice. + _Swatch( + key: const ValueKey('themeSwatch-custom'), + color: isSeedColor(selected) ? null : selected, + selected: selected != null && !isSeedColor(selected), + icon: + isSeedColor(selected) || selected == null ? Icons.colorize : null, + onTap: onCustom, + ), + ], + ); + } +} + +/// One round swatch, with a check when it is the one in use. +class _Swatch extends StatelessWidget { + const _Swatch({ + super.key, + required this.color, + required this.selected, + this.icon, + this.tooltip, + this.onTap, + }); + + final Color? color; + final bool selected; + final IconData? icon; + final String? tooltip; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final mark = selected ? Icons.check : icon; + final widget = InkWell( + onTap: onTap, + customBorder: const CircleBorder(), + child: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + border: Border.all( + color: color == null ? scheme.outline : scheme.outlineVariant, + ), + ), + child: mark == null + ? null + : Icon( + mark, + size: 20, + color: color == null + ? scheme.onSurfaceVariant + : ThemeData.estimateBrightnessForColor(color!) == + Brightness.dark + ? Colors.white + : Colors.black, + ), + ), + ); + if (tooltip == null) { + return widget; + } + return Tooltip(message: tooltip!, child: widget); + } +} diff --git a/test/chat_theme_dialog_test.dart b/test/chat_theme_dialog_test.dart new file mode 100644 index 0000000..9ad16a8 --- /dev/null +++ b/test/chat_theme_dialog_test.dart @@ -0,0 +1,41 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/dialog_utils.dart'; + +/// The per-chat dialog shares the app theme's palette, and adds the one choice +/// that only a chat has: fall back to the global color. +void main() { + testWidgets( + 'the chat dialog hands back the picked color, and null for global', + (tester) async { + final calls = []; + await tester.pumpWidget(MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => showDialog( + context: context, + builder: (context) => DialogUtils.chatThemeDialog( + context, + current: Colors.blue, + onChanged: (color) async => calls.add(color), + )), + child: const Text('open'), + ), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const ValueKey('themeSwatch-8'))); + await tester.pumpAndSettle(); + expect(calls.last?.toARGB32(), Colors.teal.toARGB32()); + + // The inherit tile is the chat dialog's own choice: the app theme dialog + // has no such tile. + await tester.tap(find.byKey(const ValueKey('themeSwatch-global'))); + await tester.pumpAndSettle(); + expect(calls.last, isNull); + }); +} diff --git a/test/theme_dialog_test.dart b/test/theme_dialog_test.dart index 6170634..ce26efe 100644 --- a/test/theme_dialog_test.dart +++ b/test/theme_dialog_test.dart @@ -65,7 +65,14 @@ void main() { // getMaterialColor builds a fresh MaterialColor, so compare values. expect(Singleton().appTheme.color.toARGB32(), Colors.teal.toARGB32()); - expect(find.byIcon(Icons.check), findsOneWidget); + // The check has to move to the picked swatch: comparing the stored + // MaterialColor by identity left it on the custom tile forever. + expect( + find.descendant( + of: find.byKey(const ValueKey('themeSwatch-8')), + matching: find.byIcon(Icons.check)), + findsOneWidget, + ); final swatch = tester.widget(find .descendant( of: find.byKey(const ValueKey('themeSwatch-8')), From 5c81ef079798e3aae512d141cd0a94e456363b03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 18:20:32 +0100 Subject: [PATCH 117/181] feat(chat): show who reacted, and mark your own pick in the reaction row Tapping the reaction badge now opens a sheet listing the emoji and everyone who used it, most used first; names come from the local user cache, so no server call. The reaction row marks the emoji this user already picked, so a second tap reads as take-it-back. The badge could not be tapped at all: it hung past its parent's bounds with Positioned, which paints but never takes a hit. The room it hangs into is now reserved inside the stack, for text, media and inside-bubble (voice/file) badges alike. --- assets/translations/cs.json | 1 + assets/translations/en.json | 1 + lib/pages/chat_page.dart | 1 + lib/utils/message_actions.dart | 73 ++++++++++++++++++++++++++++++++++ lib/widgets/chat_bubble.dart | 66 +++++++++++++++++------------- lib/widgets/media_bubble.dart | 56 ++++++++++++++------------ test/chat_bubble_test.dart | 16 ++++++++ test/reaction_list_test.dart | 22 ++++++++++ test/reaction_picker_test.dart | 48 ++++++++++++++++++++++ 9 files changed, 231 insertions(+), 53 deletions(-) create mode 100644 test/reaction_list_test.dart create mode 100644 test/reaction_picker_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 89b2501..e59b8fd 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -97,6 +97,7 @@ "yesterdayText": "Včera", "todayText": "Dnes", "meText": "Já", + "reactionsTitle": "Reakce", "accountDeleted2": "Váš účet byl smazán :P", "wsOffline": "WebSocket je offline", "attachButton": "Přiložit", diff --git a/assets/translations/en.json b/assets/translations/en.json index 12a081a..488928d 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -97,6 +97,7 @@ "yesterdayText": "Yesterday", "todayText": "Today", "meText": "Me", + "reactionsTitle": "Reactions", "accountDeleted2": "Your account has been deleted :P", "wsOffline": "WebSocket is offline", "attachButton": "Attach", diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 2d5d18a..0795aea 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1414,6 +1414,7 @@ class _ChatPageState extends State { readAt: micros == _lastOwnMicros && _readReceipts ? _peerReadAt : null, onSelect: () => _toggleSelected(message), onActions: () => _openMessageActions(message), + onReactions: () => MessageActions.showReactions(context, message), onQuickReact: () => MessageActions.react( message, widget.user.id, MessageActions.quickReaction), onReply: () => _startReply(message), diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index d4341da..911dc67 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -54,6 +54,67 @@ class MessageActions { static bool canSave(PrivateMessage message) => message.isMedia && message.localPath != null; + /// Reactions grouped by emoji, most used first, with the name of every + /// participant. [nameOf] resolves a user id, so the grouping stays free of + /// the user cache and can be tested on its own. + static List>> groupReactions( + Map reactions, String Function(String userId) nameOf) { + final grouped = >{}; + for (final entry in reactions.entries) { + grouped.putIfAbsent(entry.value, () => []).add(nameOf(entry.key)); + } + final rows = grouped.entries.toList() + ..sort((a, b) { + final byCount = b.value.length.compareTo(a.value.length); + return byCount != 0 ? byCount : a.key.compareTo(b.key); + }); + return rows; + } + + /// Who reacted with what. Names come from the local user cache, so this is a + /// cache read and never a server call. + static Future showReactions( + BuildContext context, PrivateMessage message) async { + final reactions = message.reactions ?? const {}; + if (reactions.isEmpty) { + return; + } + final me = Singleton().profile.user.id; + final names = {me: 'meText'.tr()}; + for (final id in reactions.keys) { + if (names.containsKey(id)) { + continue; + } + names[id] = (await CacheUtils.getUserById(id))?.username ?? '?'; + } + if (!context.mounted) { + return; + } + final rows = groupReactions(reactions, (id) => names[id] ?? '?'); + + await showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (ctx) => SafeArea( + child: ListView( + shrinkWrap: true, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Text('reactionsTitle'.tr(), + style: Theme.of(ctx).textTheme.titleMedium), + ), + for (final row in rows) + ListTile( + leading: Text(row.key, style: const TextStyle(fontSize: 22)), + title: Text(row.value.join(', ')), + ), + ], + ), + ), + ); + } + /// Bubble long-press sheet with all actions that apply to [message]. /// [conversationUserId] is the other side of the conversation. static Future showSheet( @@ -65,6 +126,9 @@ class MessageActions { builder: (ctx) { final canAddress = message.id?.isNotEmpty ?? false; // needs the archive id + // The emoji already picked by this user, marked so a second tap reads + // as "remove mine" instead of "pick this again". + final mine = message.reactions?[Singleton().profile.user.id]; return SafeArea( child: Wrap( children: [ @@ -77,6 +141,15 @@ class MessageActions { children: [ for (final emoji in reactionEmojis) IconButton( + style: emoji == mine + ? IconButton.styleFrom( + backgroundColor: Theme.of(ctx) + .colorScheme + .primaryContainer, + side: BorderSide( + color: Theme.of(ctx).colorScheme.primary), + ) + : null, onPressed: () { Navigator.pop(ctx); react(message, conversationUserId, emoji); diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 88a3f19..25a2d82 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -41,6 +41,9 @@ class ChatBubble extends StatefulWidget { /// Opens the action sheet (long-press). Falls back to [onSelect] when unset. final VoidCallback? onActions; + /// Opens the "who reacted" list when the reaction badge is tapped. + final VoidCallback? onReactions; + /// Quotes this message in the composer (swipe, and double-tap when no quick /// reaction is wired). final VoidCallback? onReply; @@ -60,6 +63,7 @@ class ChatBubble extends StatefulWidget { this.readAt, this.onSelect, this.onActions, + this.onReactions, this.onReply, this.onQuickReact, this.onTapQuote, @@ -89,6 +93,11 @@ class _ChatBubbleState extends State { isEmojiOnly(widget.message.message) && emojiCount(widget.message.message) <= 3; + /// Tapping the badge shows who reacted; a bubble without that callback keeps + /// offering its actions, which is what the badge used to do. + VoidCallback? get _onBadgeTap => + widget.onReactions ?? widget.onActions ?? widget.onSelect; + /// One badge for all reactions of the bubble: the emoji sit in a single pill /// with no gap between them, and a count only when the same emoji came from /// more than one participant. @@ -223,7 +232,7 @@ class _ChatBubbleState extends State { badge: widget.message.reactionEmojis.isEmpty ? null : GestureDetector( - onTap: () => (widget.onActions ?? widget.onSelect)?.call(), + onTap: _onBadgeTap, child: _reactionBadge(), ), conversationUserId: widget.user.id, @@ -424,24 +433,32 @@ class _ChatBubbleState extends State { // The reactions hang on the bubble's bottom edge as one badge, on the side // opposite the bubble's own side, the way a messenger pins them there. - final bubbleWithBadge = widget.message.reactionEmojis.isEmpty || - widget.message.isMedia - ? clippedBox - : Stack( - clipBehavior: Clip.none, - children: [ - clippedBox, - Positioned( - bottom: -12, - left: widget.message.isMe ? 8 : null, - right: widget.message.isMe ? null : 8, - child: GestureDetector( - onTap: () => (widget.onActions ?? widget.onSelect)?.call(), - child: _reactionBadge(), - ), - ), - ], - ); + final bubbleWithBadge = + widget.message.reactionEmojis.isEmpty || widget.message.isMedia + ? clippedBox + : Stack( + clipBehavior: Clip.none, + children: [ + // The room for the badge is part of the stack: a child that + // hangs past its parent's edge still paints, but it never + // receives the tap that opens the reaction list. + Padding( + // Same 12 px the badge used to hang by, now reserved + // inside the stack so the badge stays tappable. + padding: const EdgeInsets.only(bottom: 12), + child: clippedBox, + ), + Positioned( + bottom: 0, + left: widget.message.isMe ? 8 : null, + right: widget.message.isMe ? null : 8, + child: GestureDetector( + onTap: _onBadgeTap, + child: _reactionBadge(), + ), + ), + ], + ); return Padding( padding: EdgeInsets.only( @@ -520,14 +537,9 @@ class _ChatBubbleState extends State { : CrossAxisAlignment.start, children: [ Padding( - // Room for the reaction badge hanging under - // the bubble. - padding: EdgeInsets.only( - bottom: - widget.message.reactionEmojis.isEmpty || - widget.message.isMedia - ? 0 - : 14), + // The badge's room is inside the bubble's own + // stack, so this one only carries the swipe. + padding: EdgeInsets.zero, child: widget.onReply != null && !widget.selectionMode ? Dismissible( diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 2fd5de4..859c76a 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -201,9 +201,15 @@ class _MediaBubbleState extends State { return Stack( clipBehavior: Clip.none, children: [ - box, + // The room the badge hangs into is part of the stack: a child past + // the edge still paints, but it never receives the tap that opens the + // reaction list. + Padding( + padding: const EdgeInsets.only(bottom: 10), + child: box, + ), Positioned( - bottom: -10, + bottom: 0, left: widget.message.isMe ? 16 : null, right: widget.message.isMe ? null : 16, child: widget.badge!, @@ -259,33 +265,31 @@ class _MediaBubbleState extends State { : CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ - // The caption below would paint over the half of the badge that hangs - // past the media, so the media layer reserves room for it. - Padding( - padding: EdgeInsets.only( - bottom: hasCaption && widget.badge != null ? 12 : 0), - child: Stack( - // The badge hangs over the bottom edge, so the stack must not clip. - clipBehavior: Clip.none, - children: [ - ClipRRect( + // The badge hangs over the media's bottom edge, so its room sits inside + // the stack: outside it the badge would paint but never take a tap. The + // caption below starts under that room instead of over the badge. + Stack( + // The badge hangs over the bottom edge, so the stack must not clip. + clipBehavior: Clip.none, + children: [ + Padding( + padding: EdgeInsets.only(bottom: widget.badge == null ? 0 : 10), + child: ClipRRect( borderRadius: BorderRadius.circular(16), child: media, ), - // On the attachment itself: the corner of the media, not the - // level of the caption below it. - if (widget.badge != null) - Positioned( - // On the attachment's bottom edge: half of the pill hangs - // over the edge, the way a badge is pinned to it. Far enough - // from the corner that the rounded side does not cut it. - bottom: -10, - left: widget.message.isMe ? 16 : null, - right: widget.message.isMe ? null : 16, - child: widget.badge!, - ), - ], - ), + ), + // On the attachment itself: the corner of the media, not the level + // of the caption below it. Far enough from the corner that the + // rounded side does not cut it. + if (widget.badge != null) + Positioned( + bottom: 0, + left: widget.message.isMe ? 16 : null, + right: widget.message.isMe ? null : 16, + child: widget.badge!, + ), + ], ), if (hasCaption) Container( diff --git a/test/chat_bubble_test.dart b/test/chat_bubble_test.dart index ef09168..c0f4069 100644 --- a/test/chat_bubble_test.dart +++ b/test/chat_bubble_test.dart @@ -195,6 +195,8 @@ void main() { // Reactions are one badge hanging on the bubble's bottom edge: no gap // between the emoji and none between the badge and the bubble. final sentAt = DateTime(2026, 11, 19, 12); + var reactionsOpened = 0; + var actionsOpened = 0; await show(ChatBubble( null, PrivateMessage('1', 'reaguj', sentAt, sentAt, true) @@ -202,6 +204,8 @@ void main() { null, peer, accentColor: Colors.blue, + onActions: () => actionsOpened++, + onReactions: () => reactionsOpened++, )); expect(find.text('❤️'), findsOneWidget); expect(find.text('😂'), findsOneWidget); @@ -212,6 +216,11 @@ void main() { expect(heart.top, lessThan(body.bottom + 5)); // The two emoji are one badge, not two chips with a gap. expect(laugh.left - heart.right, lessThan(8)); + // Tapping the badge asks who reacted, not for the action sheet. + await tester.tap(find.text('❤️')); + await tester.pumpAndSettle(); + expect(reactionsOpened, 1); + expect(actionsOpened, 0); // Phone numbers and e-mails are underlined like a link. await show(ChatBubble( @@ -256,6 +265,7 @@ void main() { // A voice message shows the reaction it carries: the badge sits inside the // bubble's edge, so a quick react there is not a silent no-op. + var mediaReactions = 0; await show(ChatBubble( null, PrivateMessage('2', '', DateTime(2026), DateTime(2026), true, @@ -265,8 +275,14 @@ void main() { null, peer, accentColor: Colors.blue, + onReactions: () => mediaReactions++, )); expect(find.text('👍'), findsOneWidget); + // The badge on a media bubble is tappable too: it used to hang outside its + // parent's bounds, which paints but never hits. + await tester.tap(find.text('👍')); + await tester.pumpAndSettle(); + expect(mediaReactions, 1); // A jump lights the target bubble and drops the frame again afterwards. Future frame(ChatBubble bubble) async { diff --git a/test/reaction_list_test.dart b/test/reaction_list_test.dart new file mode 100644 index 0000000..ca0ee69 --- /dev/null +++ b/test/reaction_list_test.dart @@ -0,0 +1,22 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/message_actions.dart'; + +/// The reaction list groups by emoji, so one emoji with several participants is +/// one row with their names, and the busiest row is on top. +void main() { + test('reactions group by emoji, most used first', () { + final rows = MessageActions.groupReactions( + {'me': '❤️', 'a': '👍', 'b': '👍', 'c': '❤️', 'd': '👍'}, + (id) => + {'me': 'Me', 'a': 'Adam', 'b': 'Bea', 'c': 'Cyril', 'd': 'Dana'}[id]!, + ); + + expect(rows.map((row) => row.key), ['👍', '❤️']); + expect(rows.first.value, ['Adam', 'Bea', 'Dana']); + expect(rows.last.value, ['Me', 'Cyril']); + }); + + test('an empty map has no rows', () { + expect(MessageActions.groupReactions(const {}, (id) => id), isEmpty); + }); +} diff --git a/test/reaction_picker_test.dart b/test/reaction_picker_test.dart new file mode 100644 index 0000000..ff35669 --- /dev/null +++ b/test/reaction_picker_test.dart @@ -0,0 +1,48 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/models/profile.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/message_actions.dart'; +import 'package:whisper/utils/singleton.dart'; + +/// The reaction row marks the emoji this user already picked, so a second tap +/// reads as "take mine back". +void main() { + final peer = User('2', 'peer', '', false); + + setUpAll(() { + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + testWidgets('my own reaction is the only highlighted emoji', (tester) async { + final message = PrivateMessage( + '2', 'ahoj', DateTime(2026), DateTime(2026), true, + mediaId: null) + ..id = 'm-1' + ..reactions = {'1': '❤️', '2': '👍'}; + + await tester.pumpWidget(MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => MessageActions.showSheet(context, message, peer.id, + onSelect: () {}), + child: const Text('open'), + ), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + // Six emoji in the row; exactly the heart carries a background. + final marked = tester + .widgetList(find.byType(IconButton)) + .where((button) => button.style != null) + .toList(); + expect(marked, hasLength(1)); + expect((marked.single.icon as Text).data, '❤️'); + }); +} From f175ab88fb4035a64a691704697806210c8d27e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 18:38:16 +0100 Subject: [PATCH 118/181] fix(chat): give reactions back the tap the badge used to offer Tapping the badge opened the action sheet, which held the emoji row; the reaction list replaced it and left only a read-only view, so there was no obvious way to react any more. The list now starts with the same emoji row, shared with the action sheet, with the current pick marked. --- lib/pages/chat_page.dart | 3 +- lib/utils/message_actions.dart | 73 +++++++++++++++++++--------------- test/reaction_picker_test.dart | 9 +++++ test/reaction_store_test.dart | 47 ++++++++++++++++++++++ 4 files changed, 98 insertions(+), 34 deletions(-) create mode 100644 test/reaction_store_test.dart diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 0795aea..3abc987 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1414,7 +1414,8 @@ class _ChatPageState extends State { readAt: micros == _lastOwnMicros && _readReceipts ? _peerReadAt : null, onSelect: () => _toggleSelected(message), onActions: () => _openMessageActions(message), - onReactions: () => MessageActions.showReactions(context, message), + onReactions: () => + MessageActions.showReactions(context, message, widget.user.id), onQuickReact: () => MessageActions.react( message, widget.user.id, MessageActions.quickReaction), onReply: () => _startReply(message), diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 911dc67..4b4c383 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -54,6 +54,37 @@ class MessageActions { static bool canSave(PrivateMessage message) => message.isMedia && message.localPath != null; + /// The emoji row of a reaction sheet: one tap sets the caller's reaction, or + /// takes it back when it is the one already picked. + static Widget reactionRow( + BuildContext context, PrivateMessage message, String conversationUserId) { + final mine = message.reactions?[Singleton().profile.user.id]; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + for (final emoji in reactionEmojis) + IconButton( + style: emoji == mine + ? IconButton.styleFrom( + backgroundColor: + Theme.of(context).colorScheme.primaryContainer, + side: BorderSide( + color: Theme.of(context).colorScheme.primary), + ) + : null, + onPressed: () { + Navigator.pop(context); + react(message, conversationUserId, emoji); + }, + icon: Text(emoji, style: const TextStyle(fontSize: 22)), + ), + ], + ), + ); + } + /// Reactions grouped by emoji, most used first, with the name of every /// participant. [nameOf] resolves a user id, so the grouping stays free of /// the user cache and can be tested on its own. @@ -73,8 +104,8 @@ class MessageActions { /// Who reacted with what. Names come from the local user cache, so this is a /// cache read and never a server call. - static Future showReactions( - BuildContext context, PrivateMessage message) async { + static Future showReactions(BuildContext context, + PrivateMessage message, String conversationUserId) async { final reactions = message.reactions ?? const {}; if (reactions.isEmpty) { return; @@ -99,8 +130,13 @@ class MessageActions { child: ListView( shrinkWrap: true, children: [ + // The list is also where a reaction is given: tapping the badge + // used to open the action sheet, and a read-only list would take + // that away. + if (message.id?.isNotEmpty ?? false) + reactionRow(ctx, message, conversationUserId), Padding( - padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), child: Text('reactionsTitle'.tr(), style: Theme.of(ctx).textTheme.titleMedium), ), @@ -126,40 +162,11 @@ class MessageActions { builder: (ctx) { final canAddress = message.id?.isNotEmpty ?? false; // needs the archive id - // The emoji already picked by this user, marked so a second tap reads - // as "remove mine" instead of "pick this again". - final mine = message.reactions?[Singleton().profile.user.id]; return SafeArea( child: Wrap( children: [ // Reactions first: one tap, and the same emoji again removes it. - if (canAddress) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 8), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - for (final emoji in reactionEmojis) - IconButton( - style: emoji == mine - ? IconButton.styleFrom( - backgroundColor: Theme.of(ctx) - .colorScheme - .primaryContainer, - side: BorderSide( - color: Theme.of(ctx).colorScheme.primary), - ) - : null, - onPressed: () { - Navigator.pop(ctx); - react(message, conversationUserId, emoji); - }, - icon: - Text(emoji, style: const TextStyle(fontSize: 22)), - ), - ], - ), - ), + if (canAddress) reactionRow(ctx, message, conversationUserId), if (message.isMe && !message.isUndecryptable && canAddress) ListTile( leading: const Icon(editIcon), diff --git a/test/reaction_picker_test.dart b/test/reaction_picker_test.dart index ff35669..8568e24 100644 --- a/test/reaction_picker_test.dart +++ b/test/reaction_picker_test.dart @@ -44,5 +44,14 @@ void main() { .toList(); expect(marked, hasLength(1)); expect((marked.single.icon as Text).data, '❤️'); + // The row is the way a reaction is given: every chip has to be actionable, + // not decoration. (Tapping one would call the API, so only the wiring is + // checked here.) + expect( + tester + .widgetList(find.byType(IconButton)) + .every((button) => button.onPressed != null), + isTrue, + ); }); } diff --git a/test/reaction_store_test.dart b/test/reaction_store_test.dart new file mode 100644 index 0000000..3b06333 --- /dev/null +++ b/test/reaction_store_test.dart @@ -0,0 +1,47 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; + +/// Giving a reaction is a local write after the server call: if the key does +/// not match, the badge never appears even though the server took the request. +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_reaction_store'); + Hive.init(dir.path); + if (!Hive.isAdapterRegistered(3)) { + Hive.registerAdapter(PrivateMessageAdapter()); + } + }); + + setUp(() async { + for (final name in ['privateMessages', 'conversations', 'user']) { + await Hive.openBox(name); + await Hive.box(name).clear(); + } + }); + + tearDownAll(() async { + await Hive.deleteFromDisk(); + await dir.delete(recursive: true); + }); + + test('a reaction lands on the stored message', () async { + final sentAt = DateTime(2026, 11, 20, 12, 0, 0, 123, 456); + await CacheUtils.addPrivateMessages( + 'peer', [PrivateMessage('me', 'ahoj', sentAt, sentAt, true)]); + + await CacheUtils.setMessageReaction('peer', sentAt, 'me', '❤️'); + final stored = await CacheUtils.getPrivateMessages('peer'); + expect(stored.single.reactions, {'me': '❤️'}); + + // Same emoji again is the caller's toggle; null removes it. + await CacheUtils.setMessageReaction('peer', sentAt, 'me', null); + expect( + (await CacheUtils.getPrivateMessages('peer')).single.reactions, isNull); + }); +} From d8dd15da79a780732ae07570f2beb269cd04aed3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 20 Nov 2026 19:23:52 +0100 Subject: [PATCH 119/181] fix(home): let the chat list run under the folder chips The chips took layout space above the list, so an overscroll cut the top row against a band of background. They now float over the list, which pads itself by the measured strip height: rows scroll behind the chips the way they already do behind the translucent app bar. --- lib/pages/home_page.dart | 57 ++++++++++++++++++++++++++++++---------- 1 file changed, 43 insertions(+), 14 deletions(-) diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 17a199c..24c180c 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -56,6 +56,11 @@ class _HomePageState extends State /// Read cursors of the chats that publish receipts, for the seen ticks. Map _peerReadAts = {}; + /// The folder strip floats over the list, so its height is measured instead + /// of taking layout space; the list pads itself by the same amount. + final GlobalKey _filterKey = GlobalKey(); + double _filterHeight = 0; + /// Which rows the list shows; folders without extra storage. _ChatFilter _filter = _ChatFilter.all; bool _firstLoad = true; @@ -409,9 +414,14 @@ class _HomePageState extends State physics: const BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics(), ), - // The chips already clear the app bar; a scroll view's automatic - // MediaQuery padding would add a second gap above the first row. - padding: EdgeInsets.zero, + // The list runs behind the translucent app bar and under the floating + // folder strip, so it pads itself instead of using the automatic + // MediaQuery padding. + padding: EdgeInsets.only( + top: MediaQuery.viewPaddingOf(context).top + + kToolbarHeight + + _filterHeight, + ), itemCount: chats.length, itemBuilder: (context, index) { // Indexed access: `Map.entries.elementAt` is O(n) and made the list @@ -454,8 +464,26 @@ class _HomePageState extends State ); } + /// Measures the folder strip: it floats over the list, so the list needs its + /// height as padding rather than as layout space. + void _measureFilters() { + final render = _filterKey.currentContext?.findRenderObject(); + if (render is! RenderBox || !render.hasSize) { + return; + } + final height = render.size.height; + if ((height - _filterHeight).abs() > 0.5) { + setState(() => _filterHeight = height); + } + } + @override Widget build(BuildContext context) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _currentPageIndex == 0) { + _measureFilters(); + } + }); return Scaffold( extendBodyBehindAppBar: true, appBar: _currentPageIndex == 0 @@ -555,18 +583,11 @@ class _HomePageState extends State // Body body: [ // Messages - Column( + Stack( children: [ - // The body sits behind the translucent app bar; the chips do not - // scroll, so they start below it. - Padding( - padding: EdgeInsets.only( - top: MediaQuery.viewPaddingOf(context).top + kToolbarHeight, - ), - child: _filterChips(), - ), - // Messages and avatar list - Expanded( + // Messages and avatar list, behind the chips: rows scroll under + // them instead of being cut off by a strip of background. + Positioned.fill( child: _firstLoad ? Center( child: Transform.scale( @@ -578,6 +599,14 @@ class _HomePageState extends State ? Center(child: Text('noChatsInFilter'.tr())) : _getContent(_visibleChats), ), + // The body sits behind the translucent app bar; the chips do not + // scroll, so they start below it. + Positioned( + top: MediaQuery.viewPaddingOf(context).top + kToolbarHeight, + left: 0, + right: 0, + child: Container(key: _filterKey, child: _filterChips()), + ), ], ), // Admin panel From 009927e33fe2f66a512586c6da6b8b11b9982a97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sat, 21 Nov 2026 16:54:43 +0100 Subject: [PATCH 120/181] feat(chat): typing indicator and presence, both off by default Typing ramps one hint per peer every three seconds and the receiver clears it after five. Presence is announced on connect and on resume, withdrawn on pause, repeated once a minute so a killed app expires, and rendered as a chat-list dot with a status line in the header. With both switches off no frame is sent. --- assets/translations/cs.json | 6 ++ assets/translations/en.json | 6 ++ lib/pages/chat_page.dart | 42 ++++++++++++- lib/pages/home_page.dart | 15 ++++- lib/pages/settings_page.dart | 40 ++++++++++++ lib/utils/cache_utils.dart | 27 ++++++++ lib/utils/presence.dart | 107 ++++++++++++++++++++++++++++++++ lib/utils/utils.dart | 96 ++++++++++++++++++++++++++++ lib/widgets/chat_list_item.dart | 71 +++++++++++++++++---- pubspec.yaml | 4 +- test/presence_test.dart | 48 ++++++++++++++ 11 files changed, 446 insertions(+), 16 deletions(-) create mode 100644 lib/utils/presence.dart create mode 100644 test/presence_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index e59b8fd..dd52744 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -180,6 +180,12 @@ "messageUndecryptable": "Tuto zprávu se nepodařilo dešifrovat", "mediaExpired": "Příloha už není na serveru dostupná", "notificationPreview": "Zobrazovat text zpráv v notifikacích", + "typingIndicator": "Ukazovat, když píšu", + "presence": "Sdílet stav online a naposledy viděn", + "typing": "píše…", + "online": "online", + "lastSeenAt": "naposledy viděn {}", + "noConversation": "S tímto člověkem jste si ještě nenapsali", "newMessageBody": "Máte novou zprávu", "insecureServerUrl": "Server musí používat HTTPS", "internalError": "Na serveru se něco pokazilo", diff --git a/assets/translations/en.json b/assets/translations/en.json index 488928d..8042811 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -180,6 +180,12 @@ "messageUndecryptable": "This message could not be decrypted", "mediaExpired": "The attachment is no longer available on the server", "notificationPreview": "Show message text in notifications", + "typingIndicator": "Share when I am typing", + "presence": "Share online status and last seen", + "typing": "typing…", + "online": "online", + "lastSeenAt": "last seen {}", + "noConversation": "You have not exchanged a message with this person yet", "newMessageBody": "You have a new message", "insecureServerUrl": "The server must use HTTPS", "internalError": "Something went wrong on the server", diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 3abc987..41bd483 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -17,6 +17,7 @@ import '../utils/chat_sender.dart'; import '../utils/media_utils.dart'; import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; +import '../utils/presence.dart'; import '../utils/singleton.dart'; import '../utils/text_envelope.dart'; import '../utils/utils.dart' as utils; @@ -135,6 +136,7 @@ class _ChatPageState extends State { void initState() { super.initState(); MessageNotifier().addListener(_onMessagesChanged); + PresenceNotifier.instance.addListener(_onPresenceChanged); _scrollController.addListener(_onScroll); _metricsObserver = _KeyboardObserver(() { if (_atBottom) { @@ -147,6 +149,11 @@ class _ChatPageState extends State { getConceptMessage(); // Load per-chat theme _loadChatTheme(); + // A chat created since the last announcement must learn we are here; the + // call is a no-op when presence is off. + WidgetsBinding.instance.addPostFrameCallback((_) { + utils.Utils.announcePresence(); + }); } /// The read state must be captured before the chat marks it read, otherwise @@ -166,6 +173,13 @@ class _ChatPageState extends State { /// Keeps the newest message on screen when the keyboard opens. late final _KeyboardObserver _metricsObserver; + /// Typing and presence are ephemeral, so the header redraws on every change. + void _onPresenceChanged() { + if (mounted) { + setState(() {}); + } + } + /// Reload the conversation from the cache when messages or media state change. void _onMessagesChanged() { // Our own read notifies too (it marks messages read); do not re-enter. @@ -1134,6 +1148,13 @@ class _ChatPageState extends State { minLines: 1, maxLines: 5, textInputAction: TextInputAction.newline, + onChanged: (value) { + // The receiver clears the indicator on its own; this only throttles + // the frames and stays silent when the user opted out. + if (value.trim().isNotEmpty) { + utils.Utils.sendTypingHint(widget.user.id); + } + }, contentInsertionConfiguration: ContentInsertionConfiguration( allowedMimeTypes: const ['image/gif', 'image/webp'], onContentInserted: _onKeyboardContentInserted, @@ -1514,6 +1535,7 @@ class _ChatPageState extends State { @override void dispose() { MessageNotifier().removeListener(_onMessagesChanged); + PresenceNotifier.instance.removeListener(_onPresenceChanged); _scrollController.removeListener(_onScroll); WidgetsBinding.instance.removeObserver(_metricsObserver); _recordTimer?.cancel(); @@ -1644,7 +1666,25 @@ class _ChatPageState extends State { title: GestureDetector( onTap: _openChatInfo, behavior: HitTestBehavior.opaque, - child: Text(widget.user.username), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(widget.user.username), + // One line of live status; it disappears when nothing is known so + // the header keeps its plain height. + if (PresenceNotifier.instance.statusText(widget.user.id) + case final status?) + Text( + status, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.normal, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ], + ), ), // Action buttons actions: [ diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 24c180c..1b3e12d 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -40,7 +40,7 @@ class HomePage extends StatefulWidget { enum _ChatFilter { all, unread, pinned } class _HomePageState extends State - with SingleTickerProviderStateMixin { + with SingleTickerProviderStateMixin, WidgetsBindingObserver { final WebSocketManager _webSocketManager = WebSocketManager(); List _serverUsers = []; int _currentPageIndex = 0; @@ -78,6 +78,7 @@ class _HomePageState extends State @override void initState() { super.initState(); + WidgetsBinding.instance.addObserver(this); // Load all server users and invites if admin if (Singleton().profile.user.admin) { _getServerUsers(); @@ -133,8 +134,20 @@ class _HomePageState extends State /// and a foreground app has to show that itself. StreamSubscription? _fcmSubscription; + /// Presence is announced when the app comes back and withdrawn when it goes + /// away: the server keeps nothing, so a stale "online" would never clear. + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + Utils.announcePresence(); + } else if (state == AppLifecycleState.paused) { + Utils.withdrawPresence(); + } + } + @override void dispose() { + WidgetsBinding.instance.removeObserver(this); _fcmSubscription?.cancel(); _adminTabController.dispose(); MessageNotifier().removeListener(_onMessagesChanged); diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index f713ab6..9d095a7 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -29,6 +29,8 @@ class SettingsPage extends StatefulWidget { class _SettingsPageState extends State { bool _isBiometryEnabled = false; bool _notificationPreview = false; + bool _typingIndicator = false; + bool _presence = false; /// Guards the retention flow: the settings round-trip is slow, and without it /// a second tap stacks another dialog on top of the first. @@ -43,6 +45,8 @@ class _SettingsPageState extends State { Future _loadSettings() async { _isBiometryEnabled = await CacheUtils.isBiometryEnabled(); _notificationPreview = await CacheUtils.getNotificationPreview(); + _typingIndicator = await CacheUtils.isTypingIndicatorEnabled(); + _presence = await CacheUtils.isPresenceEnabled(); setState(() {}); } @@ -237,6 +241,42 @@ class _SettingsPageState extends State { }, ), ), + // Both live-metadata switches are off by default: with them off + // no frame is ever sent and the server learns nothing. + _settingsTile( + icon: Icons.edit_notifications, + label: 'typingIndicator'.tr(), + trailing: Switch( + value: _typingIndicator, + onChanged: (value) async { + setState(() { + _typingIndicator = !_typingIndicator; + }); + await CacheUtils.setTypingIndicatorEnabled( + _typingIndicator); + }, + ), + ), + _settingsTile( + icon: Icons.circle, + label: 'presence'.tr(), + trailing: Switch( + value: _presence, + onChanged: (value) async { + setState(() { + _presence = !_presence; + }); + await CacheUtils.setPresenceEnabled(_presence); + // Turning it on announces right away; turning it off tells + // the peers, so nobody keeps a stale "online". + if (_presence) { + await Utils.announcePresence(); + } else { + await Utils.withdrawPresence(); + } + }, + ), + ), const Divider(thickness: 1, indent: 10, endIndent: 10), _settingsTile( icon: Icons.fingerprint, diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 72278df..adcf4fd 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -28,6 +28,8 @@ class CacheUtils { static const _pendingSendsKey = 'pendingSends'; static const _settingsKey = 'settings'; static const _notificationPreviewKey = 'notificationPreview'; + static const _typingIndicatorKey = 'typingIndicator'; + static const _presenceKey = 'presence'; static const _biometry = 'biometry'; static const _playbackSpeed = 'playbackSpeed'; static const String _saltStorageKey = 'whisper_pbkdf2_salt'; @@ -359,6 +361,31 @@ class CacheUtils { await box.put(_notificationPreviewKey, value); } + /// Whether this device tells its peers that it is typing. Default off: with + /// it off no frame is ever sent, so the server has nothing to relay. + static Future isTypingIndicatorEnabled() async { + Box box = await Hive.openBox(_settingsKey); + return box.get(_typingIndicatorKey) as bool? ?? false; + } + + /// Turns the typing indicator on or off. + static Future setTypingIndicatorEnabled(bool value) async { + Box box = await Hive.openBox(_settingsKey); + await box.put(_typingIndicatorKey, value); + } + + /// Whether this device announces its presence and last seen. Default off. + static Future isPresenceEnabled() async { + Box box = await Hive.openBox(_settingsKey); + return box.get(_presenceKey) as bool? ?? false; + } + + /// Turns presence on or off. + static Future setPresenceEnabled(bool value) async { + Box box = await Hive.openBox(_settingsKey); + await box.put(_presenceKey, value); + } + /// Opens box with playback preferences static Future _openPlaybackBox() async { return Hive.openBox(_playbackSpeed); diff --git a/lib/utils/presence.dart b/lib/utils/presence.dart new file mode 100644 index 0000000..d4132ca --- /dev/null +++ b/lib/utils/presence.dart @@ -0,0 +1,107 @@ +import 'dart:async'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/foundation.dart'; + +/// Live, in-memory status of the other participants: who is online, when they +/// were last seen and whether they are typing. Nothing here is stored, and the +/// server keeps no presence either, so a restart or a disconnect empties it. +class PresenceNotifier extends ChangeNotifier { + PresenceNotifier._(); + + static final PresenceNotifier instance = PresenceNotifier._(); + + /// How long a typing hint stays visible after the last frame. The sender + /// repeats it while typing, so there is no "stopped typing" frame. + Duration typingTtl = const Duration(seconds: 5); + + /// How long an "online" stays believable without a new announcement. The + /// sender repeats it every minute, so an app that is killed instead of paused + /// drops off on its own. + Duration presenceTtl = const Duration(seconds: 95); + + final Map _lastSeen = {}; + final Map _presenceTimers = {}; + final Map _typingUntil = {}; + final Map _typingTimers = {}; + final Map _online = {}; + + /// True when [peerId] is known to be online; null when nothing is known. + bool? isOnline(String peerId) => _online[peerId]; + + /// When [peerId] was last seen, null while unknown. + DateTime? lastSeen(String peerId) => _lastSeen[peerId]; + + /// Whether [peerId] is typing right now. + bool isTyping(String peerId) { + final until = _typingUntil[peerId]; + return until != null && until.isAfter(DateTime.now()); + } + + /// Applies one presence frame. Going offline carries the instant the server + /// saw it, which is the only last seen this client ever gets. + void applyPresence(String peerId, + {required bool online, DateTime? lastSeenAt}) { + _online[peerId] = online; + _presenceTimers.remove(peerId)?.cancel(); + if (online) { + _lastSeen.remove(peerId); + _presenceTimers[peerId] = Timer(presenceTtl, () { + // Silence means the peer lost the network or was killed: nobody will + // announce it, so the badge expires instead of lying. + _online[peerId] = false; + _lastSeen[peerId] = DateTime.now(); + _presenceTimers.remove(peerId); + notifyListeners(); + }); + } else if (lastSeenAt != null) { + _lastSeen[peerId] = lastSeenAt.toLocal(); + } + notifyListeners(); + } + + /// Applies one typing hint and clears it again on its own after + /// [typingTtl]. + void applyTyping(String peerId) { + _typingUntil[peerId] = DateTime.now().add(typingTtl); + _typingTimers.remove(peerId)?.cancel(); + _typingTimers[peerId] = Timer(typingTtl, () { + _typingUntil.remove(peerId); + _typingTimers.remove(peerId); + notifyListeners(); + }); + notifyListeners(); + } + + /// Drops everything: without a connection nothing here is known anymore. + void clear() { + for (final timer in _typingTimers.values) { + timer.cancel(); + } + for (final timer in _presenceTimers.values) { + timer.cancel(); + } + _typingTimers.clear(); + _presenceTimers.clear(); + _typingUntil.clear(); + _online.clear(); + _lastSeen.clear(); + notifyListeners(); + } + + /// One line under a name: typing wins over online, online over last seen. + /// Null when nothing is known, so the caller keeps the plain name. + String? statusText(String peerId) { + if (isTyping(peerId)) { + return 'typing'.tr(); + } + if (_online[peerId] == true) { + return 'online'.tr(); + } + final seen = _lastSeen[peerId]; + if (seen != null) { + return 'lastSeenAt'.tr(args: [DateFormat.Hm().format(seen)]); + } + return null; + } +} diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 47cca81..f1f64a4 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:easy_localization/easy_localization.dart'; @@ -14,8 +15,10 @@ import 'package:whisper_openapi_client_dart/api.dart'; import 'package:basic_utils/basic_utils.dart' as bu; import 'package:whisper_websocket_client_dart/models/delivery_ack.dart'; import 'package:whisper_websocket_client_dart/models/message_event.dart'; +import 'package:whisper_websocket_client_dart/models/presence.dart'; import 'package:whisper_websocket_client_dart/models/read_receipt.dart'; import 'package:whisper_websocket_client_dart/models/synced.dart'; +import 'package:whisper_websocket_client_dart/models/typing.dart'; import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import 'package:whisper_websocket_client_dart/models/private_message.dart'; import 'package:whisper_websocket_client_dart/models/ws_response.dart'; @@ -25,6 +28,7 @@ import 'chat_sender.dart'; import 'crypto_utils.dart'; import 'media_utils.dart'; import 'message_notifier.dart'; +import 'presence.dart'; import 'singleton.dart'; import 'text_envelope.dart'; import '../models/private_message.dart' as pm; @@ -594,6 +598,24 @@ class Utils { MessageNotifier().notify(); break; + // The other participant is typing right now + case WsResponseType.typing: + PresenceNotifier.instance + .applyTyping((wsResponse.payload as TypingFrame).peerId); + break; + + // The other participant came online or went away + case WsResponseType.presence: + final presence = wsResponse.payload as PresenceFrame; + PresenceNotifier.instance.applyPresence(presence.peerId, + online: presence.online, lastSeenAt: presence.lastSeenAt); + break; + + // A live position is rendered by the location landing; until it exists + // there is nothing to show. + case WsResponseType.liveLocation: + break; + // Delete account case WsResponseType.deleteAccount: await CacheUtils.deleteCache(); @@ -829,6 +851,8 @@ class Utils { // Nothing is pushed on connect: ask for the archive delta above the last // seq stored here. A phone away for a week fetches only that week. await syncArchive(); + // Then tell the peers we are here, if presence is switched on. + await announcePresence(); final onConnected = Utils.onConnected; if (onConnected != null) { await onConnected(); @@ -836,6 +860,9 @@ class Utils { } catch (e) { // WebSocket connection failed Singleton().offlineMode = true; + // Nothing about the peers is known without a connection. + PresenceNotifier.instance.clear(); + _stopPresenceHeartbeat(); if (kDebugMode) { debugPrint('WebSocket connection attempt failed: $e'); @@ -854,6 +881,73 @@ class Utils { static bool get isOnline => Singleton().wsClient.isConnected && !Singleton().offlineMode; + /// Tells every peer of the chat list that this device is online, and keeps + /// saying it once a minute so a killed app drops off by itself. Silent when + /// presence is off: an off client sends no frame at all. + static Future announcePresence() async { + final sent = await _sendPresence(online: true); + _presenceHeartbeat?.cancel(); + _presenceHeartbeat = sent + ? Timer.periodic(const Duration(seconds: 60), (_) { + _sendPresence(online: true); + }) + : null; + } + + /// Withdraws presence before the app goes to the background, so a peer does + /// not keep a stale "online" with no way to learn better. + static Future withdrawPresence() async { + _stopPresenceHeartbeat(); + // No setting check: it is being turned off, and the peers must hear it. + await _sendPresence(online: false, force: true); + } + + static Timer? _presenceHeartbeat; + + static void _stopPresenceHeartbeat() { + _presenceHeartbeat?.cancel(); + _presenceHeartbeat = null; + } + + /// Returns whether a frame was actually sent. + static Future _sendPresence( + {required bool online, bool force = false}) async { + if (!force && !await CacheUtils.isPresenceEnabled()) { + return false; + } + if (!isOnline) { + return false; + } + final chats = await CacheUtils.getLatestPrivateMessages(); + final peerIds = chats.keys.map((user) => user.id).toList(); + if (peerIds.isEmpty) { + return false; + } + Singleton().wsClient.sendPresence(peerIds, online: online); + return true; + } + + /// At most one typing hint per peer every three seconds; the receiver drops + /// the indicator on its own after five. + static DateTime? _lastTypingSent; + static String? _lastTypingPeer; + + /// Tells [peerId] that this device is typing, if the user opted in. + static Future sendTypingHint(String peerId) async { + if (!await CacheUtils.isTypingIndicatorEnabled() || !isOnline) { + return; + } + final now = DateTime.now(); + if (_lastTypingPeer == peerId && + _lastTypingSent != null && + now.difference(_lastTypingSent!) < const Duration(seconds: 3)) { + return; + } + _lastTypingPeer = peerId; + _lastTypingSent = now; + Singleton().wsClient.sendTyping(peerId); + } + /// Force disconnect and set offline mode static void forceOfflineMode() { try { @@ -861,6 +955,8 @@ class Utils { } catch (_) { // Ignore disconnect errors } + PresenceNotifier.instance.clear(); + _stopPresenceHeartbeat(); Singleton().offlineMode = true; } } diff --git a/lib/widgets/chat_list_item.dart b/lib/widgets/chat_list_item.dart index 4442b3c..46964f8 100644 --- a/lib/widgets/chat_list_item.dart +++ b/lib/widgets/chat_list_item.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import '../models/private_message.dart'; import '../models/user.dart'; import '../utils/chat_date.dart'; +import '../utils/presence.dart'; class ChatListItem extends StatefulWidget { const ChatListItem(this.user, this.lastMessage, this.onPressed, @@ -27,6 +28,25 @@ class ChatListItem extends StatefulWidget { } class _ChatListItemState extends State { + @override + void initState() { + super.initState(); + PresenceNotifier.instance.addListener(_onPresenceChanged); + } + + @override + void dispose() { + PresenceNotifier.instance.removeListener(_onPresenceChanged); + super.dispose(); + } + + /// Presence and typing are ephemeral, so the row redraws on every change. + void _onPresenceChanged() { + if (mounted) { + setState(() {}); + } + } + /// Rounded counter, capped the way every messenger does it. Widget _unreadBadge() { final scheme = Theme.of(context).colorScheme; @@ -72,18 +92,42 @@ class _ChatListItemState extends State { shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), - leading: CircleAvatar( - radius: 22, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 20, - color: widget.user.avatarTextColor, + leading: Stack( + clipBehavior: Clip.none, + children: [ + CircleAvatar( + radius: 22, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 20, + color: widget.user.avatarTextColor, + ), + ), ), - ), + // The dot is the whole status badge: presence is opt-in, so an + // absent dot means "not sharing", not "offline". + if (PresenceNotifier.instance.isOnline(widget.user.id) == true) + Positioned( + right: 0, + bottom: 0, + child: Container( + width: 12, + height: 12, + decoration: BoxDecoration( + color: const Color(0xFF2E7D32), + shape: BoxShape.circle, + border: Border.all( + color: Theme.of(context).scaffoldBackgroundColor, + width: 2, + ), + ), + ), + ), + ], ), title: Row( children: [ @@ -118,7 +162,10 @@ class _ChatListItemState extends State { ), Expanded( child: Text( - getTitle(), + // A typing peer outranks the last message; it clears itself. + PresenceNotifier.instance.isTyping(widget.user.id) + ? 'typing'.tr() + : getTitle(), overflow: TextOverflow.ellipsis, style: unread ? const TextStyle(fontWeight: FontWeight.bold) : null, diff --git a/pubspec.yaml b/pubspec.yaml index b9cce94..640cd83 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,7 +3,7 @@ description: "Secure private self-hosted end-to-end encryption messaging app." publish_to: 'none' # Remove this line if you wish to publish to pub.dev # Bump before every release; the release workflow tags v and fails if # that tag already exists. The build number after + must only ever grow. -version: 0.3.0+5 +version: 0.4.0+6 environment: sdk: '>=3.4.3 <4.0.0' @@ -55,7 +55,7 @@ dependencies: whisper_websocket_client_dart: git: url: https://github.com/jsfraz/whisper_websocket_client_dart.git - ref: v0.3.0 + ref: v0.4.0 dev_dependencies: flutter_test: diff --git a/test/presence_test.dart b/test/presence_test.dart new file mode 100644 index 0000000..febac44 --- /dev/null +++ b/test/presence_test.dart @@ -0,0 +1,48 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/presence.dart'; + +void main() { + final presence = PresenceNotifier.instance; + + setUp(() { + presence.clear(); + presence.typingTtl = const Duration(milliseconds: 20); + presence.presenceTtl = const Duration(milliseconds: 30); + }); + + test('presence offline carries the last seen instant', () { + presence.applyPresence('peer', online: true); + expect(presence.isOnline('peer'), isTrue); + expect(presence.lastSeen('peer'), isNull); + + final sawAt = DateTime(2026, 11, 21, 12, 30); + presence.applyPresence('peer', online: false, lastSeenAt: sawAt); + expect(presence.isOnline('peer'), isFalse); + expect(presence.lastSeen('peer'), sawAt); + }); + + // A peer whose app was killed never announces offline, so silence has to + // expire instead of leaving a green dot forever. + test('an unrefreshed online expires into offline', () async { + presence.applyPresence('peer', online: true); + await Future.delayed(const Duration(milliseconds: 60)); + expect(presence.isOnline('peer'), isFalse); + expect(presence.lastSeen('peer'), isNotNull); + }); + + test('a typing hint clears itself', () async { + presence.applyTyping('peer'); + expect(presence.isTyping('peer'), isTrue); + await Future.delayed(const Duration(milliseconds: 60)); + expect(presence.isTyping('peer'), isFalse); + }); + + test('clear drops every known peer', () { + presence.applyPresence('peer', online: true); + presence.applyTyping('peer'); + presence.clear(); + expect(presence.isOnline('peer'), isNull); + expect(presence.isTyping('peer'), isFalse); + expect(presence.lastSeen('peer'), isNull); + }); +} From 55dea9623de72e18c4e03dbfe60ce4e9ea537470 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sat, 21 Nov 2026 17:02:44 +0100 Subject: [PATCH 121/181] feat(chat): disappearing messages, view-once media and screenshot warnings Disappearing messages are a timer both sides agree on: a control message carries the proposal, the acceptance or the refusal, the agreed timer rides on every outgoing message as ttlSeconds, and each device drops what expired. View-once is one photo or video, marked inside the ciphertext, opened once behind FLAG_SECURE and burnt for both sides afterwards; forwarding it is refused. Screenshots of ordinary messages are reported, not blocked. --- assets/translations/cs.json | 18 +++++- assets/translations/en.json | 18 +++++- lib/main.dart | 4 ++ lib/models/private_message.dart | 37 ++++++++++++ lib/models/private_message.g.dart | 16 ++++- lib/pages/chat_info_page.dart | 95 ++++++++++++++++++++++++++++++ lib/pages/chat_page.dart | 31 ++++++++-- lib/pages/home_page.dart | 24 +++++++- lib/pages/media_viewer_page.dart | 23 ++++++++ lib/utils/cache_utils.dart | 81 ++++++++++++++++++++++++++ lib/utils/chat_sender.dart | 63 +++++++++++++++++--- lib/utils/disappearing.dart | 18 ++++++ lib/utils/media_utils.dart | 18 ++++-- lib/utils/message_actions.dart | 37 +++++++++--- lib/utils/text_envelope.dart | 56 ++++++++++++++++++ lib/utils/utils.dart | 52 ++++++++++++++++- lib/widgets/chat_bubble.dart | 40 +++++++++++++ lib/widgets/media_bubble.dart | 76 ++++++++++++++++++++++++ pubspec.lock | 10 +++- pubspec.yaml | 1 + test/disappearing_test.dart | 97 +++++++++++++++++++++++++++++++ 21 files changed, 782 insertions(+), 33 deletions(-) create mode 100644 lib/utils/disappearing.dart create mode 100644 test/disappearing_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index dd52744..c70f100 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -262,5 +262,21 @@ "readReceipts": "Potvrzení o přečtení", "messageDelivered": "Doručeno", "messageRead": "Přečteno", - "attachmentCaptionUneditable": "Tetó příloze nelze upravit popisek" + "attachmentCaptionUneditable": "Tetó příloze nelze upravit popisek", + "disappearingSettings": "Mizející zprávy", + "disappearingHint": "Musí souhlasit obě strany: vaše volba je návrh, dokud ji protistrana nepřijme.", + "disappearingAccept": "Přijmout {}", + "disappearingDecline": "Odmítnout", + "disappearingProposalShort": "návrh {}", + "disappearingOff": "vypnuto", + "disappearingChanged": "Mizející zprávy se změnily", + "disappearingProposalPill": "Navrženy mizející zprávy: {}", + "disappearingEnabledPill": "Mizející zprávy: {}", + "disappearingDeclinedPill": "Návrh mizejících zpráv odmítnut", + "attachViewOnce": "Zobrazit jednou", + "viewOnceOneFile": "Jednorázově lze poslat jen jednu přílohu", + "viewOnceOpen": "Klepnutím zobrazit jednou", + "viewOnceLoad": "Klepnutím stáhnout", + "viewOnceMedia": "Jednorázová příloha", + "screenshotDetected": "Screenshot zaznamenán" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 8042811..dd35896 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -262,5 +262,21 @@ "readReceipts": "Read receipts", "messageDelivered": "Delivered", "messageRead": "Read", - "attachmentCaptionUneditable": "This attachment's caption can't be edited" + "attachmentCaptionUneditable": "This attachment's caption can't be edited", + "disappearingSettings": "Disappearing messages", + "disappearingHint": "Both sides have to agree: your choice is a proposal until the other side accepts it.", + "disappearingAccept": "Accept {}", + "disappearingDecline": "Decline", + "disappearingProposalShort": "proposal {}", + "disappearingOff": "off", + "disappearingChanged": "Disappearing messages changed", + "disappearingProposalPill": "Disappearing messages proposed: {}", + "disappearingEnabledPill": "Disappearing messages: {}", + "disappearingDeclinedPill": "Disappearing messages proposal declined", + "attachViewOnce": "View once", + "viewOnceOneFile": "Only one attachment can be view-once", + "viewOnceOpen": "Tap to view once", + "viewOnceLoad": "Tap to download", + "viewOnceMedia": "View-once attachment", + "screenshotDetected": "Screenshot detected" } diff --git a/lib/main.dart b/lib/main.dart index 643a0b9..d205ed9 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -80,6 +80,10 @@ void main() async { // restart. await MediaUtils.clearTempFiles(); + // A disappearing message that expired while the app was closed is gone + // before the first frame: it must not flash up on start. + await CacheUtils.purgeExpiredMessages(); + // Default theme Singleton().appTheme = await CacheUtils.getTheme() ?? AppTheme.fromValues(ThemeMode.system, Colors.blue); diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index 80c3a4d..6633827 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -211,6 +211,24 @@ class PrivateMessage extends HiveObject { @HiveField(23) String? mediaRefJson; + /// When the message must be gone from this device: the disappearing-message + /// deadline, or the view-once life. Null means the retention applies. + @HiveField(24) + DateTime? expiresAt; + + /// Set on a control message that carries no text: "propose", "accept" or + /// "decline" of a chat setting. Null on ordinary messages. + @HiveField(25) + String? systemState; + + /// Seconds carried by a control message. + @HiveField(26, defaultValue: 0) + int systemSeconds; + + /// A single-view attachment: opened once, then gone for both sides. + @HiveField(27, defaultValue: false) + bool viewOnce; + /// Cache for [album], keyed by the [albumJson] it was decoded from. String? _albumCacheJson; List? _albumCache; @@ -239,8 +257,21 @@ class PrivateMessage extends HiveObject { this.reactions, this.forwarded = false, this.mediaRefJson, + this.expiresAt, + this.systemState, + this.systemSeconds = 0, + this.viewOnce = false, }); + /// A control message: it carries a chat setting, not text to read. + bool get isSystem => systemState != null; + + /// True once the disappearing deadline of this message has passed. + bool get isExpired { + final deadline = expiresAt; + return deadline != null && deadline.isBefore(DateTime.now()); + } + /// References needed to re-encrypt this message with a new caption, null for /// text messages and when their key was never kept. List? get mediaReferences { @@ -395,12 +426,18 @@ class PrivateMessage extends HiveObject { if (isUndecryptable) { return 'messageUndecryptable'.tr(); } + if (isSystem) { + return 'disappearingChanged'.tr(); + } if (!isMedia || message.isNotEmpty) { return message; } if (isAlbum) { return '${'mediaAlbum'.tr()} (${album.length})'; } + if (viewOnce) { + return 'viewOnceMedia'.tr(); + } switch (mediaType) { case MediaType.image: return 'mediaPhoto'.tr(); diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index b208ed2..db672e0 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -40,13 +40,17 @@ class PrivateMessageAdapter extends TypeAdapter { reactions: (fields[21] as Map?)?.cast(), forwarded: fields[22] == null ? false : fields[22] as bool, mediaRefJson: fields[23] as String?, + expiresAt: fields[24] as DateTime?, + systemState: fields[25] as String?, + systemSeconds: fields[26] == null ? 0 : fields[26] as int, + viewOnce: fields[27] == null ? false : fields[27] as bool, )..id = fields[19] as String?; } @override void write(BinaryWriter writer, PrivateMessage obj) { writer - ..writeByte(24) + ..writeByte(28) ..writeByte(0) ..write(obj.senderId) ..writeByte(1) @@ -94,7 +98,15 @@ class PrivateMessageAdapter extends TypeAdapter { ..writeByte(22) ..write(obj.forwarded) ..writeByte(23) - ..write(obj.mediaRefJson); + ..write(obj.mediaRefJson) + ..writeByte(24) + ..write(obj.expiresAt) + ..writeByte(25) + ..write(obj.systemState) + ..writeByte(26) + ..write(obj.systemSeconds) + ..writeByte(27) + ..write(obj.viewOnce); } @override diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 9c3da8c..06d8904 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -6,6 +6,8 @@ import '../utils/nav_transitions.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../utils/cache_utils.dart'; +import '../utils/chat_sender.dart'; +import '../utils/disappearing.dart'; import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; import '../utils/dialog_utils.dart'; @@ -32,6 +34,12 @@ class _ChatInfoPageState extends State { Map _pins = {}; bool _readReceipts = false; + /// Agreed disappearing-message timer of this chat, seconds; 0 when off. + int _disappearing = 0; + + /// Timer the peer proposed and this device has not answered yet. + int? _disappearingProposal; + /// A toggle in flight: the switch stays disabled until the server call and /// the cache write are done, so it cannot be flipped back and forth. bool _readReceiptsBusy = false; @@ -43,6 +51,79 @@ class _ChatInfoPageState extends State { _loadMedia(); _loadPins(); _loadReadReceipts(); + _loadDisappearing(); + } + + Future _loadDisappearing() async { + final agreed = await CacheUtils.getDisappearingSeconds(widget.userId); + final proposal = await CacheUtils.getDisappearingProposal(widget.userId); + if (mounted) { + setState(() { + _disappearing = agreed; + _disappearingProposal = proposal; + }); + } + } + + /// A timer is agreed by both sides: this device only ever proposes, and the + /// peer's proposal is what the accept row answers. + Future _showDisappearingDialog() async { + final proposal = _disappearingProposal; + final chosen = await showDialog( + context: context, + builder: (ctx) => SimpleDialog( + title: Text('disappearingSettings'.tr()), + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(24, 0, 24, 8), + child: Text('disappearingHint'.tr()), + ), + if (proposal != null) + ListTile( + leading: const Icon(Icons.check), + title: Text( + 'disappearingAccept'.tr(args: [disappearingLabel(proposal)])), + onTap: () => Navigator.pop(ctx, proposal), + ), + if (proposal != null) + ListTile( + leading: const Icon(Icons.close), + title: Text('disappearingDecline'.tr()), + onTap: () => Navigator.pop(ctx, -1), + ), + const Divider(), + for (final option in disappearingOptions) + ListTile( + title: Text(disappearingLabel(option)), + trailing: option == _disappearing + ? const Icon(Icons.check) + : (option == proposal ? const Icon(Icons.schedule) : null), + onTap: () => Navigator.pop(ctx, option), + ), + ], + ), + ); + if (chosen == null) { + return; + } + final user = await CacheUtils.getUserById(widget.userId); + if (user == null) { + return; + } + if (chosen == -1) { + await CacheUtils.setDisappearingProposal(widget.userId, null); + await ChatSender.sendSystem(user, 'decline', 0); + } else if (proposal != null && chosen == proposal) { + await CacheUtils.setDisappearingSeconds(widget.userId, chosen); + await CacheUtils.setDisappearingProposal(widget.userId, null); + await ChatSender.sendSystem(user, 'accept', chosen); + } else { + // Nothing changes until the peer accepts, so a proposal is never a new + // local timer on its own. + await ChatSender.sendSystem(user, 'propose', chosen); + } + await _loadDisappearing(); + MessageNotifier().notify(); } Future _loadReadReceipts() async { @@ -293,6 +374,20 @@ class _ChatInfoPageState extends State { child: Text('${_pins.length}'), ), ), + // Disappearing messages: a timer both sides agree on. + SettingsTile( + icon: Icons.timer_outlined, + label: 'disappearingSettings'.tr(), + onPressed: _showDisappearingDialog, + extra: Padding( + padding: const EdgeInsets.only(left: 10), + child: Text(_disappearingProposal != null + ? 'disappearingProposalShort'.tr(args: [ + disappearingLabel(_disappearingProposal!) + ]) + : disappearingLabel(_disappearing)), + ), + ), // Chat theme SettingsTile( icon: Icons.palette, diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 41bd483..2f55ed8 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -821,7 +821,7 @@ class _ChatPageState extends State { /// Send a media attachment: probe what the type needs, then the shared send /// path (encrypt, upload, persist a bubble, send). Future _sendMedia(MediaType type, File file, - {String caption = '', int? durationMs}) async { + {String caption = '', int? durationMs, bool viewOnce = false}) async { setState(() { _isSending = true; }); @@ -833,7 +833,8 @@ class _ChatPageState extends State { width: probe.width, height: probe.height, durationMs: probe.durationMs, - fileName: MediaUtils.baseName(file.path)); + fileName: MediaUtils.baseName(file.path), + viewOnce: viewOnce); _afterSend(sent, caption); } catch (e) { await Fluttertoast.showToast( @@ -912,13 +913,21 @@ class _ChatPageState extends State { /// [forcedType] fixes the type for camera picks; [filesOnly] rejects photos /// and videos (the "File" entry must stay a document picker). Future _pickAndSend(Future> Function() picker, - {MediaType? forcedType, bool filesOnly = false}) async { + {MediaType? forcedType, + bool filesOnly = false, + bool viewOnce = false}) async { try { final picked = await picker(); if (picked.isEmpty) { return; } var files = picked; + if (viewOnce && files.length > 1) { + // One view, one attachment: a single-view album cannot be honest. + files = [files.first]; + await Fluttertoast.showToast( + msg: 'viewOnceOneFile'.tr(), backgroundColor: Colors.orange); + } if (filesOnly) { files = picked.where((file) => !MediaUtils.isVisualMedia(file)).toList(); @@ -948,7 +957,8 @@ class _ChatPageState extends State { } if (files.length == 1) { final type = forcedType ?? MediaUtils.detectType(files.first.path); - await _sendMedia(type, files.first, caption: caption); + await _sendMedia(type, files.first, + caption: caption, viewOnce: viewOnce); } else { await _sendAlbum(files, caption: caption); } @@ -1030,6 +1040,19 @@ class _ChatPageState extends State { _pickAndSend(MediaUtils.pickMultipleFiles, filesOnly: true); }, ), + ListTile( + leading: const Icon(Icons.visibility_off), + title: Text('attachViewOnce'.tr()), + onTap: () { + Navigator.pop(ctx); + // One photo or video, gone for both sides after the first + // open; the picker stays the same. + _pickAndSend(() async { + final file = await MediaUtils.pickMediaFromGallery(); + return file == null ? [] : [file]; + }, viewOnce: true); + }, + ), ], ), ); diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 1b3e12d..e651791 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -6,6 +6,7 @@ import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; +import 'package:screen_protector/screen_protector.dart'; import '../utils/nav_transitions.dart'; import 'package:sprintf/sprintf.dart'; import '../pages/chat_page.dart'; @@ -89,6 +90,9 @@ class _HomePageState extends State // Refresh the list when a message arrives or its state changes; the build // method must not create a new future on every rebuild. MessageNotifier().addListener(_onMessagesChanged); + // A screenshot outside the view-once viewer is reported, not blocked: the + // app cannot prevent it, and pretending otherwise would be a lie. + ScreenProtector.addListener(_onScreenshot, _onScreenRecord); // A pending FCM id is retried when the socket comes up instead of polling. Utils.onConnected = _sendPendingFid; // Open the chat a notification tap pointed at (after unlocking) @@ -134,12 +138,29 @@ class _HomePageState extends State /// and a foreground app has to show that itself. StreamSubscription? _fcmSubscription; + /// A screenshot of an ordinary message cannot be stopped, only noticed. + void _onScreenshot() { + Fluttertoast.showToast( + msg: 'screenshotDetected'.tr(), backgroundColor: Colors.orange); + } + + void _onScreenRecord(bool recording) { + if (!recording) { + return; + } + Fluttertoast.showToast( + msg: 'screenshotDetected'.tr(), backgroundColor: Colors.orange); + } + /// Presence is announced when the app comes back and withdrawn when it goes - /// away: the server keeps nothing, so a stale "online" would never clear. + /// away: the server keeps nothing, so a stale "online" would never clear. @override @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.resumed) { Utils.announcePresence(); + // A message whose deadline passed while the app was in the background is + // gone before it paints again. + CacheUtils.purgeExpiredMessages().then((_) => MessageNotifier().notify()); } else if (state == AppLifecycleState.paused) { Utils.withdrawPresence(); } @@ -148,6 +169,7 @@ class _HomePageState extends State @override void dispose() { WidgetsBinding.instance.removeObserver(this); + ScreenProtector.removeListener(); _fcmSubscription?.cancel(); _adminTabController.dispose(); MessageNotifier().removeListener(_onMessagesChanged); diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index f728d90..4e21cf7 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -4,6 +4,7 @@ import 'dart:typed_data'; import 'package:chewie/chewie.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:screen_protector/screen_protector.dart'; import 'package:video_player/video_player.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; @@ -26,10 +27,14 @@ class MediaViewerPage extends StatefulWidget { /// Index of the tapped attachment when [message] is an album. final int albumIndex; + /// A view-once attachment: one page, screenshot-blocked, burnt on close. + final bool viewOnce; + const MediaViewerPage({ required this.message, required this.conversationUserId, this.albumIndex = 0, + this.viewOnce = false, super.key, }); @@ -47,12 +52,27 @@ class _MediaViewerPageState extends State { @override void initState() { super.initState(); + if (widget.viewOnce) { + // The one allowed view may not be screenshotted or recorded. Android + // enforces it with FLAG_SECURE; iOS has no block, only a best-effort + // notification, which is why the app says so on the info screen. + ScreenProtector.preventScreenshotOn(); + } _loadMedia(); } /// The viewer pages through the same attachments the gallery shows, starting /// at the one that was tapped. Future _loadMedia() async { + if (widget.viewOnce) { + // One attachment, one page: swiping to the next would be a second view. + setState(() { + _media = [widget.message]; + _index = 0; + _controller = PageController(initialPage: 0); + }); + return; + } if (widget.message.isAlbum) { // Album attachments are pages of their own; keep the album order so the // tapped tile maps to the same index. @@ -93,6 +113,9 @@ class _MediaViewerPageState extends State { @override void dispose() { + if (widget.viewOnce) { + ScreenProtector.preventScreenshotOff(); + } _controller?.dispose(); super.dispose(); } diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index adcf4fd..57c7510 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -552,6 +552,35 @@ class CacheUtils { await box.delete(key); } + /// Deletes every stored message whose disappearing deadline passed, together + /// with its media files. [userId] limits the sweep to one chat. + static Future purgeExpiredMessages({String? userId}) async { + final box = await _openPrivateMessagesBox(); + final now = DateTime.now(); + final expired = {}; + for (final key in box.keys) { + if (key is! String) { + continue; + } + if (userId != null && !key.startsWith('$userId|')) { + continue; + } + final value = box.get(key); + if (value is PrivateMessage && + value.expiresAt != null && + value.expiresAt!.isBefore(now)) { + expired[key] = value; + } + } + for (final entry in expired.entries) { + await box.delete(entry.key); + for (final path in entry.value.localPaths) { + await MediaUtils.deleteLocalFile(path); + } + } + return expired.length; + } + /// Stores the newest text of an edited message, or drops the edit when the /// message is not on this device. static Future markMessageEdited( @@ -961,6 +990,58 @@ class CacheUtils { } } + /// Active disappearing-message timer of one chat in seconds, 0 when off. + /// Both participants store the same value after they agree on it. + static Future getDisappearingSeconds(String userId) async { + final box = await _openConversationsBox(); + final value = _metaOf(box, userId)['disappearing']; + return value is int ? value : 0; + } + + /// Stores the agreed disappearing-message timer of one chat. 0 turns it off. + static Future setDisappearingSeconds(String userId, int seconds) { + return _serializedMeta(() async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + if (seconds > 0) { + meta['disappearing'] = seconds; + } else { + meta.remove('disappearing'); + } + await _putMeta(box, userId, meta); + }); + } + + /// Timer the other participant proposed and this device has not answered yet, + /// null when there is none. + static Future getDisappearingProposal(String userId) async { + final box = await _openConversationsBox(); + final value = _metaOf(box, userId)['disappearingProposal']; + return value is int ? value : null; + } + + /// Stores or clears the proposal of the other participant. + static Future setDisappearingProposal(String userId, int? seconds) { + return _serializedMeta(() async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + if (seconds == null) { + meta.remove('disappearingProposal'); + } else { + meta['disappearingProposal'] = seconds; + } + await _putMeta(box, userId, meta); + }); + } + + static Future _putMeta(Box box, String userId, Map meta) async { + if (meta.isEmpty) { + await box.delete(userId); + } else { + await box.put(userId, meta); + } + } + /// Instant up to which the other participant has read this chat, null when /// they never published one. static Future getPeerReadAt(String userId) async { diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index 494f5a4..6ed9705 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -62,16 +62,19 @@ class ChatSender { static Future sendText(User recipient, String text, {ReplyRef? reply, bool forwarded = false}) async { final now = DateTime.now(); + final ttl = await _ttlFor(recipient); final message = PrivateMessage( Singleton().profile.user.id, text, now, now, true, - sendStatus: SendStatus.sending, forwarded: forwarded) + sendStatus: SendStatus.sending, + forwarded: forwarded, + expiresAt: ttl > 0 ? now.add(Duration(seconds: ttl)) : null) ..setReplyTo(reply); try { await _persist(recipient, [message]); if (!await _ensureConnected()) { return await _fail(recipient.id, message); } - await _sendText(recipient, message); + await _sendText(recipient, message, ttl: ttl); // No ack yet: the message stays `sending` until the server confirms. return true; } catch (e) { @@ -88,7 +91,8 @@ class ChatSender { int? height, int? durationMs, String? fileName, - bool forwarded = false}) async { + bool forwarded = false, + bool viewOnce = false}) async { if (!MediaUtils.uploadFits(bytes.length)) { _toastTooLarge(); return false; @@ -97,6 +101,9 @@ class ChatSender { // the content while the upload is still running. final localPath = await MediaUtils.encryptAtRest(bytes); final now = DateTime.now(); + // A view-once attachment lives a day whatever the chat timer says; anything + // else follows the agreed timer. + final ttl = viewOnce ? viewOnceTtlSeconds : await _ttlFor(recipient); final message = PrivateMessage( Singleton().profile.user.id, caption, @@ -113,6 +120,8 @@ class ChatSender { fileName: fileName, sendStatus: SendStatus.sending, forwarded: forwarded, + viewOnce: viewOnce, + expiresAt: ttl > 0 ? now.add(Duration(seconds: ttl)) : null, ); try { await _persist(recipient, [message]); @@ -132,8 +141,8 @@ class ChatSender { _outgoingReferences[CacheUtils.messageKey(recipient.id, message.sentAt)] = [reference]; final envelope = MediaUtils.buildMediaEnvelope(reference, caption, - forwarded: forwarded); - await _sendEnvelope(recipient, envelope, message.sentAt); + forwarded: forwarded, viewOnce: viewOnce); + await _sendEnvelope(recipient, envelope, message.sentAt, ttlSeconds: ttl); await CacheUtils.updateStoredMessage(recipient.id, message, (stored) { stored.mediaId = reference.mediaId; // Keep the reference (with its transport key) so the caption can be @@ -428,7 +437,8 @@ class ChatSender { /// Encrypt [message] for [recipient] and hand it to the WebSocket. The /// original timestamp is kept so a resend maps onto the same server entry. - static Future _sendText(User recipient, PrivateMessage message) async { + static Future _sendText(User recipient, PrivateMessage message, + {int ttl = 0}) async { // A reply needs the quote next to the body; everything else stays raw text // so an older client can still read it. final reply = message.replyTo; @@ -444,7 +454,8 @@ class ChatSender { data['encryptedKey']!, data['nonce']!, data['mac']!, - sentAt: message.sentAt))); + sentAt: message.sentAt, + ttlSeconds: ttl > 0 ? ttl : null))); } /// Upload one already transport-encrypted attachment and build its reference. @@ -484,7 +495,8 @@ class ChatSender { /// E2E-encrypt [envelope] for [recipient] and hand it to the WebSocket. static Future _sendEnvelope( - User recipient, Uint8List envelope, DateTime sentAt) async { + User recipient, Uint8List envelope, DateTime sentAt, + {int ttlSeconds = 0}) async { final data = await CryptoUtils.encryptMessageData( envelope, bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); Singleton().wsClient.sendMessage(WsMessage.privateMessage(NewPrivateMessage( @@ -493,7 +505,40 @@ class ChatSender { data['encryptedKey']!, data['nonce']!, data['mac']!, - sentAt: sentAt))); + sentAt: sentAt, + ttlSeconds: ttlSeconds > 0 ? ttlSeconds : null))); + } + + /// Life of a view-once attachment: one day, whether or not the chat has a + /// disappearing timer. + static const int viewOnceTtlSeconds = 86400; + + /// The agreed disappearing timer of one chat in seconds, 0 when off. + static Future _ttlFor(User recipient) => + CacheUtils.getDisappearingSeconds(recipient.id); + + /// Sends one step of the disappearing-message agreement. The message is + /// archived and encrypted like any other, so the other device and a device + /// that syncs later all see the same state. + static Future sendSystem( + User recipient, String state, int seconds) async { + final now = DateTime.now(); + final message = PrivateMessage( + Singleton().profile.user.id, '', now, now, true, + sendStatus: SendStatus.sending, + systemState: state, + systemSeconds: seconds); + try { + await _persist(recipient, [message]); + if (!await _ensureConnected()) { + return await _fail(recipient.id, message); + } + await _sendEnvelope(recipient, buildSystemEnvelope(state, seconds), now); + return true; + } catch (e) { + Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); + return await _fail(recipient.id, message); + } } /// Connect the WebSocket if needed; toasts and reports false when offline. diff --git a/lib/utils/disappearing.dart b/lib/utils/disappearing.dart new file mode 100644 index 0000000..f8dba5c --- /dev/null +++ b/lib/utils/disappearing.dart @@ -0,0 +1,18 @@ +import 'package:easy_localization/easy_localization.dart'; + +/// Timers a chat can agree on: an hour, a day, a week. [0] turns the timer off. +const List disappearingOptions = [3600, 86400, 604800, 0]; + +/// Compact label of a timer in seconds, e.g. "1 h", "24 h", "7 d". +String disappearingLabel(int seconds) { + if (seconds <= 0) { + return 'disappearingOff'.tr(); + } + if (seconds % 86400 == 0) { + return '${seconds ~/ 86400} d'; + } + if (seconds % 3600 == 0) { + return '${seconds ~/ 3600} h'; + } + return '${seconds ~/ 60} min'; +} diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 60de5a9..7f71a5a 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -6,7 +6,8 @@ import 'dart:ui' as ui; import 'package:cryptography/cryptography.dart' as cryptography; import 'package:file_picker/file_picker.dart'; import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart' show BuildContext, IconData, Icons, MediaQuery; +import 'package:flutter/material.dart' + show BuildContext, IconData, Icons, MediaQuery; import 'package:image_picker/image_picker.dart'; import 'package:mime/mime.dart'; import 'package:path_provider/path_provider.dart'; @@ -545,15 +546,18 @@ class MediaUtils { // --------------------------------------------------------------------------- /// Build the plaintext (pre-encryption) bytes for a media message: a JSON - /// envelope wrapping the [reference] and optional [caption]. + /// envelope wrapping the [reference] and optional [caption]. [viewOnce] marks + /// a single-view attachment; the flag rides inside the ciphertext, so only + /// the two participants know. static Uint8List buildMediaEnvelope(MediaReference reference, String caption, - {bool forwarded = false}) { + {bool forwarded = false, bool viewOnce = false}) { final map = { 'whisperMsg': envelopeVersion, 'kind': 'media', 'caption': caption, 'media': reference.toJson(), if (forwarded) 'forwarded': true, + if (viewOnce) 'viewOnce': true, }; return Uint8List.fromList(utf8.encode(jsonEncode(map))); } @@ -581,12 +585,13 @@ class MediaUtils { if (decoded is Map && decoded['kind'] == 'media') { final caption = (decoded['caption'] as String?) ?? ''; final forwarded = decoded['forwarded'] == true; + final viewOnce = decoded['viewOnce'] == true; if (decoded['whisperMsg'] == envelopeVersion && decoded['media'] is Map) { final reference = MediaReference.fromJson( Map.from(decoded['media'] as Map)); return ParsedMediaEnvelope([reference], caption, - forwarded: forwarded); + forwarded: forwarded, viewOnce: viewOnce); } if (decoded['whisperMsg'] == envelopeVersionAlbum && decoded['media'] is List) { @@ -672,8 +677,11 @@ class ParsedMediaEnvelope { /// The sender passed on somebody else's attachment instead of writing it. final bool forwarded; + /// A single-view attachment: one open, then gone for both sides. + final bool viewOnce; + const ParsedMediaEnvelope(this.references, this.caption, - {this.forwarded = false}); + {this.forwarded = false, this.viewOnce = false}); } /// Thin wrapper around the [AudioRecorder] for hold-to-record voice messages. diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 4b4c383..0c7024d 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -54,6 +54,26 @@ class MessageActions { static bool canSave(PrivateMessage message) => message.isMedia && message.localPath != null; + /// A view-once attachment may not be passed on: it is one open, for one + /// conversation. + static bool canForward(PrivateMessage message) => !message.viewOnce; + + /// Burns a view-once attachment after its single open: the local copy goes, + /// and so does the server row, so the other side loses it too. + static Future consumeViewOnce( + String conversationUserId, PrivateMessage message) async { + final id = message.id; + if (id != null && id.isNotEmpty) { + try { + await Utils.callApi(() => Singleton().messagesApi.deleteMessage(id)); + } catch (_) { + // The server sweep drops the row at its ttl either way. + } + } + await CacheUtils.deletePrivateMessage(conversationUserId, message); + MessageNotifier().notify(); + } + /// The emoji row of a reaction sheet: one tap sets the caller's reaction, or /// takes it back when it is the one already picked. static Widget reactionRow( @@ -212,14 +232,15 @@ class MessageActions { copy(message); }, ), - ListTile( - leading: const Icon(forwardIcon), - title: Text('forwardMessage'.tr()), - onTap: () { - Navigator.pop(ctx); - forward(context, [message]); - }, - ), + if (canForward(message)) + ListTile( + leading: const Icon(forwardIcon), + title: Text('forwardMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + forward(context, [message]); + }, + ), if (canSave(message)) ListTile( leading: const Icon(saveIcon), diff --git a/lib/utils/text_envelope.dart b/lib/utils/text_envelope.dart index 79013e1..2e75364 100644 --- a/lib/utils/text_envelope.dart +++ b/lib/utils/text_envelope.dart @@ -106,3 +106,59 @@ ParsedTextEnvelope? tryParseTextEnvelope(Uint8List plaintext) { } return null; } + +/// Envelope version of a control message: a chat setting both participants have +/// to agree on. It has its own version and kind, so no reader mistakes it for +/// text; a client that predates it shows raw JSON, which is why a timer is only +/// proposed towards a peer already on the new build. +const int systemEnvelopeVersion = 4; + +/// The only control message so far: the disappearing-message timer. +const String systemActionDisappearing = 'disappearing'; + +class ParsedSystemEnvelope { + const ParsedSystemEnvelope(this.state, this.seconds); + + /// "propose", "accept" or "decline". + final String state; + + /// The timer in seconds; 0 turns disappearing messages off. + final int seconds; +} + +/// Plaintext (pre-encryption) bytes of a disappearing-message proposal, an +/// acceptance or a refusal. +Uint8List buildSystemEnvelope(String state, int seconds) { + final map = { + 'whisperMsg': systemEnvelopeVersion, + 'kind': 'system', + 'action': systemActionDisappearing, + 'state': state, + 'seconds': seconds, + }; + return Uint8List.fromList(utf8.encode(jsonEncode(map))); +} + +/// Parses [plaintext] as a control envelope. Null for anything else. +ParsedSystemEnvelope? tryParseSystemEnvelope(Uint8List plaintext) { + try { + final decoded = jsonDecode(utf8.decode(plaintext)); + if (decoded is! Map || + decoded['kind'] != 'system' || + decoded['whisperMsg'] != systemEnvelopeVersion || + decoded['action'] != systemActionDisappearing) { + return null; + } + final state = decoded['state']; + final seconds = decoded['seconds']; + if (state is! String || seconds is! num) { + return null; + } + if (state != 'propose' && state != 'accept' && state != 'decline') { + return null; + } + return ParsedSystemEnvelope(state, seconds.toInt()); + } catch (_) { + return null; + } +} diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index f1f64a4..2841381 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -335,6 +335,7 @@ class Utils { // Media message: decode the envelope and create a placeholder. final envelope = MediaUtils.tryParseMediaEnvelope(decryptedMessage); if (envelope != null) { + final expiresAt = await _expiryFor(message.peerId, message.sentAt); if (envelope.references.length > 1) { // Album: one bubble, one download per attachment. final albumMsg = pm.PrivateMessage( @@ -345,6 +346,7 @@ class Utils { false, downloadStatus: pm.MediaDownloadStatus.pending, forwarded: envelope.forwarded, + expiresAt: expiresAt, ); albumMsg.setAlbum(envelope.references .map((ref) => pm.AlbumItem( @@ -377,10 +379,23 @@ class Utils { fileName: ref.fileName, downloadStatus: pm.MediaDownloadStatus.pending, forwarded: envelope.forwarded, + viewOnce: envelope.viewOnce, + expiresAt: expiresAt, mediaRefJson: jsonEncode(ref.toJson()), ); return (mediaMsg, [ref], message.peerId); } + // Control message: the disappearing-message agreement. It carries no + // text, so the chat renders it as a pill. + final systemEnvelope = tryParseSystemEnvelope(decryptedMessage); + if (systemEnvelope != null) { + final systemMsg = pm.PrivateMessage( + message.senderId, '', message.sentAt, DateTime.now(), false, + systemState: systemEnvelope.state, + systemSeconds: systemEnvelope.seconds) + ..id = message.id; + return (systemMsg, const [], message.peerId); + } // Plain text message (legacy/unchanged path), or a reply that carries // its quote in a text envelope. final textEnvelope = tryParseTextEnvelope(decryptedMessage); @@ -390,7 +405,8 @@ class Utils { message.sentAt, DateTime.now(), false, - forwarded: textEnvelope?.forwarded ?? false) + forwarded: textEnvelope?.forwarded ?? false, + expiresAt: await _expiryFor(message.peerId, message.sentAt)) ..setReplyTo(textEnvelope?.reply); return (textMsg, const [], message.peerId); } catch (e) { @@ -427,6 +443,14 @@ class Utils { pendingMediaRefs.putIfAbsent(message.senderId, () => []).addAll(refs); } } + // A control message changes the chat state before the bubble is stored, + // so the chat list already shows the new timer. + for (final (message, _, _) in valid) { + if (message.isSystem) { + await applySystemAgreement( + message.senderId, message.systemState!, message.systemSeconds); + } + } // Show toast only if all messages failed to decrypt if (decryptedMessages.isEmpty && messages.isNotEmpty) { @@ -643,6 +667,32 @@ class Utils { } } + /// The local disappearing deadline of one incoming message, null when the + /// chat has no timer. + static Future _expiryFor(String peerId, DateTime sentAt) async { + final seconds = await CacheUtils.getDisappearingSeconds(peerId); + return seconds > 0 ? sentAt.add(Duration(seconds: seconds)) : null; + } + + /// Applies one step of the disappearing-message agreement carried by a + /// control message from [peerId]. + static Future applySystemAgreement( + String peerId, String state, int seconds) async { + switch (state) { + case 'propose': + await CacheUtils.setDisappearingProposal(peerId, seconds); + break; + case 'accept': + // The peer accepted what this device proposed. + await CacheUtils.setDisappearingSeconds(peerId, seconds); + await CacheUtils.setDisappearingProposal(peerId, null); + break; + case 'decline': + await CacheUtils.setDisappearingProposal(peerId, null); + break; + } + } + /// Applies one entry of the mutation log: an edit, a deletion, a reaction or /// a pin of a message this device already has. The same code serves a live /// frame and a replayed sync page, so a reconnect converges on the same diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 25a2d82..eb9f17d 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -2,6 +2,7 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import '../models/user.dart'; import '../models/private_message.dart'; +import '../utils/disappearing.dart'; import '../utils/message_format.dart'; import '../utils/message_notifier.dart'; import '../utils/singleton.dart'; @@ -130,8 +131,47 @@ class _ChatBubbleState extends State { ); } + /// A control message rendered as one centred line: the disappearing-message + /// agreement, which belongs to the chat state rather than to a speaker. + Widget _systemPill(BuildContext context) { + final message = widget.message; + final label = disappearingLabel(message.systemSeconds); + final text = switch (message.systemState) { + 'propose' => 'disappearingProposalPill'.tr(args: [label]), + 'accept' => 'disappearingEnabledPill'.tr(args: [label]), + 'decline' => 'disappearingDeclinedPill'.tr(), + _ => 'disappearingChanged'.tr(), + }; + final scheme = Theme.of(context).colorScheme; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 16), + child: Center( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + text, + textAlign: TextAlign.center, + style: Theme.of(context) + .textTheme + .bodySmall + ?.copyWith(color: scheme.onSurfaceVariant), + ), + ), + ), + ); + } + @override Widget build(BuildContext context) { + // A control message has no bubble of its own: it is one centred line. + if (widget.message.isSystem) { + return _systemPill(context); + } + bool showAvatar() { if (widget.message.isMe) return false; // Show avatar if next message is null (last message) diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 859c76a..73f333a 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -11,6 +11,7 @@ import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../pages/media_viewer_page.dart'; import '../utils/media_utils.dart'; +import '../utils/message_actions.dart'; import 'voice_player.dart'; /// Renders a media attachment inside a chat bubble: image/gif thumbnail, video @@ -108,6 +109,77 @@ class _MediaBubbleState extends State { return Size(dw, dh); } + /// A single-view attachment never shows a thumbnail: nobody sees it before + /// opening it, and the open happens exactly once. + Widget _viewOnceWidget(bool hasCaption) { + final ready = widget.message.localPath != null; + return Column( + crossAxisAlignment: CrossAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [ + InkWell( + onTap: () { + if (!ready) { + if (widget.canRetry) { + widget.onRetry(); + } + return; + } + _openViewOnce(); + }, + borderRadius: BorderRadius.circular(10), + child: Container( + width: 200, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: widget.bubbleColor, + borderRadius: BorderRadius.circular(10), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.visibility_off, color: widget.textColor), + const SizedBox(height: 8), + Text( + ready ? 'viewOnceOpen'.tr() : 'viewOnceLoad'.tr(), + textAlign: TextAlign.center, + style: TextStyle(color: widget.textColor), + ), + ], + ), + ), + ), + if (hasCaption) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Text(widget.message.message, + style: TextStyle(color: widget.textColor)), + ), + ], + ); + } + + /// Opens the one allowed view, then burns the attachment. + Future _openViewOnce() async { + final message = widget.message; + await Navigator.of(context).push( + fadeRoute( + Theme( + data: Theme.of(context), + child: MediaViewerPage( + message: message, + conversationUserId: widget.conversationUserId, + viewOnce: true, + ), + ), + ), + ); + if (!mounted) { + return; + } + await MessageActions.consumeViewOnce(widget.conversationUserId, message); + } + void _openViewer({int albumIndex = 0}) { final path = widget.message.localPath; final type = widget.message.mediaType; @@ -134,6 +206,10 @@ class _MediaBubbleState extends State { final type = widget.message.mediaType; final hasCaption = widget.message.message.isNotEmpty; + if (widget.message.viewOnce) { + return _viewOnceWidget(hasCaption); + } + if (widget.message.isAlbum) { return _albumWidget(hasCaption); } diff --git a/pubspec.lock b/pubspec.lock index 0210697..dd95e06 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1372,6 +1372,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.2.3" + screen_protector: + dependency: "direct main" + description: + name: screen_protector + sha256: "66f2ffbfbe7acc26db49de893e0c49078c67b546c27a57958d9bd9901f77c38e" + url: "https://pub.dev" + source: hosted + version: "1.5.3" shared_preferences: dependency: transitive description: @@ -1790,7 +1798,7 @@ packages: path: "../whisper_websocket_client_dart" relative: true source: path - version: "0.3.0" + version: "0.4.0" win32: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 640cd83..809c111 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -41,6 +41,7 @@ dependencies: provider: ^6.1.2 qr_code_scanner_plus: ^2.0.6 record: ^7.1.2 + screen_protector: ^1.5.3 sprintf: ^7.0.0 url_launcher: ^6.3.1 uuid: ^4.5.3 diff --git a/test/disappearing_test.dart b/test/disappearing_test.dart new file mode 100644 index 0000000..3c471ce --- /dev/null +++ b/test/disappearing_test.dart @@ -0,0 +1,97 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper/utils/disappearing.dart'; +import 'package:whisper/utils/media_utils.dart'; +import 'package:whisper/utils/message_actions.dart'; +import 'package:whisper/utils/text_envelope.dart'; +import 'package:whisper_websocket_client_dart/models/media_reference.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +PrivateMessage message(String senderId, DateTime sentAt, + {DateTime? expiresAt, bool viewOnce = false}) { + return PrivateMessage(senderId, 'text', sentAt, sentAt, true, + expiresAt: expiresAt, viewOnce: viewOnce); +} + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_disappearing_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('a control message carries its state and timer both ways', () { + final parsed = + tryParseSystemEnvelope(buildSystemEnvelope('propose', 86400))!; + expect(parsed.state, 'propose'); + expect(parsed.seconds, 86400); + + // Anything that is not a control message stays text. + expect( + tryParseSystemEnvelope(Uint8List.fromList(utf8.encode('hi'))), isNull); + expect( + tryParseSystemEnvelope(Uint8List.fromList( + utf8.encode(jsonEncode({'kind': 'system', 'state': 'nope'})))), + isNull); + }); + + test('a view-once flag rides inside the media envelope', () { + final reference = MediaReference( + 'media-id', Uint8List.fromList([1, 2, 3]), MediaType.image, 3); + final parsed = MediaUtils.tryParseMediaEnvelope( + MediaUtils.buildMediaEnvelope(reference, '', viewOnce: true))!; + expect(parsed.viewOnce, isTrue); + final plain = MediaUtils.tryParseMediaEnvelope( + MediaUtils.buildMediaEnvelope(reference, ''))!; + expect(plain.viewOnce, isFalse); + }); + + // The sweep is what actually removes a disappearing message on this device. + test('the sweep drops expired rows and keeps the rest', () async { + final now = DateTime.now(); + await CacheUtils.addPrivateMessages('peer', [ + message('peer', now.subtract(const Duration(hours: 2)), + expiresAt: now.subtract(const Duration(hours: 1))), + message('peer', now.subtract(const Duration(minutes: 1)), + expiresAt: now.add(const Duration(hours: 1))), + message('peer', now), + ]); + + expect(await CacheUtils.purgeExpiredMessages(), 1); + final left = await CacheUtils.getPrivateMessages('peer'); + expect(left.length, 2); + }); + + test('a view-once attachment may not be forwarded', () { + final now = DateTime.now(); + expect(MessageActions.canForward(message('peer', now, viewOnce: true)), + isFalse); + expect(MessageActions.canForward(message('peer', now)), isTrue); + }); + + test('timers are labelled in their own unit', () { + // No localization is initialised here, so only the numeric labels are + // asserted; "off" is a translated word. + expect(disappearingLabel(3600), '1 h'); + expect(disappearingLabel(86400), '1 d'); + expect(disappearingLabel(604800), '7 d'); + }); +} From 25d1f9f837c6fbf3e3b989bfb80ebc1e16de5c6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sat, 21 Nov 2026 17:06:56 +0100 Subject: [PATCH 122/181] feat(chat): static and live location A static location is a text message with an optional location key, so an older client still shows the coordinates; the bubble opens the platform map app only on an explicit tap and never fetches tiles. Live location is an explicit opt-in for 15 minutes, an hour or eight hours: the position is encrypted for the peer and relayed as an ephemeral frame, the banner counts down, and it stops on its own or on demand. --- android/app/src/main/AndroidManifest.xml | 3 + assets/translations/cs.json | 12 +- assets/translations/en.json | 12 +- lib/models/private_message.dart | 19 +++ lib/models/private_message.g.dart | 7 +- lib/pages/chat_page.dart | 72 +++++++++ lib/utils/chat_sender.dart | 39 ++++- lib/utils/live_location.dart | 185 +++++++++++++++++++++++ lib/utils/message_actions.dart | 13 ++ lib/utils/presence.dart | 33 ++++ lib/utils/text_envelope.dart | 46 +++++- lib/utils/utils.dart | 13 +- lib/widgets/chat_bubble.dart | 62 ++++++++ lib/widgets/live_location_banner.dart | 126 +++++++++++++++ pubspec.lock | 48 ++++++ pubspec.yaml | 3 +- test/location_test.dart | 62 ++++++++ 17 files changed, 741 insertions(+), 14 deletions(-) create mode 100644 lib/utils/live_location.dart create mode 100644 lib/widgets/live_location_banner.dart create mode 100644 test/location_test.dart diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 44c496c..9e5b9cc 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -6,6 +6,9 @@ + + + diff --git a/assets/translations/cs.json b/assets/translations/cs.json index c70f100..b2ed225 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -278,5 +278,15 @@ "viewOnceOpen": "Klepnutím zobrazit jednou", "viewOnceLoad": "Klepnutím stáhnout", "viewOnceMedia": "Jednorázová příloha", - "screenshotDetected": "Screenshot zaznamenán" + "screenshotDetected": "Screenshot zaznamenán", + "locationMessage": "Poloha", + "openInMaps": "Otevřít v Mapách", + "attachLocation": "Poslat polohu", + "attachLiveLocation": "Sdílet živou polohu", + "liveLocationShare": "Sdílet živou polohu", + "liveLocationFor": "Na {}", + "liveLocationMine": "Sdílím polohu", + "liveLocationTheirs": "Sdílí polohu", + "liveLocationStop": "Ukončit sdílení", + "locationUnavailable": "Poloha není dostupná" } diff --git a/assets/translations/en.json b/assets/translations/en.json index dd35896..b14b740 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -278,5 +278,15 @@ "viewOnceOpen": "Tap to view once", "viewOnceLoad": "Tap to download", "viewOnceMedia": "View-once attachment", - "screenshotDetected": "Screenshot detected" + "screenshotDetected": "Screenshot detected", + "locationMessage": "Location", + "openInMaps": "Open in maps", + "attachLocation": "Send location", + "attachLiveLocation": "Share live location", + "liveLocationShare": "Share live location", + "liveLocationFor": "For {}", + "liveLocationMine": "Sharing location", + "liveLocationTheirs": "Sharing location", + "liveLocationStop": "Stop sharing", + "locationUnavailable": "Location is not available" } diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index 6633827..056279e 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -229,6 +229,11 @@ class PrivateMessage extends HiveObject { @HiveField(27, defaultValue: false) bool viewOnce; + /// JSON of a static location ({lat, lng, accuracy?, label?}) sent as a + /// message; null for everything else. + @HiveField(28) + String? locationJson; + /// Cache for [album], keyed by the [albumJson] it was decoded from. String? _albumCacheJson; List? _albumCache; @@ -261,8 +266,22 @@ class PrivateMessage extends HiveObject { this.systemState, this.systemSeconds = 0, this.viewOnce = false, + this.locationJson, }); + /// The static location carried by this message, null for everything else. + LocationRef? get location { + final raw = locationJson; + if (raw == null || raw.isEmpty) { + return null; + } + try { + return LocationRef.fromJson(jsonDecode(raw)); + } catch (_) { + return null; + } + } + /// A control message: it carries a chat setting, not text to read. bool get isSystem => systemState != null; diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index db672e0..6e1e5b7 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -44,13 +44,14 @@ class PrivateMessageAdapter extends TypeAdapter { systemState: fields[25] as String?, systemSeconds: fields[26] == null ? 0 : fields[26] as int, viewOnce: fields[27] == null ? false : fields[27] as bool, + locationJson: fields[28] as String?, )..id = fields[19] as String?; } @override void write(BinaryWriter writer, PrivateMessage obj) { writer - ..writeByte(28) + ..writeByte(29) ..writeByte(0) ..write(obj.senderId) ..writeByte(1) @@ -106,7 +107,9 @@ class PrivateMessageAdapter extends TypeAdapter { ..writeByte(26) ..write(obj.systemSeconds) ..writeByte(27) - ..write(obj.viewOnce); + ..write(obj.viewOnce) + ..writeByte(28) + ..write(obj.locationJson); } @override diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 2f55ed8..e482e94 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -14,6 +14,7 @@ import '../models/user.dart'; import '../utils/cache_utils.dart'; import '../utils/chat_scroll.dart'; import '../utils/chat_sender.dart'; +import '../utils/live_location.dart'; import '../utils/media_utils.dart'; import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; @@ -24,6 +25,7 @@ import '../utils/utils.dart' as utils; import '../utils/theme_utils.dart'; import '../widgets/attachment_confirm_sheet.dart'; import '../widgets/chat_bubble.dart'; +import '../widgets/live_location_banner.dart'; import 'chat_info_page.dart'; import 'forward_page.dart'; @@ -968,6 +970,57 @@ class _ChatPageState extends State { } } + /// Sends one fix as a location message. No coordinates are read until the + /// user picks this action, and they travel only inside the ciphertext. + Future _sendCurrentLocation() async { + setState(() => _isSending = true); + try { + final position = await LiveLocationSharer.currentPosition(); + if (position == null) { + await Fluttertoast.showToast( + msg: 'locationUnavailable'.tr(), backgroundColor: Colors.red); + return; + } + final sent = await ChatSender.sendLocation( + widget.user, position.latitude, position.longitude, + accuracy: position.accuracy); + _afterSend(sent, ''); + } catch (e) { + await Fluttertoast.showToast( + msg: e.toString(), backgroundColor: Colors.red); + } finally { + if (mounted) { + setState(() => _isSending = false); + } + } + } + + /// Live location is opt-in, ends on its own and can be stopped in the banner. + Future _startLiveLocation() async { + const options = [15, 60, 480]; + final minutes = await showDialog( + context: context, + builder: (ctx) => SimpleDialog( + title: Text('liveLocationShare'.tr()), + children: [ + for (final option in options) + ListTile( + title: Text('liveLocationFor'.tr(args: ['$option min'])), + onTap: () => Navigator.pop(ctx, option), + ), + ], + ), + ); + if (minutes == null) { + return; + } + final started = await LiveLocationSharer.instance + .start(widget.user, Duration(minutes: minutes)); + if (started && mounted) { + setState(() {}); + } + } + /// Bottom sheet with a caption field; returns the caption, or null to cancel. Future _confirmAttachment(int count) { return AttachmentConfirmSheet.show( @@ -1053,6 +1106,22 @@ class _ChatPageState extends State { }, viewOnce: true); }, ), + ListTile( + leading: const Icon(Icons.place), + title: Text('attachLocation'.tr()), + onTap: () { + Navigator.pop(ctx); + _sendCurrentLocation(); + }, + ), + ListTile( + leading: const Icon(Icons.my_location), + title: Text('attachLiveLocation'.tr()), + onTap: () { + Navigator.pop(ctx); + _startLiveLocation(); + }, + ), ], ), ); @@ -1789,6 +1858,9 @@ class _ChatPageState extends State { mainAxisSize: MainAxisSize.min, children: [ if (_replyTo != null) _buildReplyBar(), + // Above the field, inside the measured composer, so the + // message list keeps clearing it. + LiveLocationBanner(widget.user), Stack( alignment: Alignment.center, children: [ diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index 6ed9705..bfad490 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -438,14 +438,15 @@ class ChatSender { /// Encrypt [message] for [recipient] and hand it to the WebSocket. The /// original timestamp is kept so a resend maps onto the same server entry. static Future _sendText(User recipient, PrivateMessage message, - {int ttl = 0}) async { + {int ttl = 0, Uint8List? plaintextOverride}) async { // A reply needs the quote next to the body; everything else stays raw text // so an older client can still read it. final reply = message.replyTo; - final plaintext = reply == null && !message.forwarded - ? utf8.encode(message.message) - : buildTextEnvelope(message.message, reply, - forwarded: message.forwarded); + final plaintext = plaintextOverride ?? + (reply == null && !message.forwarded + ? utf8.encode(message.message) + : buildTextEnvelope(message.message, reply, + forwarded: message.forwarded)); final data = await CryptoUtils.encryptMessageData( plaintext, bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); Singleton().wsClient.sendMessage(WsMessage.privateMessage(NewPrivateMessage( @@ -513,6 +514,34 @@ class ChatSender { /// disappearing timer. static const int viewOnceTtlSeconds = 86400; + /// Sends a static location: an ordinary text message whose envelope also + /// carries the coordinates. The server sees only the ciphertext. + static Future sendLocation(User recipient, double lat, double lng, + {double? accuracy, String? label}) async { + final now = DateTime.now(); + final ttl = await _ttlFor(recipient); + final location = LocationRef(lat, lng, accuracy: accuracy, label: label); + final message = PrivateMessage( + Singleton().profile.user.id, location.body, now, now, true, + sendStatus: SendStatus.sending, + locationJson: jsonEncode(location.toJson()), + expiresAt: ttl > 0 ? now.add(Duration(seconds: ttl)) : null); + try { + await _persist(recipient, [message]); + if (!await _ensureConnected()) { + return await _fail(recipient.id, message); + } + await _sendText(recipient, message, + ttl: ttl, + plaintextOverride: + buildTextEnvelope(location.body, null, location: location)); + return true; + } catch (e) { + Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); + return await _fail(recipient.id, message); + } + } + /// The agreed disappearing timer of one chat in seconds, 0 when off. static Future _ttlFor(User recipient) => CacheUtils.getDisappearingSeconds(recipient.id); diff --git a/lib/utils/live_location.dart b/lib/utils/live_location.dart new file mode 100644 index 0000000..900a2fa --- /dev/null +++ b/lib/utils/live_location.dart @@ -0,0 +1,185 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:basic_utils/basic_utils.dart' as bu; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart' show Colors; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:geolocator/geolocator.dart'; + +import '../models/user.dart'; +import 'crypto_utils.dart'; +import 'singleton.dart'; + +/// One live position as the peer sees it: where, and until when. +class LiveLocationPoint { + final double lat; + final double lng; + final double? accuracy; + final DateTime until; + + const LiveLocationPoint(this.lat, this.lng, + {this.accuracy, required this.until}); + + String get coordinates => + '${lat.toStringAsFixed(5)}, ${lng.toStringAsFixed(5)}'; + + factory LiveLocationPoint.fromJson(Map json) { + return LiveLocationPoint( + (json['lat'] as num).toDouble(), + (json['lng'] as num).toDouble(), + accuracy: (json['accuracy'] as num?)?.toDouble(), + until: DateTime.parse(json['until'] as String), + ); + } + + Map toJson() => { + 'lat': lat, + 'lng': lng, + if (accuracy != null) 'accuracy': accuracy, + 'until': until.toUtc().toIso8601String(), + }; +} + +/// Wraps the four parts of one hybrid-encrypted position into one string the +/// WebSocket frame can carry. The server relays it and sees no coordinates. +String encodeEncryptedPayload(Map data) { + return base64Encode(utf8.encode(jsonEncode({ + 'data': base64Encode(data['encryptedData']!), + 'key': base64Encode(data['encryptedKey']!), + 'nonce': base64Encode(data['nonce']!), + 'mac': base64Encode(data['mac']!), + }))); +} + +/// Reverses [encodeEncryptedPayload]; null for anything malformed. +Map? decodeEncryptedPayload(String payload) { + try { + final raw = jsonDecode(utf8.decode(base64Decode(payload))); + if (raw is! Map) { + return null; + } + return { + 'encryptedData': base64Decode(raw['data'] as String), + 'encryptedKey': base64Decode(raw['key'] as String), + 'nonce': base64Decode(raw['nonce'] as String), + 'mac': base64Decode(raw['mac'] as String), + }; + } catch (_) { + return null; + } +} + +/// Decrypts one relayed position with this device's key. +Future decryptLiveLocation(String payload) async { + final parts = decodeEncryptedPayload(payload); + if (parts == null) { + return null; + } + try { + final plain = await CryptoUtils.decryptMessageData( + parts['encryptedData']!, + parts['encryptedKey']!, + parts['nonce']!, + parts['mac']!, + bu.CryptoUtils.rsaPrivateKeyFromPem(Singleton().profile.privateKey)); + return LiveLocationPoint.fromJson( + Map.from(jsonDecode(utf8.decode(plain)) as Map)); + } catch (_) { + return null; + } +} + +/// Shares this device's position for a limited time. Nothing is archived: the +/// frames stop at the deadline, and the peer keeps only the last point in +/// memory. +class LiveLocationSharer { + LiveLocationSharer._(); + + static final LiveLocationSharer instance = LiveLocationSharer._(); + + /// How often a fresh position is sent while sharing. + static const Duration interval = Duration(seconds: 10); + + Timer? _timer; + String? _peerId; + DateTime? _until; + + bool isSharing(String peerId) => _timer != null && _peerId == peerId; + + DateTime? get until => _until; + + /// Starts a session with [peer]. Returns false when there is no fix, which is + /// also what a refused permission looks like. + Future start(User peer, Duration duration) async { + await stop(); + final position = await currentPosition(); + if (position == null) { + await Fluttertoast.showToast( + msg: 'locationUnavailable'.tr(), backgroundColor: Colors.red); + return false; + } + _peerId = peer.id; + _until = DateTime.now().add(duration); + await _send(peer, position); + _timer = Timer.periodic(interval, (_) async { + final next = await currentPosition(); + if (next != null) { + await _send(peer, next); + } + final deadline = _until; + if (deadline != null && DateTime.now().isAfter(deadline)) { + await stop(); + } + }); + return true; + } + + Future stop() async { + _timer?.cancel(); + _timer = null; + _peerId = null; + _until = null; + } + + Future _send(User peer, Position position) async { + final deadline = _until; + if (deadline == null || !Singleton().wsClient.isConnected) { + return; + } + final point = LiveLocationPoint(position.latitude, position.longitude, + accuracy: position.accuracy, until: deadline); + try { + final data = await CryptoUtils.encryptMessageData( + utf8.encode(jsonEncode(point.toJson())), + bu.CryptoUtils.rsaPublicKeyFromPem(peer.publicKey)); + Singleton() + .wsClient + .sendLiveLocation(peer.id, encodeEncryptedPayload(data)); + } catch (_) { + // A frame that cannot be encrypted is dropped; the next tick retries. + } + } + + /// One fix from the platform, null when the user refused the permission or + /// location is switched off. + static Future currentPosition() async { + try { + if (!await Geolocator.isLocationServiceEnabled()) { + return null; + } + var permission = await Geolocator.checkPermission(); + if (permission == LocationPermission.denied) { + permission = await Geolocator.requestPermission(); + } + if (permission == LocationPermission.denied || + permission == LocationPermission.deniedForever) { + return null; + } + return await Geolocator.getCurrentPosition(); + } catch (_) { + return null; + } + } +} diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 0c7024d..4c5d9ad 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -6,6 +6,7 @@ import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; +import 'package:url_launcher/url_launcher.dart'; import 'package:whisper_openapi_client_dart/api.dart'; import '../models/private_message.dart'; @@ -58,6 +59,18 @@ class MessageActions { /// conversation. static bool canForward(PrivateMessage message) => !message.viewOnce; + /// Opens a static location in the platform map app. The coordinates leave the + /// app only through this explicit tap. + static Future openLocation(LocationRef location, + {void Function()? onError}) async { + final uri = Uri.parse( + 'geo:${location.lat},${location.lng}?q=${location.lat},${location.lng}'); + final opened = await launchUrl(uri, mode: LaunchMode.externalApplication); + if (!opened) { + onError?.call(); + } + } + /// Burns a view-once attachment after its single open: the local copy goes, /// and so does the server row, so the other side loses it too. static Future consumeViewOnce( diff --git a/lib/utils/presence.dart b/lib/utils/presence.dart index d4132ca..a9f26ff 100644 --- a/lib/utils/presence.dart +++ b/lib/utils/presence.dart @@ -3,6 +3,8 @@ import 'dart:async'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/foundation.dart'; +import 'live_location.dart'; + /// Live, in-memory status of the other participants: who is online, when they /// were last seen and whether they are typing. Nothing here is stored, and the /// server keeps no presence either, so a restart or a disconnect empties it. @@ -26,6 +28,32 @@ class PresenceNotifier extends ChangeNotifier { final Map _typingTimers = {}; final Map _online = {}; + /// Live positions shared with this device, dropped at their own deadline. + final Map _live = {}; + final Map _liveTimers = {}; + + /// The position [peerId] is sharing right now, null when they are not. + LiveLocationPoint? liveLocation(String peerId) { + final point = _live[peerId]; + if (point == null || point.until.isBefore(DateTime.now())) { + return null; + } + return point; + } + + /// Keeps one relayed position and forgets it at its deadline. + void applyLiveLocation(String peerId, LiveLocationPoint point) { + _live[peerId] = point; + _liveTimers.remove(peerId)?.cancel(); + final left = point.until.difference(DateTime.now()); + _liveTimers[peerId] = Timer(left.isNegative ? Duration.zero : left, () { + _live.remove(peerId); + _liveTimers.remove(peerId); + notifyListeners(); + }); + notifyListeners(); + } + /// True when [peerId] is known to be online; null when nothing is known. bool? isOnline(String peerId) => _online[peerId]; @@ -81,11 +109,16 @@ class PresenceNotifier extends ChangeNotifier { for (final timer in _presenceTimers.values) { timer.cancel(); } + for (final timer in _liveTimers.values) { + timer.cancel(); + } _typingTimers.clear(); _presenceTimers.clear(); + _liveTimers.clear(); _typingUntil.clear(); _online.clear(); _lastSeen.clear(); + _live.clear(); notifyListeners(); } diff --git a/lib/utils/text_envelope.dart b/lib/utils/text_envelope.dart index 2e75364..9255b16 100644 --- a/lib/utils/text_envelope.dart +++ b/lib/utils/text_envelope.dart @@ -53,13 +53,53 @@ class ReplyRef { /// Payload of a text message that quotes another one. class ParsedTextEnvelope { - const ParsedTextEnvelope(this.body, this.reply, {this.forwarded = false}); + const ParsedTextEnvelope(this.body, this.reply, + {this.forwarded = false, this.location}); final String body; final ReplyRef? reply; /// The sender passed on somebody else's text instead of writing it. final bool forwarded; + + /// A static location, null for an ordinary text message. + final LocationRef? location; +} + +/// A static location inside a text envelope. It stays a `text` message with an +/// optional key, so an older client shows the body ("📍 50.08, 14.42") instead +/// of raw JSON. +class LocationRef { + final double lat; + final double lng; + final double? accuracy; + final String? label; + + const LocationRef(this.lat, this.lng, {this.accuracy, this.label}); + + /// What a client without location support still shows. + String get body => '📍 ${lat.toStringAsFixed(5)}, ${lng.toStringAsFixed(5)}'; + + Map toJson() => { + 'lat': lat, + 'lng': lng, + if (accuracy != null) 'accuracy': accuracy, + if (label != null && label!.isNotEmpty) 'label': label, + }; + + static LocationRef? fromJson(dynamic json) { + if (json is! Map) { + return null; + } + final lat = json['lat']; + final lng = json['lng']; + if (lat is! num || lng is! num) { + return null; + } + return LocationRef(lat.toDouble(), lng.toDouble(), + accuracy: (json['accuracy'] as num?)?.toDouble(), + label: json['label'] as String?); + } } /// Envelope version of a text message carrying a quote. Versions 1 and 2 are @@ -72,13 +112,14 @@ const int textEnvelopeVersion = 3; /// The envelope stays version 3 and the flags are optional keys, so a reader /// that predates them still shows the body instead of raw JSON. Uint8List buildTextEnvelope(String body, ReplyRef? reply, - {bool forwarded = false}) { + {bool forwarded = false, LocationRef? location}) { final map = { 'whisperMsg': textEnvelopeVersion, 'kind': 'text', 'body': body, if (reply != null) 'replyTo': reply.toJson(), if (forwarded) 'forwarded': true, + if (location != null) 'location': location.toJson(), }; return Uint8List.fromList(utf8.encode(jsonEncode(map))); } @@ -99,6 +140,7 @@ ParsedTextEnvelope? tryParseTextEnvelope(Uint8List plaintext) { body, ReplyRef.fromJson(decoded['replyTo']), forwarded: decoded['forwarded'] == true, + location: LocationRef.fromJson(decoded['location']), ); } } catch (_) { diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 2841381..54f92ba 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -14,6 +14,7 @@ import '../pages/chat_page.dart'; import 'package:whisper_openapi_client_dart/api.dart'; import 'package:basic_utils/basic_utils.dart' as bu; import 'package:whisper_websocket_client_dart/models/delivery_ack.dart'; +import 'package:whisper_websocket_client_dart/models/live_location.dart'; import 'package:whisper_websocket_client_dart/models/message_event.dart'; import 'package:whisper_websocket_client_dart/models/presence.dart'; import 'package:whisper_websocket_client_dart/models/read_receipt.dart'; @@ -28,6 +29,7 @@ import 'chat_sender.dart'; import 'crypto_utils.dart'; import 'media_utils.dart'; import 'message_notifier.dart'; +import 'live_location.dart'; import 'presence.dart'; import 'singleton.dart'; import 'text_envelope.dart'; @@ -406,6 +408,9 @@ class Utils { DateTime.now(), false, forwarded: textEnvelope?.forwarded ?? false, + locationJson: textEnvelope?.location == null + ? null + : jsonEncode(textEnvelope!.location!.toJson()), expiresAt: await _expiryFor(message.peerId, message.sentAt)) ..setReplyTo(textEnvelope?.reply); return (textMsg, const [], message.peerId); @@ -635,9 +640,13 @@ class Utils { online: presence.online, lastSeenAt: presence.lastSeenAt); break; - // A live position is rendered by the location landing; until it exists - // there is nothing to show. + // A live position: relayed encrypted, kept in memory until it expires. case WsResponseType.liveLocation: + final frame = wsResponse.payload as LiveLocationFrame; + final point = await decryptLiveLocation(frame.payload); + if (point != null) { + PresenceNotifier.instance.applyLiveLocation(frame.peerId, point); + } break; // Delete account diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index eb9f17d..7693c5a 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -3,7 +3,9 @@ import 'package:flutter/material.dart'; import '../models/user.dart'; import '../models/private_message.dart'; import '../utils/disappearing.dart'; +import '../utils/message_actions.dart'; import '../utils/message_format.dart'; +import '../utils/text_envelope.dart'; import '../utils/message_notifier.dart'; import '../utils/singleton.dart'; import 'formatted_text.dart'; @@ -165,12 +167,72 @@ class _ChatBubbleState extends State { ); } + /// A static location: a pin, the coordinates and a way into the platform map + /// app. No tiles are fetched, so nothing leaves the device until the tap. + Widget _locationBubble(BuildContext context, LocationRef location) { + final scheme = Theme.of(context).colorScheme; + return Align( + alignment: + widget.message.isMe ? Alignment.centerRight : Alignment.centerLeft, + child: Container( + margin: const EdgeInsets.symmetric(vertical: 2, horizontal: 8), + padding: const EdgeInsets.fromLTRB(12, 10, 12, 4), + constraints: const BoxConstraints(maxWidth: 260), + decoration: BoxDecoration( + color: widget.accentColor, + borderRadius: BorderRadius.circular(12), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + const Icon(Icons.place, size: 20), + const SizedBox(width: 6), + Expanded( + child: Text( + (location.label?.isNotEmpty ?? false) + ? location.label! + : 'locationMessage'.tr(), + style: const TextStyle(fontWeight: FontWeight.w600), + ), + ), + ], + ), + Padding( + padding: const EdgeInsets.only(top: 2, left: 26), + child: Text(location.body, + style: Theme.of(context) + .textTheme + .bodySmall + ?.copyWith(color: scheme.onSurfaceVariant)), + ), + Align( + alignment: Alignment.centerRight, + child: TextButton.icon( + onPressed: () => MessageActions.openLocation(location), + icon: const Icon(Icons.map, size: 18), + label: Text('openInMaps'.tr()), + ), + ), + ], + ), + ), + ); + } + @override Widget build(BuildContext context) { // A control message has no bubble of its own: it is one centred line. if (widget.message.isSystem) { return _systemPill(context); } + // A static location is a card, not text with a pin in it. + final location = widget.message.location; + if (location != null) { + return _locationBubble(context, location); + } bool showAvatar() { if (widget.message.isMe) return false; diff --git a/lib/widgets/live_location_banner.dart b/lib/widgets/live_location_banner.dart new file mode 100644 index 0000000..4270e35 --- /dev/null +++ b/lib/widgets/live_location_banner.dart @@ -0,0 +1,126 @@ +import 'dart:async'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +import '../models/user.dart'; +import '../utils/live_location.dart'; +import '../utils/message_actions.dart'; +import '../utils/presence.dart'; +import '../utils/text_envelope.dart'; + +/// One row above the composer while a live location is on: this device's with a +/// stop button, the peer's with the last point and a way into the map app. +class LiveLocationBanner extends StatefulWidget { + final User peer; + + const LiveLocationBanner(this.peer, {super.key}); + + @override + State createState() => _LiveLocationBannerState(); +} + +class _LiveLocationBannerState extends State { + Timer? _tick; + + @override + void initState() { + super.initState(); + // The remaining time is a clock, not an event: one rebuild a second. + _tick = Timer.periodic(const Duration(seconds: 1), (_) { + if (mounted) { + setState(() {}); + } + }); + PresenceNotifier.instance.addListener(_onChanged); + } + + @override + void dispose() { + _tick?.cancel(); + PresenceNotifier.instance.removeListener(_onChanged); + super.dispose(); + } + + void _onChanged() { + if (mounted) { + setState(() {}); + } + } + + String _left(DateTime until) { + final left = until.difference(DateTime.now()); + if (left.isNegative) { + return '0:00'; + } + return '${left.inMinutes}:' + '${left.inSeconds.remainder(60).toString().padLeft(2, '0')}'; + } + + @override + Widget build(BuildContext context) { + final mine = LiveLocationSharer.instance.isSharing(widget.peer.id); + final theirs = PresenceNotifier.instance.liveLocation(widget.peer.id); + if (!mine && theirs == null) { + return const SizedBox.shrink(); + } + final scheme = Theme.of(context).colorScheme; + final until = mine ? LiveLocationSharer.instance.until : theirs?.until; + final label = mine ? 'liveLocationMine'.tr() : 'liveLocationTheirs'.tr(); + return Container( + margin: const EdgeInsets.fromLTRB(8, 4, 8, 0), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: scheme.secondaryContainer, + borderRadius: BorderRadius.circular(12), + ), + child: Row( + children: [ + Icon(Icons.my_location, size: 18, color: scheme.onSecondaryContainer), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + until == null ? label : '$label · ${_left(until)}', + style: TextStyle(color: scheme.onSecondaryContainer), + ), + if (!mine) + GestureDetector( + onTap: () { + final point = theirs; + if (point != null) { + MessageActions.openLocation( + LocationRef(point.lat, point.lng)); + } + }, + child: Text( + theirs?.coordinates ?? '', + style: TextStyle( + fontSize: 12, + decoration: TextDecoration.underline, + color: scheme.onSecondaryContainer, + ), + ), + ), + ], + ), + ), + if (mine) + IconButton( + icon: const Icon(Icons.stop_circle_outlined), + tooltip: 'liveLocationStop'.tr(), + onPressed: () async { + await LiveLocationSharer.instance.stop(); + if (mounted) { + setState(() {}); + } + }, + ), + ], + ), + ); + } +} diff --git a/pubspec.lock b/pubspec.lock index dd95e06..d5743c7 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -695,6 +695,54 @@ packages: description: flutter source: sdk version: "0.0.0" + geolocator: + dependency: "direct main" + description: + name: geolocator + sha256: ee2212a3df8292ec4c90b91183b8001d3f5a800823c974b570c5f9344ca320dc + url: "https://pub.dev" + source: hosted + version: "14.0.1" + geolocator_android: + dependency: transitive + description: + name: geolocator_android + sha256: e67583809a1fab5f4a2255902978e2bc095ace9451fde0d9624e54facd0a5c22 + url: "https://pub.dev" + source: hosted + version: "5.2.1" + geolocator_apple: + dependency: transitive + description: + name: geolocator_apple + sha256: a1e177f3081089724f2095856aeb96eb8d7d1c59e425aed8dd4de7aa2c11ab66 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + geolocator_platform_interface: + dependency: transitive + description: + name: geolocator_platform_interface + sha256: e012af6b7e2674e7500237ab11e44ac9119e87fd0105e7bb55cde1750e8e5d80 + url: "https://pub.dev" + source: hosted + version: "4.4.1" + geolocator_web: + dependency: transitive + description: + name: geolocator_web + sha256: "19e485a0f8d6a88abcf9c53cba3a4105e14b7435ed8ac1c108c067b938fe8429" + url: "https://pub.dev" + source: hosted + version: "4.1.4" + geolocator_windows: + dependency: transitive + description: + name: geolocator_windows + sha256: "175435404d20278ffd220de83c2ca293b73db95eafbdc8131fe8609be1421eb6" + url: "https://pub.dev" + source: hosted + version: "0.2.5" glob: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 809c111..332b2b2 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,7 +3,7 @@ description: "Secure private self-hosted end-to-end encryption messaging app." publish_to: 'none' # Remove this line if you wish to publish to pub.dev # Bump before every release; the release workflow tags v and fails if # that tag already exists. The build number after + must only ever grow. -version: 0.4.0+6 +version: 0.4.0+8 environment: sdk: '>=3.4.3 <4.0.0' @@ -27,6 +27,7 @@ dependencies: flutter_local_notifications: ^23.0.0 flutter_secure_storage: ^11.2.0 fluttertoast: ^10.0.2 + geolocator: ^14.0.1 hive: ^2.2.3 http: ^1.2.1 image_picker: ^1.2.2 diff --git a/test/location_test.dart b/test/location_test.dart new file mode 100644 index 0000000..0526e4f --- /dev/null +++ b/test/location_test.dart @@ -0,0 +1,62 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/live_location.dart'; +import 'package:whisper/utils/text_envelope.dart'; + +void main() { + // A location is a text message with one optional key, so an older client + // still shows the coordinates instead of raw JSON. + test('a location survives the text envelope and keeps a text fallback', () { + const location = LocationRef(50.087, 14.421, accuracy: 12, label: 'Praha'); + final parsed = tryParseTextEnvelope( + buildTextEnvelope(location.body, null, location: location))!; + + expect(parsed.body, '📍 50.08700, 14.42100'); + expect(parsed.location!.lat, 50.087); + expect(parsed.location!.lng, 14.421); + expect(parsed.location!.label, 'Praha'); + expect(parsed.location!.accuracy, 12); + }); + + test('a plain text envelope has no location', () { + final parsed = tryParseTextEnvelope(buildTextEnvelope('hello', null))!; + expect(parsed.location, isNull); + }); + + // The relayed position is one string the server cannot read; only the parts + // have to survive the base64 round trip. + test('an encrypted payload round-trips through the frame', () { + final parts = { + 'encryptedData': Uint8List.fromList([1, 2, 3]), + 'encryptedKey': Uint8List.fromList([4, 5]), + 'nonce': Uint8List.fromList([6]), + 'mac': Uint8List.fromList([7, 8]), + }; + final decoded = decodeEncryptedPayload(encodeEncryptedPayload(parts))!; + expect(decoded['encryptedData'], [1, 2, 3]); + expect(decoded['encryptedKey'], [4, 5]); + expect(decoded['nonce'], [6]); + expect(decoded['mac'], [7, 8]); + }); + + test('a malformed payload is dropped, not thrown', () { + expect(decodeEncryptedPayload('not base64!'), isNull); + expect( + decodeEncryptedPayload( + base64Encode(utf8.encode(jsonEncode({'data': 1})))), + isNull); + }); + + test('a position carries its deadline', () { + final point = LiveLocationPoint(1.5, 2.5, + accuracy: 3, until: DateTime.utc(2026, 11, 21, 12)); + final parsed = + LiveLocationPoint.fromJson(Map.from(point.toJson())); + expect(parsed.lat, 1.5); + expect(parsed.lng, 2.5); + expect(parsed.accuracy, 3); + expect(parsed.until, DateTime.utc(2026, 11, 21, 12)); + }); +} From 46a792df3db171d203c33faf683bb46c19f617fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sat, 21 Nov 2026 17:07:50 +0100 Subject: [PATCH 123/181] fix(chat): a disappearing-message control message raises no unread badge or notification It is chat state, not correspondence: the timer is applied when it arrives and the pill is stored already read. --- lib/utils/utils.dart | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 54f92ba..6178bd6 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -392,7 +392,13 @@ class Utils { final systemEnvelope = tryParseSystemEnvelope(decryptedMessage); if (systemEnvelope != null) { final systemMsg = pm.PrivateMessage( - message.senderId, '', message.sentAt, DateTime.now(), false, + message.senderId, + '', + message.sentAt, + DateTime.now(), + // Chat state, already applied above: it must not raise an + // unread badge. + true, systemState: systemEnvelope.state, systemSeconds: systemEnvelope.seconds) ..id = message.id; @@ -528,6 +534,9 @@ class Utils { return; } + // A control message is chat state, not correspondence: it never rings. + decryptedMessages.removeWhere((message) => message.isSystem); + // Remove messages from notifications if user was not online when they were sent decryptedMessages.removeWhere((x) => !messages .where((y) => y.sentAt == x.sentAt && y.senderId == x.senderId) From 5d2d42906d05adf092df2e19a8126ebc613f332f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 15:31:43 +0100 Subject: [PATCH 124/181] feat(app): keep view-once messages as tombstones and hide their content from the sender Opening a view-once attachment no longer deletes the message: the local copy goes, the row stays as a tombstone and the open is reported to the server, so the sender learns it and the other devices agree. The sender keeps no copy at all (it is removed after a successful send) and can no longer open its own attachment, which used to burn the recipient's one view; the debug self-chat is exempt, because there the sender is the receiver. Also shows the online dot in the user search list, the same badge the chat list already draws. Clients are pinned to the new contract (openapi 0.4.0, ws 0.5.0). --- assets/translations/cs.json | 5 +- assets/translations/en.json | 5 +- lib/models/private_message.dart | 6 ++ lib/models/private_message.g.dart | 7 ++- lib/utils/cache_utils.dart | 23 +++++++ lib/utils/chat_sender.dart | 8 +++ lib/utils/message_actions.dart | 13 ++-- lib/utils/utils.dart | 10 +++ lib/widgets/media_bubble.dart | 100 +++++++++++++++++------------- lib/widgets/user_list_item.dart | 65 +++++++++++++++---- pubspec.yaml | 5 +- test/user_list_item_test.dart | 45 ++++++++++++++ test/view_once_test.dart | 84 +++++++++++++++++++++++++ 13 files changed, 309 insertions(+), 67 deletions(-) create mode 100644 test/user_list_item_test.dart create mode 100644 test/view_once_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index b2ed225..7e62844 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -288,5 +288,8 @@ "liveLocationMine": "Sdílím polohu", "liveLocationTheirs": "Sdílí polohu", "liveLocationStop": "Ukončit sdílení", - "locationUnavailable": "Poloha není dostupná" + "locationUnavailable": "Poloha není dostupná", + "viewOnceSent": "Jednorázová příloha odeslána", + "viewOnceOpened": "Zobrazeno", + "viewOnceOpenedByPeer": "Otevřeno" } diff --git a/assets/translations/en.json b/assets/translations/en.json index b14b740..3f1fba4 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -288,5 +288,8 @@ "liveLocationMine": "Sharing location", "liveLocationTheirs": "Sharing location", "liveLocationStop": "Stop sharing", - "locationUnavailable": "Location is not available" + "locationUnavailable": "Location is not available", + "viewOnceSent": "View-once attachment sent", + "viewOnceOpened": "Opened", + "viewOnceOpenedByPeer": "Opened" } diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index 056279e..dd0685b 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -234,6 +234,11 @@ class PrivateMessage extends HiveObject { @HiveField(28) String? locationJson; + /// When the receiver opened this view-once attachment; null while it is still + /// unopened. Server-reported, so both sides see the same instant. + @HiveField(29) + DateTime? openedAt; + /// Cache for [album], keyed by the [albumJson] it was decoded from. String? _albumCacheJson; List? _albumCache; @@ -267,6 +272,7 @@ class PrivateMessage extends HiveObject { this.systemSeconds = 0, this.viewOnce = false, this.locationJson, + this.openedAt, }); /// The static location carried by this message, null for everything else. diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index 6e1e5b7..6646858 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -45,13 +45,14 @@ class PrivateMessageAdapter extends TypeAdapter { systemSeconds: fields[26] == null ? 0 : fields[26] as int, viewOnce: fields[27] == null ? false : fields[27] as bool, locationJson: fields[28] as String?, + openedAt: fields[29] as DateTime?, )..id = fields[19] as String?; } @override void write(BinaryWriter writer, PrivateMessage obj) { writer - ..writeByte(29) + ..writeByte(30) ..writeByte(0) ..write(obj.senderId) ..writeByte(1) @@ -109,7 +110,9 @@ class PrivateMessageAdapter extends TypeAdapter { ..writeByte(27) ..write(obj.viewOnce) ..writeByte(28) - ..write(obj.locationJson); + ..write(obj.locationJson) + ..writeByte(29) + ..write(obj.openedAt); } @override diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 57c7510..9b0495d 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -596,6 +596,29 @@ class CacheUtils { await box.put(key, value); } + /// Marks a stored message as opened by the receiver and drops its local + /// media: the one view is spent, so the bytes must not survive on any side. + /// A message that is not on this device is skipped. + static Future markMessageOpened( + String userId, DateTime sentAt, DateTime openedAt) async { + final box = await _openPrivateMessagesBox(); + final key = messageKey(userId, sentAt); + final value = box.get(key); + if (value is! PrivateMessage) { + return; + } + final paths = value.localPaths; + value.openedAt = openedAt; + value.localPath = null; + for (final item in value.album) { + item.localPath = null; + } + await box.put(key, value); + for (final path in paths) { + await MediaUtils.deleteLocalFile(path); + } + } + /// Sets or clears one participant's reaction on a stored message. static Future setMessageReaction( String userId, DateTime sentAt, String reactorId, String? emoji) async { diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index bfad490..8d8b922 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -148,7 +148,15 @@ class ChatSender { // Keep the reference (with its transport key) so the caption can be // edited later without the original upload. stored.mediaRefJson = jsonEncode(reference.toJson()); + // The sender never keeps the content of a view-once attachment: one + // open belongs to the recipient, so the local copy goes right away. + if (viewOnce) { + stored.localPath = null; + } }); + if (viewOnce) { + await MediaUtils.deleteLocalFile(localPath); + } return true; } catch (e) { Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 4c5d9ad..037e5f2 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -71,19 +71,22 @@ class MessageActions { } } - /// Burns a view-once attachment after its single open: the local copy goes, - /// and so does the server row, so the other side loses it too. + /// Spends the one view of a view-once attachment: the local copy goes, the + /// archive row stays as a tombstone and the server records the instant, so + /// the sender learns it too. The server call is best effort — a torn network + /// only costs the sender the signal, never the one-view rule. static Future consumeViewOnce( String conversationUserId, PrivateMessage message) async { final id = message.id; if (id != null && id.isNotEmpty) { try { - await Utils.callApi(() => Singleton().messagesApi.deleteMessage(id)); + await Utils.callApi(() => Singleton().messagesApi.openMessage(id)); } catch (_) { - // The server sweep drops the row at its ttl either way. + // The tombstone is local either way. } } - await CacheUtils.deletePrivateMessage(conversationUserId, message); + await CacheUtils.markMessageOpened( + conversationUserId, message.sentAt, DateTime.now()); MessageNotifier().notify(); } diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 6178bd6..e2db63a 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -490,12 +490,14 @@ class Utils { final peerOfMessage = {}; final idOfMessage = {}; final editedOfMessage = {}; + final openedOfMessage = {}; for (final message in messages) { final key = '${message.senderId}|${message.sentAt.toUtc().toIso8601String()}'; peerOfMessage[key] = message.peerId; idOfMessage[key] = message.id; editedOfMessage[key] = message.editedAt; + openedOfMessage[key] = message.openedAt; } for (final message in decryptedMessages) { final key = @@ -503,6 +505,7 @@ class Utils { // The archive id is what a delete on the server needs. message.id ??= idOfMessage[key]; message.editedAt ??= editedOfMessage[key]; + message.openedAt ??= openedOfMessage[key]?.toLocal(); final peer = peerOfMessage[key] ?? message.senderId; byPeer.putIfAbsent(peer, () => []).add(message); } @@ -625,6 +628,7 @@ class Utils { case WsResponseType.delete: case WsResponseType.reaction: case WsResponseType.pin: + case WsResponseType.open: await applyEvent(wsResponse.payload as MessageEvent); break; @@ -758,6 +762,11 @@ class Utils { await CacheUtils.setMessagePinned(event.peerId, event.messageId, event.pinned == true ? event.createdAt.toLocal() : null); break; + + case MessageEventKind.open: + await CacheUtils.markMessageOpened(event.peerId, event.sentAt, + (event.openedAt ?? event.createdAt).toLocal()); + break; } MessageNotifier().notify(); } @@ -812,6 +821,7 @@ class Utils { 'mac': message.mac, 'sentAt': message.sentAt.toIso8601String(), 'editedAt': message.editedAt?.toIso8601String(), + 'openedAt': message.openedAt?.toIso8601String(), 'recipientOnline': false, })) .toList(); diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 73f333a..5a87840 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -12,6 +12,7 @@ import '../models/private_message.dart'; import '../pages/media_viewer_page.dart'; import '../utils/media_utils.dart'; import '../utils/message_actions.dart'; +import '../utils/singleton.dart'; import 'voice_player.dart'; /// Renders a media attachment inside a chat bubble: image/gif thumbnail, video @@ -110,52 +111,63 @@ class _MediaBubbleState extends State { } /// A single-view attachment never shows a thumbnail: nobody sees it before - /// opening it, and the open happens exactly once. - Widget _viewOnceWidget(bool hasCaption) { + /// opening it, and the open happens exactly once. Its caption stays hidden + /// too, since it already shows inside the viewer once opened. An opened + /// attachment, and the sender's own copy, are read-only tombstones. + Widget _viewOnceWidget() { + final opened = widget.message.openedAt != null; + final mine = widget.message.isMe && + widget.conversationUserId != Singleton().profile.user.id; final ready = widget.message.localPath != null; - return Column( - crossAxisAlignment: CrossAxisAlignment.end, - mainAxisSize: MainAxisSize.min, - children: [ - InkWell( - onTap: () { - if (!ready) { - if (widget.canRetry) { - widget.onRetry(); - } - return; - } - _openViewOnce(); - }, - borderRadius: BorderRadius.circular(10), - child: Container( - width: 200, - padding: const EdgeInsets.all(16), - decoration: BoxDecoration( - color: widget.bubbleColor, - borderRadius: BorderRadius.circular(10), - ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(Icons.visibility_off, color: widget.textColor), - const SizedBox(height: 8), - Text( - ready ? 'viewOnceOpen'.tr() : 'viewOnceLoad'.tr(), - textAlign: TextAlign.center, - style: TextStyle(color: widget.textColor), - ), - ], - ), + + Widget frame(Widget child, {VoidCallback? onTap}) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(10), + child: Container( + width: 200, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: widget.bubbleColor, + borderRadius: BorderRadius.circular(10), ), - ), - if (hasCaption) - Padding( - padding: const EdgeInsets.only(top: 6), - child: Text(widget.message.message, - style: TextStyle(color: widget.textColor)), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.visibility_off, color: widget.textColor), + const SizedBox(height: 8), + child, + ], ), - ], + ), + ); + } + + Widget label(String text) => Text( + text, + textAlign: TextAlign.center, + style: TextStyle(color: widget.textColor), + ); + + if (mine) { + // The sender keeps no copy: one open is the recipient's, never theirs. + return frame( + label(opened ? 'viewOnceOpenedByPeer'.tr() : 'viewOnceSent'.tr())); + } + if (opened) { + return frame(label('viewOnceOpened'.tr())); + } + return frame( + label(ready ? 'viewOnceOpen'.tr() : 'viewOnceLoad'.tr()), + onTap: () { + if (!ready) { + if (widget.canRetry) { + widget.onRetry(); + } + return; + } + _openViewOnce(); + }, ); } @@ -207,7 +219,7 @@ class _MediaBubbleState extends State { final hasCaption = widget.message.message.isNotEmpty; if (widget.message.viewOnce) { - return _viewOnceWidget(hasCaption); + return _viewOnceWidget(); } if (widget.message.isAlbum) { diff --git a/lib/widgets/user_list_item.dart b/lib/widgets/user_list_item.dart index a201bf4..7271686 100644 --- a/lib/widgets/user_list_item.dart +++ b/lib/widgets/user_list_item.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import '../models/user.dart'; +import '../utils/presence.dart'; class UserListItem extends StatefulWidget { const UserListItem(this.user, this.onPressed, {super.key}); @@ -12,6 +13,25 @@ class UserListItem extends StatefulWidget { } class _UserListItemState extends State { + @override + void initState() { + super.initState(); + PresenceNotifier.instance.addListener(_onPresenceChanged); + } + + @override + void dispose() { + PresenceNotifier.instance.removeListener(_onPresenceChanged); + super.dispose(); + } + + /// Presence is ephemeral, so the row redraws on every change. + void _onPresenceChanged() { + if (mounted) { + setState(() {}); + } + } + @override Widget build(BuildContext context) { return ListTile( @@ -21,18 +41,41 @@ class _UserListItemState extends State { shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), - leading: CircleAvatar( - radius: 22, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 20, - color: widget.user.avatarTextColor, + leading: Stack( + clipBehavior: Clip.none, + children: [ + CircleAvatar( + radius: 22, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 20, + color: widget.user.avatarTextColor, + ), + ), ), - ), + // Same badge as the chat list: an absent dot means "not sharing". + if (PresenceNotifier.instance.isOnline(widget.user.id) == true) + Positioned( + right: 0, + bottom: 0, + child: Container( + width: 12, + height: 12, + decoration: BoxDecoration( + color: const Color(0xFF2E7D32), + shape: BoxShape.circle, + border: Border.all( + color: Theme.of(context).scaffoldBackgroundColor, + width: 2, + ), + ), + ), + ), + ], ), title: Text(widget.user.username), ); diff --git a/pubspec.yaml b/pubspec.yaml index 332b2b2..786084b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -42,7 +42,6 @@ dependencies: provider: ^6.1.2 qr_code_scanner_plus: ^2.0.6 record: ^7.1.2 - screen_protector: ^1.5.3 sprintf: ^7.0.0 url_launcher: ^6.3.1 uuid: ^4.5.3 @@ -53,11 +52,11 @@ dependencies: whisper_openapi_client_dart: git: url: https://github.com/jsfraz/whisper_openapi_client_dart.git - ref: v0.3.0 + ref: v0.4.0 whisper_websocket_client_dart: git: url: https://github.com/jsfraz/whisper_websocket_client_dart.git - ref: v0.4.0 + ref: v0.5.0 dev_dependencies: flutter_test: diff --git a/test/user_list_item_test.dart b/test/user_list_item_test.dart new file mode 100644 index 0000000..3f84ec1 --- /dev/null +++ b/test/user_list_item_test.dart @@ -0,0 +1,45 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/presence.dart'; +import 'package:whisper/widgets/user_list_item.dart'; + +Widget app() => MaterialApp( + home: Scaffold( + body: UserListItem(User('1', 'peer', 'key', false), () {}), + ), + ); + +/// The presence dot is the only green circle on the row. +final dot = find.byWidgetPredicate((widget) => + widget is Container && + widget.decoration is BoxDecoration && + (widget.decoration as BoxDecoration).color == const Color(0xFF2E7D32)); + +void main() { + final presence = PresenceNotifier.instance; + + setUp(() { + presence.clear(); + presence.presenceTtl = const Duration(milliseconds: 30); + }); + tearDown(presence.clear); + + testWidgets('a known online peer gets the badge', (tester) async { + await tester.pumpWidget(app()); + expect(dot, findsNothing); + + presence.applyPresence('1', online: true); + await tester.pump(); + expect(dot, findsOneWidget); + presence.clear(); + }); + + testWidgets('an offline peer has no badge and no unknown status', ( + tester, + ) async { + presence.applyPresence('1', online: false); + await tester.pumpWidget(app()); + expect(dot, findsNothing); + }); +} diff --git a/test/view_once_test.dart b/test/view_once_test.dart new file mode 100644 index 0000000..15f9280 --- /dev/null +++ b/test/view_once_test.dart @@ -0,0 +1,84 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/models/profile.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/singleton.dart'; +import 'package:whisper/widgets/media_bubble.dart'; + +Widget app(PrivateMessage message, {String peer = 'peer'}) => MaterialApp( + home: Scaffold( + body: MediaBubble( + message: message, + bubbleColor: Colors.grey, + textColor: Colors.black, + onRetry: () {}, + canRetry: false, + conversationUserId: peer, + ), + ), + ); + +PrivateMessage once({bool mine = false, DateTime? openedAt}) { + final at = DateTime(2026, 5, 1, 12); + return PrivateMessage( + mine ? 'me' : 'peer', + '', + at, + at, + true, + mediaTypeStr: 'image', + downloadStatus: MediaDownloadStatus.pending, + viewOnce: true, + openedAt: openedAt, + ); +} + +void main() { + setUp(() { + Singleton().profile = Profile('http://localhost', + User('me', 'me', 'key', false), 'key', 'private-key', '', '', true); + }); + + testWidgets('the receiver can still open an unopened attachment', ( + tester, + ) async { + await tester.pumpWidget(app(once())); + expect(find.text('viewOnceOpen'), findsNothing); + expect(find.text('viewOnceLoad'), findsOneWidget); + }); + + testWidgets('an opened attachment is a read-only tombstone', (tester) async { + await tester.pumpWidget(app(once(openedAt: DateTime(2026, 5, 1, 12, 5)))); + expect(find.text('viewOnceOpened'), findsOneWidget); + expect(find.text('viewOnceLoad'), findsNothing); + expect(tester.widget(find.byType(InkWell)).onTap, isNull); + }); + + testWidgets('the sender never gets a way to open its own attachment', ( + tester, + ) async { + await tester.pumpWidget(app(once(mine: true))); + expect(find.text('viewOnceSent'), findsOneWidget); + expect(find.text('viewOnceOpen'), findsNothing); + expect(find.text('viewOnceLoad'), findsNothing); + expect(tester.widget(find.byType(InkWell)).onTap, isNull); + }); + + testWidgets('the sender sees the opened state once the peer opened it', ( + tester, + ) async { + await tester.pumpWidget( + app(once(mine: true, openedAt: DateTime(2026, 5, 1, 12, 5)))); + expect(find.text('viewOnceOpenedByPeer'), findsOneWidget); + expect(tester.widget(find.byType(InkWell)).onTap, isNull); + }); + + testWidgets('the self-chat can still open its own attachment', ( + tester, + ) async { + await tester.pumpWidget(app(once(mine: true), peer: 'me')); + expect(find.text('viewOnceLoad'), findsOneWidget); + expect(tester.widget(find.byType(InkWell)).onTap, isNotNull); + }); +} From 9381942707e282d490a3173b0c5d5dfcf0934491 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 16:39:24 +0100 Subject: [PATCH 125/181] feat(app): block and detect screenshots through our own platform channel Replaces screen_protector with a whisper/secure_screen channel: Android sets FLAG_SECURE around the view-once viewer and reports a screenshot of any other screen from a MediaStore observer, while every other platform stays a no-op. Drops the dependency and the recording callback it fed. --- .../com/example/whisper/MainActivity.kt | 73 ++++++++++++++++++- lib/pages/home_page.dart | 15 +--- lib/pages/media_viewer_page.dart | 6 +- lib/utils/screen_guard.dart | 46 ++++++++++++ lib/utils/theme_utils.dart | 1 - pubspec.lock | 12 +-- 6 files changed, 127 insertions(+), 26 deletions(-) create mode 100644 lib/utils/screen_guard.dart diff --git a/android/app/src/main/kotlin/com/example/whisper/MainActivity.kt b/android/app/src/main/kotlin/com/example/whisper/MainActivity.kt index 585fe9a..9f2e64b 100644 --- a/android/app/src/main/kotlin/com/example/whisper/MainActivity.kt +++ b/android/app/src/main/kotlin/com/example/whisper/MainActivity.kt @@ -1,5 +1,76 @@ package cz.josefraz.whisper +import android.database.ContentObserver +import android.net.Uri +import android.os.Handler +import android.os.Looper +import android.provider.MediaStore +import android.view.WindowManager import io.flutter.embedding.android.FlutterFragmentActivity +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.MethodChannel -class MainActivity : FlutterFragmentActivity() +/** + * Hosts the app and the one piece of it that has to live in the platform: + * blocking screenshots of a view-once attachment and noticing ones taken of + * ordinary messages. Android is the only target with an enforceable block. + */ +class MainActivity : FlutterFragmentActivity() { + private var channel: MethodChannel? = null + + override fun configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + val methodChannel = + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "whisper/secure_screen") + channel = methodChannel + methodChannel.setMethodCallHandler { call, result -> + when (call.method) { + "enableSecure" -> { + window.addFlags(WindowManager.LayoutParams.FLAG_SECURE) + result.success(true) + } + "disableSecure" -> { + window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) + result.success(true) + } + else -> result.notImplemented() + } + } + watchScreenshots() + } + + /** The media store gains a row in Pictures/Screenshots when one is taken. */ + private fun watchScreenshots() { + val observer = object : ContentObserver(Handler(Looper.getMainLooper())) { + override fun onChange(selfChange: Boolean, uri: Uri?) { + super.onChange(selfChange, uri) + if (uri != null && isScreenshot(uri)) { + channel?.invokeMethod("onScreenshot", null) + } + } + } + contentResolver.registerContentObserver( + MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + true, + observer, + ) + } + + private fun isScreenshot(uri: Uri): Boolean { + return try { + contentResolver.query( + uri, + arrayOf(MediaStore.Images.Media.RELATIVE_PATH), + null, + null, + null, + )?.use { cursor -> + cursor.moveToFirst() && + (cursor.getString(0) ?: "").contains("Screenshot", ignoreCase = true) + } ?: false + } catch (_: Exception) { + // A provider that does not answer is not worth crashing over. + false + } + } +} diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index e651791..d3304eb 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -6,7 +6,6 @@ import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:screen_protector/screen_protector.dart'; import '../utils/nav_transitions.dart'; import 'package:sprintf/sprintf.dart'; import '../pages/chat_page.dart'; @@ -24,6 +23,7 @@ import 'package:whisper_openapi_client_dart/api.dart'; import '../models/user.dart'; import '../utils/admin_format.dart'; import '../utils/singleton.dart'; +import '../utils/screen_guard.dart'; import '../utils/utils.dart'; import '../widgets/admin_user_list_item.dart'; @@ -92,7 +92,8 @@ class _HomePageState extends State MessageNotifier().addListener(_onMessagesChanged); // A screenshot outside the view-once viewer is reported, not blocked: the // app cannot prevent it, and pretending otherwise would be a lie. - ScreenProtector.addListener(_onScreenshot, _onScreenRecord); + ScreenGuard.onScreenshot = _onScreenshot; + ScreenGuard.start(); // A pending FCM id is retried when the socket comes up instead of polling. Utils.onConnected = _sendPendingFid; // Open the chat a notification tap pointed at (after unlocking) @@ -144,14 +145,6 @@ class _HomePageState extends State msg: 'screenshotDetected'.tr(), backgroundColor: Colors.orange); } - void _onScreenRecord(bool recording) { - if (!recording) { - return; - } - Fluttertoast.showToast( - msg: 'screenshotDetected'.tr(), backgroundColor: Colors.orange); - } - /// Presence is announced when the app comes back and withdrawn when it goes /// away: the server keeps nothing, so a stale "online" would never clear. @override @override @@ -169,7 +162,7 @@ class _HomePageState extends State @override void dispose() { WidgetsBinding.instance.removeObserver(this); - ScreenProtector.removeListener(); + ScreenGuard.onScreenshot = null; _fcmSubscription?.cancel(); _adminTabController.dispose(); MessageNotifier().removeListener(_onMessagesChanged); diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index 4e21cf7..657f9e0 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -4,7 +4,6 @@ import 'dart:typed_data'; import 'package:chewie/chewie.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; -import 'package:screen_protector/screen_protector.dart'; import 'package:video_player/video_player.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; @@ -14,6 +13,7 @@ import '../utils/media_utils.dart'; import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; import '../utils/playback_lock.dart'; +import '../utils/screen_guard.dart'; /// Fullscreen viewer for the media of one conversation, stored /// encrypted-at-rest. Swiping moves between the attachments. @@ -56,7 +56,7 @@ class _MediaViewerPageState extends State { // The one allowed view may not be screenshotted or recorded. Android // enforces it with FLAG_SECURE; iOS has no block, only a best-effort // notification, which is why the app says so on the info screen. - ScreenProtector.preventScreenshotOn(); + ScreenGuard.enableSecure(); } _loadMedia(); } @@ -114,7 +114,7 @@ class _MediaViewerPageState extends State { @override void dispose() { if (widget.viewOnce) { - ScreenProtector.preventScreenshotOff(); + ScreenGuard.disableSecure(); } _controller?.dispose(); super.dispose(); diff --git a/lib/utils/screen_guard.dart b/lib/utils/screen_guard.dart new file mode 100644 index 0000000..063cb6d --- /dev/null +++ b/lib/utils/screen_guard.dart @@ -0,0 +1,46 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// The platform half of screenshot handling: blocking the screen of a view-once +/// attachment and reporting screenshots taken elsewhere. Android is the only +/// target where the block is enforceable, so on every other platform both calls +/// are a no-op. +class ScreenGuard { + static const MethodChannel _channel = MethodChannel('whisper/secure_screen'); + + /// Called when the platform noticed a screenshot. + static VoidCallback? onScreenshot; + + /// Wires the native callback once, at startup. + static Future start() async { + _channel.setMethodCallHandler((call) async { + if (call.method == 'onScreenshot') { + onScreenshot?.call(); + } + return null; + }); + } + + /// Makes the current window invisible to screenshots and recordings. + static Future enableSecure() async { + await _invoke('enableSecure'); + } + + /// Gives the screen back once the secure view is gone. + static Future disableSecure() async { + await _invoke('disableSecure'); + } + + static Future _invoke(String method) async { + if (defaultTargetPlatform != TargetPlatform.android) { + return; + } + try { + await _channel.invokeMethod(method); + } on MissingPluginException { + // A build without the native side still runs; it just cannot block. + } on PlatformException { + // Nothing to do: the block is a best effort on the platform side. + } + } +} diff --git a/lib/utils/theme_utils.dart b/lib/utils/theme_utils.dart index 6309b1c..6df5a22 100644 --- a/lib/utils/theme_utils.dart +++ b/lib/utils/theme_utils.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; - class ThemeUtils { /// Theme seeded with the per-chat color, or the inherited theme without an override. /// diff --git a/pubspec.lock b/pubspec.lock index d5743c7..7b967f4 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1420,14 +1420,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.2.3" - screen_protector: - dependency: "direct main" - description: - name: screen_protector - sha256: "66f2ffbfbe7acc26db49de893e0c49078c67b546c27a57958d9bd9901f77c38e" - url: "https://pub.dev" - source: hosted - version: "1.5.3" shared_preferences: dependency: transitive description: @@ -1839,14 +1831,14 @@ packages: path: "../whisper_openapi_client_dart" relative: true source: path - version: "0.3.0" + version: "0.4.0" whisper_websocket_client_dart: dependency: "direct main" description: path: "../whisper_websocket_client_dart" relative: true source: path - version: "0.4.0" + version: "0.5.0" win32: dependency: transitive description: From cb751d28504f1275fe03eb0b0e67bbfc5ad84f55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 17:12:00 +0100 Subject: [PATCH 126/181] feat(app): view-once albums, files and locations, and tombstones for deleted messages A single view is now offered for any picked attachment (album included), for a document, and for a static location; the album carries the flag in its envelope and the location in its text envelope, both staying readable by older clients. An album keeps its copies per item, so its ready/retry state is decided from the items, and a missing reference is rebuilt from the stored row after a restart. Deleting for everyone no longer drops the bubble: the content and local media go and a 'message deleted' tombstone stays where the message was, on both sides. --- assets/translations/cs.json | 5 +- assets/translations/en.json | 5 +- lib/models/private_message.dart | 13 ++++ lib/models/private_message.g.dart | 7 +- lib/pages/chat_page.dart | 81 +++++++++++--------- lib/pages/media_viewer_page.dart | 8 +- lib/utils/cache_utils.dart | 36 +++++++++ lib/utils/chat_sender.dart | 30 ++++++-- lib/utils/media_utils.dart | 11 +-- lib/utils/message_actions.dart | 28 ++++++- lib/utils/message_notifier.dart | 54 ++++++++++++++ lib/utils/text_envelope.dart | 10 ++- lib/utils/utils.dart | 18 +++-- lib/widgets/attachment_confirm_sheet.dart | 55 ++++++++++++-- lib/widgets/chat_bubble.dart | 87 ++++++++++++++++++++-- lib/widgets/media_bubble.dart | 55 +++++--------- lib/widgets/view_once_frame.dart | 47 ++++++++++++ test/attachment_confirm_sheet_test.dart | 62 +++++++++++---- test/delete_message_test.dart | 22 ++++++ test/deleted_bubble_test.dart | 59 +++++++++++++++ test/media_album_test.dart | 11 +++ test/text_envelope_test.dart | 12 +++ test/view_once_location_test.dart | 91 +++++++++++++++++++++++ test/view_once_test.dart | 27 +++++++ 24 files changed, 706 insertions(+), 128 deletions(-) create mode 100644 lib/widgets/view_once_frame.dart create mode 100644 test/deleted_bubble_test.dart create mode 100644 test/view_once_location_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 7e62844..1d370da 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -274,7 +274,6 @@ "disappearingEnabledPill": "Mizející zprávy: {}", "disappearingDeclinedPill": "Návrh mizejících zpráv odmítnut", "attachViewOnce": "Zobrazit jednou", - "viewOnceOneFile": "Jednorázově lze poslat jen jednu přílohu", "viewOnceOpen": "Klepnutím zobrazit jednou", "viewOnceLoad": "Klepnutím stáhnout", "viewOnceMedia": "Jednorázová příloha", @@ -291,5 +290,7 @@ "locationUnavailable": "Poloha není dostupná", "viewOnceSent": "Jednorázová příloha odeslána", "viewOnceOpened": "Zobrazeno", - "viewOnceOpenedByPeer": "Otevřeno" + "viewOnceOpenedByPeer": "Otevřeno", + "messageDeleted": "Zpráva byla smazána", + "viewOnceHint": "Po prvním otevření zmizí oběma stranám" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 3f1fba4..e31fd95 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -274,7 +274,6 @@ "disappearingEnabledPill": "Disappearing messages: {}", "disappearingDeclinedPill": "Disappearing messages proposal declined", "attachViewOnce": "View once", - "viewOnceOneFile": "Only one attachment can be view-once", "viewOnceOpen": "Tap to view once", "viewOnceLoad": "Tap to download", "viewOnceMedia": "View-once attachment", @@ -291,5 +290,7 @@ "locationUnavailable": "Location is not available", "viewOnceSent": "View-once attachment sent", "viewOnceOpened": "Opened", - "viewOnceOpenedByPeer": "Opened" + "viewOnceOpenedByPeer": "Opened", + "messageDeleted": "Message deleted", + "viewOnceHint": "Gone for both sides after it is opened once" } diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index dd0685b..5515180 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -239,6 +239,11 @@ class PrivateMessage extends HiveObject { @HiveField(29) DateTime? openedAt; + /// When the sender deleted this message for everyone. The row stays as a + /// tombstone in the conversation, with no content left. + @HiveField(30) + DateTime? deletedAt; + /// Cache for [album], keyed by the [albumJson] it was decoded from. String? _albumCacheJson; List? _albumCache; @@ -273,6 +278,7 @@ class PrivateMessage extends HiveObject { this.viewOnce = false, this.locationJson, this.openedAt, + this.deletedAt, }); /// The static location carried by this message, null for everything else. @@ -371,6 +377,10 @@ class PrivateMessage extends HiveObject { /// Whether the stored text is the placeholder of an undecryptable message. bool get isUndecryptable => message == undecryptableMarker; + /// Whether the sender deleted this message for everyone: the row stays as a + /// tombstone and carries nothing. + bool get isDeleted => deletedAt != null; + int get notificationId => receivedAt.microsecondsSinceEpoch % 0x7FFFFFFF; /// Whether this message carries a media attachment (single or album). @@ -448,6 +458,9 @@ class PrivateMessage extends HiveObject { /// Short text used in chat list previews and notifications. Falls back to a /// localized media label when a media message has no caption. String get preview { + if (isDeleted) { + return 'messageDeleted'.tr(); + } if (isUndecryptable) { return 'messageUndecryptable'.tr(); } diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index 6646858..b0483ed 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -46,13 +46,14 @@ class PrivateMessageAdapter extends TypeAdapter { viewOnce: fields[27] == null ? false : fields[27] as bool, locationJson: fields[28] as String?, openedAt: fields[29] as DateTime?, + deletedAt: fields[30] as DateTime?, )..id = fields[19] as String?; } @override void write(BinaryWriter writer, PrivateMessage obj) { writer - ..writeByte(30) + ..writeByte(31) ..writeByte(0) ..write(obj.senderId) ..writeByte(1) @@ -112,7 +113,9 @@ class PrivateMessageAdapter extends TypeAdapter { ..writeByte(28) ..write(obj.locationJson) ..writeByte(29) - ..write(obj.openedAt); + ..write(obj.openedAt) + ..writeByte(30) + ..write(obj.deletedAt); } @override diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index e482e94..eb46936 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -851,7 +851,8 @@ class _ChatPageState extends State { } /// Send several attachments as one album message. - Future _sendAlbum(List files, {String caption = ''}) async { + Future _sendAlbum(List files, + {String caption = '', bool viewOnce = false}) async { setState(() { _isSending = true; }); @@ -871,7 +872,7 @@ class _ChatPageState extends State { )); } final sent = await ChatSender.sendAlbum(widget.user, attachments, - caption: caption); + caption: caption, viewOnce: viewOnce); _afterSend(sent, caption); } catch (e) { await Fluttertoast.showToast( @@ -915,21 +916,13 @@ class _ChatPageState extends State { /// [forcedType] fixes the type for camera picks; [filesOnly] rejects photos /// and videos (the "File" entry must stay a document picker). Future _pickAndSend(Future> Function() picker, - {MediaType? forcedType, - bool filesOnly = false, - bool viewOnce = false}) async { + {MediaType? forcedType, bool filesOnly = false}) async { try { final picked = await picker(); if (picked.isEmpty) { return; } var files = picked; - if (viewOnce && files.length > 1) { - // One view, one attachment: a single-view album cannot be honest. - files = [files.first]; - await Fluttertoast.showToast( - msg: 'viewOnceOneFile'.tr(), backgroundColor: Colors.orange); - } if (filesOnly) { files = picked.where((file) => !MediaUtils.isVisualMedia(file)).toList(); @@ -953,16 +946,22 @@ class _ChatPageState extends State { } } - final caption = await _confirmAttachment(files.length); - if (caption == null) { + final single = files.length == 1; + final type = + single ? forcedType ?? MediaUtils.detectType(files.first.path) : null; + // Any picked attachment can travel as a single view: one visual file, a + // gallery album or a plain document all burn the same way. + final confirmed = + await _confirmAttachment(files.length, allowViewOnce: true); + if (confirmed == null) { return; } - if (files.length == 1) { - final type = forcedType ?? MediaUtils.detectType(files.first.path); - await _sendMedia(type, files.first, - caption: caption, viewOnce: viewOnce); + if (single) { + await _sendMedia(type!, files.first, + caption: confirmed.caption, viewOnce: confirmed.viewOnce); } else { - await _sendAlbum(files, caption: caption); + await _sendAlbum(files, + caption: confirmed.caption, viewOnce: confirmed.viewOnce); } } catch (e) { await Fluttertoast.showToast( @@ -973,6 +972,30 @@ class _ChatPageState extends State { /// Sends one fix as a location message. No coordinates are read until the /// user picks this action, and they travel only inside the ciphertext. Future _sendCurrentLocation() async { + // A location is a message of its own, so the single view is a choice made + // here rather than in an attachment sheet. + final viewOnce = await showDialog( + context: context, + builder: (ctx) => SimpleDialog( + title: Text('attachLocation'.tr()), + children: [ + ListTile( + leading: const Icon(Icons.place), + title: Text('attachLocation'.tr()), + onTap: () => Navigator.pop(ctx, false), + ), + ListTile( + leading: const Icon(Icons.visibility_off), + title: Text('attachViewOnce'.tr()), + subtitle: Text('viewOnceHint'.tr()), + onTap: () => Navigator.pop(ctx, true), + ), + ], + ), + ); + if (viewOnce == null || !mounted) { + return; + } setState(() => _isSending = true); try { final position = await LiveLocationSharer.currentPosition(); @@ -983,7 +1006,7 @@ class _ChatPageState extends State { } final sent = await ChatSender.sendLocation( widget.user, position.latitude, position.longitude, - accuracy: position.accuracy); + accuracy: position.accuracy, viewOnce: viewOnce); _afterSend(sent, ''); } catch (e) { await Fluttertoast.showToast( @@ -1021,11 +1044,14 @@ class _ChatPageState extends State { } } - /// Bottom sheet with a caption field; returns the caption, or null to cancel. - Future _confirmAttachment(int count) { + /// Bottom sheet with a caption field; returns the caption and the view-once + /// choice, or null to cancel. + Future _confirmAttachment(int count, + {bool allowViewOnce = false}) { return AttachmentConfirmSheet.show( context, count: count, + allowViewOnce: allowViewOnce, initialCaption: _controllerMessage.text.trim(), theme: ThemeUtils.chatTheme(context, _chatThemeColor), backgroundColor: chatBackground(tintAlpha: 0.18), @@ -1093,19 +1119,6 @@ class _ChatPageState extends State { _pickAndSend(MediaUtils.pickMultipleFiles, filesOnly: true); }, ), - ListTile( - leading: const Icon(Icons.visibility_off), - title: Text('attachViewOnce'.tr()), - onTap: () { - Navigator.pop(ctx); - // One photo or video, gone for both sides after the first - // open; the picker stays the same. - _pickAndSend(() async { - final file = await MediaUtils.pickMediaFromGallery(); - return file == null ? [] : [file]; - }, viewOnce: true); - }, - ), ListTile( leading: const Icon(Icons.place), title: Text('attachLocation'.tr()), diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index 657f9e0..de16848 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -65,9 +65,13 @@ class _MediaViewerPageState extends State { /// at the one that was tapped. Future _loadMedia() async { if (widget.viewOnce) { - // One attachment, one page: swiping to the next would be a second view. + // One attachment, one reveal: an album is one reveal of all its pages, + // and swiping past them is still that single open. + final pages = widget.message.isAlbum + ? MessageNotifier.albumMedia(widget.message) + : [widget.message]; setState(() { - _media = [widget.message]; + _media = pages; _index = 0; _controller = PageController(initialPage: 0); }); diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 9b0495d..0e96648 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -610,6 +610,9 @@ class CacheUtils { final paths = value.localPaths; value.openedAt = openedAt; value.localPath = null; + // A spent location leaves nothing behind either; the bubble reads the + // opened instant, not the coordinates. + value.locationJson = null; for (final item in value.album) { item.localPath = null; } @@ -619,6 +622,39 @@ class CacheUtils { } } + /// Marks a stored message as deleted for everyone and drops its content: the + /// text, the media reference and the local file all go, the row stays so the + /// chat keeps a tombstone where the bubble used to be. A message that is not + /// on this device is skipped. + static Future markMessageDeleted( + String userId, DateTime sentAt, DateTime deletedAt) async { + final box = await _openPrivateMessagesBox(); + final key = messageKey(userId, sentAt); + final value = box.get(key); + if (value is! PrivateMessage) { + return; + } + final paths = value.localPaths; + value + ..deletedAt = deletedAt + ..message = '' + ..mediaId = null + ..mediaTypeStr = null + ..albumJson = null + ..mediaRefJson = null + ..localPath = null + ..viewOnce = false + ..openedAt = null + ..reactions = null + ..locationJson = null + // Nothing is left to read, so a tombstone must not raise an unread badge. + ..read = true; + await box.put(key, value); + for (final path in paths) { + await MediaUtils.deleteLocalFile(path); + } + } + /// Sets or clears one participant's reaction on a stored message. static Future setMessageReaction( String userId, DateTime sentAt, String reactorId, String? emoji) async { diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index 8d8b922..9a4c61e 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -168,7 +168,9 @@ class ChatSender { /// envelope carrying all references, one WebSocket message. static Future sendAlbum( User recipient, List attachments, - {String caption = '', bool forwarded = false}) async { + {String caption = '', + bool forwarded = false, + bool viewOnce = false}) async { if (attachments.isEmpty) { return false; } @@ -185,6 +187,8 @@ class ChatSender { localPaths.add(await MediaUtils.encryptAtRest(attachment.bytes)); } final now = DateTime.now(); + // A view-once album follows the same one-day life as a single attachment. + final ttl = viewOnce ? viewOnceTtlSeconds : await _ttlFor(recipient); final message = PrivateMessage( Singleton().profile.user.id, caption, @@ -194,6 +198,8 @@ class ChatSender { downloadStatus: MediaDownloadStatus.ready, sendStatus: SendStatus.sending, forwarded: forwarded, + viewOnce: viewOnce, + expiresAt: ttl > 0 ? now.add(Duration(seconds: ttl)) : null, ); message.setAlbum([ for (var i = 0; i < attachments.length; i++) @@ -236,16 +242,25 @@ class ChatSender { _outgoingReferences[CacheUtils.messageKey(recipient.id, message.sentAt)] = references; final envelope = MediaUtils.buildAlbumEnvelope(references, caption, - forwarded: forwarded); - await _sendEnvelope(recipient, envelope, message.sentAt); + forwarded: forwarded, viewOnce: viewOnce); + await _sendEnvelope(recipient, envelope, message.sentAt, ttlSeconds: ttl); await CacheUtils.updateStoredMessage(recipient.id, message, (stored) { final items = stored.album; for (var i = 0; i < items.length && i < references.length; i++) { items[i].mediaId = references[i].mediaId; items[i].keyB64 = base64Encode(references[i].key); + // A view-once album keeps no copy on the sending side. + if (viewOnce) { + items[i].localPath = null; + } } stored.setAlbum(items); }); + if (viewOnce) { + for (final path in localPaths) { + await MediaUtils.deleteLocalFile(path); + } + } return true; } catch (e) { Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); @@ -525,14 +540,15 @@ class ChatSender { /// Sends a static location: an ordinary text message whose envelope also /// carries the coordinates. The server sees only the ciphertext. static Future sendLocation(User recipient, double lat, double lng, - {double? accuracy, String? label}) async { + {double? accuracy, String? label, bool viewOnce = false}) async { final now = DateTime.now(); - final ttl = await _ttlFor(recipient); + final ttl = viewOnce ? viewOnceTtlSeconds : await _ttlFor(recipient); final location = LocationRef(lat, lng, accuracy: accuracy, label: label); final message = PrivateMessage( Singleton().profile.user.id, location.body, now, now, true, sendStatus: SendStatus.sending, locationJson: jsonEncode(location.toJson()), + viewOnce: viewOnce, expiresAt: ttl > 0 ? now.add(Duration(seconds: ttl)) : null); try { await _persist(recipient, [message]); @@ -541,8 +557,8 @@ class ChatSender { } await _sendText(recipient, message, ttl: ttl, - plaintextOverride: - buildTextEnvelope(location.body, null, location: location)); + plaintextOverride: buildTextEnvelope(location.body, null, + location: location, viewOnce: viewOnce)); return true; } catch (e) { Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 7f71a5a..bcd991e 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -566,13 +566,14 @@ class MediaUtils { /// envelope wrapping [references] and an optional [caption]. static Uint8List buildAlbumEnvelope( List references, String caption, - {bool forwarded = false}) { + {bool forwarded = false, bool viewOnce = false}) { final map = { 'whisperMsg': envelopeVersionAlbum, 'kind': 'media', 'caption': caption, 'media': references.map((reference) => reference.toJson()).toList(), if (forwarded) 'forwarded': true, + if (viewOnce) 'viewOnce': true, }; return Uint8List.fromList(utf8.encode(jsonEncode(map))); } @@ -602,7 +603,7 @@ class MediaUtils { .toList(); if (references.isNotEmpty) { return ParsedMediaEnvelope(references, caption, - forwarded: forwarded); + forwarded: forwarded, viewOnce: viewOnce); } } } @@ -630,12 +631,6 @@ class MediaUtils { return picked == null ? null : File(picked.path); } - /// Pick a single image or video from the gallery. - static Future pickMediaFromGallery() async { - final picked = await _imagePicker.pickMedia(); - return picked == null ? null : File(picked.path); - } - /// Pick an arbitrary file (images, videos, documents, ...). static Future pickFile() async { final picked = await FilePicker.pickFile(type: FileType.any); diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 037e5f2..73f89d1 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -198,6 +198,25 @@ class MessageActions { builder: (ctx) { final canAddress = message.id?.isNotEmpty ?? false; // needs the archive id + // A tombstone carries nothing to act on; hiding it for this account is + // the only thing left. + if (message.isDeleted) { + return SafeArea( + child: Wrap( + children: [ + ListTile( + leading: const Icon(deleteIcon), + title: Text('deleteMessageForMe'.tr()), + onTap: () { + Navigator.pop(ctx); + delete(context, message, conversationUserId, + onDeleted: onDeleted); + }, + ), + ], + ), + ); + } return SafeArea( child: Wrap( children: [ @@ -512,7 +531,14 @@ class MessageActions { backgroundColor: Colors.red); return; } - await CacheUtils.deletePrivateMessage(conversationUserId, message); + if (forEveryone) { + // The row stays as a tombstone: the conversation keeps the place where + // the message was instead of closing the gap. + await CacheUtils.markMessageDeleted( + conversationUserId, message.sentAt, DateTime.now()); + } else { + await CacheUtils.deletePrivateMessage(conversationUserId, message); + } MessageNotifier().notify(); onDeleted?.call(); } diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index f601b02..42c8608 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -1,3 +1,5 @@ +import 'dart:convert'; + import 'package:flutter/material.dart'; import 'package:whisper_openapi_client_dart/api.dart'; import 'package:whisper_openapi_client_dart/media_download.dart'; @@ -156,6 +158,58 @@ class MessageNotifier extends ChangeNotifier { /// Whether a failed media download can be retried this session. bool canRetryMedia(String mediaId) => _pendingMediaRefs.containsKey(mediaId); + /// Fetches an attachment whose reference is no longer in memory (after a + /// restart) from what the stored row kept: a single message holds the media + /// envelope, an album item holds its own key. + Future downloadFromStored( + String conversationUserId, PrivateMessage message, String mediaId) async { + final reference = _storedReference(message, mediaId); + if (reference == null) { + return; + } + await CacheUtils.updatePrivateMessageMedia( + conversationUserId, + mediaId, + downloadStatus: MediaDownloadStatus.pending, + ); + notifyListeners(); + await downloadMediaMessage(conversationUserId, reference); + } + + /// Rebuilds one attachment reference from the stored message, null when the + /// row does not carry it (an old build, or a foreign media id). + MediaReference? _storedReference(PrivateMessage message, String mediaId) { + for (final item in message.album) { + if (item.mediaId != mediaId || item.keyB64 == null) { + continue; + } + return MediaReference( + item.mediaId, + base64Decode(item.keyB64!), + MediaType.values.byName(item.type), + item.size, + width: item.width, + height: item.height, + durationMs: item.durationMs, + fileName: item.fileName, + ); + } + final raw = message.mediaRefJson; + if (raw == null || raw.isEmpty) { + return null; + } + try { + final decoded = + MediaReference.fromJson(jsonDecode(raw) as Map); + if (decoded.mediaId == mediaId) { + return decoded; + } + } catch (_) { + // A reference this build cannot read: nothing to retry. + } + return null; + } + /// Add messages to cache Future addMessages(String userId, List messages) async { // Check if users exist diff --git a/lib/utils/text_envelope.dart b/lib/utils/text_envelope.dart index 9255b16..84abeb7 100644 --- a/lib/utils/text_envelope.dart +++ b/lib/utils/text_envelope.dart @@ -54,7 +54,7 @@ class ReplyRef { /// Payload of a text message that quotes another one. class ParsedTextEnvelope { const ParsedTextEnvelope(this.body, this.reply, - {this.forwarded = false, this.location}); + {this.forwarded = false, this.location, this.viewOnce = false}); final String body; final ReplyRef? reply; @@ -64,6 +64,10 @@ class ParsedTextEnvelope { /// A static location, null for an ordinary text message. final LocationRef? location; + + /// A single-view message: the body is revealed once and then burnt. Only a + /// location uses it; an attachment carries the flag in its media envelope. + final bool viewOnce; } /// A static location inside a text envelope. It stays a `text` message with an @@ -112,7 +116,7 @@ const int textEnvelopeVersion = 3; /// The envelope stays version 3 and the flags are optional keys, so a reader /// that predates them still shows the body instead of raw JSON. Uint8List buildTextEnvelope(String body, ReplyRef? reply, - {bool forwarded = false, LocationRef? location}) { + {bool forwarded = false, LocationRef? location, bool viewOnce = false}) { final map = { 'whisperMsg': textEnvelopeVersion, 'kind': 'text', @@ -120,6 +124,7 @@ Uint8List buildTextEnvelope(String body, ReplyRef? reply, if (reply != null) 'replyTo': reply.toJson(), if (forwarded) 'forwarded': true, if (location != null) 'location': location.toJson(), + if (viewOnce) 'viewOnce': true, }; return Uint8List.fromList(utf8.encode(jsonEncode(map))); } @@ -141,6 +146,7 @@ ParsedTextEnvelope? tryParseTextEnvelope(Uint8List plaintext) { ReplyRef.fromJson(decoded['replyTo']), forwarded: decoded['forwarded'] == true, location: LocationRef.fromJson(decoded['location']), + viewOnce: decoded['viewOnce'] == true, ); } } catch (_) { diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index e2db63a..de01e69 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -348,6 +348,7 @@ class Utils { false, downloadStatus: pm.MediaDownloadStatus.pending, forwarded: envelope.forwarded, + viewOnce: envelope.viewOnce, expiresAt: expiresAt, ); albumMsg.setAlbum(envelope.references @@ -414,6 +415,7 @@ class Utils { DateTime.now(), false, forwarded: textEnvelope?.forwarded ?? false, + viewOnce: textEnvelope?.viewOnce ?? false, locationJson: textEnvelope?.location == null ? null : jsonEncode(textEnvelope!.location!.toJson()), @@ -586,11 +588,12 @@ class Utils { await CacheUtils.addUser( User(peer.id, peer.username, peer.publicKey, false)); } - // A tombstone carries no ciphertext: drop the local copy instead of - // storing an undecryptable placeholder. + // A tombstone carries no ciphertext: keep the row as the "deleted" + // placeholder instead of storing an undecryptable bubble. for (final dead in synced.messages.where((message) => message.deletedAt != null)) { - await CacheUtils.deletePrivateMessageAt(dead.peerId, dead.sentAt); + await CacheUtils.markMessageDeleted( + dead.peerId, dead.sentAt, dead.deletedAt!.toLocal()); } if (synced.messages.isNotEmpty) { // History is silent: a week offline must not ring once per old @@ -722,7 +725,8 @@ class Utils { static Future applyEvent(MessageEvent event) async { switch (event.kind) { case MessageEventKind.delete: - await CacheUtils.deletePrivateMessageAt(event.peerId, event.sentAt); + await CacheUtils.markMessageDeleted( + event.peerId, event.sentAt, event.createdAt.toLocal()); await CacheUtils.setMessagePinned(event.peerId, event.messageId, null); break; @@ -801,9 +805,11 @@ class Utils { return; } // A tombstone carries no ciphertext (the sender deleted it for everyone): - // drop the local copy instead of storing an undecryptable placeholder. + // keep the row as the "deleted" placeholder instead of an undecryptable + // bubble. The content is already gone, so only the marker is stored. for (final dead in messages.where((message) => message.deletedAt != null)) { - await CacheUtils.deletePrivateMessageAt(dead.peerId, dead.sentAt); + await CacheUtils.markMessageDeleted( + dead.peerId, dead.sentAt, dead.deletedAt!.toLocal()); } messages = messages.where((message) => message.deletedAt == null).toList(); if (messages.isEmpty) { diff --git a/lib/widgets/attachment_confirm_sheet.dart b/lib/widgets/attachment_confirm_sheet.dart index bc23318..8823d5f 100644 --- a/lib/widgets/attachment_confirm_sheet.dart +++ b/lib/widgets/attachment_confirm_sheet.dart @@ -1,30 +1,47 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; -/// Sheet shown after picking an attachment: an optional caption and a -/// Send/Cancel decision. Owns its [TextEditingController], because the sheet -/// route keeps rebuilding while it animates out. +/// What the sender chose in [AttachmentConfirmSheet]: the caption, and whether +/// the attachment travels as a view-once one. +class AttachmentConfirmResult { + const AttachmentConfirmResult({required this.caption, this.viewOnce = false}); + + final String caption; + final bool viewOnce; +} + +/// Sheet shown after picking an attachment: an optional caption, an optional +/// "view once" switch and a Send/Cancel decision. Owns its +/// [TextEditingController], because the sheet route keeps rebuilding while it +/// animates out. class AttachmentConfirmSheet extends StatefulWidget { /// Number of picked attachments; more than one means an album. final int count; final String initialCaption; + /// Whether the picked attachment may be sent as a single view (one visual + /// attachment, never an album or a file). + final bool allowViewOnce; + const AttachmentConfirmSheet({ required this.count, this.initialCaption = '', + this.allowViewOnce = false, super.key, }); - /// Shows the sheet and returns the caption, or null when cancelled. + /// Shows the sheet and returns the chosen caption and flags, or null when + /// cancelled. /// /// [theme] and [backgroundColor] come from the caller: a modal route renders /// above the chat's own Theme, so without them the sheet uses the app theme. - static Future show(BuildContext context, + static Future show(BuildContext context, {required int count, String initialCaption = '', + bool allowViewOnce = false, ThemeData? theme, Color? backgroundColor}) { - return showModalBottomSheet( + return showModalBottomSheet( context: context, showDragHandle: true, isScrollControlled: true, @@ -33,6 +50,7 @@ class AttachmentConfirmSheet extends StatefulWidget { final sheet = AttachmentConfirmSheet( count: count, initialCaption: initialCaption, + allowViewOnce: allowViewOnce, ); return theme == null ? sheet : Theme(data: theme, child: sheet); }, @@ -46,6 +64,16 @@ class AttachmentConfirmSheet extends StatefulWidget { class _AttachmentConfirmSheetState extends State { late final TextEditingController _controller = TextEditingController(text: widget.initialCaption); + bool _viewOnce = false; + + void _send() { + Navigator.pop( + context, + AttachmentConfirmResult( + caption: _controller.text.trim(), + viewOnce: _viewOnce, + )); + } @override void dispose() { @@ -79,6 +107,18 @@ class _AttachmentConfirmSheetState extends State { autofocus: true, decoration: InputDecoration(hintText: 'addCaption'.tr()), ), + // One visual attachment can be turned into a single view right here, + // instead of being a separate entry in the attach sheet. + if (widget.allowViewOnce) + CheckboxListTile( + value: _viewOnce, + onChanged: (value) => setState(() => _viewOnce = value ?? false), + controlAffinity: ListTileControlAffinity.leading, + contentPadding: EdgeInsets.zero, + secondary: const Icon(Icons.visibility_off), + title: Text('attachViewOnce'.tr()), + subtitle: Text('viewOnceHint'.tr()), + ), const SizedBox(height: 12), Row( mainAxisAlignment: MainAxisAlignment.end, @@ -89,8 +129,7 @@ class _AttachmentConfirmSheetState extends State { ), const SizedBox(width: 8), FilledButton( - onPressed: () => - Navigator.pop(context, _controller.text.trim()), + onPressed: _send, child: Text('send'.tr()), ), ], diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 7693c5a..53c3118 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -10,6 +10,7 @@ import '../utils/message_notifier.dart'; import '../utils/singleton.dart'; import 'formatted_text.dart'; import 'media_bubble.dart'; +import 'view_once_frame.dart'; /// One message bubble. /// @@ -167,6 +168,38 @@ class _ChatBubbleState extends State { ); } + /// A view-once location: one reveal, then a tombstone. The reveal is the + /// platform map app, and it spends the single view on the way out. + Widget _viewOnceMessage(BuildContext context, LocationRef? location) { + final opened = widget.message.openedAt != null; + final mine = + widget.message.isMe && widget.user.id != Singleton().profile.user.id; + final bubbleColor = widget.accentColor; + final textColor = + bubbleColor.computeLuminance() > 0.5 ? Colors.black : Colors.white; + return Align( + alignment: + widget.message.isMe ? Alignment.centerRight : Alignment.centerLeft, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 8), + child: ViewOnceFrame( + label: mine + ? (opened ? 'viewOnceOpenedByPeer'.tr() : 'viewOnceSent'.tr()) + : (opened ? 'viewOnceOpened'.tr() : 'viewOnceOpen'.tr()), + bubbleColor: bubbleColor, + textColor: textColor, + onTap: mine || opened || location == null + ? null + : () async { + await MessageActions.openLocation(location); + await MessageActions.consumeViewOnce( + widget.user.id, widget.message); + }, + ), + ), + ); + } + /// A static location: a pin, the coordinates and a way into the platform map /// app. No tiles are fetched, so nothing leaves the device until the tap. Widget _locationBubble(BuildContext context, LocationRef location) { @@ -228,8 +261,13 @@ class _ChatBubbleState extends State { if (widget.message.isSystem) { return _systemPill(context); } - // A static location is a card, not text with a pin in it. + // A static location is a card, not text with a pin in it. A view-once + // location is the same card, but revealed once: a placeholder first, a + // tombstone after. final location = widget.message.location; + if (widget.message.viewOnce && !widget.message.isMedia) { + return _viewOnceMessage(context, location); + } if (location != null) { return _locationBubble(context, location); } @@ -328,7 +366,8 @@ class _ChatBubbleState extends State { } Widget content() { - if (widget.message.isMedia) { + // A tombstone is text even when it used to be an attachment. + if (widget.message.isMedia && !widget.message.isDeleted) { return MediaBubble( message: widget.message, badge: widget.message.reactionEmojis.isEmpty @@ -340,18 +379,54 @@ class _ChatBubbleState extends State { conversationUserId: widget.user.id, bubbleColor: bubbleBackground(), textColor: bubbleTextColor(), - canRetry: widget.message.mediaId != null && - MessageNotifier().canRetryMedia(widget.message.mediaId!), + // An album keeps its copies per item, so the retry has to walk them + // rather than look at the message's own media id. + canRetry: widget.message.isAlbum + ? widget.message.album.any((item) => + item.mediaId.isNotEmpty && + item.localPath == null && + (MessageNotifier().canRetryMedia(item.mediaId) || + item.keyB64 != null)) + : widget.message.mediaId != null && + (MessageNotifier().canRetryMedia(widget.message.mediaId!) || + widget.message.mediaRefJson != null), onRetry: () { - if (widget.message.mediaId != null) { + if (widget.message.isAlbum) { + for (final item in widget.message.album) { + if (item.mediaId.isEmpty || item.localPath != null) { + continue; + } + if (MessageNotifier().canRetryMedia(item.mediaId)) { + MessageNotifier() + .retryMediaDownload(widget.user.id, item.mediaId); + } else { + MessageNotifier().downloadFromStored( + widget.user.id, widget.message, item.mediaId); + } + } + return; + } + final mediaId = widget.message.mediaId; + if (mediaId == null) { + return; + } + if (MessageNotifier().canRetryMedia(mediaId)) { + MessageNotifier().retryMediaDownload(widget.user.id, mediaId); + } else { MessageNotifier() - .retryMediaDownload(widget.user.id, widget.message.mediaId!); + .downloadFromStored(widget.user.id, widget.message, mediaId); } }, ); } final color = bubbleTextColor(); + if (widget.message.isDeleted) { + return Text( + 'messageDeleted'.tr(), + style: TextStyle(color: color, fontStyle: FontStyle.italic), + ); + } if (widget.message.isUndecryptable) { return Text( 'messageUndecryptable'.tr(), diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 5a87840..efe53ff 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -13,6 +13,7 @@ import '../pages/media_viewer_page.dart'; import '../utils/media_utils.dart'; import '../utils/message_actions.dart'; import '../utils/singleton.dart'; +import 'view_once_frame.dart'; import 'voice_player.dart'; /// Renders a media attachment inside a chat bubble: image/gif thumbnail, video @@ -118,47 +119,31 @@ class _MediaBubbleState extends State { final opened = widget.message.openedAt != null; final mine = widget.message.isMe && widget.conversationUserId != Singleton().profile.user.id; - final ready = widget.message.localPath != null; - - Widget frame(Widget child, {VoidCallback? onTap}) { - return InkWell( - onTap: onTap, - borderRadius: BorderRadius.circular(10), - child: Container( - width: 200, - padding: const EdgeInsets.all(16), - decoration: BoxDecoration( - color: widget.bubbleColor, - borderRadius: BorderRadius.circular(10), - ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(Icons.visibility_off, color: widget.textColor), - const SizedBox(height: 8), - child, - ], - ), - ), - ); - } - - Widget label(String text) => Text( - text, - textAlign: TextAlign.center, - style: TextStyle(color: widget.textColor), - ); + // An album carries its copies per item; the message itself never has one. + final ready = widget.message.isAlbum + ? widget.message.album.isNotEmpty && + widget.message.album.every((item) => item.localPath != null) + : widget.message.localPath != null; if (mine) { // The sender keeps no copy: one open is the recipient's, never theirs. - return frame( - label(opened ? 'viewOnceOpenedByPeer'.tr() : 'viewOnceSent'.tr())); + return ViewOnceFrame( + label: opened ? 'viewOnceOpenedByPeer'.tr() : 'viewOnceSent'.tr(), + bubbleColor: widget.bubbleColor, + textColor: widget.textColor, + ); } if (opened) { - return frame(label('viewOnceOpened'.tr())); + return ViewOnceFrame( + label: 'viewOnceOpened'.tr(), + bubbleColor: widget.bubbleColor, + textColor: widget.textColor, + ); } - return frame( - label(ready ? 'viewOnceOpen'.tr() : 'viewOnceLoad'.tr()), + return ViewOnceFrame( + label: ready ? 'viewOnceOpen'.tr() : 'viewOnceLoad'.tr(), + bubbleColor: widget.bubbleColor, + textColor: widget.textColor, onTap: () { if (!ready) { if (widget.canRetry) { diff --git a/lib/widgets/view_once_frame.dart b/lib/widgets/view_once_frame.dart new file mode 100644 index 0000000..55a0f8c --- /dev/null +++ b/lib/widgets/view_once_frame.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart'; + +/// The box a view-once message shows before (and instead of) its content: one +/// icon, one line of state. Tapping it spends the single view; without an +/// [onTap] it is the read-only tombstone. +class ViewOnceFrame extends StatelessWidget { + const ViewOnceFrame({ + required this.label, + required this.bubbleColor, + required this.textColor, + this.onTap, + super.key, + }); + + final String label; + final Color bubbleColor; + final Color textColor; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(10), + child: Container( + width: 200, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: bubbleColor, + borderRadius: BorderRadius.circular(10), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.visibility_off, color: textColor), + const SizedBox(height: 8), + Text( + label, + textAlign: TextAlign.center, + style: TextStyle(color: textColor), + ), + ], + ), + ), + ); + } +} diff --git a/test/attachment_confirm_sheet_test.dart b/test/attachment_confirm_sheet_test.dart index 45b3d02..a85c45d 100644 --- a/test/attachment_confirm_sheet_test.dart +++ b/test/attachment_confirm_sheet_test.dart @@ -13,9 +13,11 @@ void main() { await EasyLocalization.ensureInitialized(); }); - testWidgets('cancel returns null and send returns the caption', + // One app for the whole test: easy_localization loads its bundle once, and a + // second pumpWidget would leave the tree without translations. + testWidgets('the sheet returns the caption and the view-once choice', (tester) async { - String? result = 'unset'; + AttachmentConfirmResult? result; await tester.pumpWidget(EasyLocalization( path: 'assets/translations', supportedLocales: const [Locale('en'), Locale('cs')], @@ -27,14 +29,30 @@ void main() { locale: context.locale, home: Builder( builder: (inner) => Scaffold( - body: Center( - child: ElevatedButton( - onPressed: () async { - result = await AttachmentConfirmSheet.show(inner, - count: 2, initialCaption: 'draft'); - }, - child: const Text('open'), - ), + body: Column( + children: [ + ElevatedButton( + onPressed: () async { + result = await AttachmentConfirmSheet.show(inner, + count: 2, initialCaption: 'draft'); + }, + child: const Text('album'), + ), + ElevatedButton( + onPressed: () async { + result = await AttachmentConfirmSheet.show(inner, + count: 1, allowViewOnce: true); + }, + child: const Text('single'), + ), + ElevatedButton( + onPressed: () async { + result = await AttachmentConfirmSheet.show(inner, + count: 1, allowViewOnce: false); + }, + child: const Text('plain'), + ), + ], ), ), ), @@ -45,7 +63,7 @@ void main() { await tester.pumpAndSettle(); // Cancel - await tester.tap(find.text('open')); + await tester.tap(find.text('album')); await tester.pumpAndSettle(); expect(find.text('draft'), findsOneWidget); await tester.tap(find.byType(TextButton)); @@ -55,11 +73,29 @@ void main() { // Send: the exit animation keeps rebuilding the sheet, which used to touch // a controller that had already been disposed. - await tester.tap(find.text('open')); + await tester.tap(find.text('album')); await tester.pumpAndSettle(); await tester.tap(find.byType(FilledButton)); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); - expect(result, 'draft'); + expect(result!.caption, 'draft'); + expect(result!.viewOnce, isFalse); + + // One visual attachment can be turned into a single view. + await tester.tap(find.text('single')); + await tester.pumpAndSettle(); + expect(find.byType(CheckboxListTile), findsOneWidget); + await tester.tap(find.byType(CheckboxListTile)); + await tester.pumpAndSettle(); + await tester.tap(find.byType(FilledButton)); + await tester.pumpAndSettle(); + expect(result!.viewOnce, isTrue); + + // An album or a file is never offered the switch. + await tester.tap(find.text('plain')); + await tester.pumpAndSettle(); + expect(find.byType(CheckboxListTile), findsNothing); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); }); } diff --git a/test/delete_message_test.dart b/test/delete_message_test.dart index c9de429..47ba079 100644 --- a/test/delete_message_test.dart +++ b/test/delete_message_test.dart @@ -40,4 +40,26 @@ void main() { // The other conversation is untouched expect(await CacheUtils.getPrivateMessages('2'), isEmpty); }); + + test('delete for everyone keeps a tombstone instead of a gap', () async { + final media = PrivateMessage( + '1', 'with a photo', DateTime(2026, 1, 3), DateTime(2026, 1, 3), false, + mediaTypeStr: 'image', localPath: dir.path, reactions: {'1': '👍'}); + await CacheUtils.addPrivateMessages('1', [media]); + + final at = DateTime(2026, 1, 4); + await CacheUtils.markMessageDeleted('1', media.sentAt, at); + + final messages = await CacheUtils.getPrivateMessages('1'); + final tombstone = + messages.firstWhere((message) => message.sentAt == media.sentAt); + expect(tombstone.isDeleted, isTrue); + expect(tombstone.deletedAt, at); + expect(tombstone.message, isEmpty); + expect(tombstone.isMedia, isFalse); + expect(tombstone.reactions, isNull); + // Nothing left to read, so it cannot raise a badge. + expect(tombstone.read, isTrue); + expect(messages.length, 3); + }); } diff --git a/test/deleted_bubble_test.dart b/test/deleted_bubble_test.dart new file mode 100644 index 0000000..d75d0fb --- /dev/null +++ b/test/deleted_bubble_test.dart @@ -0,0 +1,59 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/models/profile.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/singleton.dart'; +import 'package:whisper/widgets/chat_bubble.dart'; +import 'package:whisper/widgets/media_bubble.dart'; + +void main() { + final peer = User('2', 'peer', '', false); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + testWidgets('a deleted message keeps its place as a tombstone', ( + tester, + ) async { + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: const Locale('en'), + home: Scaffold( + body: Center( + child: ChatBubble( + null, + PrivateMessage('2', '', DateTime(2026), DateTime(2026), true) + ..deletedAt = DateTime(2026) + ..mediaTypeStr = 'image', + null, + peer, + accentColor: Colors.blue, + ), + ), + ), + ); + }), + )); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); + + expect(find.text('Message deleted'), findsOneWidget); + // The attachment is gone with the content. + expect(find.byType(MediaBubble), findsNothing); + }); +} diff --git a/test/media_album_test.dart b/test/media_album_test.dart index 2d04f0e..c44e31f 100644 --- a/test/media_album_test.dart +++ b/test/media_album_test.dart @@ -46,6 +46,17 @@ void main() { expect(parsed.caption, 'album caption'); }); + test('an album can be a single view', () { + final envelope = MediaUtils.buildAlbumEnvelope( + [_reference('a'), _reference('b')], + '', + viewOnce: true, + ); + final parsed = MediaUtils.tryParseMediaEnvelope(envelope); + expect(parsed!.viewOnce, isTrue); + expect(parsed.references.length, 2); + }); + test('plain text is not an envelope', () { final parsed = MediaUtils.tryParseMediaEnvelope( Uint8List.fromList(utf8.encode('just text'))); diff --git a/test/text_envelope_test.dart b/test/text_envelope_test.dart index c19a7b6..36f359a 100644 --- a/test/text_envelope_test.dart +++ b/test/text_envelope_test.dart @@ -53,6 +53,18 @@ void main() { expect(parsed!.forwarded, isFalse); }); + test('a one-time location carries its flag', () { + final envelope = buildTextEnvelope('📍 50.08, 14.42', null, + location: const LocationRef(50.08, 14.42), viewOnce: true); + + final parsed = tryParseTextEnvelope(envelope); + expect(parsed!.viewOnce, isTrue); + expect(parsed.location!.lat, 50.08); + // An older reader still opens the body instead of raw JSON. + final decoded = jsonDecode(utf8.decode(envelope)) as Map; + expect(decoded['whisperMsg'], textEnvelopeVersion); + }); + test('plain text is not an envelope', () { expect(tryParseTextEnvelope(bytes('ahoj')), isNull); }); diff --git a/test/view_once_location_test.dart b/test/view_once_location_test.dart new file mode 100644 index 0000000..d8c296e --- /dev/null +++ b/test/view_once_location_test.dart @@ -0,0 +1,91 @@ +import 'dart:convert'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/models/profile.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/singleton.dart'; +import 'package:whisper/utils/text_envelope.dart'; +import 'package:whisper/widgets/chat_bubble.dart'; +import 'package:whisper/widgets/view_once_frame.dart'; + +void main() { + final peer = User('2', 'peer', '', false); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + PrivateMessage location({bool mine = false, DateTime? openedAt}) { + final at = DateTime(2026); + return PrivateMessage( + mine ? '1' : '2', + '', + at, + at, + true, + viewOnce: true, + openedAt: openedAt, + locationJson: jsonEncode(const LocationRef(50.08, 14.42).toJson()), + ); + } + + Widget app(PrivateMessage message) => EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Scaffold( + body: Center( + child: ChatBubble( + null, + message, + null, + peer, + accentColor: Colors.blue, + ), + ), + ), + ); + }), + ); + + // One app for the whole test: easy_localization loads its bundle once. + testWidgets('a view-once location is a card revealed once', (tester) async { + await tester.pumpWidget(app(location())); + await tester.pumpAndSettle(); + + // The recipient gets the placeholder, and it is tappable. + expect(find.text('Tap to view once'), findsOneWidget); + expect(tester.widget(find.byType(ViewOnceFrame)).onTap, + isNotNull); + // The coordinates are not shown before the reveal. + expect(find.textContaining('50.08'), findsNothing); + + // Once opened it is a tombstone with no way back in. + await tester.pumpWidget(app(location(openedAt: DateTime(2026, 1, 2)))); + await tester.pumpAndSettle(); + expect(find.text('Opened'), findsOneWidget); + expect( + tester.widget(find.byType(ViewOnceFrame)).onTap, isNull); + + // The sender never gets the reveal, only the state. + await tester.pumpWidget(app(location(mine: true))); + await tester.pumpAndSettle(); + expect( + tester.widget(find.byType(ViewOnceFrame)).onTap, isNull); + expect(find.byType(ViewOnceFrame), findsOneWidget); + }); +} diff --git a/test/view_once_test.dart b/test/view_once_test.dart index 15f9280..e85f458 100644 --- a/test/view_once_test.dart +++ b/test/view_once_test.dart @@ -81,4 +81,31 @@ void main() { expect(find.text('viewOnceLoad'), findsOneWidget); expect(tester.widget(find.byType(InkWell)).onTap, isNotNull); }); + + testWidgets('a downloaded album is ready to open, not stuck on download', ( + tester, + ) async { + // An album keeps its copies per item: the message itself has no localPath. + final album = once(); + album.setAlbum([ + AlbumItem(mediaId: 'a', type: 'image', size: 10, localPath: '/a'), + AlbumItem(mediaId: 'b', type: 'video', size: 20, localPath: '/b'), + ]); + await tester.pumpWidget(app(album)); + expect(find.text('viewOnceOpen'), findsOneWidget); + expect(find.text('viewOnceLoad'), findsNothing); + expect(tester.widget(find.byType(InkWell)).onTap, isNotNull); + }); + + testWidgets('an album missing a copy still offers the download', ( + tester, + ) async { + final album = once(); + album.setAlbum([ + AlbumItem(mediaId: 'a', type: 'image', size: 10, localPath: '/a'), + AlbumItem(mediaId: 'b', type: 'video', size: 20), + ]); + await tester.pumpWidget(app(album)); + expect(find.text('viewOnceLoad'), findsOneWidget); + }); } From 46323bb97a7c634f23cb17407a5154a5841584b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 18:32:29 +0100 Subject: [PATCH 127/181] feat(app): typing dots and live location as a normal chat bubble The peer's typing shows as three pulsing dots next to their avatar above the composer, with a static fallback when the platform asks for reduced motion. Live location is no longer pinned above the input: it is a bubble in the chronology at the instant the session started, laid out like every other message (avatar only when it closes a run) and tappable into a live view of the last fix, its accuracy and the time left. Stopping sends one expired point, so the peer drops it right away instead of waiting out the deadline. --- assets/translations/cs.json | 3 +- assets/translations/en.json | 3 +- lib/pages/chat_page.dart | 84 ++++++++++++++- lib/pages/live_location_page.dart | 132 +++++++++++++++++++++++ lib/utils/live_location.dart | 38 ++++++- lib/utils/presence.dart | 21 +++- lib/widgets/chat_bubble.dart | 143 ++++++++++++------------- lib/widgets/live_location_banner.dart | 126 ---------------------- lib/widgets/live_location_bubble.dart | 144 ++++++++++++++++++++++++++ lib/widgets/typing_dots.dart | 80 ++++++++++++++ test/avatar_rule_test.dart | 83 +++++++++++++++ test/live_location_bubble_test.dart | 41 ++++++++ test/presence_test.dart | 16 +++ test/typing_dots_test.dart | 47 +++++++++ 14 files changed, 748 insertions(+), 213 deletions(-) create mode 100644 lib/pages/live_location_page.dart delete mode 100644 lib/widgets/live_location_banner.dart create mode 100644 lib/widgets/live_location_bubble.dart create mode 100644 lib/widgets/typing_dots.dart create mode 100644 test/avatar_rule_test.dart create mode 100644 test/live_location_bubble_test.dart create mode 100644 test/typing_dots_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 1d370da..dc208c9 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -292,5 +292,6 @@ "viewOnceOpened": "Zobrazeno", "viewOnceOpenedByPeer": "Otevřeno", "messageDeleted": "Zpráva byla smazána", - "viewOnceHint": "Po prvním otevření zmizí oběma stranám" + "viewOnceHint": "Po prvním otevření zmizí oběma stranám", + "liveLocationEnded": "Sdílení skončilo" } diff --git a/assets/translations/en.json b/assets/translations/en.json index e31fd95..f32e19b 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -292,5 +292,6 @@ "viewOnceOpened": "Opened", "viewOnceOpenedByPeer": "Opened", "messageDeleted": "Message deleted", - "viewOnceHint": "Gone for both sides after it is opened once" + "viewOnceHint": "Gone for both sides after it is opened once", + "liveLocationEnded": "Sharing ended" } diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index eb46936..a88fcbe 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -25,7 +25,8 @@ import '../utils/utils.dart' as utils; import '../utils/theme_utils.dart'; import '../widgets/attachment_confirm_sheet.dart'; import '../widgets/chat_bubble.dart'; -import '../widgets/live_location_banner.dart'; +import '../widgets/live_location_bubble.dart'; +import '../widgets/typing_dots.dart'; import 'chat_info_page.dart'; import 'forward_page.dart'; @@ -1522,7 +1523,8 @@ class _ChatPageState extends State { } Widget _buildBubble( - PrivateMessage message, PrivateMessage? older, PrivateMessage? newer) { + PrivateMessage message, PrivateMessage? older, PrivateMessage? newer, + {bool? showAvatar}) { final micros = message.sentAt.microsecondsSinceEpoch; final key = _messageKeys.putIfAbsent(micros, () => GlobalKey()); final showsDivider = _unreadAnchor?.microsecondsSinceEpoch == micros; @@ -1537,6 +1539,7 @@ class _ChatPageState extends State { selectionMode: _selectionMode, selected: _selected.contains(micros), highlight: _highlightMicros == micros, + showAvatar: showAvatar, readAt: micros == _lastOwnMicros && _readReceipts ? _peerReadAt : null, onSelect: () => _toggleSelected(message), onActions: () => _openMessageActions(message), @@ -1560,6 +1563,19 @@ class _ChatPageState extends State { ); } + /// When the live-location session of this chat started, null when there is + /// none. Ordering the bubble by it keeps the chat chronological. + DateTime? _liveLocationStart() { + if (LiveLocationSharer.instance.isSharing(widget.user.id)) { + return LiveLocationSharer.instance.startedAt; + } + // Only while a position is still live: a stopped session leaves no bubble. + if (PresenceNotifier.instance.liveLocation(widget.user.id) == null) { + return null; + } + return PresenceNotifier.instance.liveStartedAt(widget.user.id); + } + /// Messages, grouped by day: each day gets a sticky header. Widget _getContent(List messages) { final start = @@ -1571,6 +1587,25 @@ class _ChatPageState extends State { for (var i = 0; i < visible.length; i++) { days.putIfAbsent(_dayOf(visible[i]), () => []).add(i); } + // The live location takes the place of the message that would carry it: + // right after everything sent before the session started. -1 marks it in + // the day bucket. + final liveStart = _liveLocationStart(); + // Where the marker sits in the timeline: after visible[liveAfter], -1 when + // it precedes every message. -1 in a day bucket marks the marker itself. + var liveAfter = -1; + final liveMine = LiveLocationSharer.instance.isSharing(widget.user.id); + if (liveStart != null) { + final firstNewer = visible.indexWhere((m) => m.sentAt.isAfter(liveStart)); + liveAfter = (firstNewer < 0 ? visible.length : firstNewer) - 1; + final day = DateTime(liveStart.year, liveStart.month, liveStart.day); + final bucket = days.putIfAbsent(day, () => []); + var at = bucket.indexWhere((i) => visible[i].sentAt.isAfter(liveStart)); + if (at < 0) { + at = bucket.length; + } + bucket.insert(at, -1); + } final orderedDays = days.keys.toList()..sort(); // The scroll view is reversed: the first sliver is painted at the bottom @@ -1592,11 +1627,20 @@ class _ChatPageState extends State { itemCount: days[day]!.length, itemBuilder: (context, index) { final position = days[day]![days[day]!.length - 1 - index]; + if (position < 0) { + // The avatar belongs to whoever ends the run, here the marker + // itself when nothing follows it. + return LiveLocationBubble(widget.user, + showAvatar: !liveMine && liveAfter == visible.length - 1); + } final message = visible[position]; return _buildBubble( message, position > 0 ? visible[position - 1] : null, position < visible.length - 1 ? visible[position + 1] : null, + // The marker continues the peer's run, so a message right + // before it is not the one that closes it. + showAvatar: !liveMine && position == liveAfter ? false : null, ); }, ), @@ -1871,9 +1915,39 @@ class _ChatPageState extends State { mainAxisSize: MainAxisSize.min, children: [ if (_replyTo != null) _buildReplyBar(), - // Above the field, inside the measured composer, so the - // message list keeps clearing it. - LiveLocationBanner(widget.user), + if (PresenceNotifier.instance.isTyping(widget.user.id)) + Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 4), + child: Align( + alignment: Alignment.centerLeft, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + // The same avatar the bubbles and the chat list + // draw, one size smaller. + CircleAvatar( + radius: 10, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 10, + color: widget.user.avatarTextColor, + ), + ), + ), + const SizedBox(width: 6), + TypingDots( + color: Theme.of(context) + .colorScheme + .onSurfaceVariant, + ), + ], + ), + ), + ), Stack( alignment: Alignment.center, children: [ diff --git a/lib/pages/live_location_page.dart b/lib/pages/live_location_page.dart new file mode 100644 index 0000000..fd773dc --- /dev/null +++ b/lib/pages/live_location_page.dart @@ -0,0 +1,132 @@ +import 'dart:async'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +import '../models/user.dart'; +import '../utils/live_location.dart'; +import '../utils/message_actions.dart'; +import '../utils/presence.dart'; +import '../utils/text_envelope.dart'; + +/// The live view of one shared location: the last position, its accuracy and the +/// time left, updated in place. No tiles are fetched, so the coordinates stay on +/// the device until the map button is tapped. +class LiveLocationPage extends StatefulWidget { + const LiveLocationPage(this.peer, {super.key}); + + final User peer; + + @override + State createState() => _LiveLocationPageState(); +} + +class _LiveLocationPageState extends State { + Timer? _tick; + + @override + void initState() { + super.initState(); + _tick = Timer.periodic(const Duration(seconds: 1), (_) { + if (mounted) { + setState(() {}); + } + }); + PresenceNotifier.instance.addListener(_onChanged); + } + + @override + void dispose() { + _tick?.cancel(); + PresenceNotifier.instance.removeListener(_onChanged); + super.dispose(); + } + + void _onChanged() { + if (mounted) { + setState(() {}); + } + } + + String _left(DateTime until) { + final left = until.difference(DateTime.now()); + if (left.isNegative) { + return '0:00'; + } + return '${left.inMinutes}:' + '${left.inSeconds.remainder(60).toString().padLeft(2, '0')}'; + } + + @override + Widget build(BuildContext context) { + final mine = LiveLocationSharer.instance.isSharing(widget.peer.id); + final theirs = PresenceNotifier.instance.liveLocation(widget.peer.id); + final point = theirs; + final until = mine ? LiveLocationSharer.instance.until : point?.until; + final scheme = Theme.of(context).colorScheme; + final active = mine || point != null; + final lat = point?.lat; + final lng = point?.lng; + + return Scaffold( + appBar: AppBar(title: Text(widget.peer.username)), + body: SafeArea( + child: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.my_location, size: 72, color: scheme.primary), + const SizedBox(height: 16), + Text( + mine ? 'liveLocationMine'.tr() : 'liveLocationTheirs'.tr(), + style: Theme.of(context).textTheme.titleMedium, + ), + if (until != null) ...[ + const SizedBox(height: 4), + Text(_left(until), + style: Theme.of(context).textTheme.headlineSmall), + ], + if (point != null) ...[ + const SizedBox(height: 12), + Text(point.coordinates, + style: Theme.of(context).textTheme.bodyLarge), + if (point.accuracy != null) + Text('± ${point.accuracy!.round()} m', + style: TextStyle(color: scheme.onSurfaceVariant)), + ], + if (!active) ...[ + const SizedBox(height: 12), + Text('liveLocationEnded'.tr(), + style: TextStyle(color: scheme.onSurfaceVariant)), + ], + const SizedBox(height: 24), + if (lat != null && lng != null) + FilledButton.icon( + onPressed: () => MessageActions.openLocation( + LocationRef(lat, lng, accuracy: point?.accuracy)), + icon: const Icon(Icons.map), + label: Text('openInMaps'.tr()), + ), + if (mine) ...[ + const SizedBox(height: 8), + TextButton.icon( + onPressed: () async { + await LiveLocationSharer.instance.stop(); + if (mounted) { + setState(() {}); + } + }, + icon: const Icon(Icons.stop_circle_outlined), + label: Text('liveLocationStop'.tr()), + ), + ], + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/utils/live_location.dart b/lib/utils/live_location.dart index 900a2fa..de30db9 100644 --- a/lib/utils/live_location.dart +++ b/lib/utils/live_location.dart @@ -105,11 +105,18 @@ class LiveLocationSharer { Timer? _timer; String? _peerId; DateTime? _until; + DateTime? _started; + User? _peer; + LiveLocationPoint? _last; bool isSharing(String peerId) => _timer != null && _peerId == peerId; DateTime? get until => _until; + /// When the running session started; the bubble sits at this instant in the + /// conversation instead of being pinned to the bottom. + DateTime? get startedAt => _started; + /// Starts a session with [peer]. Returns false when there is no fix, which is /// also what a refused permission looks like. Future start(User peer, Duration duration) async { @@ -121,7 +128,10 @@ class LiveLocationSharer { return false; } _peerId = peer.id; - _until = DateTime.now().add(duration); + _peer = peer; + final now = DateTime.now(); + _started = now; + _until = now.add(duration); await _send(peer, position); _timer = Timer.periodic(interval, (_) async { final next = await currentPosition(); @@ -136,11 +146,27 @@ class LiveLocationSharer { return true; } + /// Ends the session. A peer that is still connected is told right away with + /// a last point that is already expired, so stopping early really stops it + /// for them too instead of waiting out the announced deadline. Future stop() async { + final peer = _peer; + final last = _last; + final until = _until; _timer?.cancel(); _timer = null; _peerId = null; + _peer = null; _until = null; + _started = null; + _last = null; + if (peer != null && last != null && until != null) { + await _relay( + peer, + LiveLocationPoint(last.lat, last.lng, + accuracy: last.accuracy, until: DateTime.now()), + ); + } } Future _send(User peer, Position position) async { @@ -150,6 +176,16 @@ class LiveLocationSharer { } final point = LiveLocationPoint(position.latitude, position.longitude, accuracy: position.accuracy, until: deadline); + _last = point; + await _relay(peer, point); + } + + /// Encrypts one point for [peer] and hands it to the socket. Nothing about a + /// live position is archived, so the socket is the only way in. + Future _relay(User peer, LiveLocationPoint point) async { + if (!Singleton().wsClient.isConnected) { + return; + } try { final data = await CryptoUtils.encryptMessageData( utf8.encode(jsonEncode(point.toJson())), diff --git a/lib/utils/presence.dart b/lib/utils/presence.dart index a9f26ff..4860ca6 100644 --- a/lib/utils/presence.dart +++ b/lib/utils/presence.dart @@ -32,6 +32,10 @@ class PresenceNotifier extends ChangeNotifier { final Map _live = {}; final Map _liveTimers = {}; + /// When each session was first seen here, so its bubble sits at that instant + /// in the conversation instead of being pinned to the bottom. + final Map _liveStarted = {}; + /// The position [peerId] is sharing right now, null when they are not. LiveLocationPoint? liveLocation(String peerId) { final point = _live[peerId]; @@ -41,13 +45,27 @@ class PresenceNotifier extends ChangeNotifier { return point; } - /// Keeps one relayed position and forgets it at its deadline. + /// When the live session of [peerId] started here, null without one. + DateTime? liveStartedAt(String peerId) => _liveStarted[peerId]; + + /// Keeps one relayed position and forgets it at its deadline. A point that + /// is already expired is the sender saying "stopped": it clears the session + /// instead of showing a stale position. void applyLiveLocation(String peerId, LiveLocationPoint point) { + if (!point.until.isAfter(DateTime.now())) { + _liveTimers.remove(peerId)?.cancel(); + _live.remove(peerId); + _liveStarted.remove(peerId); + notifyListeners(); + return; + } _live[peerId] = point; + _liveStarted.putIfAbsent(peerId, () => DateTime.now()); _liveTimers.remove(peerId)?.cancel(); final left = point.until.difference(DateTime.now()); _liveTimers[peerId] = Timer(left.isNegative ? Duration.zero : left, () { _live.remove(peerId); + _liveStarted.remove(peerId); _liveTimers.remove(peerId); notifyListeners(); }); @@ -119,6 +137,7 @@ class PresenceNotifier extends ChangeNotifier { _online.clear(); _lastSeen.clear(); _live.clear(); + _liveStarted.clear(); notifyListeners(); } diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 53c3118..0bf5519 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -58,6 +58,10 @@ class ChatBubble extends StatefulWidget { /// Jumps to the quoted message. final VoidCallback? onTapQuote; + /// Overrides the avatar rule. The live-location bubble is not a message, so + /// its neighbours cannot see it; the caller says who closes a run. + final bool? showAvatar; + const ChatBubble( this.previousMessage, this.message, this.nextMessage, this.user, {required this.accentColor, @@ -71,6 +75,7 @@ class ChatBubble extends StatefulWidget { this.onReply, this.onQuickReact, this.onTapQuote, + this.showAvatar, super.key}); @override @@ -177,81 +182,61 @@ class _ChatBubbleState extends State { final bubbleColor = widget.accentColor; final textColor = bubbleColor.computeLuminance() > 0.5 ? Colors.black : Colors.white; - return Align( - alignment: - widget.message.isMe ? Alignment.centerRight : Alignment.centerLeft, - child: Padding( - padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 8), - child: ViewOnceFrame( - label: mine - ? (opened ? 'viewOnceOpenedByPeer'.tr() : 'viewOnceSent'.tr()) - : (opened ? 'viewOnceOpened'.tr() : 'viewOnceOpen'.tr()), - bubbleColor: bubbleColor, - textColor: textColor, - onTap: mine || opened || location == null - ? null - : () async { - await MessageActions.openLocation(location); - await MessageActions.consumeViewOnce( - widget.user.id, widget.message); - }, - ), - ), + return ViewOnceFrame( + label: mine + ? (opened ? 'viewOnceOpenedByPeer'.tr() : 'viewOnceSent'.tr()) + : (opened ? 'viewOnceOpened'.tr() : 'viewOnceOpen'.tr()), + bubbleColor: bubbleColor, + textColor: textColor, + onTap: mine || opened || location == null + ? null + : () async { + await MessageActions.openLocation(location); + await MessageActions.consumeViewOnce( + widget.user.id, widget.message); + }, ); } /// A static location: a pin, the coordinates and a way into the platform map /// app. No tiles are fetched, so nothing leaves the device until the tap. - Widget _locationBubble(BuildContext context, LocationRef location) { - final scheme = Theme.of(context).colorScheme; - return Align( - alignment: - widget.message.isMe ? Alignment.centerRight : Alignment.centerLeft, - child: Container( - margin: const EdgeInsets.symmetric(vertical: 2, horizontal: 8), - padding: const EdgeInsets.fromLTRB(12, 10, 12, 4), - constraints: const BoxConstraints(maxWidth: 260), - decoration: BoxDecoration( - color: widget.accentColor, - borderRadius: BorderRadius.circular(12), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, + Widget _locationBubble( + BuildContext context, LocationRef location, Color color) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( children: [ - Row( - children: [ - const Icon(Icons.place, size: 20), - const SizedBox(width: 6), - Expanded( - child: Text( - (location.label?.isNotEmpty ?? false) - ? location.label! - : 'locationMessage'.tr(), - style: const TextStyle(fontWeight: FontWeight.w600), - ), - ), - ], - ), - Padding( - padding: const EdgeInsets.only(top: 2, left: 26), - child: Text(location.body, - style: Theme.of(context) - .textTheme - .bodySmall - ?.copyWith(color: scheme.onSurfaceVariant)), - ), - Align( - alignment: Alignment.centerRight, - child: TextButton.icon( - onPressed: () => MessageActions.openLocation(location), - icon: const Icon(Icons.map, size: 18), - label: Text('openInMaps'.tr()), + Icon(Icons.place, size: 20, color: color), + const SizedBox(width: 6), + Flexible( + child: Text( + (location.label?.isNotEmpty ?? false) + ? location.label! + : 'locationMessage'.tr(), + style: TextStyle(color: color, fontWeight: FontWeight.w600), ), ), ], ), - ), + Padding( + padding: const EdgeInsets.only(top: 2, left: 26), + child: Text(location.body, + style: Theme.of(context) + .textTheme + .bodySmall + ?.copyWith(color: color.withValues(alpha: 0.8))), + ), + Align( + alignment: Alignment.centerRight, + child: TextButton.icon( + onPressed: () => MessageActions.openLocation(location), + icon: const Icon(Icons.map, size: 18), + label: Text('openInMaps'.tr()), + ), + ), + ], ); } @@ -261,18 +246,9 @@ class _ChatBubbleState extends State { if (widget.message.isSystem) { return _systemPill(context); } - // A static location is a card, not text with a pin in it. A view-once - // location is the same card, but revealed once: a placeholder first, a - // tombstone after. - final location = widget.message.location; - if (widget.message.viewOnce && !widget.message.isMedia) { - return _viewOnceMessage(context, location); - } - if (location != null) { - return _locationBubble(context, location); - } bool showAvatar() { + if (widget.showAvatar != null) return widget.showAvatar!; if (widget.message.isMe) return false; // Show avatar if next message is null (last message) if (widget.nextMessage == null) return true; @@ -366,6 +342,14 @@ class _ChatBubbleState extends State { } Widget content() { + // A view-once location is the single-view frame, not text; a plain one + // is a card with a pin and a way into the map app. + if (widget.message.viewOnce && !widget.message.isMedia) { + return _viewOnceMessage(context, widget.message.location); + } + if (widget.message.location case final location?) { + return _locationBubble(context, location, bubbleTextColor()); + } // A tombstone is text even when it used to be an attachment. if (widget.message.isMedia && !widget.message.isDeleted) { return MediaBubble( @@ -560,6 +544,9 @@ class _ChatBubbleState extends State { // is the bubble, so it is clipped to the corners instead of sitting inside // a coloured frame. final isMedia = widget.message.isMedia; + // A view-once location draws its own frame, so it needs no bubble chrome + // behind it either. + final ownChrome = isMedia || widget.message.viewOnce; // Animated so a jump flashes in and fades out instead of popping. final bubbleBox = AnimatedContainer( duration: const Duration(milliseconds: 250), @@ -567,7 +554,7 @@ class _ChatBubbleState extends State { decoration: BoxDecoration( // A reply needs a surface for its quote; the attachment below fills the // rest of the bubble. - color: isMedia + color: ownChrome ? (widget.message.isReply ? bubbleBackground() : null) : (_isLargeEmoji ? null : bubbleBackground()), borderRadius: BorderRadius.circular(20), @@ -583,7 +570,7 @@ class _ChatBubbleState extends State { ), ) : null, - padding: isMedia + padding: ownChrome ? (widget.message.isReply ? const EdgeInsets.fromLTRB(8, 8, 8, 0) : EdgeInsets.zero) @@ -598,7 +585,7 @@ class _ChatBubbleState extends State { // only stops clipping: toggling Container.clipBehavior adds or drops its // clip widget, which re-mounts the attachment and throws the decoded image // away - the white flash when a reaction was added. - final clippedBox = isMedia + final clippedBox = ownChrome ? ClipRRect( borderRadius: BorderRadius.circular(20), clipBehavior: widget.message.reactionEmojis.isEmpty diff --git a/lib/widgets/live_location_banner.dart b/lib/widgets/live_location_banner.dart deleted file mode 100644 index 4270e35..0000000 --- a/lib/widgets/live_location_banner.dart +++ /dev/null @@ -1,126 +0,0 @@ -import 'dart:async'; - -import 'package:easy_localization/easy_localization.dart'; -import 'package:flutter/material.dart'; - -import '../models/user.dart'; -import '../utils/live_location.dart'; -import '../utils/message_actions.dart'; -import '../utils/presence.dart'; -import '../utils/text_envelope.dart'; - -/// One row above the composer while a live location is on: this device's with a -/// stop button, the peer's with the last point and a way into the map app. -class LiveLocationBanner extends StatefulWidget { - final User peer; - - const LiveLocationBanner(this.peer, {super.key}); - - @override - State createState() => _LiveLocationBannerState(); -} - -class _LiveLocationBannerState extends State { - Timer? _tick; - - @override - void initState() { - super.initState(); - // The remaining time is a clock, not an event: one rebuild a second. - _tick = Timer.periodic(const Duration(seconds: 1), (_) { - if (mounted) { - setState(() {}); - } - }); - PresenceNotifier.instance.addListener(_onChanged); - } - - @override - void dispose() { - _tick?.cancel(); - PresenceNotifier.instance.removeListener(_onChanged); - super.dispose(); - } - - void _onChanged() { - if (mounted) { - setState(() {}); - } - } - - String _left(DateTime until) { - final left = until.difference(DateTime.now()); - if (left.isNegative) { - return '0:00'; - } - return '${left.inMinutes}:' - '${left.inSeconds.remainder(60).toString().padLeft(2, '0')}'; - } - - @override - Widget build(BuildContext context) { - final mine = LiveLocationSharer.instance.isSharing(widget.peer.id); - final theirs = PresenceNotifier.instance.liveLocation(widget.peer.id); - if (!mine && theirs == null) { - return const SizedBox.shrink(); - } - final scheme = Theme.of(context).colorScheme; - final until = mine ? LiveLocationSharer.instance.until : theirs?.until; - final label = mine ? 'liveLocationMine'.tr() : 'liveLocationTheirs'.tr(); - return Container( - margin: const EdgeInsets.fromLTRB(8, 4, 8, 0), - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), - decoration: BoxDecoration( - color: scheme.secondaryContainer, - borderRadius: BorderRadius.circular(12), - ), - child: Row( - children: [ - Icon(Icons.my_location, size: 18, color: scheme.onSecondaryContainer), - const SizedBox(width: 8), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Text( - until == null ? label : '$label · ${_left(until)}', - style: TextStyle(color: scheme.onSecondaryContainer), - ), - if (!mine) - GestureDetector( - onTap: () { - final point = theirs; - if (point != null) { - MessageActions.openLocation( - LocationRef(point.lat, point.lng)); - } - }, - child: Text( - theirs?.coordinates ?? '', - style: TextStyle( - fontSize: 12, - decoration: TextDecoration.underline, - color: scheme.onSecondaryContainer, - ), - ), - ), - ], - ), - ), - if (mine) - IconButton( - icon: const Icon(Icons.stop_circle_outlined), - tooltip: 'liveLocationStop'.tr(), - onPressed: () async { - await LiveLocationSharer.instance.stop(); - if (mounted) { - setState(() {}); - } - }, - ), - ], - ), - ); - } -} diff --git a/lib/widgets/live_location_bubble.dart b/lib/widgets/live_location_bubble.dart new file mode 100644 index 0000000..1f32c2a --- /dev/null +++ b/lib/widgets/live_location_bubble.dart @@ -0,0 +1,144 @@ +import 'dart:async'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +import '../models/user.dart'; +import '../pages/live_location_page.dart'; +import '../utils/live_location.dart'; +import '../utils/presence.dart'; + +/// The live location as one bubble in the conversation: this device's or the +/// peer's, ticking with the time left. Tapping it opens the live view; nothing +/// is archived, so the bubble exists only while a session does. +class LiveLocationBubble extends StatefulWidget { + const LiveLocationBubble(this.peer, {this.showAvatar = true, super.key}); + + final User peer; + + /// Whether this bubble closes the peer's run of messages: the avatar is + /// drawn only there, like on every other bubble. + final bool showAvatar; + + @override + State createState() => _LiveLocationBubbleState(); +} + +class _LiveLocationBubbleState extends State { + Timer? _tick; + + @override + void initState() { + super.initState(); + // The remaining time is a clock, not an event: one rebuild a second. + _tick = Timer.periodic(const Duration(seconds: 1), (_) { + if (mounted) { + setState(() {}); + } + }); + PresenceNotifier.instance.addListener(_onChanged); + } + + @override + void dispose() { + _tick?.cancel(); + PresenceNotifier.instance.removeListener(_onChanged); + super.dispose(); + } + + void _onChanged() { + if (mounted) { + setState(() {}); + } + } + + String _left(DateTime until) { + final left = until.difference(DateTime.now()); + if (left.isNegative) { + return '0:00'; + } + return '${left.inMinutes}:' + '${left.inSeconds.remainder(60).toString().padLeft(2, '0')}'; + } + + @override + Widget build(BuildContext context) { + final mine = LiveLocationSharer.instance.isSharing(widget.peer.id); + final theirs = PresenceNotifier.instance.liveLocation(widget.peer.id); + if (!mine && theirs == null) { + return const SizedBox.shrink(); + } + final scheme = Theme.of(context).colorScheme; + final until = mine ? LiveLocationSharer.instance.until : theirs?.until; + final label = mine ? 'liveLocationMine'.tr() : 'liveLocationTheirs'.tr(); + final color = mine ? scheme.primaryContainer : scheme.surfaceContainerHigh; + final textColor = + mine ? scheme.onPrimaryContainer : scheme.onSurfaceVariant; + + // Laid out like a message bubble of this chat: the same side, the same + // width limits and, incoming, the same avatar. + final bubble = Container( + constraints: const BoxConstraints(maxWidth: 260), + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + decoration: BoxDecoration( + color: color, + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.my_location, size: 20, color: textColor), + const SizedBox(width: 8), + Flexible( + child: Text( + until == null ? label : '$label · ${_left(until)}', + style: TextStyle(color: textColor), + ), + ), + const SizedBox(width: 6), + Icon(Icons.chevron_right, size: 18, color: textColor), + ], + ), + ); + + return Padding( + padding: EdgeInsets.only( + left: mine ? 96 : 16, + right: mine ? 16 : 96, + top: 16, + ), + child: Row( + mainAxisAlignment: + mine ? MainAxisAlignment.end : MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + if (!mine && widget.showAvatar) + Padding( + padding: const EdgeInsets.only(right: 8), + child: CircleAvatar( + radius: 16, + backgroundColor: widget.peer.avatarColor, + child: Text( + widget.peer.username.isNotEmpty + ? widget.peer.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 14, + color: widget.peer.avatarTextColor, + ), + ), + ), + ), + Flexible( + child: InkWell( + borderRadius: BorderRadius.circular(20), + onTap: () => Navigator.of(context).push(MaterialPageRoute( + builder: (_) => LiveLocationPage(widget.peer))), + child: bubble, + ), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/typing_dots.dart b/lib/widgets/typing_dots.dart new file mode 100644 index 0000000..d897030 --- /dev/null +++ b/lib/widgets/typing_dots.dart @@ -0,0 +1,80 @@ +import 'dart:math' as math; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +/// Three dots that pulse in sequence, the messenger-style "typing" hint. Only +/// in the tree while the peer is typing, so the animation runs only then; a +/// platform that asks for reduced motion gets a static ellipsis instead. +class TypingDots extends StatefulWidget { + const TypingDots({this.color, this.dotSize = 6, super.key}); + + final Color? color; + final double dotSize; + + @override + State createState() => _TypingDotsState(); +} + +class _TypingDotsState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _controller = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 1200), + )..repeat(); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final color = + widget.color ?? Theme.of(context).colorScheme.onSurfaceVariant; + final static = MediaQuery.disableAnimationsOf(context); + + return Semantics( + label: 'typing'.tr(), + child: static + ? Text('…', + style: TextStyle( + color: color, + fontSize: widget.dotSize * 2, + height: 1, + )) + : AnimatedBuilder( + animation: _controller, + builder: (context, _) => Row( + mainAxisSize: MainAxisSize.min, + children: [ + for (var i = 0; i < 3; i++) + Padding( + padding: EdgeInsets.only(right: i == 2 ? 0 : 3), + child: _dot(color, i), + ), + ], + ), + ), + ); + } + + /// One dot: a sine bump of opacity and lift, each starting a little later + /// than the previous one. + Widget _dot(Color color, int index) { + final phase = (_controller.value - index * 0.12) % 1.0; + final bump = math.sin(phase * math.pi); + return Transform.translate( + offset: Offset(0, -2 * bump), + child: Container( + width: widget.dotSize, + height: widget.dotSize, + decoration: BoxDecoration( + color: color.withValues(alpha: 0.35 + 0.65 * bump), + shape: BoxShape.circle, + ), + ), + ); + } +} diff --git a/test/avatar_rule_test.dart b/test/avatar_rule_test.dart new file mode 100644 index 0000000..05b396a --- /dev/null +++ b/test/avatar_rule_test.dart @@ -0,0 +1,83 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/models/profile.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/singleton.dart'; +import 'package:whisper/widgets/chat_bubble.dart'; + +void main() { + final peer = User('2', 'peer', '', false); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + // One app for the whole test: easy_localization loads its bundle once. + testWidgets('the avatar closes a run, unless the caller says otherwise', + (tester) async { + final message = + PrivateMessage('2', 'ahoj', DateTime(2026), DateTime(2026), true); + + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Scaffold( + body: Center( + child: ChatBubble( + null, + message, + null, + peer, + accentColor: Colors.blue, + ), + ), + ), + ); + }), + )); + await tester.pumpAndSettle(); + expect(find.byType(CircleAvatar), findsOneWidget); + + // The live-location marker follows, so this message does not close the run. + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Scaffold( + body: Center( + child: ChatBubble( + null, + message, + null, + peer, + accentColor: Colors.blue, + showAvatar: false, + ), + ), + ), + ); + }), + )); + await tester.pumpAndSettle(); + expect(find.byType(CircleAvatar), findsNothing); + }); +} diff --git a/test/live_location_bubble_test.dart b/test/live_location_bubble_test.dart new file mode 100644 index 0000000..9d264e7 --- /dev/null +++ b/test/live_location_bubble_test.dart @@ -0,0 +1,41 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/live_location.dart'; +import 'package:whisper/utils/presence.dart'; +import 'package:whisper/widgets/live_location_bubble.dart'; + +void main() { + final peer = User('2', 'peer', '', false); + final presence = PresenceNotifier.instance; + + setUp(presence.clear); + tearDown(presence.clear); + + testWidgets('no session means no bubble', (tester) async { + await tester.pumpWidget( + MaterialApp(home: Scaffold(body: LiveLocationBubble(peer)))); + expect(find.byType(InkWell), findsNothing); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('the peer sharing location shows one bubble with time left', ( + tester, + ) async { + presence.applyLiveLocation( + peer.id, + LiveLocationPoint(50.08, 14.42, + until: DateTime.now().add(const Duration(minutes: 5))), + ); + await tester.pumpWidget( + MaterialApp(home: Scaffold(body: LiveLocationBubble(peer)))); + await tester.pump(); + + expect(find.textContaining('liveLocationTheirs'), findsOneWidget); + expect(find.byType(InkWell), findsOneWidget); + + // Unmount and drop the session: both own timers. + await tester.pumpWidget(const SizedBox()); + presence.clear(); + }); +} diff --git a/test/presence_test.dart b/test/presence_test.dart index febac44..174ac87 100644 --- a/test/presence_test.dart +++ b/test/presence_test.dart @@ -1,4 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/live_location.dart'; import 'package:whisper/utils/presence.dart'; void main() { @@ -37,6 +38,21 @@ void main() { expect(presence.isTyping('peer'), isFalse); }); + test('an expired live position means the session stopped', () { + presence.applyLiveLocation( + 'peer', + LiveLocationPoint(50.08, 14.42, + until: DateTime.now().add(const Duration(minutes: 5)))); + expect(presence.liveLocation('peer'), isNotNull); + expect(presence.liveStartedAt('peer'), isNotNull); + + // The sender's stop frame carries an instant that is already gone. + presence.applyLiveLocation( + 'peer', LiveLocationPoint(50.08, 14.42, until: DateTime.now())); + expect(presence.liveLocation('peer'), isNull); + expect(presence.liveStartedAt('peer'), isNull); + }); + test('clear drops every known peer', () { presence.applyPresence('peer', online: true); presence.applyTyping('peer'); diff --git a/test/typing_dots_test.dart b/test/typing_dots_test.dart new file mode 100644 index 0000000..cac0010 --- /dev/null +++ b/test/typing_dots_test.dart @@ -0,0 +1,47 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:whisper/widgets/typing_dots.dart'; + +void main() { + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + }); + + Widget app(Widget child, {bool reduceMotion = false}) { + return MaterialApp( + home: MediaQuery( + data: MediaQueryData(disableAnimations: reduceMotion), + child: Scaffold(body: Center(child: child)), + ), + ); + } + + testWidgets('typing is three animated dots', (tester) async { + await tester.pumpWidget(app(const TypingDots())); + await tester.pump(); + // Three circles, no text hint. + expect( + find.byWidgetPredicate((widget) => + widget is Container && + widget.decoration is BoxDecoration && + (widget.decoration as BoxDecoration).shape == BoxShape.circle), + findsNWidgets(3)); + }); + + testWidgets('reduced motion gets a static ellipsis instead', (tester) async { + await tester.pumpWidget(app(const TypingDots(), reduceMotion: true)); + await tester.pump(); + expect(find.text('…'), findsOneWidget); + expect( + find.byWidgetPredicate((widget) => + widget is Container && + widget.decoration is BoxDecoration && + (widget.decoration as BoxDecoration).shape == BoxShape.circle), + findsNothing); + }); +} From a644f1cb39944efa3e0fc5d9ae807731498adaff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 20:51:41 +0100 Subject: [PATCH 128/181] feat(chat): keep a jump-to-latest button while scrolled up The button used to appear only when a message arrived while reading further up. It now follows the viewport as well, with a hysteresis band between the show and hide thresholds so it cannot blink at the edge, and it fades and scales in instead of popping over the list. --- lib/pages/chat_page.dart | 78 ++++++++++++++++++++++++++++------------ 1 file changed, 55 insertions(+), 23 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index a88fcbe..15d8ec6 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -132,6 +132,10 @@ class _ChatPageState extends State { /// after it while scrolled up counts as unseen. int _newestSeenSentAt = 0; int _unseenCount = 0; + // Whether the floating "jump to latest" button is up because the viewport is + // far from the newest message. Hysteresis keeps it from blinking around the + // threshold while the finger is still moving. + bool _farFromBottom = false; bool get _selectionMode => _selected.isNotEmpty; @@ -324,9 +328,10 @@ class _ChatPageState extends State { } else { _scrollController.jumpTo(0); } - if (_unseenCount != 0) { + if (_unseenCount != 0 || _farFromBottom) { setState(() { _unseenCount = 0; + _farFromBottom = false; }); } } @@ -375,6 +380,14 @@ class _ChatPageState extends State { _unseenCount = 0; }); } + // Show after scrolling past a short threshold, hide closer to the bottom: + // one state with two edges, so the button does not flicker on the edge. + final far = _farFromBottom ? position.pixels > 60 : position.pixels > 120; + if (far != _farFromBottom) { + setState(() { + _farFromBottom = far; + }); + } // Reversed list: older messages are at the far end of the scroll extent. if (position.pixels < position.maxScrollExtent - 200) { return; @@ -1979,31 +1992,50 @@ class _ChatPageState extends State { ), ) : _getContent(_messages), - // Floating "down" button with the count of messages that - // arrived while the user was reading further up. - if (!_firstLoad && _unseenCount > 0) - Positioned( - right: 16, - bottom: _composerHeight + 16, - child: FloatingActionButton.small( - heroTag: 'jumpToBottom', - tooltip: 'jumpToLatest'.tr(), - onPressed: () => _jumpToBottom(animate: true), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.arrow_downward, size: 16), - if (_unseenCount > 1) - Padding( - padding: const EdgeInsets.only(left: 2), - child: Text('$_unseenCount', - style: - const TextStyle(fontSize: 11)), - ), - ], + // Floating "down" button: up whenever the viewport is + // far from the newest message, and carrying the count + // of what arrived while the user was reading above. + Positioned( + right: 16, + bottom: _composerHeight + 16, + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 200), + transitionBuilder: (child, animation) => + FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: Tween(begin: 0.8, end: 1) + .animate(animation), + child: child, ), ), + child: !_firstLoad && + (_farFromBottom || _unseenCount > 0) + ? FloatingActionButton.small( + key: const ValueKey('jumpToLatest'), + heroTag: 'jumpToBottom', + tooltip: 'jumpToLatest'.tr(), + onPressed: () => + _jumpToBottom(animate: true), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.arrow_downward, + size: 16), + if (_unseenCount > 1) + Padding( + padding: const EdgeInsets.only( + left: 2), + child: Text('$_unseenCount', + style: const TextStyle( + fontSize: 11)), + ), + ], + ), + ) + : const SizedBox.shrink(), ), + ), ], ), ), From 1fddd2a45063e25a044c1554143e36d26880f640 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 20:51:45 +0100 Subject: [PATCH 129/181] fix(cache): find a stored message by its millisecond, not microsecond, key Hive keeps a DateTime only to the millisecond, so a message read back from disk after a restart carries a shorter sentAt than the microsecond key it was written under. Every lookup by instant - a reaction, an edit, delete for me, a view-once open - then found nothing and returned silently: the server took the change, the peer saw it, and this device never did. Keys stay as they are, so nothing stored needs a migration; the lookup falls back to the millisecond when the exact key is missing. --- lib/utils/cache_utils.dart | 67 ++++++++++++++++++++++++++++++----- test/reaction_store_test.dart | 20 +++++++++++ 2 files changed, 78 insertions(+), 9 deletions(-) diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 0e96648..a2a8c30 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -436,6 +436,27 @@ class CacheUtils { return int.tryParse(key.substring(index + 1)) ?? 0; } + /// The key of a stored message of [userId], null when it is not on this + /// device. + /// + /// Hive keeps a [DateTime] to the millisecond, so a message read from disk + /// carries a shorter [sentAt] than the microsecond key it was written under + /// (a live one still matches, the box hands back the same instance). Every + /// lookup by instant therefore falls back to the millisecond. + static String? _storedKey(Box box, String userId, DateTime sentAt) { + final exact = messageKey(userId, sentAt); + if (box.containsKey(exact)) { + return exact; + } + final millis = sentAt.millisecondsSinceEpoch; + for (final key in _conversationKeys(box, userId)) { + if (_timestampOfKey(key) ~/ 1000 == millis) { + return key; + } + } + return null; + } + /// Keys of one conversation, in box order. static Iterable _conversationKeys(Box box, String userId) { return box.keys.whereType().where((key) { @@ -527,7 +548,10 @@ class CacheUtils { Box box = await _openPrivateMessagesBox(); await _migrateLegacyConversation(box, userId); // Removing the key also removes an emptied conversation from the list. - await box.delete(messageKey(userId, message.sentAt)); + final key = _storedKey(box, userId, message.sentAt); + if (key != null) { + await box.delete(key); + } await _deletePendingSend(userId, message.sentAt); for (final path in message.localPaths) { await MediaUtils.deleteLocalFile(path); @@ -540,7 +564,11 @@ class CacheUtils { String userId, DateTime sentAt) async { final box = await _openPrivateMessagesBox(); await _migrateLegacyConversation(box, userId); - final key = messageKey(userId, sentAt); + final key = _storedKey(box, userId, sentAt); + if (key == null) { + await _deletePendingSend(userId, sentAt); + return; + } final value = box.get(key); if (value is PrivateMessage) { for (final path in value.localPaths) { @@ -586,7 +614,10 @@ class CacheUtils { static Future markMessageEdited( String userId, DateTime sentAt, String text, DateTime editedAt) async { final box = await _openPrivateMessagesBox(); - final key = messageKey(userId, sentAt); + final key = _storedKey(box, userId, sentAt); + if (key == null) { + return; + } final value = box.get(key); if (value is! PrivateMessage) { return; @@ -602,7 +633,10 @@ class CacheUtils { static Future markMessageOpened( String userId, DateTime sentAt, DateTime openedAt) async { final box = await _openPrivateMessagesBox(); - final key = messageKey(userId, sentAt); + final key = _storedKey(box, userId, sentAt); + if (key == null) { + return; + } final value = box.get(key); if (value is! PrivateMessage) { return; @@ -629,7 +663,10 @@ class CacheUtils { static Future markMessageDeleted( String userId, DateTime sentAt, DateTime deletedAt) async { final box = await _openPrivateMessagesBox(); - final key = messageKey(userId, sentAt); + final key = _storedKey(box, userId, sentAt); + if (key == null) { + return; + } final value = box.get(key); if (value is! PrivateMessage) { return; @@ -659,7 +696,10 @@ class CacheUtils { static Future setMessageReaction( String userId, DateTime sentAt, String reactorId, String? emoji) async { final box = await _openPrivateMessagesBox(); - final key = messageKey(userId, sentAt); + final key = _storedKey(box, userId, sentAt); + if (key == null) { + return; + } final value = box.get(key); if (value is! PrivateMessage) { return; @@ -791,7 +831,10 @@ class CacheUtils { void Function(PrivateMessage stored) update) async { Box box = await _openPrivateMessagesBox(); await _migrateLegacyConversation(box, userId); - final key = messageKey(userId, message.sentAt); + final key = _storedKey(box, userId, message.sentAt); + if (key == null) { + return; + } final stored = box.get(key); if (stored is! PrivateMessage) { return; @@ -807,7 +850,10 @@ class CacheUtils { String userId, PrivateMessage message) async { Box box = await _openPrivateMessagesBox(); await _migrateLegacyConversation(box, userId); - final oldKey = messageKey(userId, message.sentAt); + final oldKey = _storedKey(box, userId, message.sentAt); + if (oldKey == null) { + return null; + } final stored = box.get(oldKey); if (stored is! PrivateMessage) { return null; @@ -833,7 +879,10 @@ class CacheUtils { {String? id}) async { Box box = await _openPrivateMessagesBox(); await _migrateLegacyConversation(box, receiverId); - final key = messageKey(receiverId, sentAt); + final key = _storedKey(box, receiverId, sentAt); + if (key == null) { + return; + } final stored = box.get(key); if (stored is! PrivateMessage) { return; diff --git a/test/reaction_store_test.dart b/test/reaction_store_test.dart index 3b06333..c70e5a5 100644 --- a/test/reaction_store_test.dart +++ b/test/reaction_store_test.dart @@ -44,4 +44,24 @@ void main() { expect( (await CacheUtils.getPrivateMessages('peer')).single.reactions, isNull); }); + + test('a reaction lands on a message loaded back from disk', () async { + // Hive keeps the instant to the millisecond, so the copy a new session + // reads has a shorter sentAt than the key it is stored under. + final sentAt = DateTime(2026, 11, 20, 12, 0, 0, 123, 456); + await CacheUtils.addPrivateMessages( + 'peer', [PrivateMessage('peer', 'ahoj', sentAt, sentAt, true)]); + await Hive.box('privateMessages').close(); + await Hive.openBox('privateMessages'); + + final loaded = (await CacheUtils.getPrivateMessages('peer')).single; + expect(loaded.sentAt.microsecondsSinceEpoch, + isNot(sentAt.microsecondsSinceEpoch), + reason: + 'the box rounds the instant, which is what used to break the key'); + + await CacheUtils.setMessageReaction('peer', loaded.sentAt, 'me', '❤️'); + expect((await CacheUtils.getPrivateMessages('peer')).single.reactions, + {'me': '❤️'}); + }); } From 67693cef7cbb572943f8c975d2e46ce6717f8405 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 20:51:49 +0100 Subject: [PATCH 130/181] feat(chat): move shared media to a page of its own Chat info carried the whole grid under its settings, so the rows and the attachments shared one scroll. The grid, its tiles and the viewer hand-off now live on ChatMediaPage, opened from a "Media" row, and say so when the chat has no attachment this device can open yet. The chat color is passed in, so the grid and the viewer keep the conversation's theme. --- assets/translations/cs.json | 1 + assets/translations/en.json | 1 + lib/pages/chat_info_page.dart | 195 ++--------------------------- lib/pages/chat_media_page.dart | 217 +++++++++++++++++++++++++++++++++ test/chat_media_page_test.dart | 76 ++++++++++++ 5 files changed, 306 insertions(+), 184 deletions(-) create mode 100644 lib/pages/chat_media_page.dart create mode 100644 test/chat_media_page_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index dc208c9..630ff71 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -119,6 +119,7 @@ "mediaGif": "GIF", "mediaVideo": "Video", "mediaTitle": "Média", + "noMedia": "V tomto chatu zatím nejsou žádná média", "mediaVoice": "Hlasová zpráva", "changePassword": "Změnit heslo", "currentPassword": "Současné heslo", diff --git a/assets/translations/en.json b/assets/translations/en.json index f32e19b..384a9b5 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -119,6 +119,7 @@ "mediaGif": "GIF", "mediaVideo": "Video", "mediaTitle": "Media", + "noMedia": "No media in this chat yet", "mediaVoice": "Voice message", "changePassword": "Change password", "currentPassword": "Current password", diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 06d8904..8598276 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -1,23 +1,18 @@ import 'package:easy_localization/easy_localization.dart'; -import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import '../utils/nav_transitions.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; -import '../models/private_message.dart'; import '../utils/cache_utils.dart'; import '../utils/chat_sender.dart'; import '../utils/disappearing.dart'; import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; import '../utils/dialog_utils.dart'; -import '../utils/media_utils.dart'; import '../utils/utils.dart'; import '../utils/theme_utils.dart'; -import '../widgets/media_bubble.dart'; import '../widgets/settings_tile.dart'; +import 'chat_media_page.dart'; import 'home_page.dart'; -import 'media_viewer_page.dart'; import 'search_page.dart'; class ChatInfoPage extends StatefulWidget { @@ -30,7 +25,6 @@ class ChatInfoPage extends StatefulWidget { class _ChatInfoPageState extends State { Color? _chatThemeColor; - List _media = []; Map _pins = {}; bool _readReceipts = false; @@ -48,7 +42,6 @@ class _ChatInfoPageState extends State { void initState() { super.initState(); _loadChatTheme(); - _loadMedia(); _loadPins(); _loadReadReceipts(); _loadDisappearing(); @@ -235,14 +228,10 @@ class _ChatInfoPageState extends State { } } - Future _loadMedia() async { - List messages = - await CacheUtils.getPrivateMessages(widget.userId); - if (mounted) { - setState(() { - _media = MessageNotifier.viewableMedia(messages); - }); - } + /// Opens the attachments of this chat on a page of their own. + void _openMedia() { + Navigator.of(context).push(fadeRoute( + ChatMediaPage(widget.userId, chatThemeColor: _chatThemeColor))); } /// Open the chat theme dialog: the same palette as the app theme, applied @@ -272,26 +261,6 @@ class _ChatInfoPageState extends State { } } - void _openMedia(PrivateMessage message) { - final path = message.localPath; - final type = message.mediaType; - if (path == null || type == null) { - return; - } - Navigator.of(context).push( - fadeRoute( - // The viewer is a separate route, so it needs the chat theme passed in - Theme( - data: ThemeUtils.chatTheme(context, _chatThemeColor), - child: MediaViewerPage( - message: message, - conversationUserId: widget.userId, - ), - ), - ), - ); - } - /// Pick a day and hand it back to the chat page, which jumps to the first /// message of that day (or the first one after it). Future _jumpToDate() async { @@ -374,6 +343,12 @@ class _ChatInfoPageState extends State { child: Text('${_pins.length}'), ), ), + // Attachments of this chat: a page of their own. + SettingsTile( + icon: Icons.photo_library_outlined, + label: 'mediaTitle'.tr(), + onPressed: _openMedia, + ), // Disappearing messages: a timer both sides agree on. SettingsTile( icon: Icons.timer_outlined, @@ -411,42 +386,9 @@ class _ChatInfoPageState extends State { ], ), ), - - // Shared media title - if (_media.isNotEmpty) - SliverToBoxAdapter( - child: Padding( - padding: EdgeInsets.fromLTRB(16, 12, 16, 8), - child: Text( - 'mediaTitle'.tr(), - style: TextStyle(fontSize: 16), - ), - ), - ), - // Grid as a sliver, so only the visible tiles decrypt - if (_media.isNotEmpty) - SliverPadding( - padding: EdgeInsets.symmetric(horizontal: 8), - sliver: SliverGrid.builder( - gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 3, - mainAxisSpacing: 4, - crossAxisSpacing: 4, - ), - itemCount: _media.length, - itemBuilder: (context, index) => _MediaTile( - message: _media[index], - onTap: () => _openMedia(_media[index]), - ), - ), - ), - SliverToBoxAdapter( child: Column( children: [ - if (_media.isNotEmpty) - Divider(thickness: 1, indent: 10, endIndent: 10), - // Delete chat SettingsTile( icon: Icons.delete_forever, @@ -487,118 +429,3 @@ class _ChatInfoPageState extends State { ); } } - -/// Square thumbnail of one shared media message. -class _MediaTile extends StatefulWidget { - const _MediaTile({required this.message, required this.onTap}); - - final PrivateMessage message; - final VoidCallback onTap; - - @override - State<_MediaTile> createState() => _MediaTileState(); -} - -class _MediaTileState extends State<_MediaTile> { - Uint8List? _bytes; - bool _error = false; - - @override - void initState() { - super.initState(); - _loadImage(); - } - - Future _loadImage() async { - // Videos get a first-frame thumbnail; documents show an icon. - if (widget.message.mediaType == MediaType.video || - widget.message.mediaType == MediaType.file) { - return; - } - final path = widget.message.localPath; - if (path == null) { - return; - } - try { - Uint8List bytes = await MediaUtils.decryptAtRest(path); - if (mounted) { - setState(() { - _bytes = bytes; - }); - } - } catch (_) { - if (mounted) { - setState(() { - _error = true; - }); - } - } - } - - /// One tile of the three-column grid, gaps and padding taken off. - double get _tileWidth => (MediaQuery.sizeOf(context).width - 24) / 3; - - @override - Widget build(BuildContext context) { - final isVideo = widget.message.mediaType == MediaType.video; - final isFile = widget.message.mediaType == MediaType.file; - return GestureDetector( - onTap: widget.onTap, - child: Container( - color: Theme.of(context).colorScheme.surfaceContainerHighest, - child: isVideo - ? _videoTile() - : _bytes != null - ? Image.memory(_bytes!, - fit: BoxFit.cover, - // Tile-sized decode: a full-resolution photo per square is - // 40+ MB of bitmap and a visible hitch while scrolling. - cacheWidth: MediaUtils.decodeWidth(context, _tileWidth)) - : Center( - child: _error - ? const Icon(Icons.broken_image, size: 24) - : isFile - ? _fileTile() - : const SizedBox( - width: 18, - height: 18, - child: - CircularProgressIndicator(strokeWidth: 2), - ), - ), - ), - ); - } - - /// Video: first frame with a play badge. - Widget _videoTile() { - return Stack( - fit: StackFit.expand, - children: [ - VideoThumbnail(path: widget.message.localPath), - const Center( - child: Icon(Icons.play_arrow, color: Colors.white, size: 28), - ), - ], - ); - } - - /// Documents: extension badge instead of a thumbnail. - Widget _fileTile() { - final name = widget.message.fileName ?? ''; - final dot = name.lastIndexOf('.'); - final extension = - dot > 0 && dot < name.length - 1 ? name.substring(dot + 1) : ''; - return Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon(MediaUtils.iconForFileName(widget.message.fileName), size: 24), - if (extension.isNotEmpty) - Text( - extension.toUpperCase(), - style: const TextStyle(fontSize: 10, fontWeight: FontWeight.bold), - ), - ], - ); - } -} diff --git a/lib/pages/chat_media_page.dart b/lib/pages/chat_media_page.dart new file mode 100644 index 0000000..003f74a --- /dev/null +++ b/lib/pages/chat_media_page.dart @@ -0,0 +1,217 @@ +import 'dart:typed_data'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import '../models/private_message.dart'; +import '../utils/cache_utils.dart'; +import '../utils/media_utils.dart'; +import '../utils/message_notifier.dart'; +import '../utils/nav_transitions.dart'; +import '../utils/theme_utils.dart'; +import '../widgets/media_bubble.dart'; +import 'media_viewer_page.dart'; + +/// Every attachment of one chat this device can open, newest first. +class ChatMediaPage extends StatefulWidget { + const ChatMediaPage(this.userId, {super.key, this.chatThemeColor}); + + final String userId; + + /// The chat's own color, so the grid and the viewer open in it. + final Color? chatThemeColor; + + @override + State createState() => _ChatMediaPageState(); +} + +class _ChatMediaPageState extends State { + List _media = []; + + @override + void initState() { + super.initState(); + _loadMedia(); + } + + Future _loadMedia() async { + List messages = + await CacheUtils.getPrivateMessages(widget.userId); + if (mounted) { + setState(() { + _media = MessageNotifier.viewableMedia(messages); + }); + } + } + + void _openMedia(PrivateMessage message) { + final path = message.localPath; + final type = message.mediaType; + if (path == null || type == null) { + return; + } + Navigator.of(context).push( + fadeRoute( + // The viewer is a separate route, so it needs the chat theme passed in + Theme( + data: ThemeUtils.chatTheme(context, widget.chatThemeColor), + child: MediaViewerPage( + message: message, + conversationUserId: widget.userId, + ), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return Theme( + data: ThemeUtils.chatTheme(context, widget.chatThemeColor), + child: Scaffold( + appBar: AppBar( + title: Text('mediaTitle'.tr()), + ), + body: SafeArea( + child: _media.isEmpty + ? Center( + child: Text( + 'noMedia'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant), + ), + ) + // A sliver grid, so only the visible tiles decrypt. + : GridView.builder( + padding: const EdgeInsets.symmetric(horizontal: 8), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 3, + mainAxisSpacing: 4, + crossAxisSpacing: 4, + ), + itemCount: _media.length, + itemBuilder: (context, index) => _MediaTile( + message: _media[index], + onTap: () => _openMedia(_media[index]), + ), + ), + ), + ), + ); + } +} + +/// Square thumbnail of one shared media message. +class _MediaTile extends StatefulWidget { + const _MediaTile({required this.message, required this.onTap}); + + final PrivateMessage message; + final VoidCallback onTap; + + @override + State<_MediaTile> createState() => _MediaTileState(); +} + +class _MediaTileState extends State<_MediaTile> { + Uint8List? _bytes; + bool _error = false; + + @override + void initState() { + super.initState(); + _loadImage(); + } + + Future _loadImage() async { + // Videos get a first-frame thumbnail; documents show an icon. + if (widget.message.mediaType == MediaType.video || + widget.message.mediaType == MediaType.file) { + return; + } + final path = widget.message.localPath; + if (path == null) { + return; + } + try { + Uint8List bytes = await MediaUtils.decryptAtRest(path); + if (mounted) { + setState(() { + _bytes = bytes; + }); + } + } catch (_) { + if (mounted) { + setState(() { + _error = true; + }); + } + } + } + + /// One tile of the three-column grid, gaps and padding taken off. + double get _tileWidth => (MediaQuery.sizeOf(context).width - 24) / 3; + + @override + Widget build(BuildContext context) { + final isVideo = widget.message.mediaType == MediaType.video; + final isFile = widget.message.mediaType == MediaType.file; + return GestureDetector( + onTap: widget.onTap, + child: Container( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + child: isVideo + ? _videoTile() + : _bytes != null + ? Image.memory(_bytes!, + fit: BoxFit.cover, + // Tile-sized decode: a full-resolution photo per square is + // 40+ MB of bitmap and a visible hitch while scrolling. + cacheWidth: MediaUtils.decodeWidth(context, _tileWidth)) + : Center( + child: _error + ? const Icon(Icons.broken_image, size: 24) + : isFile + ? _fileTile() + : const SizedBox( + width: 18, + height: 18, + child: + CircularProgressIndicator(strokeWidth: 2), + ), + ), + ), + ); + } + + /// Video: first frame with a play badge. + Widget _videoTile() { + return Stack( + fit: StackFit.expand, + children: [ + VideoThumbnail(path: widget.message.localPath), + const Center( + child: Icon(Icons.play_arrow, color: Colors.white, size: 28), + ), + ], + ); + } + + /// Documents: extension badge instead of a thumbnail. + Widget _fileTile() { + final name = widget.message.fileName ?? ''; + final dot = name.lastIndexOf('.'); + final extension = + dot > 0 && dot < name.length - 1 ? name.substring(dot + 1) : ''; + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(MediaUtils.iconForFileName(widget.message.fileName), size: 24), + if (extension.isNotEmpty) + Text( + extension.toUpperCase(), + style: const TextStyle(fontSize: 10, fontWeight: FontWeight.bold), + ), + ], + ); + } +} diff --git a/test/chat_media_page_test.dart b/test/chat_media_page_test.dart new file mode 100644 index 0000000..bf4226d --- /dev/null +++ b/test/chat_media_page_test.dart @@ -0,0 +1,76 @@ +import 'dart:io'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/pages/chat_media_page.dart'; +import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_chat_media_page'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + await Hive.openBox('conversations'); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + Widget app() => EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: const ChatMediaPage('peer'), + ); + }), + ); + + testWidgets('an empty chat says so instead of drawing nothing', + (tester) async { + await tester.runAsync(() => tester.pumpWidget(app())); + await tester.pumpAndSettle(); + + expect(find.text('No media in this chat yet'), findsOneWidget); + }); + + testWidgets('a document shows its extension badge', (tester) async { + final sentAt = DateTime(2026, 11, 20, 12); + // Hive writes are real file I/O: outside runAsync the fake test clock would + // wait on them forever. + await tester.runAsync(() => CacheUtils.addPrivateMessages('peer', [ + PrivateMessage('peer', '', sentAt, sentAt, true, + localPath: '/tmp/whisper_test_report.pdf', + mediaTypeStr: MediaType.file.name, + fileName: 'report.pdf'), + ])); + + await tester.runAsync(() => tester.pumpWidget(app())); + await tester.pumpAndSettle(); + + expect(find.text('PDF'), findsOneWidget); + expect(find.text('No media in this chat yet'), findsNothing); + }); +} From 5096380ed138adee607d7405f8eca3636333937f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 20:51:55 +0100 Subject: [PATCH 131/181] fix(chat): show a send in progress whatever the composer holds The spinner lived in the send button, which only exists while the field has text. Sending a photo without a caption, a location or a live-location start therefore showed nothing at all: reading, probing and encrypting a large file or waiting for a GPS fix can take a while, and the bubble does not exist yet. The composer now shows the spinner for the whole send, and starting a live location keeps it up until the first frame is out. --- lib/pages/chat_page.dart | 41 ++++++++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 15d8ec6..c91fd65 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1051,10 +1051,19 @@ class _ChatPageState extends State { if (minutes == null) { return; } - final started = await LiveLocationSharer.instance - .start(widget.user, Duration(minutes: minutes)); - if (started && mounted) { - setState(() {}); + // The first frame needs a GPS fix and a round trip: without a sending state + // the sheet closes into a silent screen with nothing to look at. + setState(() => _isSending = true); + try { + final started = await LiveLocationSharer.instance + .start(widget.user, Duration(minutes: minutes)); + if (started && mounted) { + setState(() {}); + } + } finally { + if (mounted) { + setState(() => _isSending = false); + } } } @@ -1297,17 +1306,25 @@ class _ChatPageState extends State { suffixIcon: ValueListenableBuilder( valueListenable: _controllerMessage, builder: (context, value, _) { + // A send in flight shows here whatever the field holds: encrypting + // and uploading a large attachment, probing a video or waiting for + // a GPS fix takes a while, and the bubble is not there yet. + if (_isSending) { + // 48 px like the icon buttons it replaces, so nothing shifts. + return const Padding( + padding: EdgeInsets.all(15), + child: SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ); + } final hasText = value.text.trim().isNotEmpty; if (hasText) { return IconButton( - onPressed: _isSending ? null : _sendMessage, - icon: _isSending - ? const SizedBox( - width: 18, - height: 18, - child: CircularProgressIndicator(strokeWidth: 2), - ) - : const Icon(Icons.send), + onPressed: _sendMessage, + icon: const Icon(Icons.send), ); } // Hold-to-record voice message. The bar is overlaid while From f4fe1502b9d4435c6200eb31c57f32671c9881e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 20:51:59 +0100 Subject: [PATCH 132/181] fix(chat): draw the new-messages divider in the chat color The helper runs above the conversation Theme, so Theme.of(context) there is the app theme: the divider and its label stayed in the global primary while the bubbles followed the picked chat color. It now uses the same accent the bubbles do. --- lib/pages/chat_page.dart | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index c91fd65..244271c 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1506,7 +1506,9 @@ class _ChatPageState extends State { /// The "new messages" divider, drawn above the first unread message. Widget _buildUnreadDivider() { - final color = Theme.of(context).colorScheme.primary; + // The picked chat color itself: this helper runs above the chat Theme, so + // Theme.of(context) would be the app theme. + final color = _chatThemeColor ?? Singleton().appTheme.color; return Padding( key: _unreadDividerKey, padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), From 49ecf14b9930e6fb4814aca6c82e228ef0634c21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 20:52:03 +0100 Subject: [PATCH 133/181] fix(chat): keep the picked color in the chat theme dialog The dialog kept its picked color inside the StatefulBuilder, so every rebuild reset it to the value the page had when the dialog opened. A tap wrote the color to the cache but repainted the sample with the old one: the chat changed only after the OK button closed the dialog and the page reloaded. --- lib/utils/dialog_utils.dart | 7 +++--- test/chat_theme_dialog_test.dart | 38 ++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/lib/utils/dialog_utils.dart b/lib/utils/dialog_utils.dart index a0f9025..5e99f12 100644 --- a/lib/utils/dialog_utils.dart +++ b/lib/utils/dialog_utils.dart @@ -218,11 +218,10 @@ class DialogUtils { required Color? current, required Future Function(Color? color) onChanged, }) { + // Outside the builder: a rebuild must not reset the pick back to the value + // the page had when the dialog opened. + Color? picked = current; return StatefulBuilder(builder: (context, setState) { - // The dialog applies on tap, so it keeps its own copy: the page reloads - // from the cache asynchronously. - Color? picked = current; - Future openColorPickerDialog() async { final value = await showDialog( context: context, diff --git a/test/chat_theme_dialog_test.dart b/test/chat_theme_dialog_test.dart index 9ad16a8..a6d37d1 100644 --- a/test/chat_theme_dialog_test.dart +++ b/test/chat_theme_dialog_test.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:whisper/utils/dialog_utils.dart'; +import 'package:whisper/widgets/theme_palette.dart'; /// The per-chat dialog shares the app theme's palette, and adds the one choice /// that only a chat has: fall back to the global color. @@ -38,4 +39,41 @@ void main() { await tester.pumpAndSettle(); expect(calls.last, isNull); }); + + testWidgets('a swatch repaints the sample before the dialog is confirmed', + (tester) async { + await tester.pumpWidget(MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => showDialog( + context: context, + builder: (_) => DialogUtils.chatThemeDialog( + context, + current: null, + onChanged: (_) async {}, + )), + child: const Text('open'), + ), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + // Nothing picked yet: the sample follows the global theme. + expect(tester.widget(find.byType(ThemePreview)).seed, isNull); + + final swatch = find.byKey(const ValueKey('themeSwatch-8')); + await tester.ensureVisible(swatch); + await tester.pumpAndSettle(); + await tester.tap(swatch); + await tester.pumpAndSettle(); + + // A rebuild used to reset the pick to the value the page had on open, so + // the preview only moved once the dialog was confirmed. + expect( + tester.widget(find.byType(ThemePreview)).seed?.toARGB32(), + Colors.teal.toARGB32()); + }); } From 30f800f7cdedc38fc2bfa09570db6a1940a70158 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 21:39:30 +0100 Subject: [PATCH 134/181] feat(app): send attachments in resumable chunks with a 100 MiB limit --- lib/utils/cache_utils.dart | 22 +++++ lib/utils/chat_sender.dart | 84 +++++++++-------- lib/utils/media_upload.dart | 177 ++++++++++++++++++++++++++++++++++++ lib/utils/media_utils.dart | 45 ++++++--- pubspec.yaml | 2 +- test/media_upload_test.dart | 34 +++++++ 6 files changed, 315 insertions(+), 49 deletions(-) create mode 100644 lib/utils/media_upload.dart create mode 100644 test/media_upload_test.dart diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index a2a8c30..8a92c48 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -403,6 +403,28 @@ class CacheUtils { await box.put(_playbackSpeed, speed); } + /// Session of an unfinished attachment upload, keyed by `|`. + /// Encrypted like the rest of the cache: it names the attachment in flight. + static const String _pendingUploadsKey = 'pendingUploads'; + + /// The recorded upload session of one attachment, or null. + static Future getPendingUpload(String key) async { + CollectionBox box = await _openBox(_pendingUploadsKey); + return await box.get(key); + } + + /// Records the upload session of one attachment so a retry can resume it. + static Future setPendingUpload(String key, String value) async { + CollectionBox box = await _openBox(_pendingUploadsKey); + await box.put(key, value); + } + + /// Forgets the upload session of one attachment. + static Future removePendingUpload(String key) async { + CollectionBox box = await _openBox(_pendingUploadsKey); + await box.delete(key); + } + /// Opens the message box. One key per message, so a write touches one entry /// instead of rewriting a whole conversation. static Future _openPrivateMessagesBox() async { diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index 9a4c61e..3d26f7f 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -5,7 +5,6 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:http/http.dart' as http; import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import 'package:whisper_websocket_client_dart/models/new_private_message.dart'; @@ -15,6 +14,7 @@ import '../models/private_message.dart'; import '../models/user.dart'; import 'cache_utils.dart'; import 'crypto_utils.dart'; +import 'media_upload.dart'; import 'media_utils.dart'; import 'message_notifier.dart'; import 'singleton.dart'; @@ -128,9 +128,8 @@ class ChatSender { if (!await _ensureConnected()) { return await _fail(recipient.id, message); } - final transport = await MediaUtils.encryptForTransport(bytes); - final reference = await _uploadReference( - recipient, type, transport.key, transport.blob, + final reference = await _uploadReference(recipient, type, bytes, + messageKey: CacheUtils.messageKey(recipient.id, message.sentAt), width: width, height: height, durationMs: durationMs, @@ -224,11 +223,13 @@ class ChatSender { // The server takes one file per request, so the album is N uploads. final references = []; - for (final attachment in attachments) { - final transport = - await MediaUtils.encryptForTransport(attachment.bytes); - final reference = await _uploadReference( - recipient, attachment.type, transport.key, transport.blob, + final messageKey = CacheUtils.messageKey(recipient.id, message.sentAt); + for (var i = 0; i < attachments.length; i++) { + final attachment = attachments[i]; + final reference = await _uploadReference(recipient, attachment.type, + attachment.bytes, + messageKey: messageKey, + index: i, width: attachment.width, height: attachment.height, durationMs: attachment.durationMs, @@ -413,7 +414,8 @@ class ChatSender { /// is missing or the upload failed. static Future?> _uploadLocalCopies( User recipient, PrivateMessage message) async { - Future upload(String? path, MediaType? type, + final messageKey = CacheUtils.messageKey(recipient.id, message.sentAt); + Future upload(String? path, MediaType? type, int index, {int? width, int? height, int? durationMs, String? fileName}) async { if (path == null || type == null) { return null; @@ -423,8 +425,9 @@ class ChatSender { _toastTooLarge(); return null; } - final transport = await MediaUtils.encryptForTransport(bytes); - return _uploadReference(recipient, type, transport.key, transport.blob, + return _uploadReference(recipient, type, bytes, + messageKey: messageKey, + index: index, width: width, height: height, durationMs: durationMs, @@ -433,8 +436,9 @@ class ChatSender { final references = []; if (message.isAlbum) { - for (final item in message.album) { - final reference = await upload(item.localPath, item.mediaType, + for (var i = 0; i < message.album.length; i++) { + final item = message.album[i]; + final reference = await upload(item.localPath, item.mediaType, i, width: item.width, height: item.height, durationMs: item.durationMs, @@ -445,7 +449,7 @@ class ChatSender { references.add(reference); } } else { - final reference = await upload(message.localPath, message.mediaType, + final reference = await upload(message.localPath, message.mediaType, 0, width: message.width, height: message.height, durationMs: message.durationMs, @@ -482,39 +486,47 @@ class ChatSender { ttlSeconds: ttl > 0 ? ttl : null))); } - /// Upload one already transport-encrypted attachment and build its reference. + /// Upload one attachment and build its reference. + /// + /// Returns null when the upload failed. The recorded session is kept, so the + /// retry of that message continues where the connection broke instead of + /// starting from zero. static Future _uploadReference( User recipient, MediaType type, - Uint8List key, - Uint8List blob, { + Uint8List bytes, { + required String messageKey, + int index = 0, int? width, int? height, int? durationMs, String? fileName, }) async { - final uploadResponse = await Utils.callApi( - () => Singleton().mediaApi.uploadMedia( - http.MultipartFile.fromBytes('file', blob, filename: 'media.bin'), - recipient.id, - ), - rethrowErr: true, - ); - if (uploadResponse == null) { + try { + final (mediaId, transport) = await MediaUploader.upload( + bytes, + receiverId: recipient.id, + messageKey: messageKey, + index: index, + ); + return MediaReference( + mediaId, + transport.key, + type, + transport.blob.length, + width: width, + height: height, + durationMs: durationMs, + fileName: fileName, + ); + } catch (e) { + if (kDebugMode) { + debugPrint('media upload failed: $e'); + } Fluttertoast.showToast( msg: 'mediaUploadFailed'.tr(), backgroundColor: Colors.red); return null; } - return MediaReference( - uploadResponse.id, - key, - type, - blob.length, - width: width, - height: height, - durationMs: durationMs, - fileName: fileName, - ); } /// E2E-encrypt [envelope] for [recipient] and hand it to the WebSocket. diff --git a/lib/utils/media_upload.dart b/lib/utils/media_upload.dart new file mode 100644 index 0000000..7015c8b --- /dev/null +++ b/lib/utils/media_upload.dart @@ -0,0 +1,177 @@ +import 'dart:convert'; +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:http/http.dart' as http; +import 'package:whisper_openapi_client_dart/api.dart'; + +import 'cache_utils.dart'; +import 'media_utils.dart'; +import 'singleton.dart'; +import 'utils.dart'; + +/// One recorded upload session of an unfinished attachment. +class _Record { + final String id; + final int totalSize; + final Uint8List key; + final Uint8List nonce; + + const _Record(this.id, this.totalSize, this.key, this.nonce); +} + +/// Resumable upload of one attachment. +/// +/// The server appends one chunk per request and reports the offset it holds, so +/// a connection that dies halfway costs only the bytes since the last accepted +/// chunk. While an upload is unfinished its session is recorded together with +/// the transport key and nonce, which is what lets a retry continue it (even +/// after a restart) instead of uploading the whole ciphertext again: the same +/// key and nonce reproduce the same bytes. +class MediaUploader { + MediaUploader._(); + + /// Upload the plaintext [bytes] of one attachment for [receiverId] and return + /// the media id and the transport encryption used. + /// + /// [messageKey] and [index] identify the attachment of a stored message; when + /// a session is recorded for that pair it is resumed. + static Future<(String, TransportEncryption)> upload( + Uint8List bytes, { + required String receiverId, + String? messageKey, + int index = 0, + }) async { + final recordKey = messageKey == null ? null : '$messageKey|$index'; + final totalSize = bytes.length + MediaUtils.transportOverheadBytes; + TransportEncryption? transport; + String? uploadId; + var received = 0; + + final record = await _read(recordKey); + if (record != null && record.totalSize == totalSize) { + transport = await MediaUtils.encryptForTransport(bytes, + key: record.key, nonce: record.nonce); + final state = await _state(record.id); + if (state != null && state.totalSize == totalSize) { + uploadId = record.id; + received = state.received; + } + } + + transport ??= await MediaUtils.encryptForTransport(bytes); + if (uploadId == null) { + final session = await Utils.callApi( + () => Singleton().mediaApi.createMediaUpload( + createMediaUploadInput: CreateMediaUploadInput( + receiverId: receiverId, + totalSize: totalSize, + ), + ), + rethrowErr: true, + ); + if (session == null) { + throw Exception('mediaUploadFailed'.tr()); + } + uploadId = session.id; + received = session.received; + if (recordKey != null) { + await CacheUtils.setPendingUpload( + recordKey, + jsonEncode({ + 'id': uploadId, + 'totalSize': totalSize, + 'key': base64Encode(transport.key), + 'nonce': base64Encode(transport.nonce), + 'receiverId': receiverId, + })); + } + } + + final blob = transport.blob; + while (received < blob.length) { + final start = received; + final end = min(start + MediaUtils.uploadChunkBytes, blob.length); + final chunk = http.MultipartFile.fromBytes( + 'chunk', blob.sublist(start, end), + filename: 'chunk.bin'); + try { + final session = await Utils.callApi( + () => + Singleton().mediaApi.uploadMediaChunk(uploadId!, start, chunk), + rethrowErr: true, + showError: false, + ); + received = session == null ? end : session.received; + } on ApiException catch (e) { + if (e.code != 409) { + rethrow; + } + // 409 is the resume path: the server holds a different offset. + final state = await _state(uploadId); + if (state == null || state.totalSize != totalSize) { + // The session expired or belongs to another file: start over. + if (recordKey != null) { + await CacheUtils.removePendingUpload(recordKey); + } + return upload(bytes, + receiverId: receiverId, messageKey: messageKey, index: index); + } + received = state.received; + } + } + + final completed = await Utils.callApi( + () => Singleton().mediaApi.completeMediaUpload(uploadId!), + rethrowErr: true, + ); + if (completed == null) { + throw Exception('mediaUploadFailed'.tr()); + } + if (recordKey != null) { + await CacheUtils.removePendingUpload(recordKey); + } + return (completed.id, transport); + } + + /// The recorded session of one attachment, or null. + static Future<_Record?> _read(String? recordKey) async { + if (recordKey == null) { + return null; + } + final raw = await CacheUtils.getPendingUpload(recordKey); + if (raw == null) { + return null; + } + try { + final json = jsonDecode(raw) as Map; + return _Record( + json['id'] as String, + (json['totalSize'] as num).toInt(), + base64Decode(json['key'] as String), + base64Decode(json['nonce'] as String), + ); + } catch (_) { + await CacheUtils.removePendingUpload(recordKey); + return null; + } + } + + /// The server's view of one session, or null when it is gone. + static Future _state( + String uploadId) async { + try { + return await Utils.callApi( + () => Singleton().mediaApi.getMediaUpload(uploadId), + rethrowErr: true, + showError: false, + ); + } on ApiException catch (e) { + if (e.code == 404) { + return null; + } + rethrow; + } + } +} diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index bcd991e..f37d00c 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -27,7 +27,10 @@ class TransportEncryption { final Uint8List blob; final Uint8List key; - const TransportEncryption(this.blob, this.key); + /// Nonce of [blob]; kept so a resumed upload reproduces the same ciphertext. + final Uint8List nonce; + + const TransportEncryption(this.blob, this.key, this.nonce); } /// Metadata extracted from a media file before sending. @@ -44,7 +47,10 @@ class _GcmArgs { final Uint8List data; final Uint8List key; - const _GcmArgs(this.data, this.key); + /// Pinned nonce, used to reproduce a blob that is already partly uploaded. + final Uint8List? nonce; + + const _GcmArgs(this.data, this.key, [this.nonce]); } /// AES-GCM nonce length (bytes). @@ -58,7 +64,8 @@ const int _macLength = 16; Future _gcmEncrypt(_GcmArgs args) async { final algorithm = cryptography.AesGcm.with256bits(); final secretKey = cryptography.SecretKey(args.key); - final box = await algorithm.encrypt(args.data, secretKey: secretKey); + final box = await algorithm.encrypt(args.data, + secretKey: secretKey, nonce: args.nonce); final nonce = box.nonce; final mac = box.mac.bytes; final out = Uint8List(nonce.length + mac.length + box.cipherText.length); @@ -111,14 +118,22 @@ class MediaUtils { // Transport encryption // --------------------------------------------------------------------------- - /// Encrypt [bytes] with a fresh random key for upload. - static Future encryptForTransport( - Uint8List bytes) async { - final algorithm = cryptography.AesGcm.with256bits(); - final secretKey = await algorithm.newSecretKey(); - final keyBytes = Uint8List.fromList(await secretKey.extractBytes()); - final blob = await compute(_gcmEncrypt, _GcmArgs(bytes, keyBytes)); - return TransportEncryption(blob, keyBytes); + /// Encrypt [bytes] for upload. + /// + /// A fresh key and nonce per file, unless [key] and [nonce] are given: a + /// resumed upload must append the bytes the server already holds, so it + /// re-encrypts with the same pair. + static Future encryptForTransport(Uint8List bytes, + {Uint8List? key, Uint8List? nonce}) async { + var keyBytes = key; + if (keyBytes == null) { + final algorithm = cryptography.AesGcm.with256bits(); + keyBytes = Uint8List.fromList( + await (await algorithm.newSecretKey()).extractBytes()); + } + final blob = await compute(_gcmEncrypt, _GcmArgs(bytes, keyBytes, nonce)); + return TransportEncryption( + blob, keyBytes, Uint8List.fromList(blob.sublist(0, _nonceLength))); } /// Decrypt a downloaded [blob] using the transport [key] from the reference. @@ -413,7 +428,13 @@ class MediaUtils { } /// Largest upload the server accepts (mirrors MEDIA_MAX_UPLOAD_SIZE). - static const int maxUploadBytes = 25 * 1024 * 1024; + /// + /// shortcut: a file is still encrypted, chunked and decrypted in memory, so + /// raising this much further needs streaming GCM before it is safe. + static const int maxUploadBytes = 100 * 1024 * 1024; + + /// Upload chunk size (mirrors what the server appends per request). + static const int uploadChunkBytes = 1024 * 1024; /// AES-GCM overhead added to every uploaded file (nonce + mac). static const int transportOverheadBytes = _nonceLength + _macLength; diff --git a/pubspec.yaml b/pubspec.yaml index 786084b..a2a1c91 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -52,7 +52,7 @@ dependencies: whisper_openapi_client_dart: git: url: https://github.com/jsfraz/whisper_openapi_client_dart.git - ref: v0.4.0 + ref: v0.5.0 whisper_websocket_client_dart: git: url: https://github.com/jsfraz/whisper_websocket_client_dart.git diff --git a/test/media_upload_test.dart b/test/media_upload_test.dart new file mode 100644 index 0000000..b11dd82 --- /dev/null +++ b/test/media_upload_test.dart @@ -0,0 +1,34 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/media_utils.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + // A resumed upload appends to the bytes the server already holds, so it must + // rebuild the exact same ciphertext from the recorded key and nonce. + test('re-encrypting with the recorded key and nonce reproduces the blob', + () async { + final bytes = Uint8List.fromList(List.generate(5000, (i) => i % 251)); + + final first = await MediaUtils.encryptForTransport(bytes); + final resumed = await MediaUtils.encryptForTransport(bytes, + key: first.key, nonce: first.nonce); + + expect(resumed.blob, equals(first.blob)); + expect(resumed.nonce, equals(first.nonce)); + expect(await MediaUtils.decryptTransport(resumed.blob, resumed.key), + equals(bytes)); + }); + + test('a fresh upload encrypts with its own key', () async { + final bytes = Uint8List.fromList(List.generate(5000, (i) => i % 251)); + + final first = await MediaUtils.encryptForTransport(bytes); + final second = await MediaUtils.encryptForTransport(bytes); + + expect(second.key, isNot(equals(first.key))); + expect(second.blob, isNot(equals(first.blob))); + }); +} From 958eed90e8dc4cd254919e3914ec5bc7ece92388 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 21:42:28 +0100 Subject: [PATCH 135/181] feat(app): storage screen with per-chat usage and auto-delete --- assets/translations/cs.json | 13 ++- assets/translations/en.json | 13 ++- lib/main.dart | 4 + lib/pages/chat_info_page.dart | 28 +++++++ lib/pages/settings_page.dart | 8 ++ lib/pages/storage_page.dart | 153 ++++++++++++++++++++++++++++++++++ lib/utils/cache_utils.dart | 35 ++++++++ lib/utils/media_upload.dart | 3 +- lib/utils/media_utils.dart | 6 ++ lib/utils/storage_utils.dart | 125 +++++++++++++++++++++++++++ pubspec.lock | 2 +- test/storage_utils_test.dart | 71 ++++++++++++++++ 12 files changed, 456 insertions(+), 5 deletions(-) create mode 100644 lib/pages/storage_page.dart create mode 100644 lib/utils/storage_utils.dart create mode 100644 test/storage_utils_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 630ff71..6d729b7 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -294,5 +294,16 @@ "viewOnceOpenedByPeer": "Otevřeno", "messageDeleted": "Zpráva byla smazána", "viewOnceHint": "Po prvním otevření zmizí oběma stranám", - "liveLocationEnded": "Sdílení skončilo" + "liveLocationEnded": "Sdílení skončilo", + "storageTitle": "Úložiště a data", + "storageTotal": "Média na tomto zařízení", + "storageMediaCount": "příloh", + "storageAutoDelete": "Mazat média po", + "storageDaysSuffix": "dní", + "storageNever": "Nikdy", + "storageSingleDelivery": "Média jsou jednorázová: co se tady smaže, už nelze znovu stáhnout.", + "storageClearCache": "Vymazat keš", + "storageCacheCleared": "Keš vymazána", + "storagePurged": "Uvolněno", + "storageEmpty": "Zatím žádná média" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 384a9b5..8964e27 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -294,5 +294,16 @@ "viewOnceOpenedByPeer": "Opened", "messageDeleted": "Message deleted", "viewOnceHint": "Gone for both sides after it is opened once", - "liveLocationEnded": "Sharing ended" + "liveLocationEnded": "Sharing ended", + "storageTitle": "Storage and data", + "storageTotal": "Media on this device", + "storageMediaCount": "attachments", + "storageAutoDelete": "Delete media after", + "storageDaysSuffix": "days", + "storageNever": "Never", + "storageSingleDelivery": "Media is single delivery: what is deleted here cannot be downloaded again.", + "storageClearCache": "Clear cache", + "storageCacheCleared": "Cache cleared", + "storagePurged": "Freed", + "storageEmpty": "No media yet" } diff --git a/lib/main.dart b/lib/main.dart index d205ed9..e1801d7 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -21,6 +21,7 @@ import 'models/profile.dart'; import 'models/user.dart'; import 'pages/whisper_page.dart'; import 'utils/media_utils.dart'; +import 'utils/storage_utils.dart'; import 'utils/notification_service.dart'; import 'utils/singleton.dart'; import 'utils/theme_notifier.dart'; @@ -84,6 +85,9 @@ void main() async { // before the first frame: it must not flash up on start. await CacheUtils.purgeExpiredMessages(); + // Same for attachments the user asked to drop after a while. + await StorageUtils.purgeIfDue(); + // Default theme Singleton().appTheme = await CacheUtils.getTheme() ?? AppTheme.fromValues(ThemeMode.system, Colors.blue); diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 8598276..b2cb5aa 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -5,13 +5,16 @@ import '../utils/nav_transitions.dart'; import '../utils/cache_utils.dart'; import '../utils/chat_sender.dart'; import '../utils/disappearing.dart'; +import '../utils/media_utils.dart'; import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; import '../utils/dialog_utils.dart'; import '../utils/utils.dart'; +import '../utils/storage_utils.dart'; import '../utils/theme_utils.dart'; import '../widgets/settings_tile.dart'; import 'chat_media_page.dart'; +import 'storage_page.dart'; import 'home_page.dart'; import 'search_page.dart'; @@ -34,6 +37,9 @@ class _ChatInfoPageState extends State { /// Timer the peer proposed and this device has not answered yet. int? _disappearingProposal; + /// Bytes this conversation keeps on this device. + int _mediaBytes = 0; + /// A toggle in flight: the switch stays disabled until the server call and /// the cache write are done, so it cannot be flipped back and forth. bool _readReceiptsBusy = false; @@ -45,6 +51,14 @@ class _ChatInfoPageState extends State { _loadPins(); _loadReadReceipts(); _loadDisappearing(); + _loadMediaUsage(); + } + + Future _loadMediaUsage() async { + final usage = await StorageUtils.usageFor(widget.userId); + if (mounted) { + setState(() => _mediaBytes = usage.bytes); + } } Future _loadDisappearing() async { @@ -331,6 +345,20 @@ class _ChatInfoPageState extends State { _readReceiptsBusy ? null : _toggleReadReceipts, ), ), + // How much this chat costs on disk, and the way to free it + SettingsTile( + icon: Icons.storage, + label: 'storageTitle'.tr(), + onPressed: () async { + await Navigator.push( + context, stepRoute(const StoragePage())); + await _loadMediaUsage(); + }, + extra: Padding( + padding: const EdgeInsets.only(left: 10), + child: Text(MediaUtils.formatBytes(_mediaBytes)), + ), + ), // Pinned messages, shared with the other participant SettingsTile( icon: Icons.push_pin, diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 9d095a7..3664692 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -18,6 +18,7 @@ import '../widgets/change_password_dialog.dart'; import '../widgets/settings_tile.dart'; import '../utils/nav_transitions.dart'; import 'devices_page.dart'; +import 'storage_page.dart'; class SettingsPage extends StatefulWidget { const SettingsPage({super.key}); @@ -295,6 +296,13 @@ class _SettingsPageState extends State { ), _settingsTile( icon: Icons.storage, + label: 'storageTitle'.tr(), + onPressed: () async { + await Navigator.push(context, stepRoute(const StoragePage())); + }, + ), + _settingsTile( + icon: Icons.archive, label: 'retentionSettings'.tr(), onPressed: _showRetentionDialog, ), diff --git a/lib/pages/storage_page.dart b/lib/pages/storage_page.dart new file mode 100644 index 0000000..7b34d1e --- /dev/null +++ b/lib/pages/storage_page.dart @@ -0,0 +1,153 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +import '../utils/cache_utils.dart'; +import '../utils/media_utils.dart'; +import '../utils/storage_utils.dart'; +import '../widgets/settings_tile.dart'; + +/// What attachments cost on this device: per conversation, plus the two ways to +/// get the space back. +class StoragePage extends StatefulWidget { + const StoragePage({super.key}); + + @override + State createState() => _StoragePageState(); +} + +class _StoragePageState extends State { + /// Auto-delete choices in days; 0 keeps the media forever. + static const List _autoDeleteChoices = [0, 7, 30, 90]; + + List _usage = const []; + Map _names = {}; + int _days = 0; + bool _loading = true; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + final usage = await StorageUtils.usageByConversation(); + final names = {}; + for (final entry in usage) { + final user = await CacheUtils.getUserById(entry.conversationId); + names[entry.conversationId] = user?.username ?? entry.conversationId; + } + final days = await CacheUtils.getAutoDeleteMediaDays(); + if (!mounted) { + return; + } + setState(() { + _usage = usage; + _names = names; + _days = days; + _loading = false; + }); + } + + Future _setDays(int days) async { + setState(() => _days = days); + await CacheUtils.setAutoDeleteMediaDays(days); + final freed = days == 0 ? 0 : await StorageUtils.purgeOlderThanDays(days); + await _load(); + if (freed > 0 && mounted) { + await Fluttertoast.showToast( + msg: '${'storagePurged'.tr()} ${MediaUtils.formatBytes(freed)}'); + } + } + + Future _clearCache() async { + await StorageUtils.clearCache(); + if (mounted) { + await Fluttertoast.showToast(msg: 'storageCacheCleared'.tr()); + } + } + + @override + Widget build(BuildContext context) { + final totalBytes = _usage.fold(0, (sum, entry) => sum + entry.bytes); + final totalFiles = + _usage.fold(0, (sum, entry) => sum + entry.attachments); + return Scaffold( + appBar: AppBar(title: Text('storageTitle'.tr())), + body: SafeArea( + child: _loading + ? const Center(child: CircularProgressIndicator()) + : ListView( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 24, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(MediaUtils.formatBytes(totalBytes), + style: Theme.of(context).textTheme.headlineMedium), + Text( + '${'storageTotal'.tr()} · $totalFiles ${'storageMediaCount'.tr()}', + ), + ], + ), + ), + const Divider(thickness: 1, indent: 10, endIndent: 10), + SettingsTile( + icon: Icons.auto_delete, + label: 'storageAutoDelete'.tr(), + onPressed: () => _setDays(_days), + trailing: DropdownButton( + value: _days, + underline: const SizedBox.shrink(), + onChanged: (days) { + if (days != null) { + _setDays(days); + } + }, + items: [ + for (final days in _autoDeleteChoices) + DropdownMenuItem( + value: days, + child: Text(days == 0 + ? 'storageNever'.tr() + : '$days ${'storageDaysSuffix'.tr()}'), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Text( + 'storageSingleDelivery'.tr(), + style: Theme.of(context).textTheme.bodySmall, + ), + ), + SettingsTile( + icon: Icons.cleaning_services, + label: 'storageClearCache'.tr(), + onPressed: _clearCache, + ), + const Divider(thickness: 1, indent: 10, endIndent: 10), + if (_usage.isEmpty) + Padding( + padding: const EdgeInsets.all(16), + child: Text('storageEmpty'.tr()), + ) + else + for (final usage in _usage) + ListTile( + leading: const Icon(Icons.folder_outlined), + title: Text(_names[usage.conversationId] ?? ''), + subtitle: Text( + '${usage.attachments} ${'storageMediaCount'.tr()}', + ), + trailing: Text(MediaUtils.formatBytes(usage.bytes)), + ), + ], + ), + ), + ); + } +} diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 8a92c48..032cd9c 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -425,6 +425,41 @@ class CacheUtils { await box.delete(key); } + static const String _autoDeleteMediaKey = 'autoDeleteMediaDays'; + + /// Days after which this device drops an attachment's local copy, 0 = never. + static Future getAutoDeleteMediaDays() async { + Box box = await Hive.openBox(_settingsKey); + return (box.get(_autoDeleteMediaKey) as num?)?.toInt() ?? 0; + } + + /// Sets how long attachments are kept on this device, 0 = never. + static Future setAutoDeleteMediaDays(int days) async { + Box box = await Hive.openBox(_settingsKey); + await box.put(_autoDeleteMediaKey, days); + } + + /// Every stored message grouped by conversation, from one box scan. Callers + /// that need the whole history (storage usage, media purge) would otherwise + /// reopen the box per conversation. + static Future>> + getAllConversationMessages() async { + Box box = await _openPrivateMessagesBox(); + final result = >{}; + for (final key in box.keys) { + final value = box.get(key); + if (value is! PrivateMessage) { + continue; + } + final conversation = conversationOfKey(key); + if (conversation == null) { + continue; + } + (result[conversation] ??= []).add(value); + } + return result; + } + /// Opens the message box. One key per message, so a write touches one entry /// instead of rewriting a whole conversation. static Future _openPrivateMessagesBox() async { diff --git a/lib/utils/media_upload.dart b/lib/utils/media_upload.dart index 7015c8b..1d10320 100644 --- a/lib/utils/media_upload.dart +++ b/lib/utils/media_upload.dart @@ -98,8 +98,7 @@ class MediaUploader { filename: 'chunk.bin'); try { final session = await Utils.callApi( - () => - Singleton().mediaApi.uploadMediaChunk(uploadId!, start, chunk), + () => Singleton().mediaApi.uploadMediaChunk(uploadId!, start, chunk), rethrowErr: true, showError: false, ); diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index f37d00c..d6948eb 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -354,6 +354,12 @@ class MediaUtils { } } + /// Forgets the decrypted copies kept in memory. They are plaintext, so + /// dropping them is the cheapest way to take readable media out of reach. + static void clearDecryptedCache() { + _mediaCache.clear(); + } + /// Delete a single (encrypted) media file, ignoring errors. static Future deleteLocalFile(String? path) async { if (path == null) { diff --git a/lib/utils/storage_utils.dart b/lib/utils/storage_utils.dart new file mode 100644 index 0000000..171bf97 --- /dev/null +++ b/lib/utils/storage_utils.dart @@ -0,0 +1,125 @@ +import '../models/private_message.dart'; +import 'cache_utils.dart'; +import 'media_utils.dart'; + +/// What the attachments of one conversation cost on this device. +class ConversationUsage { + const ConversationUsage(this.conversationId, this.bytes, this.attachments); + + final String conversationId; + final int bytes; + final int attachments; +} + +/// Local media accounting, and the two ways to get the space back. +/// +/// Attachments are the only thing here that grows without bound: the archive is +/// text, but every video leaves an encrypted copy on disk until something +/// removes it. +class StorageUtils { + StorageUtils._(); + + /// Bytes and attachment count per conversation, newest biggest first. + static Future> usageByConversation() async { + final messages = await CacheUtils.getAllConversationMessages(); + final usage = []; + for (final entry in messages.entries) { + var bytes = 0; + var count = 0; + for (final message in entry.value) { + bytes += _messageBytes(message); + count += message.localPaths.length; + } + if (count > 0) { + usage.add(ConversationUsage(entry.key, bytes, count)); + } + } + usage.sort((a, b) => b.bytes.compareTo(a.bytes)); + return usage; + } + + /// What one conversation keeps on this device. + static Future usageFor(String conversationId) async { + for (final usage in await usageByConversation()) { + if (usage.conversationId == conversationId) { + return usage; + } + } + return ConversationUsage(conversationId, 0, 0); + } + + /// Drops the local copy of every attachment older than [days] and marks it + /// expired, keeping the messages themselves. Returns the bytes freed. + /// + /// The media is single delivery: once dropped it cannot be downloaded again, + /// which is why the setting spells that out before it is applied. + static Future purgeOlderThanDays(int days) async { + if (days <= 0) { + return 0; + } + final cutoff = DateTime.now().subtract(Duration(days: days)); + final messages = await CacheUtils.getAllConversationMessages(); + var freed = 0; + for (final entry in messages.entries) { + for (final message in entry.value) { + if (message.sentAt.isAfter(cutoff)) { + continue; + } + final paths = message.localPaths; + if (paths.isEmpty) { + continue; + } + freed += _messageBytes(message); + for (final path in paths) { + await MediaUtils.deleteLocalFile(path); + } + await CacheUtils.updateStoredMessage(entry.key, message, (stored) { + stored.localPath = null; + stored.downloadStatus = MediaDownloadStatus.expired; + if (!stored.isAlbum) { + return; + } + final items = stored.album; + for (final item in items) { + if (item.localPath != null) { + item.localPath = null; + item.status = MediaDownloadStatus.expired; + } + } + stored.setAlbum(items); + }); + } + } + return freed; + } + + /// Empties the temporary plaintext files and the in-memory decrypt cache. + /// The stored attachments stay: only copies that were never meant to outlive + /// the session go. + static Future clearCache() async { + await MediaUtils.clearTempFiles(); + MediaUtils.clearDecryptedCache(); + } + + /// Applies the configured auto-delete once at start-up. + static Future purgeIfDue() async { + final days = await CacheUtils.getAutoDeleteMediaDays(); + if (days > 0) { + await purgeOlderThanDays(days); + } + } + + /// Bytes one stored message keeps on disk, including the encryption overhead. + static int _messageBytes(PrivateMessage message) { + var bytes = 0; + if (message.localPath != null) { + bytes += (message.mediaSize ?? 0) + MediaUtils.transportOverheadBytes; + } + for (final item in message.album) { + if (item.localPath != null) { + bytes += item.size + MediaUtils.transportOverheadBytes; + } + } + return bytes; + } +} diff --git a/pubspec.lock b/pubspec.lock index 7b967f4..14802ce 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1831,7 +1831,7 @@ packages: path: "../whisper_openapi_client_dart" relative: true source: path - version: "0.4.0" + version: "0.5.0" whisper_websocket_client_dart: dependency: "direct main" description: diff --git a/test/storage_utils_test.dart b/test/storage_utils_test.dart new file mode 100644 index 0000000..e298ba3 --- /dev/null +++ b/test/storage_utils_test.dart @@ -0,0 +1,71 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper/utils/storage_utils.dart'; + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_storage_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + PrivateMessage attachment(String text, DateTime sentAt, String? path, + {int size = 1000}) => + PrivateMessage('1', text, sentAt, sentAt, true, + mediaTypeStr: 'image', localPath: path, mediaSize: size); + + test('usage sums only attachments that still have a local copy', () async { + final file = File('${dir.path}/a')..writeAsBytesSync([1, 2, 3]); + await CacheUtils.addPrivateMessages('1', [ + attachment('on disk', DateTime.now(), file.path), + attachment('gone', DateTime.now(), null, size: 5000), + ]); + + final usage = await StorageUtils.usageByConversation(); + + expect(usage.single.attachments, 1); + expect(usage.single.bytes, greaterThanOrEqualTo(1000)); + }); + + test('purge drops the file and marks the attachment expired', () async { + final file = File('${dir.path}/b')..writeAsBytesSync([1, 2, 3]); + await CacheUtils.addPrivateMessages('1', [ + attachment( + 'old', DateTime.now().subtract(const Duration(days: 40)), file.path), + ]); + + final freed = await StorageUtils.purgeOlderThanDays(30); + + expect(freed, greaterThanOrEqualTo(1000)); + expect(file.existsSync(), isFalse); + final stored = (await CacheUtils.getPrivateMessages('1')).single; + expect(stored.localPath, isNull); + expect(stored.downloadStatus, MediaDownloadStatus.expired); + }); + + test('purge keeps the media of recent messages', () async { + final file = File('${dir.path}/c')..writeAsBytesSync([1, 2, 3]); + await CacheUtils.addPrivateMessages( + '1', [attachment('new', DateTime.now(), file.path)]); + + await StorageUtils.purgeOlderThanDays(30); + + expect(file.existsSync(), isTrue); + }); +} From 25018f358a439e11b151a891ff4a106ca76cd264 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 21:59:56 +0100 Subject: [PATCH 136/181] feat(app): voice waveform, hands-free lock and playback of the next voice message --- assets/translations/cs.json | 4 +- assets/translations/en.json | 4 +- lib/models/private_message.dart | 2 + lib/pages/chat_page.dart | 39 ++++++-- lib/utils/chat_sender.dart | 23 +++-- lib/utils/media_utils.dart | 43 ++++++++- lib/utils/voice_autoplay.dart | 38 ++++++++ lib/widgets/media_bubble.dart | 5 + lib/widgets/voice_player.dart | 165 +++++++++++++++++++++++++------- pubspec.lock | 2 +- pubspec.yaml | 2 +- test/voice_autoplay_test.dart | 71 ++++++++++++++ 12 files changed, 345 insertions(+), 53 deletions(-) create mode 100644 lib/utils/voice_autoplay.dart create mode 100644 test/voice_autoplay_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 6d729b7..24c35ce 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -305,5 +305,7 @@ "storageClearCache": "Vymazat keš", "storageCacheCleared": "Keš vymazána", "storagePurged": "Uvolněno", - "storageEmpty": "Zatím žádná média" + "storageEmpty": "Zatím žádná média", + "recordingLocked": "Nahrávání zamčeno, zastavte ho tlačítkem", + "mediaSticker": "Nálepka" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 8964e27..4d1fc3c 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -305,5 +305,7 @@ "storageClearCache": "Clear cache", "storageCacheCleared": "Cache cleared", "storagePurged": "Freed", - "storageEmpty": "No media yet" + "storageEmpty": "No media yet", + "recordingLocked": "Recording locked, stop it with the button", + "mediaSticker": "Sticker" } diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index 5515180..36ac45e 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -487,6 +487,8 @@ class PrivateMessage extends HiveObject { return 'mediaVoice'.tr(); case MediaType.file: return fileName ?? 'mediaFile'.tr(); + case MediaType.sticker: + return 'mediaSticker'.tr(); case null: return message; } diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 244271c..2c4d3ea 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -76,6 +76,10 @@ class _ChatPageState extends State { bool _isRecording = false; bool _recordingStarting = false; bool _stopRequested = false; + + /// Sliding up while recording locks it: the finger can be lifted and the + /// recording keeps going until the bar's stop button is tapped. + bool _recordingLocked = false; bool _cancelRecording = false; MediaRecorderController? _recorderController; Duration _recordDuration = Duration.zero; @@ -837,7 +841,10 @@ class _ChatPageState extends State { /// Send a media attachment: probe what the type needs, then the shared send /// path (encrypt, upload, persist a bubble, send). Future _sendMedia(MediaType type, File file, - {String caption = '', int? durationMs, bool viewOnce = false}) async { + {String caption = '', + int? durationMs, + List? waveform, + bool viewOnce = false}) async { setState(() { _isSending = true; }); @@ -850,6 +857,7 @@ class _ChatPageState extends State { height: probe.height, durationMs: probe.durationMs, fileName: MediaUtils.baseName(file.path), + waveform: waveform, viewOnce: viewOnce); _afterSend(sent, caption); } catch (e) { @@ -1196,6 +1204,7 @@ class _ChatPageState extends State { _recorderController = controller; _isRecording = true; _cancelRecording = false; + _recordingLocked = false; _recordDuration = Duration.zero; }); _recordTimer = Timer.periodic(const Duration(seconds: 1), (_) { @@ -1234,6 +1243,7 @@ class _ChatPageState extends State { return; } final recorded = await controller.stop(); + final waveform = controller.waveform; await controller.dispose(); if (recorded == null) { return; @@ -1246,7 +1256,7 @@ class _ChatPageState extends State { return; } await _sendMedia(MediaType.voice, recorded.file, - durationMs: recorded.durationMs); + durationMs: recorded.durationMs, waveform: waveform); } /// Stop and drop the recording (bar button). @@ -1337,7 +1347,18 @@ class _ChatPageState extends State { } }, onLongPressMoveUpdate: (details) { - final shouldCancel = details.localOffsetFromOrigin.dx < -80; + if (_recordingLocked) { + return; + } + final offset = details.localOffsetFromOrigin; + if (offset.dy < -60) { + setState(() { + _recordingLocked = true; + _cancelRecording = false; + }); + return; + } + final shouldCancel = offset.dx < -80; if (shouldCancel != _cancelRecording) { setState(() { _cancelRecording = shouldCancel; @@ -1345,9 +1366,11 @@ class _ChatPageState extends State { } }, onLongPressEnd: (_) { - if (_isRecording) { + // A locked recording outlives the gesture: it stops from the + // bar, which is all the release used to do. + if (_isRecording && !_recordingLocked) { _stopRecording(); - } else { + } else if (!_isRecording) { _stopRequested = true; } }, @@ -1444,7 +1467,11 @@ class _ChatPageState extends State { const SizedBox(width: 16), Expanded( child: Text( - _cancelRecording ? 'releaseToCancel'.tr() : 'slideToCancel'.tr(), + _recordingLocked + ? 'recordingLocked'.tr() + : (_cancelRecording + ? 'releaseToCancel'.tr() + : 'slideToCancel'.tr()), style: TextStyle(color: Colors.grey[600]), overflow: TextOverflow.ellipsis, ), diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index 3d26f7f..c4af021 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -91,6 +91,7 @@ class ChatSender { int? height, int? durationMs, String? fileName, + List? waveform, bool forwarded = false, bool viewOnce = false}) async { if (!MediaUtils.uploadFits(bytes.length)) { @@ -133,7 +134,8 @@ class ChatSender { width: width, height: height, durationMs: durationMs, - fileName: fileName); + fileName: fileName, + waveform: waveform); if (reference == null) { return await _fail(recipient.id, message); } @@ -226,8 +228,8 @@ class ChatSender { final messageKey = CacheUtils.messageKey(recipient.id, message.sentAt); for (var i = 0; i < attachments.length; i++) { final attachment = attachments[i]; - final reference = await _uploadReference(recipient, attachment.type, - attachment.bytes, + final reference = await _uploadReference( + recipient, attachment.type, attachment.bytes, messageKey: messageKey, index: i, width: attachment.width, @@ -416,7 +418,11 @@ class ChatSender { User recipient, PrivateMessage message) async { final messageKey = CacheUtils.messageKey(recipient.id, message.sentAt); Future upload(String? path, MediaType? type, int index, - {int? width, int? height, int? durationMs, String? fileName}) async { + {int? width, + int? height, + int? durationMs, + String? fileName, + List? waveform}) async { if (path == null || type == null) { return null; } @@ -431,7 +437,8 @@ class ChatSender { width: width, height: height, durationMs: durationMs, - fileName: fileName); + fileName: fileName, + waveform: waveform); } final references = []; @@ -453,7 +460,9 @@ class ChatSender { width: message.width, height: message.height, durationMs: message.durationMs, - fileName: message.fileName); + fileName: message.fileName, + // A voice message keeps its recorded shape across a retry. + waveform: message.mediaReferences?.first.waveform); if (reference == null) { return null; } @@ -501,6 +510,7 @@ class ChatSender { int? height, int? durationMs, String? fileName, + List? waveform, }) async { try { final (mediaId, transport) = await MediaUploader.upload( @@ -518,6 +528,7 @@ class ChatSender { height: height, durationMs: durationMs, fileName: fileName, + waveform: waveform, ); } catch (e) { if (kDebugMode) { diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index d6948eb..1e24c87 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -428,6 +428,8 @@ class MediaUtils { return '.mp4'; case MediaType.voice: return '.m4a'; + case MediaType.sticker: + return '.png'; case MediaType.file: return ''; } @@ -525,6 +527,8 @@ class MediaUtils { return 'mediaVideo'; case MediaType.voice: return 'mediaVoice'; + case MediaType.sticker: + return 'mediaSticker'; case MediaType.file: return 'mediaFile'; } @@ -711,6 +715,18 @@ class MediaRecorderController { final AudioRecorder _recorder = AudioRecorder(); String? _path; DateTime? _startedAt; + final List _waveform = []; + StreamSubscription? _amplitudeSub; + + /// Ten minutes of samples at one per 100 ms: a longer recording keeps its + /// shape from the first ten minutes rather than growing without bound. + static const int maxWaveformSamples = 600; + + /// Loudness samples of the recording, 0-100, oldest first. + /// + /// The recipient cannot derive these without decoding the file, so they + /// travel in the message reference. + List get waveform => List.unmodifiable(_waveform); Future hasPermission() => _recorder.hasPermission(); @@ -723,10 +739,25 @@ class MediaRecorderController { path: _path!, ); _startedAt = DateTime.now(); + _waveform.clear(); + _amplitudeSub = + _recorder.onAmplitudeChanged(const Duration(milliseconds: 100)).listen( + (amplitude) { + if (_waveform.length >= maxWaveformSamples) { + return; + } + // dBFS sits around -60..0 for speech; anything quieter is silence. + final level = ((amplitude.current + 60) / 60 * 100).clamp(0.0, 100.0); + _waveform.add(level.round()); + }, + onError: (_) {}, + ); } /// Stop recording and return the resulting file and its duration. Future stop() async { + await _amplitudeSub?.cancel(); + _amplitudeSub = null; final path = await _recorder.stop(); final durationMs = _startedAt == null ? 0 @@ -739,6 +770,8 @@ class MediaRecorderController { /// Abort recording and discard the partial file. Future cancel() async { + await _amplitudeSub?.cancel(); + _amplitudeSub = null; try { await _recorder.stop(); } catch (_) { @@ -747,11 +780,11 @@ class MediaRecorderController { await MediaUtils.deleteLocalFile(_path); } - /// Live amplitude stream for the recording UI. - Stream amplitudeStream() => - _recorder.onAmplitudeChanged(const Duration(milliseconds: 200)); - - Future dispose() => _recorder.dispose(); + Future dispose() async { + await _amplitudeSub?.cancel(); + _amplitudeSub = null; + await _recorder.dispose(); + } } /// A finished voice recording. diff --git a/lib/utils/voice_autoplay.dart b/lib/utils/voice_autoplay.dart new file mode 100644 index 0000000..0ad3617 --- /dev/null +++ b/lib/utils/voice_autoplay.dart @@ -0,0 +1,38 @@ +import 'package:flutter/foundation.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +import 'cache_utils.dart'; + +/// Chains voice messages: when one finishes, the next one of the same chat +/// starts. +/// +/// The request is the key of the message that should play, and only the player +/// owning that key picks it up, so no bubble has to reach into another one. +class VoiceAutoplay { + VoiceAutoplay._(); + + /// Key of the message that should start playing, consumed by its player. + static final ValueNotifier request = ValueNotifier(null); + + /// Asks the next voice message after [afterSentAt] in [conversationId] to + /// play. Stops at the end of the chat, and skips a voice message that is not + /// on this device: it could not play, so skipping is honest. + /// + /// shortcut: a player only exists while its bubble is built, so a request for + /// an off-screen message is dropped; upgrade by hoisting playback into a + /// service that owns the queue. + static Future next(String conversationId, DateTime afterSentAt) async { + final messages = await CacheUtils.getPrivateMessages(conversationId); + messages.sort((a, b) => a.sentAt.compareTo(b.sentAt)); + for (final message in messages) { + if (!message.sentAt.isAfter(afterSentAt)) { + continue; + } + if (message.mediaType != MediaType.voice || message.localPath == null) { + continue; + } + request.value = CacheUtils.messageKey(conversationId, message.sentAt); + return; + } + } +} diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index efe53ff..aa9eb16 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -221,6 +221,7 @@ class _MediaBubbleState extends State { switch (type) { case MediaType.image: case MediaType.gif: + case MediaType.sticker: media = _imageWidget(); break; case MediaType.video: @@ -506,6 +507,9 @@ class _MediaBubbleState extends State { localPath: widget.message.localPath!, durationMs: widget.message.durationMs, color: widget.textColor, + conversationId: widget.conversationUserId, + sentAt: widget.message.sentAt, + waveform: widget.message.mediaReferences?.first.waveform, ); } @@ -665,6 +669,7 @@ class _AlbumTileState extends State { switch (type) { case MediaType.image: case MediaType.gif: + case MediaType.sticker: return FutureBuilder( future: _imageFuture, builder: (context, snapshot) { diff --git a/lib/widgets/voice_player.dart b/lib/widgets/voice_player.dart index cecfb33..765956b 100644 --- a/lib/widgets/voice_player.dart +++ b/lib/widgets/voice_player.dart @@ -8,6 +8,7 @@ import '../utils/cache_utils.dart'; import '../utils/media_utils.dart'; import '../utils/playback_lock.dart'; import '../utils/playback_speed.dart'; +import '../utils/voice_autoplay.dart'; /// Inline player for a voice message stored encrypted-at-rest. /// @@ -18,10 +19,21 @@ class VoicePlayer extends StatefulWidget { final int? durationMs; final Color color; + /// The chat this message lives in, and when it was sent: together they are + /// the key the next-message chain looks for. + final String conversationId; + final DateTime sentAt; + + /// Loudness samples recorded with the message, empty for older ones. + final List? waveform; + const VoicePlayer({ required this.localPath, required this.color, + required this.conversationId, + required this.sentAt, this.durationMs, + this.waveform, super.key, }); @@ -36,20 +48,48 @@ class _VoicePlayerState extends State with WidgetsBindingObserver { bool _error = false; double _speed = playbackSpeeds.first; + /// Set once the finished message has asked for the next one, so a repeated + /// `completed` event does not restart the chain. + bool _chained = false; + + late final String _key = + CacheUtils.messageKey(widget.conversationId, widget.sentAt); + @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _player.playerStateStream.listen((state) { - if (!state.playing || - state.processingState == ProcessingState.completed) { + if (state.processingState == ProcessingState.completed) { + PlaybackLock.release(this); + if (!_chained) { + _chained = true; + VoiceAutoplay.next(widget.conversationId, widget.sentAt); + } + return; + } + if (!state.playing) { PlaybackLock.release(this); } }); PlaybackLock.owner.addListener(_onLockChanged); + VoiceAutoplay.request.addListener(_onAutoplayRequest); _prepare(); } + /// Starts this message when the previous one finished and asked for it. + void _onAutoplayRequest() { + if (VoiceAutoplay.request.value != _key) { + return; + } + VoiceAutoplay.request.value = null; + if (_loading || _error) { + return; + } + PlaybackLock.claim(this); + _player.play(); + } + /// Pauses when another voice message or a video starts playing. void _onLockChanged() { if (!identical(PlaybackLock.owner.value, this) && _player.playing) { @@ -90,6 +130,7 @@ class _VoicePlayerState extends State with WidgetsBindingObserver { void dispose() { WidgetsBinding.instance.removeObserver(this); PlaybackLock.owner.removeListener(_onLockChanged); + VoiceAutoplay.request.removeListener(_onAutoplayRequest); PlaybackLock.release(this); _player.dispose(); MediaUtils.deleteLocalFile(_tempFile?.path); @@ -112,6 +153,42 @@ class _VoicePlayerState extends State with WidgetsBindingObserver { return '$minutes:$seconds'; } + /// Waveform of the message, or a plain track for a message recorded before + /// the shape was stored. Tap or drag seeks, like the slider it replaces. + Widget _waveformBar(BuildContext context, Duration total, Duration position) { + final progress = total.inMilliseconds == 0 + ? 0.0 + : (position.inMilliseconds / total.inMilliseconds).clamp(0.0, 1.0); + return LayoutBuilder( + builder: (context, constraints) { + void seek(Offset local) { + if (_loading || total.inMilliseconds == 0) { + return; + } + final fraction = (local.dx / constraints.maxWidth).clamp(0.0, 1.0); + _player.seek(Duration( + milliseconds: (total.inMilliseconds * fraction).round())); + } + + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTapDown: (details) => seek(details.localPosition), + onHorizontalDragUpdate: (details) => seek(details.localPosition), + child: SizedBox( + height: 26, + child: CustomPaint( + painter: _WaveformPainter( + samples: widget.waveform ?? const [], + progress: progress, + color: widget.color, + ), + ), + ), + ); + }, + ); + } + @override Widget build(BuildContext context) { if (_error) { @@ -164,8 +241,10 @@ class _VoicePlayerState extends State with WidgetsBindingObserver { } else { PlaybackLock.claim(this); if (completed) { + _chained = false; await _player.seek(Duration.zero); } + _chained = false; await _player.play(); } }, @@ -177,14 +256,9 @@ class _VoicePlayerState extends State with WidgetsBindingObserver { stream: _player.positionStream, builder: (context, snapshot) { final position = snapshot.data ?? Duration.zero; - final max = total.inMilliseconds == 0 - ? 1.0 - : total.inMilliseconds.toDouble(); - final value = - position.inMilliseconds.clamp(0, max.toInt()).toDouble(); - // Slider and the time label sit on one line, so the track is - // vertically centred in the row instead of being pushed up by - // a stacked label. + // The waveform and the time label sit on one line, so the bars + // are vertically centred in the row instead of being pushed up + // by a stacked label. return StreamBuilder( stream: _player.playerStateStream, builder: (context, stateSnapshot) { @@ -204,28 +278,7 @@ class _VoicePlayerState extends State with WidgetsBindingObserver { Row( children: [ Expanded( - child: SliderTheme( - data: SliderTheme.of(context).copyWith( - trackHeight: 2, - thumbShape: const RoundSliderThumbShape( - enabledThumbRadius: 6), - overlayShape: const RoundSliderOverlayShape( - overlayRadius: 12), - activeTrackColor: widget.color, - thumbColor: widget.color, - inactiveTrackColor: - widget.color.withValues(alpha: 0.3), - ), - child: Slider( - min: 0, - max: max, - value: value, - onChanged: _loading - ? null - : (v) => _player.seek( - Duration(milliseconds: v.toInt())), - ), - ), + child: _waveformBar(context, total, position), ), const SizedBox(width: 4), Text( @@ -273,3 +326,51 @@ class _VoicePlayerState extends State with WidgetsBindingObserver { ); } } + +/// Draws the loudness bars of a voice message, the played part in full colour. +class _WaveformPainter extends CustomPainter { + _WaveformPainter({ + required this.samples, + required this.progress, + required this.color, + }); + + final List samples; + final double progress; + final Color color; + + @override + void paint(Canvas canvas, Size size) { + if (samples.isEmpty) { + final paint = Paint() + ..color = color.withValues(alpha: 0.3) + ..strokeWidth = 2 + ..strokeCap = StrokeCap.round; + canvas.drawLine(Offset(0, size.height / 2), + Offset(size.width, size.height / 2), paint); + return; + } + final step = size.width / samples.length; + final barWidth = (step * 0.6).clamp(1.0, 4.0); + final played = Paint()..color = color; + final rest = Paint()..color = color.withValues(alpha: 0.3); + for (var i = 0; i < samples.length; i++) { + final height = (samples[i] / 100 * size.height).clamp(2.0, size.height); + final rect = RRect.fromRectAndRadius( + Rect.fromCenter( + center: Offset(i * step + step / 2, size.height / 2), + width: barWidth, + height: height, + ), + const Radius.circular(1), + ); + canvas.drawRRect(rect, i / samples.length <= progress ? played : rest); + } + } + + @override + bool shouldRepaint(covariant _WaveformPainter oldDelegate) => + oldDelegate.progress != progress || + oldDelegate.color != color || + oldDelegate.samples != samples; +} diff --git a/pubspec.lock b/pubspec.lock index 14802ce..a19efff 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1838,7 +1838,7 @@ packages: path: "../whisper_websocket_client_dart" relative: true source: path - version: "0.5.0" + version: "0.6.0" win32: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index a2a1c91..4cd2279 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -56,7 +56,7 @@ dependencies: whisper_websocket_client_dart: git: url: https://github.com/jsfraz/whisper_websocket_client_dart.git - ref: v0.5.0 + ref: v0.6.0 dev_dependencies: flutter_test: diff --git a/test/voice_autoplay_test.dart b/test/voice_autoplay_test.dart new file mode 100644 index 0000000..54b226d --- /dev/null +++ b/test/voice_autoplay_test.dart @@ -0,0 +1,71 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper/utils/voice_autoplay.dart'; + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_voice_autoplay_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + VoiceAutoplay.request.value = null; + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + PrivateMessage voice(DateTime sentAt, {String? path = '/tmp/voice'}) => + PrivateMessage('1', '', sentAt, sentAt, true, + mediaTypeStr: 'voice', localPath: path, durationMs: 1000); + + test('the next voice message in the chat is requested', () async { + final first = DateTime(2026, 1, 1, 10); + final second = DateTime(2026, 1, 1, 10, 1); + await CacheUtils.addPrivateMessages('1', [voice(first), voice(second)]); + + await VoiceAutoplay.next('1', first); + + expect(VoiceAutoplay.request.value, CacheUtils.messageKey('1', second)); + }); + + test('a text message between two voice messages is skipped', () async { + final first = DateTime(2026, 1, 1, 10); + final text = DateTime(2026, 1, 1, 10, 1); + final second = DateTime(2026, 1, 1, 10, 2); + await CacheUtils.addPrivateMessages('1', [ + voice(first), + PrivateMessage('1', 'hello', text, text, true), + voice(second), + ]); + + await VoiceAutoplay.next('1', first); + + expect(VoiceAutoplay.request.value, CacheUtils.messageKey('1', second)); + }); + + test('a voice message without a local copy is skipped and the end stops', + () async { + final first = DateTime(2026, 1, 1, 10); + final missing = DateTime(2026, 1, 1, 10, 1); + await CacheUtils.addPrivateMessages('1', [ + voice(first), + voice(missing, path: null), + ]); + + await VoiceAutoplay.next('1', first); + + expect(VoiceAutoplay.request.value, isNull); + }); +} From f8884686a88dc4604a3abfe71d5231423cd95a84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 22:01:23 +0100 Subject: [PATCH 137/181] feat(app): download attachments by network type with a manual fallback --- assets/translations/cs.json | 7 +++- assets/translations/en.json | 7 +++- lib/pages/settings_page.dart | 32 +++++++++++++++++++ lib/utils/auto_download.dart | 60 +++++++++++++++++++++++++++++++++++ lib/utils/cache_utils.dart | 19 +++++++++++ lib/utils/utils.dart | 8 ++++- lib/widgets/media_bubble.dart | 25 ++++++++++++++- pubspec.lock | 24 ++++++++++++++ pubspec.yaml | 1 + test/auto_download_test.dart | 57 +++++++++++++++++++++++++++++++++ 10 files changed, 236 insertions(+), 4 deletions(-) create mode 100644 lib/utils/auto_download.dart create mode 100644 test/auto_download_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 24c35ce..36e8a9b 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -307,5 +307,10 @@ "storagePurged": "Uvolněno", "storageEmpty": "Zatím žádná média", "recordingLocked": "Nahrávání zamčeno, zastavte ho tlačítkem", - "mediaSticker": "Nálepka" + "mediaSticker": "Nálepka", + "autoDownloadTitle": "Stahování médií", + "autoDownloadAlways": "Vždy", + "autoDownloadWifi": "Jen Wi-Fi", + "autoDownloadNever": "Nikdy", + "downloadMedia": "Stáhnout" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 4d1fc3c..6649501 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -307,5 +307,10 @@ "storagePurged": "Freed", "storageEmpty": "No media yet", "recordingLocked": "Recording locked, stop it with the button", - "mediaSticker": "Sticker" + "mediaSticker": "Sticker", + "autoDownloadTitle": "Media download", + "autoDownloadAlways": "Always", + "autoDownloadWifi": "Wi-Fi only", + "autoDownloadNever": "Never", + "downloadMedia": "Download" } diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 3664692..c4ab3f7 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -7,6 +7,7 @@ import 'package:fluttertoast/fluttertoast.dart'; import 'package:sprintf/sprintf.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:whisper_openapi_client_dart/api.dart'; +import '../utils/auto_download.dart'; import '../utils/biometric_auth.dart'; import '../utils/cache_utils.dart'; import '../utils/singleton.dart'; @@ -32,6 +33,7 @@ class _SettingsPageState extends State { bool _notificationPreview = false; bool _typingIndicator = false; bool _presence = false; + AutoDownloadPolicy _autoDownload = AutoDownloadPolicy.wifi; /// Guards the retention flow: the settings round-trip is slow, and without it /// a second tap stacks another dialog on top of the first. @@ -48,6 +50,7 @@ class _SettingsPageState extends State { _notificationPreview = await CacheUtils.getNotificationPreview(); _typingIndicator = await CacheUtils.isTypingIndicatorEnabled(); _presence = await CacheUtils.isPresenceEnabled(); + _autoDownload = await CacheUtils.getAutoDownloadPolicy(); setState(() {}); } @@ -301,6 +304,35 @@ class _SettingsPageState extends State { await Navigator.push(context, stepRoute(const StoragePage())); }, ), + _settingsTile( + icon: Icons.download_for_offline_outlined, + label: 'autoDownloadTitle'.tr(), + trailing: DropdownButton( + value: _autoDownload, + underline: const SizedBox.shrink(), + onChanged: (policy) async { + if (policy == null) { + return; + } + setState(() => _autoDownload = policy); + await CacheUtils.setAutoDownloadPolicy(policy); + }, + items: [ + DropdownMenuItem( + value: AutoDownloadPolicy.always, + child: Text('autoDownloadAlways'.tr()), + ), + DropdownMenuItem( + value: AutoDownloadPolicy.wifi, + child: Text('autoDownloadWifi'.tr()), + ), + DropdownMenuItem( + value: AutoDownloadPolicy.never, + child: Text('autoDownloadNever'.tr()), + ), + ], + ), + ), _settingsTile( icon: Icons.archive, label: 'retentionSettings'.tr(), diff --git a/lib/utils/auto_download.dart b/lib/utils/auto_download.dart new file mode 100644 index 0000000..a8d3a7d --- /dev/null +++ b/lib/utils/auto_download.dart @@ -0,0 +1,60 @@ +import 'package:connectivity_plus/connectivity_plus.dart'; +import 'package:whisper_websocket_client_dart/models/media_reference.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +import 'cache_utils.dart'; + +/// When an incoming attachment is downloaded without asking. +enum AutoDownloadPolicy { + /// Always, on any network. + always, + + /// Only on Wi-Fi, so a photo does not eat the mobile data plan. + wifi, + + /// Never automatically; the bubble offers a download button. + never, +} + +/// Decides whether an incoming attachment may be downloaded right away. +/// +/// The setting exists because attachments are the only part of a chat that can +/// quietly cost money: they arrive on their own, unlike a message. +class AutoDownload { + AutoDownload._(); + + /// Attachments below this size are always fetched: a voice message or a + /// sticker is what makes the chat readable at all. + static const int smallAttachmentBytes = 1024 * 1024; + + /// Whether [reference] may be downloaded now. + static Future allows(MediaReference reference) async { + if (reference.type == MediaType.voice || + reference.type == MediaType.sticker || + reference.size <= smallAttachmentBytes) { + return true; + } + switch (await CacheUtils.getAutoDownloadPolicy()) { + case AutoDownloadPolicy.always: + return true; + case AutoDownloadPolicy.wifi: + return await onWifi(); + case AutoDownloadPolicy.never: + return false; + } + } + + /// Whether the device is on an unmetered network right now. + /// + /// Unknown reads as "not on Wi-Fi": guessing the other way spends the user's + /// mobile data on a policy that says not to. + static Future onWifi() async { + try { + final results = await Connectivity().checkConnectivity(); + return results.contains(ConnectivityResult.wifi) || + results.contains(ConnectivityResult.ethernet); + } catch (_) { + return false; + } + } +} diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 032cd9c..2014f6c 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -13,6 +13,7 @@ import '../models/profile.dart'; import '../models/user.dart'; import 'color_utils.dart'; import 'crypto_utils.dart'; +import 'auto_download.dart'; import 'media_utils.dart'; import 'message_search.dart'; import 'singleton.dart'; @@ -426,6 +427,24 @@ class CacheUtils { } static const String _autoDeleteMediaKey = 'autoDeleteMediaDays'; + static const String _autoDownloadKey = 'autoDownloadPolicy'; + + /// When an incoming attachment is downloaded automatically. Default Wi-Fi: + /// arriving photos must not spend a mobile data plan on their own. + static Future getAutoDownloadPolicy() async { + Box box = await Hive.openBox(_settingsKey); + final stored = box.get(_autoDownloadKey) as String?; + return AutoDownloadPolicy.values.firstWhere( + (policy) => policy.name == stored, + orElse: () => AutoDownloadPolicy.wifi, + ); + } + + /// Sets when attachments are downloaded automatically. + static Future setAutoDownloadPolicy(AutoDownloadPolicy policy) async { + Box box = await Hive.openBox(_settingsKey); + await box.put(_autoDownloadKey, policy.name); + } /// Days after which this device drops an attachment's local copy, 0 = never. static Future getAutoDeleteMediaDays() async { diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index de01e69..8813ac4 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -24,6 +24,7 @@ import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import 'package:whisper_websocket_client_dart/models/private_message.dart'; import 'package:whisper_websocket_client_dart/models/ws_response.dart'; import 'package:whisper_websocket_client_dart/models/ws_response_type.dart'; +import 'auto_download.dart'; import 'cache_utils.dart'; import 'chat_sender.dart'; import 'crypto_utils.dart'; @@ -513,8 +514,13 @@ class Utils { } for (final entry in byPeer.entries) { await MessageNotifier().addMessages(entry.key, entry.value); - // Kick off media downloads now that placeholders are persisted. + // Kick off media downloads now that placeholders are persisted. The + // network setting decides which ones: what is skipped stays pending and + // the bubble offers a download button. for (final ref in pendingMediaRefs[entry.key] ?? const []) { + if (!await AutoDownload.allows(ref)) { + continue; + } // Fire-and-forget; updates the message + notifies on completion. MessageNotifier().downloadMediaMessage(entry.key, ref); } diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index aa9eb16..a025fba 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -248,7 +248,7 @@ class _MediaBubbleState extends State { ) : _fileWidget(); } else if (widget.message.downloadStatus == MediaDownloadStatus.pending) { - media = _placeholder(child: const CircularProgressIndicator()); + media = _pendingMedia(); } else if (widget.message.downloadStatus == MediaDownloadStatus.failed || widget.message.downloadStatus == MediaDownloadStatus.expired) { media = _failed(); @@ -382,6 +382,29 @@ class _MediaBubbleState extends State { ); } + /// A pending attachment waits for the network setting; the icon is also the + /// way to fetch it now. + Widget _pendingMedia() { + final retryable = widget.canRetry; + return InkWell( + onTap: retryable ? widget.onRetry : null, + child: Padding( + padding: const EdgeInsets.all(12), + child: retryable + ? Tooltip( + message: 'downloadMedia'.tr(), + child: Icon(Icons.download_for_offline_outlined, + size: 28, color: widget.textColor), + ) + : const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ), + ); + } + Widget _placeholder({required Widget child}) { final size = _displaySize(); return Container( diff --git a/pubspec.lock b/pubspec.lock index a19efff..b1bf256 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -217,6 +217,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.19.1" + connectivity_plus: + dependency: "direct main" + description: + name: connectivity_plus + sha256: d7749fd36d8b404a4935612b94eca7c3ce3705377ab678e24ff2a4301436f741 + url: "https://pub.dev" + source: hosted + version: "7.3.2" + connectivity_plus_platform_interface: + dependency: transitive + description: + name: connectivity_plus_platform_interface + sha256: "3c09627c536d22fd24691a905cdd8b14520de69da52c7a97499c8be5284a32ed" + url: "https://pub.dev" + source: hosted + version: "2.1.0" convert: dependency: transitive description: @@ -1148,6 +1164,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.0" + nm: + dependency: transitive + description: + name: nm + sha256: "2ae480aa3379716b8bb58dfebb168e2919394c92b629efaaa0baaa5d140786e6" + url: "https://pub.dev" + source: hosted + version: "0.6.0" objective_c: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 4cd2279..7473798 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -12,6 +12,7 @@ dependencies: basic_utils: ^5.7.0 bcrypt: ^1.1.3 chewie: ^1.17.4 + connectivity_plus: ^7.3.2 crypto: ^3.0.5 cryptography: ^2.7.0 dart_jsonwebtoken: ^3.2.0 diff --git a/test/auto_download_test.dart b/test/auto_download_test.dart new file mode 100644 index 0000000..c8b212d --- /dev/null +++ b/test/auto_download_test.dart @@ -0,0 +1,57 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/utils/auto_download.dart'; +import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper_websocket_client_dart/models/media_reference.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_auto_download_test'); + Hive.init(dir.path); + }); + + setUp(() async { + await Hive.openBox('settings'); + await Hive.box('settings').clear(); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + MediaReference reference(MediaType type, int size) => + MediaReference('id', Uint8List(32), type, size); + + test('a voice message is always fetched, whatever the network', () async { + await CacheUtils.setAutoDownloadPolicy(AutoDownloadPolicy.never); + + expect( + await AutoDownload.allows(reference(MediaType.voice, 5 << 20)), isTrue); + expect(await AutoDownload.allows(reference(MediaType.sticker, 5 << 20)), + isTrue); + }); + + test('a large photo is not fetched under the never policy', () async { + await CacheUtils.setAutoDownloadPolicy(AutoDownloadPolicy.never); + + expect(await AutoDownload.allows(reference(MediaType.image, 4 << 20)), + isFalse); + }); + + test('a small attachment is fetched even under the never policy', () async { + await CacheUtils.setAutoDownloadPolicy(AutoDownloadPolicy.never); + + expect(await AutoDownload.allows(reference(MediaType.image, 1024)), isTrue); + }); + + test('the default policy is Wi-Fi only', () async { + expect(await CacheUtils.getAutoDownloadPolicy(), AutoDownloadPolicy.wifi); + }); +} From f3f506be510c4ed2c8d2924b21da4c2a022ff5b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 22:03:19 +0100 Subject: [PATCH 138/181] feat(app): edit a photo or trim a video before sending it --- assets/translations/cs.json | 10 +- assets/translations/en.json | 10 +- lib/pages/chat_page.dart | 45 +++- lib/pages/image_editor_page.dart | 304 ++++++++++++++++++++++ lib/pages/video_trim_page.dart | 102 ++++++++ lib/widgets/attachment_confirm_sheet.dart | 27 +- pubspec.lock | 16 ++ pubspec.yaml | 2 + 8 files changed, 506 insertions(+), 10 deletions(-) create mode 100644 lib/pages/image_editor_page.dart create mode 100644 lib/pages/video_trim_page.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 36e8a9b..3a43acd 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -312,5 +312,13 @@ "autoDownloadAlways": "Vždy", "autoDownloadWifi": "Jen Wi-Fi", "autoDownloadNever": "Nikdy", - "downloadMedia": "Stáhnout" + "downloadMedia": "Stáhnout", + "editAttachment": "Upravit", + "editImage": "Upravit fotku", + "rotate": "Otočit", + "crop": "Ořez", + "draw": "Kreslit", + "undo": "Zpět", + "applyCrop": "Použít ořez", + "trimVideo": "Oříznout video" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 6649501..71a0ffb 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -312,5 +312,13 @@ "autoDownloadAlways": "Always", "autoDownloadWifi": "Wi-Fi only", "autoDownloadNever": "Never", - "downloadMedia": "Download" + "downloadMedia": "Download", + "editAttachment": "Edit", + "editImage": "Edit photo", + "rotate": "Rotate", + "crop": "Crop", + "draw": "Draw", + "undo": "Undo", + "applyCrop": "Apply crop", + "trimVideo": "Trim video" } diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 2c4d3ea..0ea1aa7 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -5,6 +5,7 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; +import 'package:path_provider/path_provider.dart'; import 'package:sprintf/sprintf.dart'; import '../utils/dialog_utils.dart'; import '../utils/nav_transitions.dart'; @@ -28,6 +29,8 @@ import '../widgets/chat_bubble.dart'; import '../widgets/live_location_bubble.dart'; import '../widgets/typing_dots.dart'; import 'chat_info_page.dart'; +import 'image_editor_page.dart'; +import 'video_trim_page.dart'; import 'forward_page.dart'; class ChatPage extends StatefulWidget { @@ -972,12 +975,22 @@ class _ChatPageState extends State { final type = single ? forcedType ?? MediaUtils.detectType(files.first.path) : null; // Any picked attachment can travel as a single view: one visual file, a - // gallery album or a plain document all burn the same way. - final confirmed = - await _confirmAttachment(files.length, allowViewOnce: true); + // gallery album or a plain document all burn the same way. Only a single + // photo or video can be edited first. + final editable = + single && (type == MediaType.image || type == MediaType.video); + final confirmed = await _confirmAttachment(files.length, + allowViewOnce: true, allowEdit: editable); if (confirmed == null) { return; } + if (single && confirmed.edit) { + final edited = await _editAttachment(type!, files.first); + if (edited == null) { + return; + } + files = [edited]; + } if (single) { await _sendMedia(type!, files.first, caption: confirmed.caption, viewOnce: confirmed.viewOnce); @@ -991,6 +1004,29 @@ class _ChatPageState extends State { } } + /// Runs the editor for one picked attachment. Returns null when the user + /// backs out, which aborts the send instead of silently sending the original. + Future _editAttachment(MediaType type, File file) async { + if (type == MediaType.image) { + final bytes = await file.readAsBytes(); + if (!mounted) { + return null; + } + final edited = await ImageEditorPage.open(context, bytes); + if (edited == null) { + return null; + } + final dir = await getTemporaryDirectory(); + final path = + '${dir.path}/whisper_edited_${DateTime.now().microsecondsSinceEpoch}.png'; + return File(path)..writeAsBytesSync(edited, flush: true); + } + if (!mounted) { + return null; + } + return VideoTrimPage.open(context, file); + } + /// Sends one fix as a location message. No coordinates are read until the /// user picks this action, and they travel only inside the ciphertext. Future _sendCurrentLocation() async { @@ -1078,11 +1114,12 @@ class _ChatPageState extends State { /// Bottom sheet with a caption field; returns the caption and the view-once /// choice, or null to cancel. Future _confirmAttachment(int count, - {bool allowViewOnce = false}) { + {bool allowViewOnce = false, bool allowEdit = false}) { return AttachmentConfirmSheet.show( context, count: count, allowViewOnce: allowViewOnce, + allowEdit: allowEdit, initialCaption: _controllerMessage.text.trim(), theme: ThemeUtils.chatTheme(context, _chatThemeColor), backgroundColor: chatBackground(tintAlpha: 0.18), diff --git a/lib/pages/image_editor_page.dart b/lib/pages/image_editor_page.dart new file mode 100644 index 0000000..b91e417 --- /dev/null +++ b/lib/pages/image_editor_page.dart @@ -0,0 +1,304 @@ +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:crop_your_image/crop_your_image.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +enum _EditMode { preview, crop, draw } + +/// Crop, rotate and draw on a photo before it leaves the device. +/// +/// Returns the edited bytes from [open], or null when the user backs out. The +/// strokes and the rotation are composited into a PNG at the original +/// resolution, so nothing is lost to the preview size. +class ImageEditorPage extends StatefulWidget { + const ImageEditorPage(this.bytes, {super.key}); + + final Uint8List bytes; + + /// Opens the editor and returns the edited bytes, or null. + static Future open(BuildContext context, Uint8List bytes) { + return Navigator.push( + context, MaterialPageRoute(builder: (_) => ImageEditorPage(bytes))); + } + + @override + State createState() => _ImageEditorPageState(); +} + +class _ImageEditorPageState extends State { + static const Color _ink = Color(0xFFFF3B30); + + final CropController _cropController = CropController(); + late Uint8List _bytes = widget.bytes; + _EditMode _mode = _EditMode.preview; + final List> _strokes = []; + bool _busy = false; + + /// Width of a stroke relative to the picture, so the line looks the same at + /// any screen size and at the exported resolution. + static const double _strokeFraction = 1 / 60; + + Future _rotate() async { + setState(() => _busy = true); + try { + final rendered = await _render(_bytes, _strokes, quarterTurns: 1); + _strokes.clear(); + setState(() => _bytes = rendered); + } finally { + if (mounted) { + setState(() => _busy = false); + } + } + } + + Future _done() async { + setState(() => _busy = true); + try { + final rendered = await _render(_bytes, _strokes); + if (mounted) { + Navigator.pop(context, rendered); + } + } finally { + if (mounted) { + setState(() => _busy = false); + } + } + } + + void _undo() { + if (_strokes.isEmpty) { + return; + } + setState(() => _strokes.removeLast()); + } + + /// Draws [strokes] over the decoded [base] and rotates by [quarterTurns] 90° + /// steps, all at the image's own resolution. + Future _render(Uint8List base, List> strokes, + {int quarterTurns = 0}) async { + final codec = await ui.instantiateImageCodec(base); + final frame = await codec.getNextFrame(); + final image = frame.image; + final width = image.width; + final height = image.height; + final swap = quarterTurns.isOdd; + final recorder = ui.PictureRecorder(); + final canvas = Canvas(recorder); + if (swap) { + canvas.translate(height.toDouble(), 0); + canvas.rotate(1.5707963267948966); + } + canvas.drawImage(image, Offset.zero, Paint()); + final paint = Paint() + ..color = _ink + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..strokeWidth = width * _strokeFraction; + for (final stroke in strokes) { + if (stroke.length == 1) { + final point = stroke.first; + canvas.drawPoints(ui.PointMode.points, + [Offset(point.dx * width, point.dy * height)], paint); + continue; + } + final path = Path(); + for (var i = 0; i < stroke.length; i++) { + final point = Offset(stroke[i].dx * width, stroke[i].dy * height); + i == 0 + ? path.moveTo(point.dx, point.dy) + : path.lineTo(point.dx, point.dy); + } + canvas.drawPath(path, paint); + } + final picture = recorder.endRecording(); + final output = + await picture.toImage(swap ? height : width, swap ? width : height); + final data = await output.toByteData(format: ui.ImageByteFormat.png); + picture.dispose(); + output.dispose(); + image.dispose(); + return data!.buffer.asUint8List(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text('editImage'.tr()), + actions: [ + IconButton( + tooltip: 'rotate'.tr(), + onPressed: _busy || _mode == _EditMode.crop ? null : _rotate, + icon: const Icon(Icons.rotate_90_degrees_ccw), + ), + IconButton( + tooltip: 'crop'.tr(), + onPressed: _busy + ? null + : () => setState(() { + _mode = _mode == _EditMode.crop + ? _EditMode.preview + : _EditMode.crop; + }), + icon: Icon(_mode == _EditMode.crop ? Icons.check : Icons.crop), + ), + IconButton( + tooltip: 'draw'.tr(), + onPressed: _busy + ? null + : () => setState(() { + _mode = _mode == _EditMode.draw + ? _EditMode.preview + : _EditMode.draw; + }), + icon: Icon(_mode == _EditMode.draw ? Icons.edit : Icons.brush), + ), + if (_mode == _EditMode.draw) + IconButton( + tooltip: 'undo'.tr(), + onPressed: _strokes.isEmpty ? null : _undo, + icon: const Icon(Icons.undo), + ), + IconButton( + tooltip: 'save'.tr(), + onPressed: _busy ? null : _done, + icon: const Icon(Icons.check_circle), + ), + ], + ), + body: _busy + ? const Center(child: CircularProgressIndicator()) + : _mode == _EditMode.crop + ? _cropView() + : _drawView(), + ); + } + + Widget _cropView() { + return Column( + children: [ + Expanded( + child: Crop( + image: _bytes, + controller: _cropController, + onCropped: (result) { + switch (result) { + case CropSuccess(:final croppedImage): + setState(() { + _bytes = croppedImage; + _strokes.clear(); + _mode = _EditMode.preview; + }); + case CropFailure(): + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text('mediaError'.tr()))); + } + }, + ), + ), + SafeArea( + child: Padding( + padding: const EdgeInsets.all(12), + child: SizedBox( + width: double.infinity, + child: FilledButton( + onPressed: () => _cropController.crop(), + child: Text('applyCrop'.tr()), + ), + ), + ), + ), + ], + ); + } + + Widget _drawView() { + return Center( + child: LayoutBuilder( + builder: (context, constraints) { + final drawing = _mode == _EditMode.draw; + return GestureDetector( + onPanStart: drawing + ? (details) => setState(() { + _strokes.add( + [_normalize(details.localPosition, constraints)]); + }) + : null, + onPanUpdate: drawing + ? (details) => setState(() { + _strokes.last + .add(_normalize(details.localPosition, constraints)); + }) + : null, + child: Stack( + children: [ + Image.memory(_bytes), + Positioned.fill( + child: CustomPaint( + painter: _StrokePainter(_strokes, _ink), + ), + ), + ], + ), + ); + }, + ), + ); + } + + /// Strokes are kept relative to the picture, so the export does not depend on + /// the size it was drawn at. + Offset _normalize(Offset local, BoxConstraints constraints) { + return Offset( + (local.dx / constraints.maxWidth).clamp(0.0, 1.0), + (local.dy / constraints.maxHeight).clamp(0.0, 1.0), + ); + } +} + +class _StrokePainter extends CustomPainter { + _StrokePainter(this.strokes, this.color); + + final List> strokes; + final Color color; + + @override + void paint(Canvas canvas, Size size) { + final paint = Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..strokeWidth = size.width * _ImageEditorPageState._strokeFraction; + for (final stroke in strokes) { + if (stroke.length == 1) { + canvas.drawPoints( + ui.PointMode.points, + [ + Offset( + stroke.first.dx * size.width, stroke.first.dy * size.height) + ], + paint); + continue; + } + final path = Path(); + for (var i = 0; i < stroke.length; i++) { + final point = + Offset(stroke[i].dx * size.width, stroke[i].dy * size.height); + i == 0 + ? path.moveTo(point.dx, point.dy) + : path.lineTo(point.dx, point.dy); + } + canvas.drawPath(path, paint); + } + } + + @override + bool shouldRepaint(covariant _StrokePainter oldDelegate) => + oldDelegate.strokes.length != strokes.length || + (strokes.isNotEmpty && + oldDelegate.strokes.last.length != strokes.last.length); +} diff --git a/lib/pages/video_trim_page.dart b/lib/pages/video_trim_page.dart new file mode 100644 index 0000000..28b14a1 --- /dev/null +++ b/lib/pages/video_trim_page.dart @@ -0,0 +1,102 @@ +import 'dart:io'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:video_trimmer/video_trimmer.dart'; + +/// Picks the part of a video that is worth sending. +/// +/// The platform encoder does the cut (Media3 on Android), so the output is a +/// plain mp4 that every recipient can play. Returns the trimmed file from +/// [open], or null when the user backs out. +class VideoTrimPage extends StatefulWidget { + const VideoTrimPage(this.file, {super.key}); + + final File file; + + static Future open(BuildContext context, File file) { + return Navigator.push( + context, MaterialPageRoute(builder: (_) => VideoTrimPage(file))); + } + + @override + State createState() => _VideoTrimPageState(); +} + +class _VideoTrimPageState extends State { + final Trimmer _trimmer = Trimmer(); + double _startValue = 0; + double _endValue = 1; + bool _ready = false; + bool _saving = false; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + await _trimmer.loadVideo(videoPath: widget.file.path); + if (mounted) { + setState(() => _ready = true); + } + } + + Future _save() async { + setState(() => _saving = true); + await _trimmer.saveTrimmedVideo( + startValue: _startValue, + endValue: _endValue, + onSave: (path) { + if (!mounted) { + return; + } + Navigator.pop(context, path == null ? null : File(path)); + }, + ); + if (mounted) { + setState(() => _saving = false); + } + } + + @override + void dispose() { + _trimmer.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text('trimVideo'.tr()), + actions: [ + IconButton( + tooltip: 'save'.tr(), + onPressed: _ready && !_saving ? _save : null, + icon: _saving + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2)) + : const Icon(Icons.check_circle), + ), + ], + ), + body: !_ready + ? const Center(child: CircularProgressIndicator()) + : SafeArea( + child: Center( + child: TrimViewer( + trimmer: _trimmer, + viewerWidth: MediaQuery.sizeOf(context).width, + viewerHeight: 240, + onChangeStart: (value) => _startValue = value, + onChangeEnd: (value) => _endValue = value, + ), + ), + ), + ); + } +} diff --git a/lib/widgets/attachment_confirm_sheet.dart b/lib/widgets/attachment_confirm_sheet.dart index 8823d5f..aa9a2e4 100644 --- a/lib/widgets/attachment_confirm_sheet.dart +++ b/lib/widgets/attachment_confirm_sheet.dart @@ -1,13 +1,18 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; -/// What the sender chose in [AttachmentConfirmSheet]: the caption, and whether -/// the attachment travels as a view-once one. +/// What the sender chose in [AttachmentConfirmSheet]: the caption, whether the +/// attachment travels as a view-once one, and whether it should be edited first. class AttachmentConfirmResult { - const AttachmentConfirmResult({required this.caption, this.viewOnce = false}); + const AttachmentConfirmResult( + {required this.caption, this.viewOnce = false, this.edit = false}); final String caption; final bool viewOnce; + + /// The sender wants the editor before sending: crop/draw for a photo, trim + /// for a video. + final bool edit; } /// Sheet shown after picking an attachment: an optional caption, an optional @@ -23,10 +28,14 @@ class AttachmentConfirmSheet extends StatefulWidget { /// attachment, never an album or a file). final bool allowViewOnce; + /// Whether the picker offers the editor (one photo or one video). + final bool allowEdit; + const AttachmentConfirmSheet({ required this.count, this.initialCaption = '', this.allowViewOnce = false, + this.allowEdit = false, super.key, }); @@ -39,6 +48,7 @@ class AttachmentConfirmSheet extends StatefulWidget { {required int count, String initialCaption = '', bool allowViewOnce = false, + bool allowEdit = false, ThemeData? theme, Color? backgroundColor}) { return showModalBottomSheet( @@ -51,6 +61,7 @@ class AttachmentConfirmSheet extends StatefulWidget { count: count, initialCaption: initialCaption, allowViewOnce: allowViewOnce, + allowEdit: allowEdit, ); return theme == null ? sheet : Theme(data: theme, child: sheet); }, @@ -66,12 +77,13 @@ class _AttachmentConfirmSheetState extends State { TextEditingController(text: widget.initialCaption); bool _viewOnce = false; - void _send() { + void _send({bool edit = false}) { Navigator.pop( context, AttachmentConfirmResult( caption: _controller.text.trim(), viewOnce: _viewOnce, + edit: edit, )); } @@ -127,6 +139,13 @@ class _AttachmentConfirmSheetState extends State { onPressed: () => Navigator.pop(context), child: Text('cancel'.tr()), ), + const Spacer(), + if (widget.allowEdit) + TextButton.icon( + onPressed: () => _send(edit: true), + icon: const Icon(Icons.tune), + label: Text('editAttachment'.tr()), + ), const SizedBox(width: 8), FilledButton( onPressed: _send, diff --git a/pubspec.lock b/pubspec.lock index b1bf256..6dff40b 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -241,6 +241,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.2" + crop_your_image: + dependency: "direct main" + description: + name: crop_your_image + sha256: "8cd2936d5e2f1a23b330390df0c7e59d685892d63f374196e498905e0896cc2c" + url: "https://pub.dev" + source: hosted + version: "2.0.1" cross_file: dependency: transitive description: @@ -1785,6 +1793,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.4.0" + video_trimmer: + dependency: "direct main" + description: + name: video_trimmer + sha256: b6d16e80bb7df0ad5acbde6b69359df14a60e866643afd7402db6a494fa0513a + url: "https://pub.dev" + source: hosted + version: "6.0.0" vm_service: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 7473798..c43a8a5 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -13,6 +13,8 @@ dependencies: bcrypt: ^1.1.3 chewie: ^1.17.4 connectivity_plus: ^7.3.2 + crop_your_image: ^2.0.1 + video_trimmer: ^6.0.0 crypto: ^3.0.5 cryptography: ^2.7.0 dart_jsonwebtoken: ^3.2.0 From b652df5783e417c09fa1246047be1c7192d02cef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 22:04:43 +0100 Subject: [PATCH 139/181] feat(app): custom stickers imported from a file --- assets/translations/cs.json | 6 +- assets/translations/en.json | 6 +- lib/pages/chat_page.dart | 23 ++++++ lib/utils/cache_utils.dart | 26 +++++++ lib/utils/sticker_store.dart | 69 ++++++++++++++++++ lib/widgets/media_bubble.dart | 8 +++ lib/widgets/sticker_sheet.dart | 125 +++++++++++++++++++++++++++++++++ 7 files changed, 261 insertions(+), 2 deletions(-) create mode 100644 lib/utils/sticker_store.dart create mode 100644 lib/widgets/sticker_sheet.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 3a43acd..8a43a42 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -320,5 +320,9 @@ "draw": "Kreslit", "undo": "Zpět", "applyCrop": "Použít ořez", - "trimVideo": "Oříznout video" + "trimVideo": "Oříznout video", + "attachStickers": "Nálepky", + "stickerUnsupported": "Tenhle soubor nejde použít jako nálepku", + "deleteSticker": "Smazat nálepku", + "deleteStickerConfirm": "Nálepka se z tohoto zařízení smaže. Opravdu?" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 71a0ffb..0ecb909 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -320,5 +320,9 @@ "draw": "Draw", "undo": "Undo", "applyCrop": "Apply crop", - "trimVideo": "Trim video" + "trimVideo": "Trim video", + "attachStickers": "Stickers", + "stickerUnsupported": "This file cannot be used as a sticker", + "deleteSticker": "Delete sticker", + "deleteStickerConfirm": "The sticker is removed from this device. Continue?" } diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 0ea1aa7..838ae75 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -29,6 +29,7 @@ import '../widgets/chat_bubble.dart'; import '../widgets/live_location_bubble.dart'; import '../widgets/typing_dots.dart'; import 'chat_info_page.dart'; +import '../widgets/sticker_sheet.dart'; import 'image_editor_page.dart'; import 'video_trim_page.dart'; import 'forward_page.dart'; @@ -1004,6 +1005,20 @@ class _ChatPageState extends State { } } + /// Opens the sticker collection and sends the picked one as it is: a sticker + /// travels as its own media type, so the recipient draws it without a bubble. + Future _pickSticker() async { + final sticker = await StickerSheet.show(context); + if (sticker == null) { + return; + } + final bytes = await MediaUtils.decryptAtRest(sticker.path); + final sent = await ChatSender.sendMedia( + widget.user, MediaType.sticker, bytes, + fileName: MediaUtils.baseName(sticker.path)); + _afterSend(sent, ''); + } + /// Runs the editor for one picked attachment. Returns null when the user /// backs out, which aborts the send instead of silently sending the original. Future _editAttachment(MediaType type, File file) async { @@ -1179,6 +1194,14 @@ class _ChatPageState extends State { _pickAndSend(MediaUtils.pickMultipleMediaFromGallery); }, ), + ListTile( + leading: const Icon(Icons.emoji_emotions_outlined), + title: Text('attachStickers'.tr()), + onTap: () { + Navigator.pop(ctx); + _pickSticker(); + }, + ), ListTile( leading: const Icon(Icons.insert_drive_file), title: Text('attachFile'.tr()), diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 2014f6c..09005d3 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -428,6 +428,32 @@ class CacheUtils { static const String _autoDeleteMediaKey = 'autoDeleteMediaDays'; static const String _autoDownloadKey = 'autoDownloadPolicy'; + static const String _stickersKey = 'stickers'; + + /// Sticker ids mapped to their encrypted-at-rest file, oldest first. + static Future> getStickers() async { + CollectionBox box = await _openBox(_stickersKey); + final stickers = {}; + for (final entry in (await box.getAllValues()).entries) { + final value = entry.value; + if (value is String) { + stickers[entry.key] = value; + } + } + return stickers; + } + + /// Records one imported sticker. + static Future putSticker(String id, String path) async { + CollectionBox box = await _openBox(_stickersKey); + await box.put(id, path); + } + + /// Forgets one sticker; the caller deletes its file. + static Future deleteSticker(String id) async { + CollectionBox box = await _openBox(_stickersKey); + await box.delete(id); + } /// When an incoming attachment is downloaded automatically. Default Wi-Fi: /// arriving photos must not spend a mobile data plan on their own. diff --git a/lib/utils/sticker_store.dart b/lib/utils/sticker_store.dart new file mode 100644 index 0000000..0007bcf --- /dev/null +++ b/lib/utils/sticker_store.dart @@ -0,0 +1,69 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:uuid/uuid.dart'; + +import 'cache_utils.dart'; +import 'media_utils.dart'; + +/// One sticker of the local collection. +class Sticker { + const Sticker(this.id, this.path); + + /// Id of the entry in the sticker box. + final String id; + + /// Encrypted-at-rest file on this device. + final String path; +} + +/// Custom stickers: pictures imported from a file, kept on this device. +/// +/// There is no third-party sticker store: the bytes are the user's, encrypted +/// at rest like every other attachment, and the only metadata is the path. +class StickerStore { + StickerStore._(); + + static const Uuid _uuid = Uuid(); + + /// Extensions a sticker may have. The renderer plays animated GIFs natively, + /// so both still and animated stickers work without extra code. + static const List _extensions = ['.png', '.gif', '.webp', '.jpg']; + + static bool _supported(String? fileName) { + if (fileName == null) { + return false; + } + final lower = fileName.toLowerCase(); + return _extensions.any(lower.endsWith); + } + + /// Every sticker still present on disk, oldest first. + static Future> all() async { + final entries = await CacheUtils.getStickers(); + final stickers = []; + for (final entry in entries.entries) { + if (File(entry.value).existsSync()) { + stickers.add(Sticker(entry.key, entry.value)); + } + } + return stickers; + } + + /// Imports [bytes] as a new sticker. Null when the file is not a picture. + static Future add(Uint8List bytes, String? fileName) async { + if (!_supported(fileName)) { + return null; + } + final path = await MediaUtils.encryptAtRest(bytes); + final sticker = Sticker(_uuid.v4(), path); + await CacheUtils.putSticker(sticker.id, sticker.path); + return sticker; + } + + /// Removes a sticker and its file. + static Future remove(Sticker sticker) async { + await CacheUtils.deleteSticker(sticker.id); + await MediaUtils.deleteLocalFile(sticker.path); + } +} diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index a025fba..e0dacf6 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -292,6 +292,14 @@ class _MediaBubbleState extends State { ); } + // A sticker is drawn bare: no bubble, no rounded frame, its own size. + if (type == MediaType.sticker) { + return _withCaption( + SizedBox(width: 160, height: 160, child: Center(child: media)), + hasCaption, + ); + } + // Visual media: rounded thumbnail with optional caption underneath. return _withCaption(media, hasCaption); } diff --git a/lib/widgets/sticker_sheet.dart b/lib/widgets/sticker_sheet.dart new file mode 100644 index 0000000..aabad6d --- /dev/null +++ b/lib/widgets/sticker_sheet.dart @@ -0,0 +1,125 @@ +import 'dart:typed_data'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +import '../utils/dialog_utils.dart'; +import '../utils/media_utils.dart'; +import '../utils/sticker_store.dart'; + +/// The local sticker collection: tap one to send it, long-press to delete, +/// "+" to import a picture from a file. +class StickerSheet extends StatefulWidget { + const StickerSheet({super.key}); + + /// Shows the collection and returns the sticker the user picked, or null. + static Future show(BuildContext context) { + return showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (_) => const StickerSheet(), + ); + } + + @override + State createState() => _StickerSheetState(); +} + +class _StickerSheetState extends State { + List _stickers = const []; + bool _loading = true; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + final stickers = await StickerStore.all(); + if (!mounted) { + return; + } + setState(() { + _stickers = stickers; + _loading = false; + }); + } + + Future _import() async { + final picked = await MediaUtils.pickMultipleMediaFromGallery(); + var added = 0; + for (final file in picked) { + final sticker = await StickerStore.add( + await file.readAsBytes(), MediaUtils.baseName(file.path)); + if (sticker != null) { + added++; + } + } + if (picked.isNotEmpty && added == 0) { + await Fluttertoast.showToast( + msg: 'stickerUnsupported'.tr(), backgroundColor: Colors.orange); + } + await _load(); + } + + Future _delete(Sticker sticker) async { + await DialogUtils.yesNoDialog( + context, 'deleteSticker'.tr(), 'deleteStickerConfirm'.tr(), () async { + await StickerStore.remove(sticker); + await _load(); + }); + } + + @override + Widget build(BuildContext context) { + return SafeArea( + child: SizedBox( + height: 320, + child: _loading + ? const Center(child: CircularProgressIndicator()) + : GridView.builder( + padding: const EdgeInsets.all(12), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 4, + mainAxisSpacing: 8, + crossAxisSpacing: 8, + ), + itemCount: _stickers.length + 1, + itemBuilder: (context, index) { + if (index == _stickers.length) { + return InkWell( + onTap: _import, + child: DecoratedBox( + decoration: BoxDecoration( + border: + Border.all(color: Theme.of(context).dividerColor), + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.add), + ), + ); + } + final sticker = _stickers[index]; + return GestureDetector( + onTap: () => Navigator.pop(context, sticker), + onLongPress: () => _delete(sticker), + child: FutureBuilder( + future: MediaUtils.decryptAtRest(sticker.path), + builder: (context, snapshot) { + if (!snapshot.hasData) { + return const Center( + child: CircularProgressIndicator(strokeWidth: 2)); + } + return Image.memory(snapshot.data!, + fit: BoxFit.contain); + }, + ), + ); + }, + ), + ), + ); + } +} From 2811bcab601b7267c1e8a639eb9f1db1d757d37a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 22:07:38 +0100 Subject: [PATCH 140/181] feat(app): share to another app and receive Android shares --- android/app/src/main/AndroidManifest.xml | 35 ++++++- assets/translations/cs.json | 5 +- assets/translations/en.json | 5 +- lib/main.dart | 4 + lib/pages/whisper_page.dart | 2 + lib/utils/app_navigator.dart | 5 + lib/utils/cache_utils.dart | 6 ++ lib/utils/message_actions.dart | 46 +++++++++ lib/utils/share_intent.dart | 124 +++++++++++++++++++++++ pubspec.lock | 24 +++++ pubspec.yaml | 2 + test/message_actions_test.dart | 1 + 12 files changed, 256 insertions(+), 3 deletions(-) create mode 100644 lib/utils/app_navigator.dart create mode 100644 lib/utils/share_intent.dart diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 9e5b9cc..c9f0124 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -38,7 +38,7 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 8a43a42..a7e7a0b 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -324,5 +324,8 @@ "attachStickers": "Nálepky", "stickerUnsupported": "Tenhle soubor nejde použít jako nálepku", "deleteSticker": "Smazat nálepku", - "deleteStickerConfirm": "Nálepka se z tohoto zařízení smaže. Opravdu?" + "deleteStickerConfirm": "Nálepka se z tohoto zařízení smaže. Opravdu?", + "shareMessage": "Sdílet do jiné aplikace", + "shareToChat": "Sdílet do chatu", + "shareFailed": "Sdílení se nepovedlo" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 0ecb909..c4bab76 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -324,5 +324,8 @@ "attachStickers": "Stickers", "stickerUnsupported": "This file cannot be used as a sticker", "deleteSticker": "Delete sticker", - "deleteStickerConfirm": "The sticker is removed from this device. Continue?" + "deleteStickerConfirm": "The sticker is removed from this device. Continue?", + "shareMessage": "Share to another app", + "shareToChat": "Share to a chat", + "shareFailed": "Sharing failed" } diff --git a/lib/main.dart b/lib/main.dart index e1801d7..76b8086 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -21,6 +21,7 @@ import 'models/profile.dart'; import 'models/user.dart'; import 'pages/whisper_page.dart'; import 'utils/media_utils.dart'; +import 'utils/share_intent.dart'; import 'utils/storage_utils.dart'; import 'utils/notification_service.dart'; import 'utils/singleton.dart'; @@ -88,6 +89,9 @@ void main() async { // Same for attachments the user asked to drop after a while. await StorageUtils.purgeIfDue(); + // Pictures and files shared from other apps arrive here. + SharedInbox.start(); + // Default theme Singleton().appTheme = await CacheUtils.getTheme() ?? AppTheme.fromValues(ThemeMode.system, Colors.blue); diff --git a/lib/pages/whisper_page.dart b/lib/pages/whisper_page.dart index 765221a..2076572 100644 --- a/lib/pages/whisper_page.dart +++ b/lib/pages/whisper_page.dart @@ -2,6 +2,7 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import '../utils/app_navigator.dart'; import '../utils/page_navigator_observer.dart'; import '../utils/theme_notifier.dart'; import '../pages/scan_invite_button_page.dart'; @@ -52,6 +53,7 @@ class WhisperPage extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( + navigatorKey: appNavigatorKey, navigatorObservers: [PageNavigatorObserver()], debugShowCheckedModeBanner: true, // Every DateFormat in the app (chat rows, bubbles, day headers, search) diff --git a/lib/utils/app_navigator.dart b/lib/utils/app_navigator.dart new file mode 100644 index 0000000..19d5d32 --- /dev/null +++ b/lib/utils/app_navigator.dart @@ -0,0 +1,5 @@ +import 'package:flutter/widgets.dart'; + +/// Navigator of the running app, for code that has no widget of its own: an +/// inbound share has to open a chat picker before any screen exists. +final GlobalKey appNavigatorKey = GlobalKey(); diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 09005d3..71d9714 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -1045,6 +1045,12 @@ class CacheUtils { return Hive.openBox(_userKey); } + /// Every cached contact, for pickers that are not tied to one chat. + static Future> getAllUsers() async { + Box box = await _openUserBox(); + return box.values.whereType().toList(); + } + /// Gets user by ID static Future getUserById(String userId) async { Box box = await _openUserBox(); diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 73f89d1..13b8e3c 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -1,4 +1,5 @@ import 'dart:convert'; +import 'dart:io'; import 'package:basic_utils/basic_utils.dart' as bu; import 'package:easy_localization/easy_localization.dart'; @@ -6,7 +7,10 @@ import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:share_plus/share_plus.dart'; import 'package:url_launcher/url_launcher.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; import 'package:whisper_openapi_client_dart/api.dart'; import '../models/private_message.dart'; @@ -276,6 +280,15 @@ class MessageActions { forward(context, [message]); }, ), + if (canShare(message)) + ListTile( + leading: const Icon(Icons.ios_share), + title: Text('shareMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + shareToApp(message); + }, + ), if (canSave(message)) ListTile( leading: const Icon(saveIcon), @@ -449,6 +462,39 @@ class MessageActions { } } + /// Whether the message can be handed to another app. + static bool canShare(PrivateMessage message) => + !message.viewOnce && + (message.message.isNotEmpty || message.localPath != null); + + /// Hand the text, or a decrypted copy of the attachment, to another app. + /// + /// The plaintext copy is written under the temporary-media prefix, so it is + /// swept on the next start even if the app is killed while sharing; here it + /// is deleted as soon as the share sheet returns. + static Future shareToApp(PrivateMessage message) async { + final path = message.localPath; + try { + if (path == null) { + await SharePlus.instance.share(ShareParams(text: message.message)); + return; + } + final bytes = await MediaUtils.decryptAtRest(path); + final dir = await getTemporaryDirectory(); + final file = File( + '${dir.path}/whisper_send_share_${message.sentAt.microsecondsSinceEpoch}${MediaUtils.extensionForType(message.mediaType ?? MediaType.file)}'); + await file.writeAsBytes(bytes, flush: true); + await SharePlus.instance.share(ShareParams( + files: [XFile(file.path)], + text: message.message.isEmpty ? null : message.message, + )); + await MediaUtils.deleteLocalFile(file.path); + } catch (_) { + Fluttertoast.showToast( + msg: 'shareFailed'.tr(), backgroundColor: Colors.red); + } + } + /// Save the decrypted attachment wherever the user picks. static Future save(PrivateMessage message) async { final path = message.localPath; diff --git a/lib/utils/share_intent.dart b/lib/utils/share_intent.dart new file mode 100644 index 0000000..060919e --- /dev/null +++ b/lib/utils/share_intent.dart @@ -0,0 +1,124 @@ +import 'dart:io'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:receive_sharing_intent/receive_sharing_intent.dart'; + +import '../models/user.dart'; +import '../pages/chat_page.dart'; +import 'app_navigator.dart'; +import 'cache_utils.dart'; +import 'chat_sender.dart'; +import 'media_utils.dart'; + +/// Receives pictures, videos and files shared from other apps. +/// +/// The picked chat decides where the files go; nothing is sent before the user +/// picks one, so a share into the app cannot become a message to the wrong +/// person. +class SharedInbox { + SharedInbox._(); + + /// How many shared files one message may carry. + static const int maxFiles = 10; + + /// Starts listening for inbound shares: once for a cold start, and then for + /// every share while the app runs. + static Future start() async { + try { + final initial = await ReceiveSharingIntent.instance.getInitialMedia(); + if (initial.isNotEmpty) { + ReceiveSharingIntent.instance.reset(); + await _offer(initial); + } + ReceiveSharingIntent.instance.getMediaStream().listen((shared) { + if (shared.isNotEmpty) { + _offer(shared); + } + }); + } catch (_) { + // A platform without share intents simply has no inbox. + } + } + + static Future _offer(List shared) async { + final navigator = appNavigatorKey.currentState; + if (navigator == null) { + return; + } + final users = await CacheUtils.getAllUsers(); + if (users.isEmpty) { + return; + } + final target = await showModalBottomSheet( + context: navigator.context, + showDragHandle: true, + builder: (ctx) => SafeArea( + child: ListView( + shrinkWrap: true, + children: [ + Padding( + padding: const EdgeInsets.all(16), + child: Text('shareToChat'.tr(), + style: Theme.of(ctx).textTheme.titleMedium), + ), + for (final user in users) + ListTile( + leading: CircleAvatar( + backgroundColor: user.avatarColor, + child: Text(user.username.isEmpty + ? '?' + : user.username[0].toUpperCase()), + ), + title: Text(user.username), + onTap: () => Navigator.pop(ctx, user), + ), + ], + ), + ), + ); + if (target == null) { + return; + } + await _send(target, shared.take(maxFiles).toList()); + } + + static Future _send(User target, List shared) async { + try { + if (shared.length == 1) { + final file = File(shared.single.path); + final bytes = await file.readAsBytes(); + if (!MediaUtils.uploadFits(bytes.length)) { + throw Exception('fileTooLarge'.tr()); + } + await ChatSender.sendMedia( + target, MediaUtils.detectType(file.path), bytes, + fileName: MediaUtils.baseName(file.path)); + } else { + final attachments = []; + for (final item in shared) { + final file = File(item.path); + final bytes = await file.readAsBytes(); + if (!MediaUtils.uploadFits(bytes.length)) { + continue; + } + attachments.add(OutgoingAttachment( + type: MediaUtils.detectType(file.path), + bytes: bytes, + fileName: MediaUtils.baseName(file.path), + )); + } + if (attachments.isEmpty) { + throw Exception('fileTooLarge'.tr()); + } + await ChatSender.sendAlbum(target, attachments); + } + appNavigatorKey.currentState + ?.push(MaterialPageRoute(builder: (_) => ChatPage(target))); + } catch (e) { + await Fluttertoast.showToast( + msg: e.toString(), backgroundColor: Colors.red); + } + } +} diff --git a/pubspec.lock b/pubspec.lock index 6dff40b..a7928fd 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1372,6 +1372,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.3" + receive_sharing_intent: + dependency: "direct main" + description: + name: receive_sharing_intent + sha256: "72f229a38f2910029c11d840770c173b27072e348ef3376130b37514bc4556f6" + url: "https://pub.dev" + source: hosted + version: "1.9.0" record: dependency: "direct main" description: @@ -1452,6 +1460,22 @@ packages: url: "https://pub.dev" source: hosted version: "0.2.3" + share_plus: + dependency: "direct main" + description: + name: share_plus + sha256: db40767f130189d53f3ae8a6393c217ff4a492da1baff718a9873679c0c00224 + url: "https://pub.dev" + source: hosted + version: "13.3.1" + share_plus_platform_interface: + dependency: transitive + description: + name: share_plus_platform_interface + sha256: "365ef7379fc22507256adda3385152942ffce08935452bc972c2e52a0bebae41" + url: "https://pub.dev" + source: hosted + version: "7.2.0" shared_preferences: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index c43a8a5..268944f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -14,6 +14,8 @@ dependencies: chewie: ^1.17.4 connectivity_plus: ^7.3.2 crop_your_image: ^2.0.1 + receive_sharing_intent: ^1.9.0 + share_plus: ^13.3.1 video_trimmer: ^6.0.0 crypto: ^3.0.5 cryptography: ^2.7.0 diff --git a/test/message_actions_test.dart b/test/message_actions_test.dart index 881d87f..578b62e 100644 --- a/test/message_actions_test.dart +++ b/test/message_actions_test.dart @@ -58,6 +58,7 @@ void main() { expect(find.text('Forward'), findsOneWidget); expect(find.text('Delete for me'), findsOneWidget); expect(find.text('Save attachment'), findsNothing); + expect(find.text('Share to another app'), findsOneWidget); // Close the sheet await tester.tapAt(const Offset(10, 10)); From 1a6d29bf96e11bd3b56daf40aa16186c51882449 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Sun, 22 Nov 2026 22:10:28 +0100 Subject: [PATCH 141/181] feat(app): record and send a round video note --- assets/translations/cs.json | 4 +- assets/translations/en.json | 4 +- lib/pages/chat_page.dart | 21 ++++ lib/pages/video_note_page.dart | 197 +++++++++++++++++++++++++++++++++ lib/utils/chat_sender.dart | 11 +- lib/widgets/media_bubble.dart | 22 ++++ pubspec.lock | 42 ++++++- pubspec.yaml | 3 +- 8 files changed, 298 insertions(+), 6 deletions(-) create mode 100644 lib/pages/video_note_page.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index a7e7a0b..165b870 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -327,5 +327,7 @@ "deleteStickerConfirm": "Nálepka se z tohoto zařízení smaže. Opravdu?", "shareMessage": "Sdílet do jiné aplikace", "shareToChat": "Sdílet do chatu", - "shareFailed": "Sdílení se nepovedlo" + "shareFailed": "Sdílení se nepovedlo", + "videoNote": "Kruhové video", + "cameraUnavailable": "Kamera není dostupná" } diff --git a/assets/translations/en.json b/assets/translations/en.json index c4bab76..114822f 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -327,5 +327,7 @@ "deleteStickerConfirm": "The sticker is removed from this device. Continue?", "shareMessage": "Share to another app", "shareToChat": "Share to a chat", - "shareFailed": "Sharing failed" + "shareFailed": "Sharing failed", + "videoNote": "Round video", + "cameraUnavailable": "Camera is not available" } diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 838ae75..08d4426 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -31,6 +31,7 @@ import '../widgets/typing_dots.dart'; import 'chat_info_page.dart'; import '../widgets/sticker_sheet.dart'; import 'image_editor_page.dart'; +import 'video_note_page.dart'; import 'video_trim_page.dart'; import 'forward_page.dart'; @@ -848,6 +849,7 @@ class _ChatPageState extends State { {String caption = '', int? durationMs, List? waveform, + bool videoNote = false, bool viewOnce = false}) async { setState(() { _isSending = true; @@ -862,6 +864,7 @@ class _ChatPageState extends State { durationMs: probe.durationMs, fileName: MediaUtils.baseName(file.path), waveform: waveform, + videoNote: videoNote, viewOnce: viewOnce); _afterSend(sent, caption); } catch (e) { @@ -1005,6 +1008,16 @@ class _ChatPageState extends State { } } + /// Records a round video note and sends it as it is: it is a glance, so no + /// caption and no editor. + Future _recordVideoNote() async { + final file = await VideoNotePage.open(context); + if (file == null) { + return; + } + await _sendMedia(MediaType.video, file, videoNote: true); + } + /// Opens the sticker collection and sends the picked one as it is: a sticker /// travels as its own media type, so the recipient draws it without a bubble. Future _pickSticker() async { @@ -1186,6 +1199,14 @@ class _ChatPageState extends State { }, forcedType: MediaType.video); }, ), + ListTile( + leading: const Icon(Icons.videocam_outlined), + title: Text('videoNote'.tr()), + onTap: () { + Navigator.pop(ctx); + _recordVideoNote(); + }, + ), ListTile( leading: const Icon(Icons.photo_library), title: Text('attachGallery'.tr()), diff --git a/lib/pages/video_note_page.dart b/lib/pages/video_note_page.dart new file mode 100644 index 0000000..e6aad5f --- /dev/null +++ b/lib/pages/video_note_page.dart @@ -0,0 +1,197 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:camera/camera.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +/// Records a round video note. +/// +/// The picture is drawn inside a circle here and on the recipient side; the +/// file is an ordinary mp4, so nothing about playback needs a new format. +class VideoNotePage extends StatefulWidget { + const VideoNotePage({super.key}); + + /// Longest video note, seconds. A note is a glance, not a video message. + static const Duration maxLength = Duration(seconds: 60); + + /// Opens the recorder and returns the recorded file, or null. + static Future open(BuildContext context) { + return Navigator.push( + context, MaterialPageRoute(builder: (_) => const VideoNotePage())); + } + + @override + State createState() => _VideoNotePageState(); +} + +class _VideoNotePageState extends State + with WidgetsBindingObserver { + CameraController? _controller; + Timer? _timer; + Duration _elapsed = Duration.zero; + bool _recording = false; + bool _ready = false; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _openCamera(); + } + + Future _openCamera() async { + try { + final cameras = await availableCameras(); + if (cameras.isEmpty) { + throw CameraException('noCamera', 'no camera on this device'); + } + // The front camera is what a video note is for: it is a message to a + // person, not a recording of the room. + final front = cameras.firstWhere( + (camera) => camera.lensDirection == CameraLensDirection.front, + orElse: () => cameras.first, + ); + final controller = + CameraController(front, ResolutionPreset.medium, enableAudio: true); + await controller.initialize(); + if (!mounted) { + await controller.dispose(); + return; + } + setState(() { + _controller = controller; + _ready = true; + }); + } catch (e) { + if (mounted) { + await Fluttertoast.showToast( + msg: 'cameraUnavailable'.tr(), backgroundColor: Colors.red); + Navigator.pop(context); + } + } + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + // The plugin does not park the camera by itself: leaving it running while + // the app is in the background keeps the camera light on. + final controller = _controller; + if (controller == null || !controller.value.isInitialized) { + return; + } + if (state == AppLifecycleState.inactive) { + controller.dispose(); + setState(() => _ready = false); + } else if (state == AppLifecycleState.resumed) { + _openCamera(); + } + } + + Future _toggleRecording() async { + final controller = _controller; + if (controller == null || !_ready) { + return; + } + if (_recording) { + await _stop(); + return; + } + try { + await controller.startVideoRecording(); + } catch (_) { + return; + } + setState(() { + _recording = true; + _elapsed = Duration.zero; + }); + _timer = Timer.periodic(const Duration(seconds: 1), (timer) { + if (!mounted) { + return; + } + setState(() => _elapsed += const Duration(seconds: 1)); + if (_elapsed >= VideoNotePage.maxLength) { + _stop(); + } + }); + } + + Future _stop() async { + _timer?.cancel(); + _timer = null; + final controller = _controller; + if (controller == null || !_recording) { + return; + } + setState(() => _recording = false); + try { + final file = await controller.stopVideoRecording(); + if (mounted) { + Navigator.pop(context, File(file.path)); + } + } catch (_) { + if (mounted) { + Navigator.pop(context); + } + } + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _timer?.cancel(); + _controller?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final controller = _controller; + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + backgroundColor: Colors.transparent, + foregroundColor: Colors.white, + title: Text('videoNote'.tr()), + ), + body: Center( + child: !_ready || controller == null + ? const CircularProgressIndicator() + : ClipOval( + child: SizedBox( + width: 280, + height: 280, + child: FittedBox( + fit: BoxFit.cover, + child: SizedBox( + width: controller.value.previewSize?.height ?? 280, + height: controller.value.previewSize?.width ?? 280, + child: CameraPreview(controller), + ), + ), + ), + ), + ), + floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, + floatingActionButton: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (_recording) + Text( + '${_elapsed.inSeconds}s / ${VideoNotePage.maxLength.inSeconds}s', + style: const TextStyle(color: Colors.white), + ), + const SizedBox(height: 8), + FloatingActionButton( + onPressed: _ready ? _toggleRecording : null, + backgroundColor: _recording ? Colors.red : Colors.white, + child: Icon(_recording ? Icons.stop : Icons.videocam, + color: _recording ? Colors.white : Colors.black), + ), + ], + ), + ); + } +} diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index c4af021..7ddd8f3 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -92,6 +92,7 @@ class ChatSender { int? durationMs, String? fileName, List? waveform, + bool videoNote = false, bool forwarded = false, bool viewOnce = false}) async { if (!MediaUtils.uploadFits(bytes.length)) { @@ -135,7 +136,9 @@ class ChatSender { height: height, durationMs: durationMs, fileName: fileName, - waveform: waveform); + waveform: waveform, + // Only a single video is ever a note; the stored reference says so. + videoNote: message.mediaReferences?.first.videoNote ?? false); if (reference == null) { return await _fail(recipient.id, message); } @@ -438,7 +441,9 @@ class ChatSender { height: height, durationMs: durationMs, fileName: fileName, - waveform: waveform); + waveform: waveform, + // Only a single video is ever a note; the stored reference says so. + videoNote: message.mediaReferences?.first.videoNote ?? false); } final references = []; @@ -511,6 +516,7 @@ class ChatSender { int? durationMs, String? fileName, List? waveform, + bool videoNote = false, }) async { try { final (mediaId, transport) = await MediaUploader.upload( @@ -529,6 +535,7 @@ class ChatSender { durationMs: durationMs, fileName: fileName, waveform: waveform, + videoNote: videoNote, ); } catch (e) { if (kDebugMode) { diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index e0dacf6..d83bd4b 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -292,6 +292,20 @@ class _MediaBubbleState extends State { ); } + // A round video note keeps its circle whatever state it is in. + if (type == MediaType.video && _isVideoNote) { + return _withCaption( + ClipOval( + child: SizedBox( + width: 200, + height: 200, + child: media, + ), + ), + hasCaption, + ); + } + // A sticker is drawn bare: no bubble, no rounded frame, its own size. if (type == MediaType.sticker) { return _withCaption( @@ -390,6 +404,14 @@ class _MediaBubbleState extends State { ); } + /// Whether this video was recorded as a round video note. + bool get _isVideoNote { + final references = widget.message.mediaReferences; + return references != null && + references.isNotEmpty && + references.first.videoNote; + } + /// A pending attachment waits for the network setting; the icon is also the /// way to fetch it now. Widget _pendingMedia() { diff --git a/pubspec.lock b/pubspec.lock index a7928fd..52dfc79 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -153,6 +153,46 @@ packages: url: "https://pub.dev" source: hosted version: "8.13.0" + camera: + dependency: "direct main" + description: + name: camera + sha256: "4a0863bc142f6fbfdca19161205574fd8a8f00d4753b48d214c4dfbdcc534c51" + url: "https://pub.dev" + source: hosted + version: "0.12.2" + camera_android_camerax: + dependency: transitive + description: + name: camera_android_camerax + sha256: daefacb4c2c575426772a83ac312b93e2c49c003224962cddab904426dc04dbc + url: "https://pub.dev" + source: hosted + version: "0.7.6+2" + camera_avfoundation: + dependency: transitive + description: + name: camera_avfoundation + sha256: "971f7b4938ae761797dd667c078af92f1b6a1bb7760774c0cbcf9c9d4a14bdf1" + url: "https://pub.dev" + source: hosted + version: "0.11.1" + camera_platform_interface: + dependency: transitive + description: + name: camera_platform_interface + sha256: c22b8403d7925c6cc6a37fc0cf01f645c1400bdfb0e765f81373a3ac080d93e3 + url: "https://pub.dev" + source: hosted + version: "2.15.1" + camera_web: + dependency: transitive + description: + name: camera_web + sha256: "54183db5a296cf29478dd150d7685b761f9e8eeb4a11114bcbc2792adea7cb3b" + url: "https://pub.dev" + source: hosted + version: "0.3.6" characters: dependency: transitive description: @@ -1902,7 +1942,7 @@ packages: path: "../whisper_websocket_client_dart" relative: true source: path - version: "0.6.0" + version: "0.7.0" win32: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 268944f..ee8c52a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -11,6 +11,7 @@ environment: dependencies: basic_utils: ^5.7.0 bcrypt: ^1.1.3 + camera: ^0.12.2 chewie: ^1.17.4 connectivity_plus: ^7.3.2 crop_your_image: ^2.0.1 @@ -61,7 +62,7 @@ dependencies: whisper_websocket_client_dart: git: url: https://github.com/jsfraz/whisper_websocket_client_dart.git - ref: v0.6.0 + ref: v0.7.0 dev_dependencies: flutter_test: From 9c3eee98f0a7e3b62ac9784de08427f55b880a64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 00:18:09 +0100 Subject: [PATCH 142/181] fix(app): keep the pencil icon for the draw action --- lib/pages/image_editor_page.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pages/image_editor_page.dart b/lib/pages/image_editor_page.dart index b91e417..0fdea12 100644 --- a/lib/pages/image_editor_page.dart +++ b/lib/pages/image_editor_page.dart @@ -154,7 +154,7 @@ class _ImageEditorPageState extends State { ? _EditMode.preview : _EditMode.draw; }), - icon: Icon(_mode == _EditMode.draw ? Icons.edit : Icons.brush), + icon: const Icon(Icons.edit), ), if (_mode == _EditMode.draw) IconButton( From c322877bae2f6d28ee821e6258eff62c094266db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 00:27:03 +0100 Subject: [PATCH 143/181] fix(app): draw image strokes in the picture's own box --- lib/pages/image_editor_page.dart | 77 +++++++++++++++++++++----------- 1 file changed, 51 insertions(+), 26 deletions(-) diff --git a/lib/pages/image_editor_page.dart b/lib/pages/image_editor_page.dart index 0fdea12..2cca086 100644 --- a/lib/pages/image_editor_page.dart +++ b/lib/pages/image_editor_page.dart @@ -36,6 +36,27 @@ class _ImageEditorPageState extends State { final List> _strokes = []; bool _busy = false; + /// Width / height of [_bytes]. The drawing surface is locked to it, so a + /// stroke lands under the finger instead of somewhere offset from it. + double _aspect = 1; + + @override + void initState() { + super.initState(); + _measure(_bytes); + } + + Future _measure(Uint8List bytes) async { + final codec = await ui.instantiateImageCodec(bytes); + final frame = await codec.getNextFrame(); + final aspect = frame.image.width / frame.image.height; + frame.image.dispose(); + codec.dispose(); + if (mounted) { + setState(() => _aspect = aspect); + } + } + /// Width of a stroke relative to the picture, so the line looks the same at /// any screen size and at the exported resolution. static const double _strokeFraction = 1 / 60; @@ -46,6 +67,7 @@ class _ImageEditorPageState extends State { final rendered = await _render(_bytes, _strokes, quarterTurns: 1); _strokes.clear(); setState(() => _bytes = rendered); + await _measure(rendered); } finally { if (mounted) { setState(() => _busy = false); @@ -192,6 +214,7 @@ class _ImageEditorPageState extends State { _strokes.clear(); _mode = _EditMode.preview; }); + _measure(croppedImage); case CropFailure(): ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: Text('mediaError'.tr()))); @@ -217,34 +240,36 @@ class _ImageEditorPageState extends State { Widget _drawView() { return Center( - child: LayoutBuilder( - builder: (context, constraints) { - final drawing = _mode == _EditMode.draw; - return GestureDetector( - onPanStart: drawing - ? (details) => setState(() { - _strokes.add( - [_normalize(details.localPosition, constraints)]); - }) - : null, - onPanUpdate: drawing - ? (details) => setState(() { - _strokes.last - .add(_normalize(details.localPosition, constraints)); - }) - : null, - child: Stack( - children: [ - Image.memory(_bytes), - Positioned.fill( - child: CustomPaint( + child: AspectRatio( + aspectRatio: _aspect, + child: LayoutBuilder( + builder: (context, constraints) { + final drawing = _mode == _EditMode.draw; + return GestureDetector( + onPanStart: drawing + ? (details) => setState(() { + _strokes.add( + [_normalize(details.localPosition, constraints)]); + }) + : null, + onPanUpdate: drawing + ? (details) => setState(() { + _strokes.last.add( + _normalize(details.localPosition, constraints)); + }) + : null, + child: Stack( + fit: StackFit.expand, + children: [ + Image.memory(_bytes, fit: BoxFit.contain), + CustomPaint( painter: _StrokePainter(_strokes, _ink), ), - ), - ], - ), - ); - }, + ], + ), + ); + }, + ), ), ); } From f9a7fb25da9551161a94bd87935e238a01817f71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 00:47:37 +0100 Subject: [PATCH 144/181] feat(app): choose the drawing colour in the image editor --- lib/pages/image_editor_page.dart | 58 ++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/lib/pages/image_editor_page.dart b/lib/pages/image_editor_page.dart index 2cca086..9489745 100644 --- a/lib/pages/image_editor_page.dart +++ b/lib/pages/image_editor_page.dart @@ -28,7 +28,19 @@ class ImageEditorPage extends StatefulWidget { } class _ImageEditorPageState extends State { - static const Color _ink = Color(0xFFFF3B30); + /// Colours a stroke can be drawn in: enough to stand out on a photo, few + /// enough to pick without a dialog. + static const List _palette = [ + Color(0xFFFF3B30), + Color(0xFFFFCC00), + Color(0xFF34C759), + Color(0xFF007AFF), + Color(0xFFAF52DE), + Color(0xFFFFFFFF), + Color(0xFF000000), + ]; + + Color _ink = _palette.first; final CropController _cropController = CropController(); late Uint8List _bytes = widget.bytes; @@ -195,7 +207,12 @@ class _ImageEditorPageState extends State { ? const Center(child: CircularProgressIndicator()) : _mode == _EditMode.crop ? _cropView() - : _drawView(), + : Column( + children: [ + Expanded(child: _drawView()), + if (_mode == _EditMode.draw) _paletteBar(), + ], + ), ); } @@ -274,6 +291,42 @@ class _ImageEditorPageState extends State { ); } + /// Colour choices for drawing. Shown only while drawing, so the picture keeps + /// the whole screen otherwise. + Widget _paletteBar() { + final outline = Theme.of(context).colorScheme.onSurface; + return SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + for (final color in _palette) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 6), + child: GestureDetector( + onTap: () => setState(() => _ink = color), + child: Container( + width: 28, + height: 28, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + border: Border.all( + color: color == _ink ? outline : Colors.transparent, + width: 2, + ), + ), + ), + ), + ), + ], + ), + ), + ); + } + /// Strokes are kept relative to the picture, so the export does not depend on /// the size it was drawn at. Offset _normalize(Offset local, BoxConstraints constraints) { @@ -323,6 +376,7 @@ class _StrokePainter extends CustomPainter { @override bool shouldRepaint(covariant _StrokePainter oldDelegate) => + oldDelegate.color != color || oldDelegate.strokes.length != strokes.length || (strokes.isNotEmpty && oldDelegate.strokes.last.length != strokes.last.length); From 61be31a9b8f834818f0e1daf71e6c3e6e79c22e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 00:51:16 +0100 Subject: [PATCH 145/181] fix(app): hide view-once content from previews and drop emojis from them --- lib/models/private_message.dart | 25 ++++++++-- lib/utils/cache_utils.dart | 7 ++- test/view_once_preview_test.dart | 79 ++++++++++++++++++++++++++++++++ 3 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 test/view_once_preview_test.dart diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index 36ac45e..d1b64d4 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -455,6 +455,15 @@ class PrivateMessage extends HiveObject { } } + /// Emojis and their modifiers, stripped from previews: a list row is a + /// summary of what was said, and a pin or a smiley is not one. + static final RegExp _previewEmoji = RegExp( + r'[\p{Extended_Pictographic}\u{FE0F}\u{200D}\u{20E3}]', + unicode: true, + ); + + static final RegExp _previewWhitespace = RegExp(r'\s+'); + /// Short text used in chat list previews and notifications. Falls back to a /// localized media label when a media message has no caption. String get preview { @@ -467,15 +476,25 @@ class PrivateMessage extends HiveObject { if (isSystem) { return 'disappearingChanged'.tr(); } + // A view-once message never shows its content in a list: not its caption, + // not the coordinates of a location, before or after it is opened. + if (viewOnce) { + return openedAt == null ? 'viewOnceMedia'.tr() : 'viewOnceOpened'.tr(); + } + return _previewText + .replaceAll(_previewEmoji, '') + .replaceAll(_previewWhitespace, ' ') + .trim(); + } + + /// The untrimmed preview: the text, or a media label when there is none. + String get _previewText { if (!isMedia || message.isNotEmpty) { return message; } if (isAlbum) { return '${'mediaAlbum'.tr()} (${album.length})'; } - if (viewOnce) { - return 'viewOnceMedia'.tr(); - } switch (mediaType) { case MediaType.image: return 'mediaPhoto'.tr(); diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 71d9714..1b64b7e 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -747,8 +747,13 @@ class CacheUtils { value.openedAt = openedAt; value.localPath = null; // A spent location leaves nothing behind either; the bubble reads the - // opened instant, not the coordinates. + // opened instant, not the coordinates. The text goes too: for a location it + // is the coordinates, and for media it is the caption, so a chat list + // preview or a notification must not still be able to show it. value.locationJson = null; + if (value.viewOnce) { + value.message = ''; + } for (final item in value.album) { item.localPath = null; } diff --git a/test/view_once_preview_test.dart b/test/view_once_preview_test.dart new file mode 100644 index 0000000..8ada38c --- /dev/null +++ b/test/view_once_preview_test.dart @@ -0,0 +1,79 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper/utils/text_envelope.dart'; + +void main() { + late Directory dir; + final now = DateTime(2026, 11, 23, 10); + const location = LocationRef(50.17595, 14.42); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + dir = Directory.systemTemp.createTempSync('whisper_view_once_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + PrivateMessage locationMessage({required bool viewOnce}) => PrivateMessage( + '1', + location.body, + now, + now, + true, + viewOnce: viewOnce, + locationJson: jsonEncode(location.toJson()), + ); + + test('a view-once location never previews its coordinates', () { + final message = locationMessage(viewOnce: true); + + expect(message.preview, 'viewOnceMedia'.tr()); + + message.openedAt = now; + expect(message.preview, 'viewOnceOpened'.tr()); + }); + + test('a normal location previews without the pin emoji', () { + expect(locationMessage(viewOnce: false).preview, '50.17595, 14.42000'); + }); + + test('previews drop emojis from the text', () { + final message = PrivateMessage('1', 'ahoj 😀👍 svět', now, now, true); + + expect(message.preview, 'ahoj svět'); + }); + + test('opening a view-once message clears its text and coordinates', () async { + final message = locationMessage(viewOnce: true); + await CacheUtils.addPrivateMessages('2', [message]); + + await CacheUtils.markMessageOpened( + '2', now, now.add(const Duration(minutes: 1))); + + final stored = (await CacheUtils.getPrivateMessages('2')).single; + expect(stored.openedAt, isNotNull); + expect(stored.message, isEmpty); + expect(stored.locationJson, isNull); + expect(stored.preview, 'viewOnceOpened'.tr()); + }); +} From e150f43da4414daec23cf8f3ed2d6ec24eda0c92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 00:53:47 +0100 Subject: [PATCH 146/181] fix(app): preview a location without the pin, keep emojis elsewhere --- lib/models/private_message.dart | 21 ++++++++------------- test/view_once_preview_test.dart | 4 ++-- 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index d1b64d4..29b4698 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -455,15 +455,6 @@ class PrivateMessage extends HiveObject { } } - /// Emojis and their modifiers, stripped from previews: a list row is a - /// summary of what was said, and a pin or a smiley is not one. - static final RegExp _previewEmoji = RegExp( - r'[\p{Extended_Pictographic}\u{FE0F}\u{200D}\u{20E3}]', - unicode: true, - ); - - static final RegExp _previewWhitespace = RegExp(r'\s+'); - /// Short text used in chat list previews and notifications. Falls back to a /// localized media label when a media message has no caption. String get preview { @@ -481,10 +472,14 @@ class PrivateMessage extends HiveObject { if (viewOnce) { return openedAt == null ? 'viewOnceMedia'.tr() : 'viewOnceOpened'.tr(); } - return _previewText - .replaceAll(_previewEmoji, '') - .replaceAll(_previewWhitespace, ' ') - .trim(); + final location = this.location; + if (location != null) { + // Without the pin: a map marker belongs in the bubble, not in a one-line + // summary, and rows stored by an older build keep their emoji in the text. + return '${location.lat.toStringAsFixed(5)}, ' + '${location.lng.toStringAsFixed(5)}'; + } + return _previewText; } /// The untrimmed preview: the text, or a media label when there is none. diff --git a/test/view_once_preview_test.dart b/test/view_once_preview_test.dart index 8ada38c..1fc0ff6 100644 --- a/test/view_once_preview_test.dart +++ b/test/view_once_preview_test.dart @@ -57,10 +57,10 @@ void main() { expect(locationMessage(viewOnce: false).preview, '50.17595, 14.42000'); }); - test('previews drop emojis from the text', () { + test('other previews keep their emojis', () { final message = PrivateMessage('1', 'ahoj 😀👍 svět', now, now, true); - expect(message.preview, 'ahoj svět'); + expect(message.preview, 'ahoj 😀👍 svět'); }); test('opening a view-once message clears its text and coordinates', () async { From 9b6c0dfa6990e8c888ec25b8c65d3ee510ce6d5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 00:58:35 +0100 Subject: [PATCH 147/181] fix(app): rebuild the video trim screen around the picture --- assets/translations/cs.json | 3 +- assets/translations/en.json | 3 +- lib/pages/video_trim_page.dart | 146 ++++++++++++++++++++++++++++----- 3 files changed, 128 insertions(+), 24 deletions(-) diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 165b870..5ed3c3c 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -329,5 +329,6 @@ "shareToChat": "Sdílet do chatu", "shareFailed": "Sdílení se nepovedlo", "videoNote": "Kruhové video", - "cameraUnavailable": "Kamera není dostupná" + "cameraUnavailable": "Kamera není dostupná", + "applyTrim": "Oříznout" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 114822f..1a9dd91 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -329,5 +329,6 @@ "shareToChat": "Share to a chat", "shareFailed": "Sharing failed", "videoNote": "Round video", - "cameraUnavailable": "Camera is not available" + "cameraUnavailable": "Camera is not available", + "applyTrim": "Trim" } diff --git a/lib/pages/video_trim_page.dart b/lib/pages/video_trim_page.dart index 28b14a1..22b648a 100644 --- a/lib/pages/video_trim_page.dart +++ b/lib/pages/video_trim_page.dart @@ -25,9 +25,12 @@ class VideoTrimPage extends StatefulWidget { class _VideoTrimPageState extends State { final Trimmer _trimmer = Trimmer(); + + /// Selection in milliseconds, as the trim viewer reports it. double _startValue = 0; - double _endValue = 1; + double _endValue = 0; bool _ready = false; + bool _playing = false; bool _saving = false; @override @@ -38,8 +41,27 @@ class _VideoTrimPageState extends State { Future _load() async { await _trimmer.loadVideo(videoPath: widget.file.path); + // The viewer starts on the whole clip; without this the selection would be + // the 0..0 range it is initialised with. + final durationMs = _trimmer + .videoPlayerController?.value.duration.inMilliseconds + .toDouble() ?? + 0; if (mounted) { - setState(() => _ready = true); + setState(() { + _ready = true; + _endValue = durationMs; + }); + } + } + + Future _togglePlayback() async { + final playing = await _trimmer.videoPlaybackControl( + startValue: _startValue, + endValue: _endValue, + ); + if (mounted && playing != _playing) { + setState(() => _playing = playing); } } @@ -66,35 +88,115 @@ class _VideoTrimPageState extends State { super.dispose(); } + String _format(double milliseconds) { + final total = Duration(milliseconds: milliseconds.round()); + final minutes = total.inMinutes.remainder(60).toString().padLeft(2, '0'); + final seconds = total.inSeconds.remainder(60).toString().padLeft(2, '0'); + final tenths = (total.inMilliseconds.remainder(1000) ~/ 100); + return '$minutes:$seconds.$tenths'; + } + @override Widget build(BuildContext context) { + final hasRange = _endValue > _startValue; return Scaffold( + backgroundColor: Colors.black, appBar: AppBar( + backgroundColor: Colors.black, + foregroundColor: Colors.white, title: Text('trimVideo'.tr()), - actions: [ - IconButton( - tooltip: 'save'.tr(), - onPressed: _ready && !_saving ? _save : null, - icon: _saving - ? const SizedBox( - width: 18, - height: 18, - child: CircularProgressIndicator(strokeWidth: 2)) - : const Icon(Icons.check_circle), - ), - ], + bottom: _saving + ? const PreferredSize( + preferredSize: Size.fromHeight(2), + child: LinearProgressIndicator(minHeight: 2), + ) + : null, ), body: !_ready ? const Center(child: CircularProgressIndicator()) : SafeArea( - child: Center( - child: TrimViewer( - trimmer: _trimmer, - viewerWidth: MediaQuery.sizeOf(context).width, - viewerHeight: 240, - onChangeStart: (value) => _startValue = value, - onChangeEnd: (value) => _endValue = value, - ), + child: Column( + children: [ + // The picture gets the room: this is where the cut is judged. + Expanded( + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 0), + child: VideoViewer( + trimmer: _trimmer, + borderColor: Colors.white24, + ), + ), + ), + const SizedBox(height: 8), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(_format(_startValue), + style: const TextStyle( + color: Colors.white70, + fontFeatures: [FontFeature.tabularFigures()])), + Text(_format(_endValue - _startValue), + style: const TextStyle( + color: Color(0xFFFFC400), + fontWeight: FontWeight.w600)), + Text(_format(_endValue), + style: const TextStyle( + color: Colors.white70, + fontFeatures: [FontFeature.tabularFigures()])), + ], + ), + ), + Padding( + padding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: TrimViewer( + trimmer: _trimmer, + viewerWidth: MediaQuery.sizeOf(context).width - 32, + viewerHeight: 56, + showDuration: false, + paddingFraction: 0.15, + onChangeStart: (value) => + setState(() => _startValue = value), + onChangeEnd: (value) => setState(() => _endValue = value), + onChangePlaybackState: (value) => + setState(() => _playing = value), + ), + ), + IconButton( + iconSize: 56, + color: Colors.white, + onPressed: hasRange ? _togglePlayback : null, + icon: Icon( + _playing + ? Icons.pause_circle_filled + : Icons.play_circle_fill, + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 12), + child: Row( + children: [ + Expanded( + child: OutlinedButton( + onPressed: + _saving ? null : () => Navigator.pop(context), + child: Text('cancel'.tr()), + ), + ), + const SizedBox(width: 12), + Expanded( + child: FilledButton.icon( + onPressed: hasRange && !_saving ? _save : null, + icon: const Icon(Icons.content_cut), + label: Text('applyTrim'.tr()), + ), + ), + ], + ), + ), + ], ), ), ); From 6fe3a23594c17672e285666ed15aa3363171ac19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 01:10:59 +0100 Subject: [PATCH 148/181] feat(app): paperclip composer with a chat-coloured mic beside it --- lib/pages/chat_page.dart | 142 +++++++++++++++++++++++---------------- 1 file changed, 83 insertions(+), 59 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 08d4426..9e16bdf 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1357,76 +1357,78 @@ class _ChatPageState extends State { return '$minutes:$seconds'; } - /// Default message input bar: attach inside the field on the left, mic or - /// send on the right. + /// Composer: a paperclip inside the field on the left, one round action + /// beside the field on the right — mic while it is empty, send once there is + /// text — painted in the chat's colour. Widget _buildInputBar() { return Padding( - padding: const EdgeInsets.only(right: 5, left: 5), - child: TextField( - controller: _controllerMessage, - minLines: 1, - maxLines: 5, - textInputAction: TextInputAction.newline, - onChanged: (value) { - // The receiver clears the indicator on its own; this only throttles - // the frames and stays silent when the user opted out. - if (value.trim().isNotEmpty) { - utils.Utils.sendTypingHint(widget.user.id); - } - }, - contentInsertionConfiguration: ContentInsertionConfiguration( - allowedMimeTypes: const ['image/gif', 'image/webp'], - onContentInserted: _onKeyboardContentInserted, - ), - decoration: InputDecoration( - hintText: 'yourMessage'.tr(), - // The attach button lives inside the field, mirroring the mic. - prefixIcon: IconButton( - icon: const Icon(Icons.add), - tooltip: 'attachButton'.tr(), - onPressed: _isSending ? null : _showAttachSheet, - ), - filled: true, - fillColor: chatTheme.brightness == Brightness.dark - ? chatTheme.colorScheme.surfaceBright - : chatTheme.colorScheme.surfaceDim, - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(30), - borderSide: BorderSide.none, + padding: const EdgeInsets.fromLTRB(5, 4, 8, 4), + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Expanded( + child: TextField( + controller: _controllerMessage, + minLines: 1, + maxLines: 5, + textInputAction: TextInputAction.newline, + onChanged: (value) { + // The receiver clears the indicator on its own; this only + // throttles the frames and stays silent when the user opted out. + if (value.trim().isNotEmpty) { + utils.Utils.sendTypingHint(widget.user.id); + } + }, + contentInsertionConfiguration: ContentInsertionConfiguration( + allowedMimeTypes: const ['image/gif', 'image/webp'], + onContentInserted: _onKeyboardContentInserted, + ), + decoration: InputDecoration( + hintText: 'yourMessage'.tr(), + prefixIcon: IconButton( + icon: const Icon(Icons.attach_file), + tooltip: 'attachButton'.tr(), + onPressed: _isSending ? null : _showAttachSheet, + ), + filled: true, + fillColor: chatTheme.brightness == Brightness.dark + ? chatTheme.colorScheme.surfaceBright + : chatTheme.colorScheme.surfaceDim, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(30), + borderSide: BorderSide.none, + ), + ), + ), ), - suffixIcon: ValueListenableBuilder( + const SizedBox(width: 8), + ValueListenableBuilder( valueListenable: _controllerMessage, builder: (context, value, _) { // A send in flight shows here whatever the field holds: encrypting // and uploading a large attachment, probing a video or waiting for // a GPS fix takes a while, and the bubble is not there yet. if (_isSending) { - // 48 px like the icon buttons it replaces, so nothing shifts. - return const Padding( - padding: EdgeInsets.all(15), - child: SizedBox( + return _composerButton( + child: const SizedBox( width: 18, height: 18, - child: CircularProgressIndicator(strokeWidth: 2), + child: CircularProgressIndicator( + strokeWidth: 2, color: Colors.white), ), ); } - final hasText = value.text.trim().isNotEmpty; - if (hasText) { - return IconButton( + if (value.text.trim().isNotEmpty) { + return _composerButton( onPressed: _sendMessage, - icon: const Icon(Icons.send), + child: const Icon(Icons.send), ); } // Hold-to-record voice message. The bar is overlaid while - // recording, so this detector stays mounted and its - // long-press end still fires. + // recording, so this detector stays mounted and its long-press + // end still fires. return GestureDetector( - onLongPressStart: (_) { - if (!_isSending) { - _startRecording(); - } - }, + onLongPressStart: (_) => _startRecording(), onLongPressMoveUpdate: (details) { if (_recordingLocked) { return; @@ -1455,18 +1457,40 @@ class _ChatPageState extends State { _stopRequested = true; } }, - child: IconButton( - onPressed: _isSending - ? null - : () async { - await Fluttertoast.showToast( - msg: 'holdToRecord'.tr()); - }, - icon: const Icon(Icons.mic), + child: _composerButton( + onPressed: () async { + await Fluttertoast.showToast(msg: 'holdToRecord'.tr()); + }, + child: const Icon(Icons.mic), ), ); }, ), + ], + ), + ); + } + + /// The round action beside the composer, filled with the chat colour. + Widget _composerButton({Widget? child, VoidCallback? onPressed}) { + final color = chatTheme.colorScheme.primary; + final onColor = + ThemeData.estimateBrightnessForColor(color) == Brightness.dark + ? Colors.white + : Colors.black87; + return SizedBox( + width: 48, + height: 48, + child: Material( + color: color, + shape: const CircleBorder(), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: onPressed, + child: IconTheme( + data: IconThemeData(color: onColor), + child: Center(child: child), + ), ), ), ); From b95e2fc2373ffab7cf687d0d78a898691aa0fc3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 01:14:15 +0100 Subject: [PATCH 149/181] fix(app): align the mic button with the composer field --- lib/pages/chat_page.dart | 212 ++++++++++++++++++++------------------- 1 file changed, 111 insertions(+), 101 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 9e16bdf..53c555f 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1363,115 +1363,126 @@ class _ChatPageState extends State { Widget _buildInputBar() { return Padding( padding: const EdgeInsets.fromLTRB(5, 4, 8, 4), - child: Row( - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Expanded( - child: TextField( - controller: _controllerMessage, - minLines: 1, - maxLines: 5, - textInputAction: TextInputAction.newline, - onChanged: (value) { - // The receiver clears the indicator on its own; this only - // throttles the frames and stays silent when the user opted out. - if (value.trim().isNotEmpty) { - utils.Utils.sendTypingHint(widget.user.id); - } - }, - contentInsertionConfiguration: ContentInsertionConfiguration( - allowedMimeTypes: const ['image/gif', 'image/webp'], - onContentInserted: _onKeyboardContentInserted, - ), - decoration: InputDecoration( - hintText: 'yourMessage'.tr(), - prefixIcon: IconButton( - icon: const Icon(Icons.attach_file), - tooltip: 'attachButton'.tr(), - onPressed: _isSending ? null : _showAttachSheet, + // Stretching the row makes the button exactly as tall as the field, so + // the two are aligned however many lines the field grows to. + child: IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: TextField( + controller: _controllerMessage, + minLines: 1, + maxLines: 5, + textInputAction: TextInputAction.newline, + onChanged: (value) { + // The receiver clears the indicator on its own; this only + // throttles the frames and stays silent when the user opted + // out. + if (value.trim().isNotEmpty) { + utils.Utils.sendTypingHint(widget.user.id); + } + }, + contentInsertionConfiguration: ContentInsertionConfiguration( + allowedMimeTypes: const ['image/gif', 'image/webp'], + onContentInserted: _onKeyboardContentInserted, ), - filled: true, - fillColor: chatTheme.brightness == Brightness.dark - ? chatTheme.colorScheme.surfaceBright - : chatTheme.colorScheme.surfaceDim, - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(30), - borderSide: BorderSide.none, + decoration: InputDecoration( + hintText: 'yourMessage'.tr(), + isDense: true, + contentPadding: const EdgeInsets.symmetric(vertical: 12), + prefixIconConstraints: + const BoxConstraints(minWidth: 44, minHeight: 44), + prefixIcon: IconButton( + icon: const Icon(Icons.attach_file), + tooltip: 'attachButton'.tr(), + onPressed: _isSending ? null : _showAttachSheet, + ), + filled: true, + fillColor: chatTheme.brightness == Brightness.dark + ? chatTheme.colorScheme.surfaceBright + : chatTheme.colorScheme.surfaceDim, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(30), + borderSide: BorderSide.none, + ), ), ), ), - ), - const SizedBox(width: 8), - ValueListenableBuilder( - valueListenable: _controllerMessage, - builder: (context, value, _) { - // A send in flight shows here whatever the field holds: encrypting - // and uploading a large attachment, probing a video or waiting for - // a GPS fix takes a while, and the bubble is not there yet. - if (_isSending) { - return _composerButton( - child: const SizedBox( - width: 18, - height: 18, - child: CircularProgressIndicator( - strokeWidth: 2, color: Colors.white), + const SizedBox(width: 8), + ValueListenableBuilder( + valueListenable: _controllerMessage, + builder: (context, value, _) { + // A send in flight shows here whatever the field holds: + // encrypting and uploading a large attachment, probing a video + // or waiting for a GPS fix takes a while, and the bubble is not + // there yet. + if (_isSending) { + return _composerButton( + child: const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, color: Colors.white), + ), + ); + } + if (value.text.trim().isNotEmpty) { + return _composerButton( + onPressed: _sendMessage, + child: const Icon(Icons.send), + ); + } + // Hold-to-record voice message. The bar is overlaid while + // recording, so this detector stays mounted and its long-press + // end still fires. + return GestureDetector( + onLongPressStart: (_) => _startRecording(), + onLongPressMoveUpdate: (details) { + if (_recordingLocked) { + return; + } + final offset = details.localOffsetFromOrigin; + if (offset.dy < -60) { + setState(() { + _recordingLocked = true; + _cancelRecording = false; + }); + return; + } + final shouldCancel = offset.dx < -80; + if (shouldCancel != _cancelRecording) { + setState(() { + _cancelRecording = shouldCancel; + }); + } + }, + onLongPressEnd: (_) { + // A locked recording outlives the gesture: it stops from + // the bar, which is all the release used to do. + if (_isRecording && !_recordingLocked) { + _stopRecording(); + } else if (!_isRecording) { + _stopRequested = true; + } + }, + child: _composerButton( + onPressed: () async { + await Fluttertoast.showToast(msg: 'holdToRecord'.tr()); + }, + child: const Icon(Icons.mic), ), ); - } - if (value.text.trim().isNotEmpty) { - return _composerButton( - onPressed: _sendMessage, - child: const Icon(Icons.send), - ); - } - // Hold-to-record voice message. The bar is overlaid while - // recording, so this detector stays mounted and its long-press - // end still fires. - return GestureDetector( - onLongPressStart: (_) => _startRecording(), - onLongPressMoveUpdate: (details) { - if (_recordingLocked) { - return; - } - final offset = details.localOffsetFromOrigin; - if (offset.dy < -60) { - setState(() { - _recordingLocked = true; - _cancelRecording = false; - }); - return; - } - final shouldCancel = offset.dx < -80; - if (shouldCancel != _cancelRecording) { - setState(() { - _cancelRecording = shouldCancel; - }); - } - }, - onLongPressEnd: (_) { - // A locked recording outlives the gesture: it stops from the - // bar, which is all the release used to do. - if (_isRecording && !_recordingLocked) { - _stopRecording(); - } else if (!_isRecording) { - _stopRequested = true; - } - }, - child: _composerButton( - onPressed: () async { - await Fluttertoast.showToast(msg: 'holdToRecord'.tr()); - }, - child: const Icon(Icons.mic), - ), - ); - }, - ), - ], + }, + ), + ], + ), ), ); } - /// The round action beside the composer, filled with the chat colour. + /// The round action beside the composer, filled with the chat's colour. It + /// takes the row's height, so it is a circle while the field has one line. Widget _composerButton({Widget? child, VoidCallback? onPressed}) { final color = chatTheme.colorScheme.primary; final onColor = @@ -1480,10 +1491,9 @@ class _ChatPageState extends State { : Colors.black87; return SizedBox( width: 48, - height: 48, child: Material( color: color, - shape: const CircleBorder(), + shape: const StadiumBorder(), clipBehavior: Clip.antiAlias, child: InkWell( onTap: onPressed, From 3e6580a5816d901d93509c45f7cd6c6d3c943879 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 01:25:49 +0100 Subject: [PATCH 150/181] feat(app): camera button in the composer with photo, video and round notes --- assets/translations/cs.json | 8 +- assets/translations/en.json | 8 +- lib/pages/camera_page.dart | 307 ++++++++++++++++++++++++++++ lib/pages/chat_page.dart | 211 +++++++++++++++---- lib/pages/video_note_page.dart | 197 ------------------ lib/utils/media_utils.dart | 16 +- lib/utils/round_video_recorder.dart | 93 +++++++++ 7 files changed, 579 insertions(+), 261 deletions(-) create mode 100644 lib/pages/camera_page.dart delete mode 100644 lib/pages/video_note_page.dart create mode 100644 lib/utils/round_video_recorder.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 5ed3c3c..d69621e 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -101,8 +101,7 @@ "accountDeleted2": "Váš účet byl smazán :P", "wsOffline": "WebSocket je offline", "attachButton": "Přiložit", - "attachCamera": "Vyfotit", - "attachVideoCamera": "Natočit video", + "attachCamera": "Foťák", "attachGallery": "Galerie fotek a videí", "gifFromKeyboardFailed": "GIF z klávesnice se nepodařilo načíst", "attachFile": "Soubor", @@ -328,7 +327,8 @@ "shareMessage": "Sdílet do jiné aplikace", "shareToChat": "Sdílet do chatu", "shareFailed": "Sdílení se nepovedlo", - "videoNote": "Kruhové video", "cameraUnavailable": "Kamera není dostupná", - "applyTrim": "Oříznout" + "applyTrim": "Oříznout", + "shutterHint": "Klepnutím fotka, držením video", + "captureFailed": "Nepodařilo se vyfotit" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 1a9dd91..7144155 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -101,8 +101,7 @@ "accountDeleted2": "Your account has been deleted :P", "wsOffline": "WebSocket is offline", "attachButton": "Attach", - "attachCamera": "Take a photo", - "attachVideoCamera": "Record a video", + "attachCamera": "Camera", "attachGallery": "Photo & video gallery", "gifFromKeyboardFailed": "This keyboard GIF could not be read", "attachFile": "File", @@ -328,7 +327,8 @@ "shareMessage": "Share to another app", "shareToChat": "Share to a chat", "shareFailed": "Sharing failed", - "videoNote": "Round video", "cameraUnavailable": "Camera is not available", - "applyTrim": "Trim" + "applyTrim": "Trim", + "shutterHint": "Tap for a photo, hold for a video", + "captureFailed": "Could not capture" } diff --git a/lib/pages/camera_page.dart b/lib/pages/camera_page.dart new file mode 100644 index 0000000..6807bf9 --- /dev/null +++ b/lib/pages/camera_page.dart @@ -0,0 +1,307 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:camera/camera.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +/// In-app camera: tap the shutter for a photo, hold it to record a video. +/// +/// Returns the captured file from [open], or null when the user backs out. The +/// caller detects whether it is a photo or a video, so the chat handles it like +/// any other attachment. +class CameraPage extends StatefulWidget { + const CameraPage({super.key}); + + /// Longest clip the shutter records, same as the picker used to allow. + static const Duration maxVideoLength = Duration(seconds: 60); + + static Future open(BuildContext context) { + return Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const CameraPage(), fullscreenDialog: true)); + } + + @override + State createState() => _CameraPageState(); +} + +class _CameraPageState extends State with WidgetsBindingObserver { + List _cameras = const []; + CameraController? _controller; + bool _flashOn = false; + bool _recording = false; + bool _busy = false; + Duration _elapsed = Duration.zero; + Timer? _timer; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _openCamera(); + } + + Future _openCamera({bool front = false}) async { + try { + if (_cameras.isEmpty) { + _cameras = await availableCameras(); + } + if (_cameras.isEmpty) { + throw CameraException('noCamera', 'no camera on this device'); + } + // Whatever the caller asked for, falling back to the first camera keeps a + // single-camera device usable. + final wanted = + front ? CameraLensDirection.front : CameraLensDirection.back; + final camera = _cameras.firstWhere( + (entry) => entry.lensDirection == wanted, + orElse: () => _cameras.first, + ); + final controller = + CameraController(camera, ResolutionPreset.high, enableAudio: true); + await controller.initialize(); + await controller.setFlashMode(_flashOn ? FlashMode.torch : FlashMode.off); + if (!mounted) { + await controller.dispose(); + return; + } + setState(() => _controller = controller); + } catch (_) { + if (mounted) { + await Fluttertoast.showToast( + msg: 'cameraUnavailable'.tr(), backgroundColor: Colors.red); + Navigator.pop(context); + } + } + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + // The plugin does not park the camera by itself: left running in the + // background it keeps the camera light on and the next open fails. + final controller = _controller; + if (controller == null || !controller.value.isInitialized) { + return; + } + if (state == AppLifecycleState.inactive) { + controller.dispose(); + setState(() => _controller = null); + } else if (state == AppLifecycleState.resumed) { + _openCamera(front: false); + } + } + + Future _switchCamera() async { + if (_recording || _busy) { + return; + } + final front = _cameras.isNotEmpty && + _controller?.description.lensDirection == CameraLensDirection.front; + await _controller?.dispose(); + setState(() => _controller = null); + await _openCamera(front: !front); + } + + Future _toggleFlash() async { + if (_recording) { + return; + } + final on = !_flashOn; + try { + await _controller?.setFlashMode(on ? FlashMode.torch : FlashMode.off); + } catch (_) { + return; + } + if (mounted) { + setState(() => _flashOn = on); + } + } + + Future _takePhoto() async { + final controller = _controller; + if (controller == null || _busy || _recording) { + return; + } + setState(() => _busy = true); + try { + final captured = await controller.takePicture(); + if (mounted) { + Navigator.pop(context, File(captured.path)); + } + } catch (_) { + if (mounted) { + await Fluttertoast.showToast( + msg: 'captureFailed'.tr(), backgroundColor: Colors.red); + setState(() => _busy = false); + } + } + } + + Future _startVideo() async { + final controller = _controller; + if (controller == null || _busy || _recording) { + return; + } + try { + await controller.startVideoRecording(); + } catch (_) { + return; + } + setState(() { + _recording = true; + _elapsed = Duration.zero; + }); + _timer = Timer.periodic(const Duration(seconds: 1), (timer) { + if (!mounted) { + return; + } + setState(() => _elapsed += const Duration(seconds: 1)); + if (_elapsed >= CameraPage.maxVideoLength) { + _stopVideo(); + } + }); + } + + Future _stopVideo() async { + _timer?.cancel(); + _timer = null; + final controller = _controller; + if (controller == null || !_recording) { + return; + } + setState(() => _recording = false); + try { + final captured = await controller.stopVideoRecording(); + if (mounted) { + Navigator.pop(context, File(captured.path)); + } + } catch (_) { + if (mounted) { + setState(() => _busy = false); + } + } + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _timer?.cancel(); + _controller?.dispose(); + super.dispose(); + } + + String _format(Duration duration) { + final minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0'); + final seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0'); + return '$minutes:$seconds'; + } + + @override + Widget build(BuildContext context) { + final controller = _controller; + return Scaffold( + backgroundColor: Colors.black, + body: Stack( + fit: StackFit.expand, + children: [ + if (controller != null && controller.value.isInitialized) + Center( + child: AspectRatio( + aspectRatio: controller.value.aspectRatio, + child: CameraPreview(controller), + ), + ) + else + const Center(child: CircularProgressIndicator()), + SafeArea( + child: Column( + children: [ + Row( + children: [ + IconButton( + color: Colors.white, + onPressed: () => Navigator.pop(context), + icon: const Icon(Icons.close), + ), + const Spacer(), + if (_recording) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Row( + children: [ + const Icon(Icons.fiber_manual_record, + color: Colors.red, size: 14), + const SizedBox(width: 6), + Text( + '${_format(_elapsed)} / ${_format(CameraPage.maxVideoLength)}', + style: const TextStyle(color: Colors.white), + ), + ], + ), + ), + IconButton( + color: _flashOn ? Colors.amber : Colors.white, + onPressed: _toggleFlash, + icon: Icon(_flashOn ? Icons.flash_on : Icons.flash_off), + ), + IconButton( + color: Colors.white, + onPressed: _switchCamera, + icon: const Icon(Icons.cameraswitch), + ), + ], + ), + const Spacer(), + Padding( + padding: const EdgeInsets.only(bottom: 32), + child: GestureDetector( + onTap: _takePhoto, + onLongPressStart: (_) => _startVideo(), + onLongPressEnd: (_) => _stopVideo(), + child: _shutter(), + ), + ), + Padding( + padding: const EdgeInsets.only(bottom: 16), + child: Text( + 'shutterHint'.tr(), + style: const TextStyle(color: Colors.white70, fontSize: 12), + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _shutter() { + return Container( + width: 78, + height: 78, + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 4), + ), + padding: const EdgeInsets.all(6), + child: DecoratedBox( + decoration: BoxDecoration( + shape: _recording ? BoxShape.rectangle : BoxShape.circle, + borderRadius: _recording ? BorderRadius.circular(6) : null, + color: _recording ? Colors.red : Colors.white, + ), + child: _busy + ? const Center( + child: SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2))) + : null, + ), + ); + } +} diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 53c555f..22ddecb 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -4,6 +4,7 @@ import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:camera/camera.dart' show CameraPreview; import 'package:fluttertoast/fluttertoast.dart'; import 'package:path_provider/path_provider.dart'; import 'package:sprintf/sprintf.dart'; @@ -20,6 +21,7 @@ import '../utils/media_utils.dart'; import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; import '../utils/presence.dart'; +import '../utils/round_video_recorder.dart'; import '../utils/singleton.dart'; import '../utils/text_envelope.dart'; import '../utils/utils.dart' as utils; @@ -28,10 +30,10 @@ import '../widgets/attachment_confirm_sheet.dart'; import '../widgets/chat_bubble.dart'; import '../widgets/live_location_bubble.dart'; import '../widgets/typing_dots.dart'; +import 'camera_page.dart'; import 'chat_info_page.dart'; import '../widgets/sticker_sheet.dart'; import 'image_editor_page.dart'; -import 'video_note_page.dart'; import 'video_trim_page.dart'; import 'forward_page.dart'; @@ -85,6 +87,16 @@ class _ChatPageState extends State { /// Sliding up while recording locks it: the finger can be lifted and the /// recording keeps going until the bar's stop button is tapped. bool _recordingLocked = false; + + /// Round video note started by holding the composer's camera button. It lives + /// only as long as the finger is down. + RoundVideoRecorder? _noteRecorder; + bool _isRecordingNote = false; + bool _noteStarting = false; + bool _noteStopRequested = false; + bool _noteCancel = false; + Duration _noteElapsed = Duration.zero; + Timer? _noteTimer; bool _cancelRecording = false; MediaRecorderController? _recorderController; Duration _recordDuration = Duration.zero; @@ -1008,16 +1020,6 @@ class _ChatPageState extends State { } } - /// Records a round video note and sends it as it is: it is a glance, so no - /// caption and no editor. - Future _recordVideoNote() async { - final file = await VideoNotePage.open(context); - if (file == null) { - return; - } - await _sendMedia(MediaType.video, file, videoNote: true); - } - /// Opens the sticker collection and sends the picked one as it is: a sticker /// travels as its own media type, so the recipient draws it without a bubble. Future _pickSticker() async { @@ -1032,6 +1034,135 @@ class _ChatPageState extends State { _afterSend(sent, ''); } + /// Opens the in-app camera. What comes back is a photo or a video, and it + /// goes through the same confirm sheet as a gallery pick. + Future _captureFromCamera() async { + final file = await CameraPage.open(context); + if (file == null) { + return; + } + final type = MediaUtils.detectType(file.path); + await _pickAndSend(() async => [file], + forcedType: + type == MediaType.video ? MediaType.video : MediaType.image); + } + + /// Starts a round video note from the composer. It runs only while the finger + /// is down; releasing sends it, sliding left throws it away. + Future _startRoundNote() async { + if (_isRecordingNote || _noteStarting || _isSending) { + return; + } + _noteStarting = true; + final recorder = RoundVideoRecorder(); + try { + if (!await recorder.start()) { + await recorder.dispose(); + await Fluttertoast.showToast( + msg: 'cameraUnavailable'.tr(), backgroundColor: Colors.red); + return; + } + } finally { + _noteStarting = false; + } + if (!mounted) { + await recorder.dispose(); + return; + } + setState(() { + _noteRecorder = recorder; + _isRecordingNote = true; + _noteCancel = false; + _noteElapsed = Duration.zero; + }); + _noteTimer = Timer.periodic(const Duration(seconds: 1), (_) { + if (!mounted) { + return; + } + setState(() => _noteElapsed += const Duration(seconds: 1)); + if (_noteElapsed >= RoundVideoRecorder.maxLength) { + _stopRoundNote(); + } + }); + // The finger was lifted while the camera was still opening. + if (_noteStopRequested) { + _noteStopRequested = false; + await _stopRoundNote(); + } + } + + /// Stops the round note and sends it, unless it was dragged away. + Future _stopRoundNote() async { + _noteTimer?.cancel(); + _noteTimer = null; + final recorder = _noteRecorder; + _noteRecorder = null; + final cancelled = _noteCancel; + _noteCancel = false; + if (mounted) { + setState(() => _isRecordingNote = false); + } + if (recorder == null) { + return; + } + if (cancelled) { + await recorder.cancel(); + return; + } + final file = await recorder.stop(); + if (file == null) { + return; + } + await _sendMedia(MediaType.video, file, videoNote: true); + } + + /// The circle above the composer while a round note is being recorded. + Widget _buildRoundNotePreview() { + final controller = _noteRecorder?.controller; + final color = _noteCancel ? Colors.red : chatTheme.colorScheme.primary; + final ready = controller != null && controller.value.isInitialized; + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ClipOval( + child: SizedBox( + width: 150, + height: 150, + child: ready + ? FittedBox( + fit: BoxFit.cover, + child: SizedBox( + width: controller.value.previewSize?.height ?? 150, + height: controller.value.previewSize?.width ?? 150, + child: CameraPreview(controller), + ), + ) + : const ColoredBox( + color: Colors.black26, + child: Center(child: CircularProgressIndicator()), + ), + ), + ), + const SizedBox(height: 4), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.fiber_manual_record, + size: 12, color: Colors.red), + const SizedBox(width: 4), + Text( + '${_formatRecordDuration(_noteElapsed)} · ${'slideToCancel'.tr()}', + style: TextStyle(color: color, fontSize: 12), + ), + ], + ), + ], + ), + ); + } + /// Runs the editor for one picked attachment. Returns null when the user /// backs out, which aborts the send instead of silently sending the original. Future _editAttachment(MediaType type, File file) async { @@ -1177,36 +1308,6 @@ class _ChatPageState extends State { return SafeArea( child: Wrap( children: [ - ListTile( - leading: const Icon(Icons.photo_camera), - title: Text('attachCamera'.tr()), - onTap: () { - Navigator.pop(ctx); - _pickAndSend(() async { - final file = await MediaUtils.pickImageFromCamera(); - return file == null ? [] : [file]; - }, forcedType: MediaType.image); - }, - ), - ListTile( - leading: const Icon(Icons.videocam), - title: Text('attachVideoCamera'.tr()), - onTap: () { - Navigator.pop(ctx); - _pickAndSend(() async { - final file = await MediaUtils.pickVideoFromCamera(); - return file == null ? [] : [file]; - }, forcedType: MediaType.video); - }, - ), - ListTile( - leading: const Icon(Icons.videocam_outlined), - title: Text('videoNote'.tr()), - onTap: () { - Navigator.pop(ctx); - _recordVideoNote(); - }, - ), ListTile( leading: const Icon(Icons.photo_library), title: Text('attachGallery'.tr()), @@ -1398,6 +1499,33 @@ class _ChatPageState extends State { tooltip: 'attachButton'.tr(), onPressed: _isSending ? null : _showAttachSheet, ), + // Tap opens the camera, holding it records a round video note + // and releasing sends it. Only the long press is registered + // here, so a tap stays the plain button. + suffixIcon: GestureDetector( + onLongPressStart: (_) => _startRoundNote(), + onLongPressMoveUpdate: (details) { + if (!_isRecordingNote) { + return; + } + final cancel = details.localOffsetFromOrigin.dx < -80; + if (cancel != _noteCancel) { + setState(() => _noteCancel = cancel); + } + }, + onLongPressEnd: (_) { + if (_isRecordingNote) { + _stopRoundNote(); + } else { + _noteStopRequested = true; + } + }, + child: IconButton( + icon: const Icon(Icons.photo_camera_outlined), + tooltip: 'attachCamera'.tr(), + onPressed: _isSending ? null : _captureFromCamera, + ), + ), filled: true, fillColor: chatTheme.brightness == Brightness.dark ? chatTheme.colorScheme.surfaceBright @@ -2089,6 +2217,7 @@ class _ChatPageState extends State { mainAxisSize: MainAxisSize.min, children: [ if (_replyTo != null) _buildReplyBar(), + if (_isRecordingNote) _buildRoundNotePreview(), if (PresenceNotifier.instance.isTyping(widget.user.id)) Padding( padding: const EdgeInsets.fromLTRB(12, 0, 12, 4), diff --git a/lib/pages/video_note_page.dart b/lib/pages/video_note_page.dart deleted file mode 100644 index e6aad5f..0000000 --- a/lib/pages/video_note_page.dart +++ /dev/null @@ -1,197 +0,0 @@ -import 'dart:async'; -import 'dart:io'; - -import 'package:camera/camera.dart'; -import 'package:easy_localization/easy_localization.dart'; -import 'package:flutter/material.dart'; -import 'package:fluttertoast/fluttertoast.dart'; - -/// Records a round video note. -/// -/// The picture is drawn inside a circle here and on the recipient side; the -/// file is an ordinary mp4, so nothing about playback needs a new format. -class VideoNotePage extends StatefulWidget { - const VideoNotePage({super.key}); - - /// Longest video note, seconds. A note is a glance, not a video message. - static const Duration maxLength = Duration(seconds: 60); - - /// Opens the recorder and returns the recorded file, or null. - static Future open(BuildContext context) { - return Navigator.push( - context, MaterialPageRoute(builder: (_) => const VideoNotePage())); - } - - @override - State createState() => _VideoNotePageState(); -} - -class _VideoNotePageState extends State - with WidgetsBindingObserver { - CameraController? _controller; - Timer? _timer; - Duration _elapsed = Duration.zero; - bool _recording = false; - bool _ready = false; - - @override - void initState() { - super.initState(); - WidgetsBinding.instance.addObserver(this); - _openCamera(); - } - - Future _openCamera() async { - try { - final cameras = await availableCameras(); - if (cameras.isEmpty) { - throw CameraException('noCamera', 'no camera on this device'); - } - // The front camera is what a video note is for: it is a message to a - // person, not a recording of the room. - final front = cameras.firstWhere( - (camera) => camera.lensDirection == CameraLensDirection.front, - orElse: () => cameras.first, - ); - final controller = - CameraController(front, ResolutionPreset.medium, enableAudio: true); - await controller.initialize(); - if (!mounted) { - await controller.dispose(); - return; - } - setState(() { - _controller = controller; - _ready = true; - }); - } catch (e) { - if (mounted) { - await Fluttertoast.showToast( - msg: 'cameraUnavailable'.tr(), backgroundColor: Colors.red); - Navigator.pop(context); - } - } - } - - @override - void didChangeAppLifecycleState(AppLifecycleState state) { - // The plugin does not park the camera by itself: leaving it running while - // the app is in the background keeps the camera light on. - final controller = _controller; - if (controller == null || !controller.value.isInitialized) { - return; - } - if (state == AppLifecycleState.inactive) { - controller.dispose(); - setState(() => _ready = false); - } else if (state == AppLifecycleState.resumed) { - _openCamera(); - } - } - - Future _toggleRecording() async { - final controller = _controller; - if (controller == null || !_ready) { - return; - } - if (_recording) { - await _stop(); - return; - } - try { - await controller.startVideoRecording(); - } catch (_) { - return; - } - setState(() { - _recording = true; - _elapsed = Duration.zero; - }); - _timer = Timer.periodic(const Duration(seconds: 1), (timer) { - if (!mounted) { - return; - } - setState(() => _elapsed += const Duration(seconds: 1)); - if (_elapsed >= VideoNotePage.maxLength) { - _stop(); - } - }); - } - - Future _stop() async { - _timer?.cancel(); - _timer = null; - final controller = _controller; - if (controller == null || !_recording) { - return; - } - setState(() => _recording = false); - try { - final file = await controller.stopVideoRecording(); - if (mounted) { - Navigator.pop(context, File(file.path)); - } - } catch (_) { - if (mounted) { - Navigator.pop(context); - } - } - } - - @override - void dispose() { - WidgetsBinding.instance.removeObserver(this); - _timer?.cancel(); - _controller?.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - final controller = _controller; - return Scaffold( - backgroundColor: Colors.black, - appBar: AppBar( - backgroundColor: Colors.transparent, - foregroundColor: Colors.white, - title: Text('videoNote'.tr()), - ), - body: Center( - child: !_ready || controller == null - ? const CircularProgressIndicator() - : ClipOval( - child: SizedBox( - width: 280, - height: 280, - child: FittedBox( - fit: BoxFit.cover, - child: SizedBox( - width: controller.value.previewSize?.height ?? 280, - height: controller.value.previewSize?.width ?? 280, - child: CameraPreview(controller), - ), - ), - ), - ), - ), - floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, - floatingActionButton: Column( - mainAxisSize: MainAxisSize.min, - children: [ - if (_recording) - Text( - '${_elapsed.inSeconds}s / ${VideoNotePage.maxLength.inSeconds}s', - style: const TextStyle(color: Colors.white), - ), - const SizedBox(height: 8), - FloatingActionButton( - onPressed: _ready ? _toggleRecording : null, - backgroundColor: _recording ? Colors.red : Colors.white, - child: Icon(_recording ? Icons.stop : Icons.videocam, - color: _recording ? Colors.white : Colors.black), - ), - ], - ), - ); - } -} diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 1e24c87..551e432 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -648,21 +648,7 @@ class MediaUtils { // Pickers // --------------------------------------------------------------------------- - /// Capture a photo with the camera. - static Future pickImageFromCamera() async { - final picked = await _imagePicker.pickImage( - source: ImageSource.camera, imageQuality: 85); - return picked == null ? null : File(picked.path); - } - - /// Capture a video with the camera. - static Future pickVideoFromCamera() async { - final picked = await _imagePicker.pickVideo( - source: ImageSource.camera, maxDuration: const Duration(minutes: 1)); - return picked == null ? null : File(picked.path); - } - - /// Pick an arbitrary file (images, videos, documents, ...). + /// Pick one arbitrary file. static Future pickFile() async { final picked = await FilePicker.pickFile(type: FileType.any); final path = picked?.path; diff --git a/lib/utils/round_video_recorder.dart b/lib/utils/round_video_recorder.dart new file mode 100644 index 0000000..bb0bfaf --- /dev/null +++ b/lib/utils/round_video_recorder.dart @@ -0,0 +1,93 @@ +import 'dart:io'; + +import 'package:camera/camera.dart'; + +/// Records the round video note started by holding down the composer's camera +/// button. +/// +/// The chat page owns the camera for the few seconds the finger is down, shows +/// the circle above the composer and hands the file over when it is released. +class RoundVideoRecorder { + /// Longest note. A note is a glance, not a video message. + static const Duration maxLength = Duration(seconds: 60); + + CameraController? _controller; + bool _recording = false; + + CameraController? get controller => _controller; + + bool get isReady => _controller?.value.isInitialized ?? false; + + /// Opens the front camera and starts recording. False when there is no camera + /// or it cannot be opened (permission, busy). + Future start() async { + try { + final cameras = await availableCameras(); + if (cameras.isEmpty) { + return false; + } + // A note is a message to a person, not a recording of the room. + final front = cameras.firstWhere( + (camera) => camera.lensDirection == CameraLensDirection.front, + orElse: () => cameras.first, + ); + final controller = + CameraController(front, ResolutionPreset.medium, enableAudio: true); + await controller.initialize(); + _controller = controller; + await controller.startVideoRecording(); + _recording = true; + return true; + } catch (_) { + await dispose(); + return false; + } + } + + /// Stops and returns the recorded file, or null when nothing was recorded. + Future stop() async { + final controller = _controller; + if (controller == null || !_recording) { + await dispose(); + return null; + } + _recording = false; + try { + final captured = await controller.stopVideoRecording(); + final file = File(captured.path); + await dispose(); + return file; + } catch (_) { + await dispose(); + return null; + } + } + + /// Stops and throws the recording away. + Future cancel() async { + final controller = _controller; + if (controller != null && _recording) { + _recording = false; + try { + final captured = await controller.stopVideoRecording(); + await File(captured.path) + .delete() + .catchError((_) => File(captured.path)); + } catch (_) { + // Nothing to keep. + } + } + await dispose(); + } + + Future dispose() async { + final controller = _controller; + _controller = null; + _recording = false; + try { + await controller?.dispose(); + } catch (_) { + // The platform side may already be gone. + } + } +} From 48f690d74fec61dd100ae15fc9b24a91edbab60d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 01:34:54 +0100 Subject: [PATCH 151/181] fix(app): fill the camera preview and follow the device orientation --- lib/pages/camera_page.dart | 34 ++++++++++++++++++++++++++++------ lib/utils/media_utils.dart | 11 +++++++---- 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/lib/pages/camera_page.dart b/lib/pages/camera_page.dart index 6807bf9..be10ee7 100644 --- a/lib/pages/camera_page.dart +++ b/lib/pages/camera_page.dart @@ -4,6 +4,7 @@ import 'dart:io'; import 'package:camera/camera.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; /// In-app camera: tap the shutter for a photo, hold it to record a video. @@ -41,6 +42,13 @@ class _CameraPageState extends State with WidgetsBindingObserver { void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); + // The camera is the one screen that follows the phone: a photo taken on a + // turned phone is a landscape photo. Everything else stays portrait. + SystemChrome.setPreferredOrientations(const [ + DeviceOrientation.portraitUp, + DeviceOrientation.landscapeLeft, + DeviceOrientation.landscapeRight, + ]); _openCamera(); } @@ -190,6 +198,7 @@ class _CameraPageState extends State with WidgetsBindingObserver { WidgetsBinding.instance.removeObserver(this); _timer?.cancel(); _controller?.dispose(); + SystemChrome.setPreferredOrientations(const [DeviceOrientation.portraitUp]); super.dispose(); } @@ -208,12 +217,7 @@ class _CameraPageState extends State with WidgetsBindingObserver { fit: StackFit.expand, children: [ if (controller != null && controller.value.isInitialized) - Center( - child: AspectRatio( - aspectRatio: controller.value.aspectRatio, - child: CameraPreview(controller), - ), - ) + _preview(controller) else const Center(child: CircularProgressIndicator()), SafeArea( @@ -279,6 +283,24 @@ class _CameraPageState extends State with WidgetsBindingObserver { ); } + /// The sensor reports a landscape frame; on a turned phone the sides swap, so + /// the fill has to cover the screen instead of sitting in a letterboxed band. + Widget _preview(CameraController controller) { + final portrait = MediaQuery.orientationOf(context) == Orientation.portrait; + final aspect = controller.value.aspectRatio; + final width = portrait ? 1 / aspect : aspect; + return SizedBox.expand( + child: FittedBox( + fit: BoxFit.cover, + child: SizedBox( + width: width * 1000, + height: 1000, + child: CameraPreview(controller), + ), + ), + ); + } + Widget _shutter() { return Container( width: 78, diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 551e432..5152d9d 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -559,11 +559,14 @@ class MediaUtils { try { await controller.initialize(); final size = controller.value.size; - final duration = controller.value.duration; + // A phone held upright records a portrait video into a landscape frame + // plus a rotation flag, so the coded size alone would show it the wrong + // way round in a bubble. + final turned = controller.value.rotationCorrection % 180 != 0; return MediaProbe( - width: size.width.round(), - height: size.height.round(), - durationMs: duration.inMilliseconds, + width: (turned ? size.height : size.width).round(), + height: (turned ? size.width : size.height).round(), + durationMs: controller.value.duration.inMilliseconds, ); } catch (_) { return const MediaProbe(); From d36663e312a02784fe9d5cdbbffda7174ddf5060 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 01:37:50 +0100 Subject: [PATCH 152/181] fix(app): move the camera shutter to the right when turned --- assets/translations/cs.json | 1 - assets/translations/en.json | 1 - lib/pages/camera_page.dart | 134 ++++++++++++++++++++++-------------- 3 files changed, 81 insertions(+), 55 deletions(-) diff --git a/assets/translations/cs.json b/assets/translations/cs.json index d69621e..8c22efe 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -329,6 +329,5 @@ "shareFailed": "Sdílení se nepovedlo", "cameraUnavailable": "Kamera není dostupná", "applyTrim": "Oříznout", - "shutterHint": "Klepnutím fotka, držením video", "captureFailed": "Nepodařilo se vyfotit" } diff --git a/assets/translations/en.json b/assets/translations/en.json index 7144155..e95231c 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -329,6 +329,5 @@ "shareFailed": "Sharing failed", "cameraUnavailable": "Camera is not available", "applyTrim": "Trim", - "shutterHint": "Tap for a photo, hold for a video", "captureFailed": "Could not capture" } diff --git a/lib/pages/camera_page.dart b/lib/pages/camera_page.dart index be10ee7..f2ca1aa 100644 --- a/lib/pages/camera_page.dart +++ b/lib/pages/camera_page.dart @@ -211,6 +211,7 @@ class _CameraPageState extends State with WidgetsBindingObserver { @override Widget build(BuildContext context) { final controller = _controller; + final portrait = MediaQuery.orientationOf(context) == Orientation.portrait; return Scaffold( backgroundColor: Colors.black, body: Stack( @@ -221,62 +222,79 @@ class _CameraPageState extends State with WidgetsBindingObserver { else const Center(child: CircularProgressIndicator()), SafeArea( - child: Column( - children: [ - Row( - children: [ - IconButton( - color: Colors.white, - onPressed: () => Navigator.pop(context), - icon: const Icon(Icons.close), - ), - const Spacer(), - if (_recording) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 8), - child: Row( - children: [ - const Icon(Icons.fiber_manual_record, - color: Colors.red, size: 14), - const SizedBox(width: 6), - Text( - '${_format(_elapsed)} / ${_format(CameraPage.maxVideoLength)}', - style: const TextStyle(color: Colors.white), - ), - ], + child: portrait + ? Column( + children: [ + _topBar(showTimer: true), + const Spacer(), + _shutter(), + const SizedBox(height: 40), + ], + ) + // Turned to the side, the shutter moves to the right edge where + // the thumb rests, the way the system camera does it. + : Stack( + children: [ + Align( + alignment: Alignment.topCenter, + child: _topBar(showTimer: false), + ), + Align( + alignment: Alignment.centerRight, + child: Padding( + padding: const EdgeInsets.only(right: 32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (_recording) _timerChip(), + _shutter(), + ], + ), ), ), - IconButton( - color: _flashOn ? Colors.amber : Colors.white, - onPressed: _toggleFlash, - icon: Icon(_flashOn ? Icons.flash_on : Icons.flash_off), - ), - IconButton( - color: Colors.white, - onPressed: _switchCamera, - icon: const Icon(Icons.cameraswitch), - ), - ], - ), - const Spacer(), - Padding( - padding: const EdgeInsets.only(bottom: 32), - child: GestureDetector( - onTap: _takePhoto, - onLongPressStart: (_) => _startVideo(), - onLongPressEnd: (_) => _stopVideo(), - child: _shutter(), - ), - ), - Padding( - padding: const EdgeInsets.only(bottom: 16), - child: Text( - 'shutterHint'.tr(), - style: const TextStyle(color: Colors.white70, fontSize: 12), + ], ), - ), - ], - ), + ), + ], + ), + ); + } + + Widget _topBar({required bool showTimer}) { + return Row( + children: [ + IconButton( + color: Colors.white, + onPressed: () => Navigator.pop(context), + icon: const Icon(Icons.close), + ), + const Spacer(), + if (showTimer && _recording) _timerChip(), + IconButton( + color: _flashOn ? Colors.amber : Colors.white, + onPressed: _toggleFlash, + icon: Icon(_flashOn ? Icons.flash_on : Icons.flash_off), + ), + IconButton( + color: Colors.white, + onPressed: _switchCamera, + icon: const Icon(Icons.cameraswitch), + ), + ], + ); + } + + Widget _timerChip() { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.fiber_manual_record, color: Colors.red, size: 14), + const SizedBox(width: 6), + Text( + '${_format(_elapsed)} / ${_format(CameraPage.maxVideoLength)}', + style: const TextStyle(color: Colors.white), ), ], ), @@ -301,7 +319,17 @@ class _CameraPageState extends State with WidgetsBindingObserver { ); } + /// Tap takes a photo, holding records a video until it is released. Widget _shutter() { + return GestureDetector( + onTap: _takePhoto, + onLongPressStart: (_) => _startVideo(), + onLongPressEnd: (_) => _stopVideo(), + child: _shutterButton(), + ); + } + + Widget _shutterButton() { return Container( width: 78, height: 78, From 18bc411d0e1d2ae846c1ab5d86f958d6541d4f99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 01:40:07 +0100 Subject: [PATCH 153/181] fix(app): shrink the recording stop square in the camera shutter --- lib/pages/camera_page.dart | 39 ++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/lib/pages/camera_page.dart b/lib/pages/camera_page.dart index f2ca1aa..65ebf8b 100644 --- a/lib/pages/camera_page.dart +++ b/lib/pages/camera_page.dart @@ -338,20 +338,31 @@ class _CameraPageState extends State with WidgetsBindingObserver { border: Border.all(color: Colors.white, width: 4), ), padding: const EdgeInsets.all(6), - child: DecoratedBox( - decoration: BoxDecoration( - shape: _recording ? BoxShape.rectangle : BoxShape.circle, - borderRadius: _recording ? BorderRadius.circular(6) : null, - color: _recording ? Colors.red : Colors.white, - ), - child: _busy - ? const Center( - child: SizedBox( - width: 20, - height: 20, - child: CircularProgressIndicator(strokeWidth: 2))) - : null, - ), + child: _busy + ? const Center( + child: SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2))) + // Recording: a small stop square inside the ring, so the button keeps + // its size and only the glyph changes. + : _recording + ? Center( + child: Container( + width: 28, + height: 28, + decoration: BoxDecoration( + color: Colors.red, + borderRadius: BorderRadius.circular(5), + ), + ), + ) + : const DecoratedBox( + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.white, + ), + ), ); } } From 2d3b1c53f5cf89004cae2a5036fd6557be654a59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 01:44:27 +0100 Subject: [PATCH 154/181] fix(app): read video rotation from the container so portrait clips stay portrait --- lib/utils/media_utils.dart | 10 +++- lib/utils/mp4_rotation.dart | 102 ++++++++++++++++++++++++++++++++++ lib/widgets/media_bubble.dart | 61 ++++++++++++++++++-- test/fixtures/portrait.mp4 | Bin 0 -> 5389 bytes test/mp4_rotation_test.dart | 23 ++++++++ 5 files changed, 188 insertions(+), 8 deletions(-) create mode 100644 lib/utils/mp4_rotation.dart create mode 100644 test/fixtures/portrait.mp4 create mode 100644 test/mp4_rotation_test.dart diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 5152d9d..f9bb032 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -18,6 +18,7 @@ import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import 'singleton.dart'; +import 'mp4_rotation.dart'; import 'utils.dart'; /// Result of encrypting a file for transport: the uploadable [blob] @@ -561,8 +562,13 @@ class MediaUtils { final size = controller.value.size; // A phone held upright records a portrait video into a landscape frame // plus a rotation flag, so the coded size alone would show it the wrong - // way round in a bubble. - final turned = controller.value.rotationCorrection % 180 != 0; + // way round in a bubble. The container is the source of truth; the + // player's own value is only a fallback. + var rotation = await Mp4Rotation.ofFile(File(filePath)); + if (rotation == 0) { + rotation = controller.value.rotationCorrection; + } + final turned = rotation % 180 != 0; return MediaProbe( width: (turned ? size.height : size.width).round(), height: (turned ? size.width : size.height).round(), diff --git a/lib/utils/mp4_rotation.dart b/lib/utils/mp4_rotation.dart new file mode 100644 index 0000000..b1714a6 --- /dev/null +++ b/lib/utils/mp4_rotation.dart @@ -0,0 +1,102 @@ +import 'dart:io'; +import 'dart:math' as math; +import 'dart:typed_data'; + +/// Reads the display rotation a phone writes into an mp4 instead of rotating +/// the pixels: a portrait clip is often stored as a landscape frame plus a +/// rotation in the track header. +/// +/// The player plugin reports the same value, but not every platform and file +/// combination does, and a bubble sized from the unrotated frame shows a +/// portrait video lying on its side. +class Mp4Rotation { + Mp4Rotation._(); + + /// Rotation of the first track in degrees (0, 90, 180 or 270). Zero when the + /// file is not an mp4 or carries no rotation. + static Future ofFile(File file) async { + RandomAccessFile? handle; + try { + handle = await file.open(); + final end = await handle.length(); + final tkhd = await _findTkhd(handle, 0, end); + return tkhd ?? 0; + } catch (_) { + return 0; + } finally { + await handle?.close(); + } + } + + /// Walks the box tree (moov > trak > tkhd) without reading the media data. + static Future _findTkhd( + RandomAccessFile handle, int start, int end) async { + var offset = start; + while (offset + 8 <= end) { + await handle.setPosition(offset); + final header = await handle.read(8); + if (header.length < 8) { + return null; + } + final data = ByteData.sublistView(header); + var size = data.getUint32(0); + final type = String.fromCharCodes(header.sublist(4, 8)); + var headerSize = 8; + if (size == 1) { + final large = await handle.read(8); + if (large.length < 8) { + return null; + } + size = ByteData.sublistView(large).getUint64(0); + headerSize = 16; + } else if (size == 0) { + size = end - offset; + } + if (size < headerSize || offset + size > end) { + return null; + } + final bodyStart = offset + headerSize; + final bodyEnd = offset + size; + if (type == 'moov' || type == 'trak') { + final found = await _findTkhd(handle, bodyStart, bodyEnd); + if (found != null) { + return found; + } + } else if (type == 'tkhd') { + return _rotationFromTkhd(handle, bodyStart, bodyEnd); + } + offset = bodyEnd; + } + return null; + } + + /// The rotation hides in the tkhd display matrix: `a` and `b` of + /// `[a b u c d v x y w]` are the cosine and sine of the angle. + static Future _rotationFromTkhd( + RandomAccessFile handle, int start, int end) async { + if (end - start < 48) { + return null; + } + await handle.setPosition(start); + final payload = await handle.read(end - start); + if (payload.isEmpty) { + return null; + } + final data = ByteData.sublistView(payload); + final version = payload[0]; + // version + flags, then timestamps and ids: the matrix follows them. + var matrix = version == 1 ? 4 + 24 + 8 + 8 : 4 + 16 + 4 + 8 + 8; + if (matrix + 8 > payload.length) { + return null; + } + final a = data.getInt32(matrix) / 65536.0; + final b = data.getInt32(matrix + 4) / 65536.0; + if (a == 0 && b == 0) { + return 0; + } + // The matrix maps the picture into the track; the display turns the other + // way, which is why the angle is negated (ffmpeg does the same). + final degrees = (-math.atan2(b, a) * 180 / math.pi).round(); + return ((degrees % 360) + 360) % 360; + } +} diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index d83bd4b..b831268 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -10,7 +10,9 @@ import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../pages/media_viewer_page.dart'; +import '../utils/cache_utils.dart'; import '../utils/media_utils.dart'; +import '../utils/mp4_rotation.dart'; import '../utils/message_actions.dart'; import '../utils/singleton.dart'; import 'view_once_frame.dart'; @@ -90,12 +92,15 @@ class _MediaBubbleState extends State { } /// Constrained display size derived from the original media dimensions. - Size _displaySize() { + /// Size the video player reported for this bubble, used when the stored + /// dimensions of an older message are the unrotated frame. + Size? _videoFrame; + + /// Fits [w]x[h] into the bubble's box. + Size _fitToBox(int w, int h) { const maxW = 240.0; const maxH = 320.0; - final w = widget.message.width; - final h = widget.message.height; - if (w == null || h == null || w <= 0 || h <= 0) { + if (w <= 0 || h <= 0) { return const Size(220, 220); } double dw = w.toDouble(); @@ -111,6 +116,33 @@ class _MediaBubbleState extends State { return Size(dw, dh); } + Size _displaySize() { + final frame = _videoFrame; + if (frame != null) { + return _fitToBox(frame.width.round(), frame.height.round()); + } + return _fitToBox(widget.message.width ?? 0, widget.message.height ?? 0); + } + + /// Takes the size the player sees (rotation included) and stores it, so an + /// older message stops showing a portrait video in a landscape bubble. + void _onVideoFrame(Size frame) { + if (_videoFrame == frame) { + return; + } + setState(() => _videoFrame = frame); + final width = frame.width.round(); + final height = frame.height.round(); + if (widget.message.width == width && widget.message.height == height) { + return; + } + CacheUtils.updateStoredMessage(widget.conversationUserId, widget.message, + (stored) { + stored.width = width; + stored.height = height; + }); + } + /// A single-view attachment never shows a thumbnail: nobody sees it before /// opening it, and the open happens exactly once. Its caption stays hidden /// too, since it already shows inside the viewer once opened. An opened @@ -512,7 +544,10 @@ class _MediaBubbleState extends State { alignment: Alignment.center, fit: StackFit.expand, children: [ - VideoThumbnail(path: widget.message.localPath), + VideoThumbnail( + path: widget.message.localPath, + onFrame: _onVideoFrame, + ), Container( decoration: BoxDecoration( color: Colors.black.withValues(alpha: 0.25), @@ -767,7 +802,10 @@ class _AlbumTileState extends State { class VideoThumbnail extends StatefulWidget { final String? path; - const VideoThumbnail({this.path, super.key}); + /// Called once the frame is known, with the rotation already applied. + final ValueChanged? onFrame; + + const VideoThumbnail({this.path, this.onFrame, super.key}); @override State createState() => _VideoThumbnailState(); @@ -803,6 +841,17 @@ class _VideoThumbnailState extends State { final controller = VideoPlayerController.file(temp); await controller.initialize(); await controller.setVolume(0); + // The stored dimensions can be the unrotated frame; the container knows. + var rotation = await Mp4Rotation.ofFile(temp); + if (rotation == 0) { + rotation = controller.value.rotationCorrection; + } + final size = controller.value.size; + if (rotation % 180 != 0) { + widget.onFrame?.call(Size(size.height, size.width)); + } else if (size.width > 0 && size.height > 0) { + widget.onFrame?.call(size); + } if (!mounted) { await controller.dispose(); MediaUtils.deleteLocalFile(temp.path); diff --git a/test/fixtures/portrait.mp4 b/test/fixtures/portrait.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..c3641abb5ffb78861ad58dbdec848dae426f080c GIT binary patch literal 5389 zcmZuV2|Sct_m6}uX?c;XV~LbyW^5^Aj}#%<*D*7g%$R9r>?&Ikg^+9^St2w=$XZfD zDv~|>l6a9VW&7Vzec$_i-~arad(J)EJ@=gR<8dJfg1OTC$apG=2thj_1_g*jdt(qp zvJwJyen9^F^vC!Q@~V5(NiC zs3^lIiby09=Ax*q0#`-@#VL7UpkQoz(m+lLrfsPUEU`EYQ0S7#egvE=4Tgln73Gj{ zq%sh?(`e-53JN|xKJwmpERIA#d&-k2ZVHT3GPhzQ`}L_vGH;ZO(_7{;AKBBGsuD*{HN;0Odf6>!IVk6|%1 zz+f&CQE-p~8tYH;#G#M~Sp)*+il)+>$W#wJnPKrOz(ukX$<>vLqoL%GFq%6Bcu-MF zFan9>fp!NQr#~_Tj7q>`KrVj-aF{1$`wR@8h^8^}zv=6zG)`8jB_~ZsFqOf=5#shu|r= z?R)v)@NVuj7oa1Nah^_YBr?$c5|V+d2hI<~Mj@5qzgZ_D-V=p@!>AaXCl2F9Ln*-- zX;RRPl2UL~ci>LJIQ{Fo3_S&d!cbgcL>Ew3#!!9x|gM!Pe0G7-MyiL)* zC>1pzpwe(;P&qsqGzkm@=pl%Oz6koy=q3~dL2O@e5n+(#*5-Hjj2)?t4v4-3-k&3& z7*VC>;{B07q^8yl z#T{6ri21PUinT^JI-KZ`3XJPG9eChI?G+nr$!xrS-Lu@R7{6DnkDT~sH95serD{nf z4|DHQvzJr>ZhrT!UCXv|9LKLvb(yU*auQc6#s01;%r=f&e`6RPc{#as zYOqG7DW0NhAYZFF6pOj@G`cjcN<8PWZa1Yfm#L6;GgM%7O*!xKhuk-WwUCg6fJzC<^d z14%CRp@L=dB%e#YQgZfQ(GP}VvKe~m153U`x)CD5yds#9SYmWarcB9Jr#1U^H|}bE z{Lukt?)Wd$n;dvwjM}wJf%54-hIF^{vbQb5Am3Qy%vyn@g=4T!Oatx7g=+6H*}HE4 zJyaDf216azE2v_l$*gjh+Vq#i8XNtrRg>AJirvW< z!$0xLjEkq=Ix$4|FF*#hoBh09Dx4C+V!)Hofarf}FmcWzwO&r#-}%87GKTIx>f5Gr z<=_R0-2FGxxy*Q-?m64%^b)Jci#A;ErVJzKa>d3>I@) zhetxvM%*WMBY$S+zdX}Gn>wo{e9PL5+!DjXLiADPr#9=R&6M`~r)3Epl6&ADtQi`r zcV0yQ2$jt8Xy}Q2rN*9~@D%$`-EFKY83i4$sxgfkF+gH7pUh#%q@b5tFtv=x9X30B1kbhUy?gix5p%sol33Y-w||R)jm_3{h+W6gkH5%1q$OS2 zdH&_Pi}spq;>L;Gim{2aAIj}!#?!A|-1#lJN5Nh2`Q3{CW6v)mD`MQ+UAU7K6HVK? z@O}FeF!c#u9D?z!wUylOE*z8aDlN6lLFiWsezz+PY!O@^R_bBes7Al!Sm_QwAYC&q z^4FrCpJGj~T4L(M(K{#i?f*#Um^3STXvCT2PR~(H>NUFWZmMi8F!v?dS-W#dv?#|T zyOmF%tv~aEMcGtg5~WH~r5V-Km6=B&;-boewYWv|zd2nNFkr7h}TQfiMDl@)o5Ew1%!I> z(NN3Gyk$I})sg6W&1-t*N35FGilfv8%qubi4LZHzMW#@5Y9Gt`*Vg8xpC@!|g%Jri zQL4_azNH2)c#^pgPV4}}r;!=QD~s-j|wk`I6CtjYzYd` zX7Y0(PI?U$t(n_CvCa#Szy82x;Jn8AnbT?as%Oq|?By{ZnvXLS{`ysTmh4t^ypcOe zbXq+U9kUa8$?hn3CfDg__Yn8`9lUATW=WJW#gXruL98=ga}%_W>v5a{snm=3-akbcF-TcXe%!ar)sLuke4@#}>7|*|9 z#zpVavK-0^%~cby6OM9$6(g;pvt zIuCyE_Ct?u6#u(a&DhO6w^Lesci~LguHZPiGY-?}z5I5U`~uk*TXj^DhVLFaxdpyf z`?OQU2)bLF`FGUz=0RdV1m+%ij0N^>nX``!`8J!Ed6uR6d52b7XYZl&B;BwbNi=?T zK*ioc#+MT}xR~aHdSJwL?FmArsKboM#Pun$us5miNbRGsrno&5cLh~!l=%7D=hm8Z zl?3Y*?(08|DJqODW)=A6!9Ey2l$`G6&)admub;m*P@>B`R3Xoe%AsjxonzMCfZ)bI z5>NTC%Xz}6z$~O!lI3cVjXK|Zn5nT5XZ>iL{R;Ui|D05`!XYfq{M?P1hT5nSOh9G! z9Rc=e!B4xDUfTtpd=EZlpfB1fI_hHaGGTkSHVZ7E3z07A!f$P%(*kC-4e=tA+1Soz z^wW2q>ShN+7VE#!q7uPJVw6{!91zG&a9*(TrFfe4JTC_vz`aOesFfeaSpzbK7fmr*%dA5XJh^J^2PW^fjHRL)s-1v_nk1poP4Z&-Zl?8mxZ)7+9 zId8LY&+_!mFpb@3vtp~N`}XR?L;FL{5S@>7+AKAR&5L@F3)|^=Mk(^kvQ@#nj5~d; zp>#k*)L?OJcWF-(E*p}5<#6ErQttG3J4;Q~65lt`3SuSaCGl-rWA{vN_deUWd3N7w zZ^MWv!r#1-E5=u`xc9aCtu5DQO+S=OF8VbNHkfv3%S^p$%Zv@SSat*UB(@v+f|IQ(-1X=q*U>*7yKn+ZRjLH%H>H}f+e?Uv`KQ1 z&-Yu^>uV!mOkB-3=X$EgS@)Jbstj6f<4%Zo6t0L^jP}+WyHb0aoZ&TpD0DFxzAvB_({*Grpm^lAQKcnQ3Ad&Ze_N%nwF|EMb{7n8j`2&Ru-Z{-iwhQbVKOC$Y zhzcw}o~TE&IgY8fQ(rXkM*+KA0Ql>|Ge`VxLuKUO5;Co7e@@Z zLx$KK>Fw`}PX#<-3%PaYXNu~1`U70TrbO#2$7)4WRP}S7v=up<&^3Cn$&~Yy1b_09 z{@g-w;!U^I#6sJB3Hxk^D!e9DYB;OYT9zevU#R(q+{uL;fASPoI@uiEa(nC7*m{mT zp&IXacOv|}LDlF{!NZ0Nuvgg`<>#BCWm=3y!t>83^fVb;@`STVeGt&uxRv`uPv^o@ zACPdRcFLDu2@C(4Bzv`e>(DM8iKZ2ndd@|bnikBHVAjUis{sK7lI6#%r=m_AOWq%g z<^O(|I-g%<9vH5{Wi@>Efl9*>dSY6oal8s9Y4K)G0{(>&nmWq%uC?K^77E7Kg!*l#Ywp~&tp?d=Xs5FO%3g45GcSx;5Z}II9b%JL z^e|oLBNmpYf15xP>!lMGWW_tIEH8}jJA=8C#d+e*ZTZjf9ncdiE_Jw&fO%eV14mz?>mo!fO)pLQ9}BV4~aApWiPqd`2xXAtR)qbH~Eb zT1{96w8{{jEC*ZL3T|7>=E=bR$&U%3a+*wZ|=&t(3G)$eGGv;P;i7=LaV@Ly*# zL|Tj`6QD1Hfh2KQ8Wm6>9Dxd+khTGMG2-s}?Z4v?5sOCy0gQF#{gx(KV$xqWP)p-0xSa=z{Fz&>{S%y5%LH)5=Owg zFy66#>3*&J+r?A?R=P}Bh+}IQI_L&yVUJGOW&534U^EydWnpf(jtgRfSly>bTg0Dl ztTKMvLwm_+Dj85l9t`9G4=BHj9N7&)421ZpwCx4}cH4#nf_5@^9&j&4V;JzqACCFA zEyD;51ZdK>p6fT=_GS4k7XmRb37^OAm>O2>>$7yU~&x5Jpii! z4gh=%uomEbfFL&v2~Y+w;=%!.filled(64, 0)); + addTearDown(() => file.deleteSync()); + + expect(await Mp4Rotation.ofFile(file), 0); + }); +} From e2a7d1140edca10f9c4042024da4a87886189d79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 01:51:30 +0100 Subject: [PATCH 155/181] fix(app): trust the player's rotated video size instead of rotating again --- lib/utils/media_utils.dart | 17 ++---- lib/utils/mp4_rotation.dart | 102 ---------------------------------- lib/widgets/media_bubble.dart | 14 ++--- test/fixtures/portrait.mp4 | Bin 5389 -> 0 bytes test/mp4_rotation_test.dart | 23 -------- 5 files changed, 10 insertions(+), 146 deletions(-) delete mode 100644 lib/utils/mp4_rotation.dart delete mode 100644 test/fixtures/portrait.mp4 delete mode 100644 test/mp4_rotation_test.dart diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index f9bb032..58807b7 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -18,7 +18,6 @@ import 'package:whisper_websocket_client_dart/models/media_reference.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import 'singleton.dart'; -import 'mp4_rotation.dart'; import 'utils.dart'; /// Result of encrypting a file for transport: the uploadable [blob] @@ -559,19 +558,13 @@ class MediaUtils { final controller = VideoPlayerController.file(File(filePath)); try { await controller.initialize(); + // The player reports the size with the recorded rotation already applied + // (a portrait clip comes back 480x720 from a 720x480 frame), so applying + // the rotation again here would lay it back on its side. final size = controller.value.size; - // A phone held upright records a portrait video into a landscape frame - // plus a rotation flag, so the coded size alone would show it the wrong - // way round in a bubble. The container is the source of truth; the - // player's own value is only a fallback. - var rotation = await Mp4Rotation.ofFile(File(filePath)); - if (rotation == 0) { - rotation = controller.value.rotationCorrection; - } - final turned = rotation % 180 != 0; return MediaProbe( - width: (turned ? size.height : size.width).round(), - height: (turned ? size.width : size.height).round(), + width: size.width.round(), + height: size.height.round(), durationMs: controller.value.duration.inMilliseconds, ); } catch (_) { diff --git a/lib/utils/mp4_rotation.dart b/lib/utils/mp4_rotation.dart deleted file mode 100644 index b1714a6..0000000 --- a/lib/utils/mp4_rotation.dart +++ /dev/null @@ -1,102 +0,0 @@ -import 'dart:io'; -import 'dart:math' as math; -import 'dart:typed_data'; - -/// Reads the display rotation a phone writes into an mp4 instead of rotating -/// the pixels: a portrait clip is often stored as a landscape frame plus a -/// rotation in the track header. -/// -/// The player plugin reports the same value, but not every platform and file -/// combination does, and a bubble sized from the unrotated frame shows a -/// portrait video lying on its side. -class Mp4Rotation { - Mp4Rotation._(); - - /// Rotation of the first track in degrees (0, 90, 180 or 270). Zero when the - /// file is not an mp4 or carries no rotation. - static Future ofFile(File file) async { - RandomAccessFile? handle; - try { - handle = await file.open(); - final end = await handle.length(); - final tkhd = await _findTkhd(handle, 0, end); - return tkhd ?? 0; - } catch (_) { - return 0; - } finally { - await handle?.close(); - } - } - - /// Walks the box tree (moov > trak > tkhd) without reading the media data. - static Future _findTkhd( - RandomAccessFile handle, int start, int end) async { - var offset = start; - while (offset + 8 <= end) { - await handle.setPosition(offset); - final header = await handle.read(8); - if (header.length < 8) { - return null; - } - final data = ByteData.sublistView(header); - var size = data.getUint32(0); - final type = String.fromCharCodes(header.sublist(4, 8)); - var headerSize = 8; - if (size == 1) { - final large = await handle.read(8); - if (large.length < 8) { - return null; - } - size = ByteData.sublistView(large).getUint64(0); - headerSize = 16; - } else if (size == 0) { - size = end - offset; - } - if (size < headerSize || offset + size > end) { - return null; - } - final bodyStart = offset + headerSize; - final bodyEnd = offset + size; - if (type == 'moov' || type == 'trak') { - final found = await _findTkhd(handle, bodyStart, bodyEnd); - if (found != null) { - return found; - } - } else if (type == 'tkhd') { - return _rotationFromTkhd(handle, bodyStart, bodyEnd); - } - offset = bodyEnd; - } - return null; - } - - /// The rotation hides in the tkhd display matrix: `a` and `b` of - /// `[a b u c d v x y w]` are the cosine and sine of the angle. - static Future _rotationFromTkhd( - RandomAccessFile handle, int start, int end) async { - if (end - start < 48) { - return null; - } - await handle.setPosition(start); - final payload = await handle.read(end - start); - if (payload.isEmpty) { - return null; - } - final data = ByteData.sublistView(payload); - final version = payload[0]; - // version + flags, then timestamps and ids: the matrix follows them. - var matrix = version == 1 ? 4 + 24 + 8 + 8 : 4 + 16 + 4 + 8 + 8; - if (matrix + 8 > payload.length) { - return null; - } - final a = data.getInt32(matrix) / 65536.0; - final b = data.getInt32(matrix + 4) / 65536.0; - if (a == 0 && b == 0) { - return 0; - } - // The matrix maps the picture into the track; the display turns the other - // way, which is why the angle is negated (ffmpeg does the same). - final degrees = (-math.atan2(b, a) * 180 / math.pi).round(); - return ((degrees % 360) + 360) % 360; - } -} diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index b831268..f14023b 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -3,6 +3,7 @@ import 'dart:io'; import 'dart:typed_data'; import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import '../utils/nav_transitions.dart'; import 'package:video_player/video_player.dart'; @@ -12,7 +13,6 @@ import '../models/private_message.dart'; import '../pages/media_viewer_page.dart'; import '../utils/cache_utils.dart'; import '../utils/media_utils.dart'; -import '../utils/mp4_rotation.dart'; import '../utils/message_actions.dart'; import '../utils/singleton.dart'; import 'view_once_frame.dart'; @@ -841,15 +841,11 @@ class _VideoThumbnailState extends State { final controller = VideoPlayerController.file(temp); await controller.initialize(); await controller.setVolume(0); - // The stored dimensions can be the unrotated frame; the container knows. - var rotation = await Mp4Rotation.ofFile(temp); - if (rotation == 0) { - rotation = controller.value.rotationCorrection; - } + // The player already applies the recorded rotation, so this is the size + // the frame really has. It also repairs a message stored with the + // unrotated dimensions. final size = controller.value.size; - if (rotation % 180 != 0) { - widget.onFrame?.call(Size(size.height, size.width)); - } else if (size.width > 0 && size.height > 0) { + if (size.width > 0 && size.height > 0) { widget.onFrame?.call(size); } if (!mounted) { diff --git a/test/fixtures/portrait.mp4 b/test/fixtures/portrait.mp4 deleted file mode 100644 index c3641abb5ffb78861ad58dbdec848dae426f080c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5389 zcmZuV2|Sct_m6}uX?c;XV~LbyW^5^Aj}#%<*D*7g%$R9r>?&Ikg^+9^St2w=$XZfD zDv~|>l6a9VW&7Vzec$_i-~arad(J)EJ@=gR<8dJfg1OTC$apG=2thj_1_g*jdt(qp zvJwJyen9^F^vC!Q@~V5(NiC zs3^lIiby09=Ax*q0#`-@#VL7UpkQoz(m+lLrfsPUEU`EYQ0S7#egvE=4Tgln73Gj{ zq%sh?(`e-53JN|xKJwmpERIA#d&-k2ZVHT3GPhzQ`}L_vGH;ZO(_7{;AKBBGsuD*{HN;0Odf6>!IVk6|%1 zz+f&CQE-p~8tYH;#G#M~Sp)*+il)+>$W#wJnPKrOz(ukX$<>vLqoL%GFq%6Bcu-MF zFan9>fp!NQr#~_Tj7q>`KrVj-aF{1$`wR@8h^8^}zv=6zG)`8jB_~ZsFqOf=5#shu|r= z?R)v)@NVuj7oa1Nah^_YBr?$c5|V+d2hI<~Mj@5qzgZ_D-V=p@!>AaXCl2F9Ln*-- zX;RRPl2UL~ci>LJIQ{Fo3_S&d!cbgcL>Ew3#!!9x|gM!Pe0G7-MyiL)* zC>1pzpwe(;P&qsqGzkm@=pl%Oz6koy=q3~dL2O@e5n+(#*5-Hjj2)?t4v4-3-k&3& z7*VC>;{B07q^8yl z#T{6ri21PUinT^JI-KZ`3XJPG9eChI?G+nr$!xrS-Lu@R7{6DnkDT~sH95serD{nf z4|DHQvzJr>ZhrT!UCXv|9LKLvb(yU*auQc6#s01;%r=f&e`6RPc{#as zYOqG7DW0NhAYZFF6pOj@G`cjcN<8PWZa1Yfm#L6;GgM%7O*!xKhuk-WwUCg6fJzC<^d z14%CRp@L=dB%e#YQgZfQ(GP}VvKe~m153U`x)CD5yds#9SYmWarcB9Jr#1U^H|}bE z{Lukt?)Wd$n;dvwjM}wJf%54-hIF^{vbQb5Am3Qy%vyn@g=4T!Oatx7g=+6H*}HE4 zJyaDf216azE2v_l$*gjh+Vq#i8XNtrRg>AJirvW< z!$0xLjEkq=Ix$4|FF*#hoBh09Dx4C+V!)Hofarf}FmcWzwO&r#-}%87GKTIx>f5Gr z<=_R0-2FGxxy*Q-?m64%^b)Jci#A;ErVJzKa>d3>I@) zhetxvM%*WMBY$S+zdX}Gn>wo{e9PL5+!DjXLiADPr#9=R&6M`~r)3Epl6&ADtQi`r zcV0yQ2$jt8Xy}Q2rN*9~@D%$`-EFKY83i4$sxgfkF+gH7pUh#%q@b5tFtv=x9X30B1kbhUy?gix5p%sol33Y-w||R)jm_3{h+W6gkH5%1q$OS2 zdH&_Pi}spq;>L;Gim{2aAIj}!#?!A|-1#lJN5Nh2`Q3{CW6v)mD`MQ+UAU7K6HVK? z@O}FeF!c#u9D?z!wUylOE*z8aDlN6lLFiWsezz+PY!O@^R_bBes7Al!Sm_QwAYC&q z^4FrCpJGj~T4L(M(K{#i?f*#Um^3STXvCT2PR~(H>NUFWZmMi8F!v?dS-W#dv?#|T zyOmF%tv~aEMcGtg5~WH~r5V-Km6=B&;-boewYWv|zd2nNFkr7h}TQfiMDl@)o5Ew1%!I> z(NN3Gyk$I})sg6W&1-t*N35FGilfv8%qubi4LZHzMW#@5Y9Gt`*Vg8xpC@!|g%Jri zQL4_azNH2)c#^pgPV4}}r;!=QD~s-j|wk`I6CtjYzYd` zX7Y0(PI?U$t(n_CvCa#Szy82x;Jn8AnbT?as%Oq|?By{ZnvXLS{`ysTmh4t^ypcOe zbXq+U9kUa8$?hn3CfDg__Yn8`9lUATW=WJW#gXruL98=ga}%_W>v5a{snm=3-akbcF-TcXe%!ar)sLuke4@#}>7|*|9 z#zpVavK-0^%~cby6OM9$6(g;pvt zIuCyE_Ct?u6#u(a&DhO6w^Lesci~LguHZPiGY-?}z5I5U`~uk*TXj^DhVLFaxdpyf z`?OQU2)bLF`FGUz=0RdV1m+%ij0N^>nX``!`8J!Ed6uR6d52b7XYZl&B;BwbNi=?T zK*ioc#+MT}xR~aHdSJwL?FmArsKboM#Pun$us5miNbRGsrno&5cLh~!l=%7D=hm8Z zl?3Y*?(08|DJqODW)=A6!9Ey2l$`G6&)admub;m*P@>B`R3Xoe%AsjxonzMCfZ)bI z5>NTC%Xz}6z$~O!lI3cVjXK|Zn5nT5XZ>iL{R;Ui|D05`!XYfq{M?P1hT5nSOh9G! z9Rc=e!B4xDUfTtpd=EZlpfB1fI_hHaGGTkSHVZ7E3z07A!f$P%(*kC-4e=tA+1Soz z^wW2q>ShN+7VE#!q7uPJVw6{!91zG&a9*(TrFfe4JTC_vz`aOesFfeaSpzbK7fmr*%dA5XJh^J^2PW^fjHRL)s-1v_nk1poP4Z&-Zl?8mxZ)7+9 zId8LY&+_!mFpb@3vtp~N`}XR?L;FL{5S@>7+AKAR&5L@F3)|^=Mk(^kvQ@#nj5~d; zp>#k*)L?OJcWF-(E*p}5<#6ErQttG3J4;Q~65lt`3SuSaCGl-rWA{vN_deUWd3N7w zZ^MWv!r#1-E5=u`xc9aCtu5DQO+S=OF8VbNHkfv3%S^p$%Zv@SSat*UB(@v+f|IQ(-1X=q*U>*7yKn+ZRjLH%H>H}f+e?Uv`KQ1 z&-Yu^>uV!mOkB-3=X$EgS@)Jbstj6f<4%Zo6t0L^jP}+WyHb0aoZ&TpD0DFxzAvB_({*Grpm^lAQKcnQ3Ad&Ze_N%nwF|EMb{7n8j`2&Ru-Z{-iwhQbVKOC$Y zhzcw}o~TE&IgY8fQ(rXkM*+KA0Ql>|Ge`VxLuKUO5;Co7e@@Z zLx$KK>Fw`}PX#<-3%PaYXNu~1`U70TrbO#2$7)4WRP}S7v=up<&^3Cn$&~Yy1b_09 z{@g-w;!U^I#6sJB3Hxk^D!e9DYB;OYT9zevU#R(q+{uL;fASPoI@uiEa(nC7*m{mT zp&IXacOv|}LDlF{!NZ0Nuvgg`<>#BCWm=3y!t>83^fVb;@`STVeGt&uxRv`uPv^o@ zACPdRcFLDu2@C(4Bzv`e>(DM8iKZ2ndd@|bnikBHVAjUis{sK7lI6#%r=m_AOWq%g z<^O(|I-g%<9vH5{Wi@>Efl9*>dSY6oal8s9Y4K)G0{(>&nmWq%uC?K^77E7Kg!*l#Ywp~&tp?d=Xs5FO%3g45GcSx;5Z}II9b%JL z^e|oLBNmpYf15xP>!lMGWW_tIEH8}jJA=8C#d+e*ZTZjf9ncdiE_Jw&fO%eV14mz?>mo!fO)pLQ9}BV4~aApWiPqd`2xXAtR)qbH~Eb zT1{96w8{{jEC*ZL3T|7>=E=bR$&U%3a+*wZ|=&t(3G)$eGGv;P;i7=LaV@Ly*# zL|Tj`6QD1Hfh2KQ8Wm6>9Dxd+khTGMG2-s}?Z4v?5sOCy0gQF#{gx(KV$xqWP)p-0xSa=z{Fz&>{S%y5%LH)5=Owg zFy66#>3*&J+r?A?R=P}Bh+}IQI_L&yVUJGOW&534U^EydWnpf(jtgRfSly>bTg0Dl ztTKMvLwm_+Dj85l9t`9G4=BHj9N7&)421ZpwCx4}cH4#nf_5@^9&j&4V;JzqACCFA zEyD;51ZdK>p6fT=_GS4k7XmRb37^OAm>O2>>$7yU~&x5Jpii! z4gh=%uomEbfFL&v2~Y+w;=%!.filled(64, 0)); - addTearDown(() => file.deleteSync()); - - expect(await Mp4Rotation.ofFile(file), 0); - }); -} From 612621dc96e50199bfb9fb3bf36d81917e173474 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 02:00:06 +0100 Subject: [PATCH 156/181] fix(app): colour an opened view-once bubble by its owner --- lib/widgets/chat_bubble.dart | 43 ++++++++++++++++++-------------- lib/widgets/media_bubble.dart | 1 + lib/widgets/view_once_frame.dart | 6 ++++- 3 files changed, 30 insertions(+), 20 deletions(-) diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 0bf5519..93a6e76 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -173,21 +173,42 @@ class _ChatBubbleState extends State { ); } + /// Filled colour of this bubble: the chat accent on our side, a neutral tone + /// on theirs. + Color bubbleBackground() { + if (widget.message.isMe) { + return widget.accentColor; + } + // The other side stays neutral, only the tone follows the brightness. + if (Theme.of(context).brightness == Brightness.dark) { + return Theme.of(context).colorScheme.surfaceContainerHigh; + } + return Theme.of(context).colorScheme.surfaceDim; + } + + Color bubbleTextColor() { + return bubbleBackground().computeLuminance() > 0.5 + ? Colors.black + : Colors.white; + } + /// A view-once location: one reveal, then a tombstone. The reveal is the /// platform map app, and it spends the single view on the way out. Widget _viewOnceMessage(BuildContext context, LocationRef? location) { final opened = widget.message.openedAt != null; final mine = widget.message.isMe && widget.user.id != Singleton().profile.user.id; - final bubbleColor = widget.accentColor; - final textColor = - bubbleColor.computeLuminance() > 0.5 ? Colors.black : Colors.white; + // Same owner colour as a text bubble (accent for mine, neutral for theirs), + // so an opened tombstone never reads as the other side's message. + final bubbleColor = bubbleBackground(); + final textColor = bubbleTextColor(); return ViewOnceFrame( label: mine ? (opened ? 'viewOnceOpenedByPeer'.tr() : 'viewOnceSent'.tr()) : (opened ? 'viewOnceOpened'.tr() : 'viewOnceOpen'.tr()), bubbleColor: bubbleColor, textColor: textColor, + dimmed: opened, onTap: mine || opened || location == null ? null : () async { @@ -305,22 +326,6 @@ class _ChatBubbleState extends State { } } - Color bubbleBackground() { - if (widget.message.isMe) { - return widget.accentColor; - } - // The other side stays neutral, only the tone follows the brightness. - if (Theme.of(context).brightness == Brightness.dark) { - return Theme.of(context).colorScheme.surfaceContainerHigh; - } - return Theme.of(context).colorScheme.surfaceDim; - } - - Color bubbleTextColor() { - final backgroundColor = bubbleBackground(); - double luminance = backgroundColor.computeLuminance(); - return luminance > 0.5 ? Colors.black : Colors.white; - } /// Gesture handling: select in selection mode, otherwise tooltip + reply. void onTap() { diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index f14023b..6cf9abe 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -170,6 +170,7 @@ class _MediaBubbleState extends State { label: 'viewOnceOpened'.tr(), bubbleColor: widget.bubbleColor, textColor: widget.textColor, + dimmed: true, ); } return ViewOnceFrame( diff --git a/lib/widgets/view_once_frame.dart b/lib/widgets/view_once_frame.dart index 55a0f8c..06ae50c 100644 --- a/lib/widgets/view_once_frame.dart +++ b/lib/widgets/view_once_frame.dart @@ -9,6 +9,7 @@ class ViewOnceFrame extends StatelessWidget { required this.bubbleColor, required this.textColor, this.onTap, + this.dimmed = false, super.key, }); @@ -17,6 +18,9 @@ class ViewOnceFrame extends StatelessWidget { final Color textColor; final VoidCallback? onTap; + /// Already opened: the box is drawn fainter, the hue still marks the owner. + final bool dimmed; + @override Widget build(BuildContext context) { return InkWell( @@ -26,7 +30,7 @@ class ViewOnceFrame extends StatelessWidget { width: 200, padding: const EdgeInsets.all(16), decoration: BoxDecoration( - color: bubbleColor, + color: dimmed ? bubbleColor.withValues(alpha: 0.55) : bubbleColor, borderRadius: BorderRadius.circular(10), ), child: Column( From 6bdc40b279a76688e10bf81c9039ff30b6f0ab95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 02:04:56 +0100 Subject: [PATCH 157/181] fix(app): carry the chat colour into everything opened from chat info --- lib/pages/chat_info_page.dart | 24 ++++++++++++++++-------- lib/utils/dialog_utils.dart | 11 +++++++---- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index b2cb5aa..94ee029 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -78,7 +78,7 @@ class _ChatInfoPageState extends State { final proposal = _disappearingProposal; final chosen = await showDialog( context: context, - builder: (ctx) => SimpleDialog( + builder: (ctx) => _chatThemed(SimpleDialog( title: Text('disappearingSettings'.tr()), children: [ Padding( @@ -108,7 +108,7 @@ class _ChatInfoPageState extends State { onTap: () => Navigator.pop(ctx, option), ), ], - ), + )), ); if (chosen == null) { return; @@ -192,7 +192,7 @@ class _ChatInfoPageState extends State { await showModalBottomSheet( context: context, showDragHandle: true, - builder: (ctx) => SafeArea( + builder: (ctx) => _chatThemed(SafeArea( child: ListView( shrinkWrap: true, children: [ @@ -229,10 +229,17 @@ class _ChatInfoPageState extends State { ), ], ), - ), + )), ); } + /// Routes, sheets and dialogs opened from this page are pushed on the + /// Navigator, above the Theme this page is wrapped in, so each of them has to + /// carry the chat theme itself or it falls back to the app theme. + ThemeData get _chatTheme => ThemeUtils.chatTheme(context, _chatThemeColor); + + Widget _chatThemed(Widget child) => Theme(data: _chatTheme, child: child); + Future _loadChatTheme() async { Color? color = await CacheUtils.getChatTheme(widget.userId); if (mounted) { @@ -284,6 +291,7 @@ class _ChatInfoPageState extends State { initialDate: now, firstDate: DateTime(now.year - 10), lastDate: now, + builder: (ctx, child) => _chatThemed(child ?? const SizedBox.shrink()), ); if (picked != null && mounted) { Navigator.pop(context, picked); @@ -298,7 +306,7 @@ class _ChatInfoPageState extends State { return; } final picked = await Navigator.of(context) - .push(stepRoute(MessageSearchPage(user))); + .push(stepRoute(_chatThemed(MessageSearchPage(user)))); if (picked != null && mounted) { Navigator.pop(context, picked); } @@ -350,8 +358,8 @@ class _ChatInfoPageState extends State { icon: Icons.storage, label: 'storageTitle'.tr(), onPressed: () async { - await Navigator.push( - context, stepRoute(const StoragePage())); + await Navigator.push(context, + stepRoute(_chatThemed(const StoragePage()))); await _loadMediaUsage(); }, extra: Padding( @@ -444,7 +452,7 @@ class _ChatInfoPageState extends State { fadeRoute(const HomePage()), (route) => false, ); - }); + }, theme: _chatTheme); }, ), ], diff --git a/lib/utils/dialog_utils.dart b/lib/utils/dialog_utils.dart index 5e99f12..1aa7bd3 100644 --- a/lib/utils/dialog_utils.dart +++ b/lib/utils/dialog_utils.dart @@ -385,13 +385,15 @@ class DialogUtils { }); } - /// Returns yes/no dialog + /// Returns yes/no dialog. [theme] carries the chat colour when the dialog is + /// opened from a chat, whose Theme does not reach the Navigator's overlay. static Future yesNoDialog( - BuildContext context, String title, String content, Function onYes) { + BuildContext context, String title, String content, Function onYes, + {ThemeData? theme}) { return showDialog( context: context, - builder: (BuildContext context) { - return BackdropFilter( + builder: (dialogContext) { + final dialog = BackdropFilter( filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10), child: AlertDialog( title: Text(title), @@ -436,6 +438,7 @@ class DialogUtils { ], ), ); + return theme == null ? dialog : Theme(data: theme, child: dialog); }, ); } From a90e8e1c09a80ce9bf5480450c02ed05a0121fa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 02:15:34 +0100 Subject: [PATCH 158/181] fix(app): start a round note from the composer camera button --- lib/pages/chat_page.dart | 64 +++++++++++++++++++++----------------- lib/utils/chat_sender.dart | 3 +- 2 files changed, 37 insertions(+), 30 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 22ddecb..c9b811d 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:io'; import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:camera/camera.dart' show CameraPreview; @@ -1054,6 +1055,7 @@ class _ChatPageState extends State { return; } _noteStarting = true; + FocusScope.of(context).unfocus(); final recorder = RoundVideoRecorder(); try { if (!await recorder.start()) { @@ -1499,33 +1501,6 @@ class _ChatPageState extends State { tooltip: 'attachButton'.tr(), onPressed: _isSending ? null : _showAttachSheet, ), - // Tap opens the camera, holding it records a round video note - // and releasing sends it. Only the long press is registered - // here, so a tap stays the plain button. - suffixIcon: GestureDetector( - onLongPressStart: (_) => _startRoundNote(), - onLongPressMoveUpdate: (details) { - if (!_isRecordingNote) { - return; - } - final cancel = details.localOffsetFromOrigin.dx < -80; - if (cancel != _noteCancel) { - setState(() => _noteCancel = cancel); - } - }, - onLongPressEnd: (_) { - if (_isRecordingNote) { - _stopRoundNote(); - } else { - _noteStopRequested = true; - } - }, - child: IconButton( - icon: const Icon(Icons.photo_camera_outlined), - tooltip: 'attachCamera'.tr(), - onPressed: _isSending ? null : _captureFromCamera, - ), - ), filled: true, fillColor: chatTheme.brightness == Brightness.dark ? chatTheme.colorScheme.surfaceBright @@ -1537,7 +1512,40 @@ class _ChatPageState extends State { ), ), ), - const SizedBox(width: 8), + const SizedBox(width: 4), + // Tap opens the camera, holding it records a round note. It sits + // beside the field, not inside it: a long press in the field belongs + // to text selection and would swallow the press. + GestureDetector( + onLongPressStart: (_) => _startRoundNote(), + onLongPressMoveUpdate: (details) { + if (!_isRecordingNote) { + return; + } + final cancel = details.localOffsetFromOrigin.dx < -80; + if (cancel != _noteCancel) { + setState(() => _noteCancel = cancel); + } + }, + onLongPressEnd: (_) { + if (_isRecordingNote) { + _stopRoundNote(); + } else { + _noteStopRequested = true; + } + }, + // No tooltip on purpose: a tooltip's long press wins the gesture + // arena and the round-note press would only show the label. + child: Semantics( + button: true, + label: 'attachCamera'.tr(), + child: IconButton( + icon: const Icon(Icons.photo_camera_outlined), + onPressed: _isSending ? null : _captureFromCamera, + ), + ), + ), + const SizedBox(width: 4), ValueListenableBuilder( valueListenable: _controllerMessage, builder: (context, value, _) { diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index 7ddd8f3..91f1a9c 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -137,8 +137,7 @@ class ChatSender { durationMs: durationMs, fileName: fileName, waveform: waveform, - // Only a single video is ever a note; the stored reference says so. - videoNote: message.mediaReferences?.first.videoNote ?? false); + videoNote: videoNote); if (reference == null) { return await _fail(recipient.id, message); } From 19eeaea89f6d4d848ee6550d5b888232a9cbcd2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 02:25:44 +0100 Subject: [PATCH 159/181] fix(app): keep the camera button in the composer and start notes from it --- lib/pages/chat_page.dart | 96 ++++++++++++++++++++++++++-------------- 1 file changed, 62 insertions(+), 34 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index c9b811d..9f46139 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -98,6 +98,12 @@ class _ChatPageState extends State { bool _noteCancel = false; Duration _noteElapsed = Duration.zero; Timer? _noteTimer; + + /// Press that may turn into a round note. A raw [Listener] is used instead of + /// a long-press recognizer: inside a TextField the field's own recognizer wins + /// the gesture arena and the press would never reach us. + Timer? _noteHoldTimer; + Offset? _notePressOrigin; bool _cancelRecording = false; MediaRecorderController? _recorderController; Duration _recordDuration = Duration.zero; @@ -1048,6 +1054,43 @@ class _ChatPageState extends State { type == MediaType.video ? MediaType.video : MediaType.image); } + /// A press on the camera button starts the hold timer; a tap still opens the + /// camera through the button itself. + void _onCameraPressStart(PointerDownEvent event) { + // The press is inside the field's tap region, which would focus it and + // raise the keyboard over the note preview. + FocusScope.of(context).unfocus(); + _notePressOrigin = event.position; + _noteHoldTimer?.cancel(); + _noteHoldTimer = Timer(const Duration(milliseconds: 400), () { + _noteHoldTimer = null; + _startRoundNote(); + }); + } + + void _onCameraPressMove(PointerMoveEvent event) { + final origin = _notePressOrigin; + if (origin == null || !_isRecordingNote) { + return; + } + final cancel = event.position.dx - origin.dx < -80; + if (cancel != _noteCancel) { + setState(() => _noteCancel = cancel); + } + } + + void _onCameraPressEnd(PointerEvent event) { + _noteHoldTimer?.cancel(); + _noteHoldTimer = null; + _notePressOrigin = null; + if (_isRecordingNote) { + _stopRoundNote(); + } else if (_noteStarting) { + // Released while the camera was still opening. + _noteStopRequested = true; + } + } + /// Starts a round video note from the composer. It runs only while the finger /// is down; releasing sends it, sliding left throws it away. Future _startRoundNote() async { @@ -1501,6 +1544,23 @@ class _ChatPageState extends State { tooltip: 'attachButton'.tr(), onPressed: _isSending ? null : _showAttachSheet, ), + // Tap opens the camera, holding it records a round note. No + // tooltip: its long press would win the gesture arena and the + // note would never start. + suffixIcon: Listener( + onPointerDown: _onCameraPressStart, + onPointerMove: _onCameraPressMove, + onPointerUp: _onCameraPressEnd, + onPointerCancel: _onCameraPressEnd, + child: Semantics( + button: true, + label: 'attachCamera'.tr(), + child: IconButton( + icon: const Icon(Icons.photo_camera_outlined), + onPressed: _isSending ? null : _captureFromCamera, + ), + ), + ), filled: true, fillColor: chatTheme.brightness == Brightness.dark ? chatTheme.colorScheme.surfaceBright @@ -1512,40 +1572,7 @@ class _ChatPageState extends State { ), ), ), - const SizedBox(width: 4), - // Tap opens the camera, holding it records a round note. It sits - // beside the field, not inside it: a long press in the field belongs - // to text selection and would swallow the press. - GestureDetector( - onLongPressStart: (_) => _startRoundNote(), - onLongPressMoveUpdate: (details) { - if (!_isRecordingNote) { - return; - } - final cancel = details.localOffsetFromOrigin.dx < -80; - if (cancel != _noteCancel) { - setState(() => _noteCancel = cancel); - } - }, - onLongPressEnd: (_) { - if (_isRecordingNote) { - _stopRoundNote(); - } else { - _noteStopRequested = true; - } - }, - // No tooltip on purpose: a tooltip's long press wins the gesture - // arena and the round-note press would only show the label. - child: Semantics( - button: true, - label: 'attachCamera'.tr(), - child: IconButton( - icon: const Icon(Icons.photo_camera_outlined), - onPressed: _isSending ? null : _captureFromCamera, - ), - ), - ), - const SizedBox(width: 4), + const SizedBox(width: 8), ValueListenableBuilder( valueListenable: _controllerMessage, builder: (context, value, _) { @@ -1993,6 +2020,7 @@ class _ChatPageState extends State { @override void dispose() { + _noteHoldTimer?.cancel(); MessageNotifier().removeListener(_onMessagesChanged); PresenceNotifier.instance.removeListener(_onPresenceChanged); _scrollController.removeListener(_onScroll); From 42e1ad8496af9e598e24ec5a9a8b715d65c74a0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 02:27:48 +0100 Subject: [PATCH 160/181] fix(app): keep an opened view-once frame opaque --- lib/widgets/view_once_frame.dart | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/widgets/view_once_frame.dart b/lib/widgets/view_once_frame.dart index 06ae50c..c83675e 100644 --- a/lib/widgets/view_once_frame.dart +++ b/lib/widgets/view_once_frame.dart @@ -23,6 +23,12 @@ class ViewOnceFrame extends StatelessWidget { @override Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + // An opened frame is a little duller, never translucent: the peer's colour + // is already close to the chat background and alpha made it look invisible. + final fill = dimmed + ? Color.alphaBlend(scheme.surface.withValues(alpha: 0.35), bubbleColor) + : bubbleColor; return InkWell( onTap: onTap, borderRadius: BorderRadius.circular(10), @@ -30,7 +36,7 @@ class ViewOnceFrame extends StatelessWidget { width: 200, padding: const EdgeInsets.all(16), decoration: BoxDecoration( - color: dimmed ? bubbleColor.withValues(alpha: 0.55) : bubbleColor, + color: fill, borderRadius: BorderRadius.circular(10), ), child: Column( From a146c0c00a94cd299c015f82d44c148cb5327286 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 02:31:44 +0100 Subject: [PATCH 161/181] fix(app): draw a round note as a circle while it is still sending --- lib/models/private_message.dart | 22 ++++++++++++++++++ lib/utils/chat_sender.dart | 8 +++++++ lib/widgets/media_bubble.dart | 10 +------- test/video_note_test.dart | 41 +++++++++++++++++++++++++++++++++ 4 files changed, 72 insertions(+), 9 deletions(-) create mode 100644 test/video_note_test.dart diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index 29b4698..cd5555d 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -336,6 +336,28 @@ class PrivateMessage extends HiveObject { } } + /// Whether this video was recorded as a round note. + /// + /// The flag rides in the media reference, which only exists once the upload + /// finished; while a note is still sending, the message carries a bare marker + /// written when the send started. + bool get isVideoNote { + final references = mediaReferences; + if (references != null && references.isNotEmpty) { + return references.first.videoNote; + } + final raw = mediaRefJson; + if (raw == null || raw.isEmpty) { + return false; + } + try { + final json = jsonDecode(raw); + return json is Map && json['videoNote'] == true; + } catch (_) { + return false; + } + } + /// Whether the sender edited the text after sending it. bool get isEdited => editedAt != null; diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index 91f1a9c..02c5e23 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -127,6 +127,14 @@ class ChatSender { ); try { await _persist(recipient, [message]); + if (videoNote) { + // The reference only exists after the upload, but the bubble has to know + // it is a round note from the first frame: mark it now, the finished + // reference overwrites this below. + await CacheUtils.updateStoredMessage(recipient.id, message, (stored) { + stored.mediaRefJson = jsonEncode({'videoNote': true}); + }); + } if (!await _ensureConnected()) { return await _fail(recipient.id, message); } diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 6cf9abe..3d4dfe1 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -326,7 +326,7 @@ class _MediaBubbleState extends State { } // A round video note keeps its circle whatever state it is in. - if (type == MediaType.video && _isVideoNote) { + if (type == MediaType.video && widget.message.isVideoNote) { return _withCaption( ClipOval( child: SizedBox( @@ -437,14 +437,6 @@ class _MediaBubbleState extends State { ); } - /// Whether this video was recorded as a round video note. - bool get _isVideoNote { - final references = widget.message.mediaReferences; - return references != null && - references.isNotEmpty && - references.first.videoNote; - } - /// A pending attachment waits for the network setting; the icon is also the /// way to fetch it now. Widget _pendingMedia() { diff --git a/test/video_note_test.dart b/test/video_note_test.dart new file mode 100644 index 0000000..028e38c --- /dev/null +++ b/test/video_note_test.dart @@ -0,0 +1,41 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper_websocket_client_dart/models/media_reference.dart'; +import 'package:whisper_websocket_client_dart/models/media_type.dart'; + +void main() { + PrivateMessage video({String? referenceJson}) => PrivateMessage( + '1', + '', + DateTime(2026, 11, 23), + DateTime(2026, 11, 23), + true, + mediaTypeStr: 'video', + mediaRefJson: referenceJson, + ); + + String referenceJson({required bool note}) => jsonEncode(MediaReference( + 'id', + Uint8List(32), + MediaType.video, + 1024, + videoNote: note, + ).toJson()); + + test('a round note is recognised from its finished reference', () { + expect(video(referenceJson: referenceJson(note: true)).isVideoNote, isTrue); + }); + + test('a round note still sending is recognised from its marker', () { + expect(video(referenceJson: '{"videoNote":true}').isVideoNote, isTrue); + }); + + test('a plain video is not a round note', () { + expect( + video(referenceJson: referenceJson(note: false)).isVideoNote, isFalse); + expect(video().isVideoNote, isFalse); + }); +} From 9cb8804df08f9ac7ed3b974db3fe51e5cec371e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 02:35:23 +0100 Subject: [PATCH 162/181] fix(app): fold the voice waveform into fewer, visible bars --- lib/widgets/voice_player.dart | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/lib/widgets/voice_player.dart b/lib/widgets/voice_player.dart index 765956b..c9a8224 100644 --- a/lib/widgets/voice_player.dart +++ b/lib/widgets/voice_player.dart @@ -339,9 +339,34 @@ class _WaveformPainter extends CustomPainter { final double progress; final Color color; + /// Bars drawn at most. A long recording has one sample per 100 ms, which + /// would be sub-pixel wide: the samples are folded into this many peaks. + static const int maxBars = 32; + + /// Folds [samples] into at most [maxBars] peaks, so a bar is always visible. + List _bars() { + if (samples.length <= maxBars) { + return samples; + } + final bucket = samples.length / maxBars; + return List.generate(maxBars, (index) { + final start = (index * bucket).floor(); + final end = + ((index + 1) * bucket).ceil().clamp(start + 1, samples.length); + var peak = 0; + for (var i = start; i < end; i++) { + if (samples[i] > peak) { + peak = samples[i]; + } + } + return peak; + }); + } + @override void paint(Canvas canvas, Size size) { - if (samples.isEmpty) { + final bars = _bars(); + if (bars.isEmpty) { final paint = Paint() ..color = color.withValues(alpha: 0.3) ..strokeWidth = 2 @@ -350,12 +375,12 @@ class _WaveformPainter extends CustomPainter { Offset(size.width, size.height / 2), paint); return; } - final step = size.width / samples.length; + final step = size.width / bars.length; final barWidth = (step * 0.6).clamp(1.0, 4.0); final played = Paint()..color = color; final rest = Paint()..color = color.withValues(alpha: 0.3); - for (var i = 0; i < samples.length; i++) { - final height = (samples[i] / 100 * size.height).clamp(2.0, size.height); + for (var i = 0; i < bars.length; i++) { + final height = (bars[i] / 100 * size.height).clamp(2.0, size.height); final rect = RRect.fromRectAndRadius( Rect.fromCenter( center: Offset(i * step + step / 2, size.height / 2), @@ -364,7 +389,7 @@ class _WaveformPainter extends CustomPainter { ), const Radius.circular(1), ); - canvas.drawRRect(rect, i / samples.length <= progress ? played : rest); + canvas.drawRRect(rect, i / bars.length <= progress ? played : rest); } } From 55526479ce74676be336635584f0ba934e610c7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 02:41:00 +0100 Subject: [PATCH 163/181] fix(app): stop the voice chain at our own message --- assets/translations/cs.json | 4 ++-- lib/utils/voice_autoplay.dart | 18 +++++++++++++++--- test/voice_autoplay_test.dart | 26 ++++++++++++++++++++++++-- 3 files changed, 41 insertions(+), 7 deletions(-) diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 8c22efe..2dec36b 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -301,8 +301,8 @@ "storageDaysSuffix": "dní", "storageNever": "Nikdy", "storageSingleDelivery": "Média jsou jednorázová: co se tady smaže, už nelze znovu stáhnout.", - "storageClearCache": "Vymazat keš", - "storageCacheCleared": "Keš vymazána", + "storageClearCache": "Vymazat mezipaměť", + "storageCacheCleared": "Mezipaměť vymazána", "storagePurged": "Uvolněno", "storageEmpty": "Zatím žádná média", "recordingLocked": "Nahrávání zamčeno, zastavte ho tlačítkem", diff --git a/lib/utils/voice_autoplay.dart b/lib/utils/voice_autoplay.dart index 0ad3617..dd93bcf 100644 --- a/lib/utils/voice_autoplay.dart +++ b/lib/utils/voice_autoplay.dart @@ -15,8 +15,12 @@ class VoiceAutoplay { static final ValueNotifier request = ValueNotifier(null); /// Asks the next voice message after [afterSentAt] in [conversationId] to - /// play. Stops at the end of the chat, and skips a voice message that is not - /// on this device: it could not play, so skipping is honest. + /// play. + /// + /// The chain is for listening to the other side: it stops at our own voice + /// message instead of playing it back. It also stops at the end of the chat, + /// and skips a message that is not on this device, since that one could not + /// play anyway. /// /// shortcut: a player only exists while its bubble is built, so a request for /// an off-screen message is dropped; upgrade by hoisting playback into a @@ -28,7 +32,15 @@ class VoiceAutoplay { if (!message.sentAt.isAfter(afterSentAt)) { continue; } - if (message.mediaType != MediaType.voice || message.localPath == null) { + if (message.mediaType != MediaType.voice) { + continue; + } + // Our own message ends the chain: playback continues only into what the + // other side said. + if (message.isMe) { + return; + } + if (message.localPath == null) { continue; } request.value = CacheUtils.messageKey(conversationId, message.sentAt); diff --git a/test/voice_autoplay_test.dart b/test/voice_autoplay_test.dart index 54b226d..411bd2f 100644 --- a/test/voice_autoplay_test.dart +++ b/test/voice_autoplay_test.dart @@ -3,6 +3,9 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; import 'package:whisper/models/private_message.dart'; +import 'package:whisper/models/profile.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/singleton.dart'; import 'package:whisper/utils/cache_utils.dart'; import 'package:whisper/utils/voice_autoplay.dart'; @@ -13,6 +16,9 @@ void main() { dir = Directory.systemTemp.createTempSync('whisper_voice_autoplay_test'); Hive.init(dir.path); Hive.registerAdapter(PrivateMessageAdapter()); + // isMe compares against the signed-in user. + Singleton().profile = + Profile('', User('me', 'me', '', false), '', '', '', '', false); }); setUp(() async { @@ -26,8 +32,9 @@ void main() { dir.deleteSync(recursive: true); }); - PrivateMessage voice(DateTime sentAt, {String? path = '/tmp/voice'}) => - PrivateMessage('1', '', sentAt, sentAt, true, + PrivateMessage voice(DateTime sentAt, + {String? path = '/tmp/voice', String sender = 'peer'}) => + PrivateMessage(sender, '', sentAt, sentAt, true, mediaTypeStr: 'voice', localPath: path, durationMs: 1000); test('the next voice message in the chat is requested', () async { @@ -68,4 +75,19 @@ void main() { expect(VoiceAutoplay.request.value, isNull); }); + + test('playback stops instead of playing our own voice message', () async { + final first = DateTime(2026, 1, 1, 10); + final mine = DateTime(2026, 1, 1, 10, 1); + final later = DateTime(2026, 1, 1, 10, 2); + await CacheUtils.addPrivateMessages('1', [ + voice(first), + voice(mine, sender: 'me'), + voice(later), + ]); + + await VoiceAutoplay.next('1', first); + + expect(VoiceAutoplay.request.value, isNull); + }); } From 87cacf05152b3988f6c1956df6305c15e66c22ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 02:54:15 +0100 Subject: [PATCH 164/181] fix(app): keep the keyboard down when a chat sheet or camera closes --- lib/pages/chat_page.dart | 176 ++++++++++++++++++++++++--------------- 1 file changed, 107 insertions(+), 69 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 9f46139..9e1e76f 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -23,6 +23,7 @@ import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; import '../utils/presence.dart'; import '../utils/round_video_recorder.dart'; +import '../utils/sticker_store.dart'; import '../utils/singleton.dart'; import '../utils/text_envelope.dart'; import '../utils/utils.dart' as utils; @@ -510,17 +511,35 @@ class _ChatPageState extends State { } } + /// Runs [open] with the composer unfocused and unfocuses again afterwards. + /// + /// A sheet or a page pushed over the chat hands the focus (and with it the + /// keyboard) back to the field when it closes; without this the keyboard pops + /// up on its own after every attachment sheet or message action. + Future _withoutComposerFocus(Future Function() open) async { + FocusManager.instance.primaryFocus?.unfocus(); + await open(); + if (!mounted) { + return; + } + FocusManager.instance.primaryFocus?.unfocus(); + await WidgetsBinding.instance.endOfFrame; + if (mounted) { + FocusScope.of(context).unfocus(); + } + } + /// Opens the long-press sheet for one message. The pin state of the sheet is /// the one this device knows, so the entry reads "unpin" when it applies. - void _openMessageActions(PrivateMessage message) { + Future _openMessageActions(PrivateMessage message) { final id = message.id; - MessageActions.showSheet( - context, - message, - widget.user.id, - pinned: id != null && _pins.containsKey(id), - onSelect: () => _toggleSelected(message), - ); + return _withoutComposerFocus(() => MessageActions.showSheet( + context, + message, + widget.user.id, + pinned: id != null && _pins.containsKey(id), + onSelect: () => _toggleSelected(message), + )); } /// Pinned messages this device holds, newest pin first: the strip walks them. @@ -1030,26 +1049,34 @@ class _ChatPageState extends State { /// Opens the sticker collection and sends the picked one as it is: a sticker /// travels as its own media type, so the recipient draws it without a bubble. Future _pickSticker() async { - final sticker = await StickerSheet.show(context); - if (sticker == null) { + Sticker? sticker; + await _withoutComposerFocus(() async { + sticker = await StickerSheet.show(context); + }); + final picked = sticker; + if (picked == null) { return; } - final bytes = await MediaUtils.decryptAtRest(sticker.path); + final bytes = await MediaUtils.decryptAtRest(picked.path); final sent = await ChatSender.sendMedia( widget.user, MediaType.sticker, bytes, - fileName: MediaUtils.baseName(sticker.path)); + fileName: MediaUtils.baseName(picked.path)); _afterSend(sent, ''); } /// Opens the in-app camera. What comes back is a photo or a video, and it /// goes through the same confirm sheet as a gallery pick. Future _captureFromCamera() async { - final file = await CameraPage.open(context); - if (file == null) { + File? file; + await _withoutComposerFocus(() async { + file = await CameraPage.open(context); + }); + final captured = file; + if (captured == null) { return; } - final type = MediaUtils.detectType(file.path); - await _pickAndSend(() async => [file], + final type = MediaUtils.detectType(captured.path); + await _pickAndSend(() async => [captured], forcedType: type == MediaType.video ? MediaType.video : MediaType.image); } @@ -1120,6 +1147,13 @@ class _ChatPageState extends State { _noteCancel = false; _noteElapsed = Duration.zero; }); + // The press lands inside the field's tap region, which can hand the focus + // (and the keyboard) back once the preview is on screen. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + FocusScope.of(context).unfocus(); + } + }); _noteTimer = Timer.periodic(const Duration(seconds: 1), (_) { if (!mounted) { return; @@ -1155,6 +1189,9 @@ class _ChatPageState extends State { return; } final file = await recorder.stop(); + if (mounted) { + FocusScope.of(context).unfocus(); + } if (file == null) { return; } @@ -1346,58 +1383,59 @@ class _ChatPageState extends State { /// Show the attachment options bottom sheet. void _showAttachSheet() { - showModalBottomSheet( - context: context, - showDragHandle: true, - builder: (ctx) { - return SafeArea( - child: Wrap( - children: [ - ListTile( - leading: const Icon(Icons.photo_library), - title: Text('attachGallery'.tr()), - onTap: () { - Navigator.pop(ctx); - _pickAndSend(MediaUtils.pickMultipleMediaFromGallery); - }, - ), - ListTile( - leading: const Icon(Icons.emoji_emotions_outlined), - title: Text('attachStickers'.tr()), - onTap: () { - Navigator.pop(ctx); - _pickSticker(); - }, - ), - ListTile( - leading: const Icon(Icons.insert_drive_file), - title: Text('attachFile'.tr()), - onTap: () { - Navigator.pop(ctx); - _pickAndSend(MediaUtils.pickMultipleFiles, filesOnly: true); - }, - ), - ListTile( - leading: const Icon(Icons.place), - title: Text('attachLocation'.tr()), - onTap: () { - Navigator.pop(ctx); - _sendCurrentLocation(); - }, - ), - ListTile( - leading: const Icon(Icons.my_location), - title: Text('attachLiveLocation'.tr()), - onTap: () { - Navigator.pop(ctx); - _startLiveLocation(); - }, + _withoutComposerFocus(() => showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (ctx) { + return SafeArea( + child: Wrap( + children: [ + ListTile( + leading: const Icon(Icons.photo_library), + title: Text('attachGallery'.tr()), + onTap: () { + Navigator.pop(ctx); + _pickAndSend(MediaUtils.pickMultipleMediaFromGallery); + }, + ), + ListTile( + leading: const Icon(Icons.emoji_emotions_outlined), + title: Text('attachStickers'.tr()), + onTap: () { + Navigator.pop(ctx); + _pickSticker(); + }, + ), + ListTile( + leading: const Icon(Icons.insert_drive_file), + title: Text('attachFile'.tr()), + onTap: () { + Navigator.pop(ctx); + _pickAndSend(MediaUtils.pickMultipleFiles, + filesOnly: true); + }, + ), + ListTile( + leading: const Icon(Icons.place), + title: Text('attachLocation'.tr()), + onTap: () { + Navigator.pop(ctx); + _sendCurrentLocation(); + }, + ), + ListTile( + leading: const Icon(Icons.my_location), + title: Text('attachLiveLocation'.tr()), + onTap: () { + Navigator.pop(ctx); + _startLiveLocation(); + }, + ), + ], ), - ], - ), - ); - }, - ); + ); + }, + )); } /// Start recording a voice message (hold-to-record). @@ -2115,8 +2153,8 @@ class _ChatPageState extends State { IconButton( icon: const Icon(Icons.more_vert), tooltip: 'moreActions'.tr(), - onPressed: () => - MessageActions.showSheet(context, single, widget.user.id), + onPressed: () => _withoutComposerFocus(() => + MessageActions.showSheet(context, single, widget.user.id)), ), ], ); From 6c629153e2f2b373a31057a830c4b2f76c8615c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 03:11:01 +0100 Subject: [PATCH 165/181] feat(app): move the attach and camera buttons beside the composer --- lib/pages/chat_page.dart | 47 ++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 9e1e76f..f232ec8 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1553,6 +1553,11 @@ class _ChatPageState extends State { child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + IconButton( + icon: const Icon(Icons.attach_file), + tooltip: 'attachButton'.tr(), + onPressed: _isSending ? null : _showAttachSheet, + ), Expanded( child: TextField( controller: _controllerMessage, @@ -1575,30 +1580,6 @@ class _ChatPageState extends State { hintText: 'yourMessage'.tr(), isDense: true, contentPadding: const EdgeInsets.symmetric(vertical: 12), - prefixIconConstraints: - const BoxConstraints(minWidth: 44, minHeight: 44), - prefixIcon: IconButton( - icon: const Icon(Icons.attach_file), - tooltip: 'attachButton'.tr(), - onPressed: _isSending ? null : _showAttachSheet, - ), - // Tap opens the camera, holding it records a round note. No - // tooltip: its long press would win the gesture arena and the - // note would never start. - suffixIcon: Listener( - onPointerDown: _onCameraPressStart, - onPointerMove: _onCameraPressMove, - onPointerUp: _onCameraPressEnd, - onPointerCancel: _onCameraPressEnd, - child: Semantics( - button: true, - label: 'attachCamera'.tr(), - child: IconButton( - icon: const Icon(Icons.photo_camera_outlined), - onPressed: _isSending ? null : _captureFromCamera, - ), - ), - ), filled: true, fillColor: chatTheme.brightness == Brightness.dark ? chatTheme.colorScheme.surfaceBright @@ -1610,6 +1591,24 @@ class _ChatPageState extends State { ), ), ), + // Tap opens the camera, holding it records a round note and + // releasing sends it. The raw pointer listener is here because a + // long-press recognizer loses to the keyboard's own gestures when it + // sits inside the field. + Listener( + onPointerDown: _onCameraPressStart, + onPointerMove: _onCameraPressMove, + onPointerUp: _onCameraPressEnd, + onPointerCancel: _onCameraPressEnd, + child: Semantics( + button: true, + label: 'attachCamera'.tr(), + child: IconButton( + icon: const Icon(Icons.photo_camera_outlined), + onPressed: _isSending ? null : _captureFromCamera, + ), + ), + ), const SizedBox(width: 8), ValueListenableBuilder( valueListenable: _controllerMessage, From 72b741a275237c62de990a35f8ad7543e6888361 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 03:14:07 +0100 Subject: [PATCH 166/181] fix(app): compact the composer icons so the field keeps its width --- lib/pages/chat_page.dart | 40 +++++++++++++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index f232ec8..b62592b 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1553,11 +1553,13 @@ class _ChatPageState extends State { child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - IconButton( - icon: const Icon(Icons.attach_file), + _composerIcon( + icon: Icons.attach_file, + label: 'attachButton'.tr(), tooltip: 'attachButton'.tr(), onPressed: _isSending ? null : _showAttachSheet, ), + const SizedBox(width: 2), Expanded( child: TextField( controller: _controllerMessage, @@ -1595,21 +1597,19 @@ class _ChatPageState extends State { // releasing sends it. The raw pointer listener is here because a // long-press recognizer loses to the keyboard's own gestures when it // sits inside the field. + const SizedBox(width: 2), Listener( onPointerDown: _onCameraPressStart, onPointerMove: _onCameraPressMove, onPointerUp: _onCameraPressEnd, onPointerCancel: _onCameraPressEnd, - child: Semantics( - button: true, + child: _composerIcon( + icon: Icons.photo_camera_outlined, label: 'attachCamera'.tr(), - child: IconButton( - icon: const Icon(Icons.photo_camera_outlined), - onPressed: _isSending ? null : _captureFromCamera, - ), + onPressed: _isSending ? null : _captureFromCamera, ), ), - const SizedBox(width: 8), + const SizedBox(width: 6), ValueListenableBuilder( valueListenable: _controllerMessage, builder: (context, value, _) { @@ -1681,6 +1681,28 @@ class _ChatPageState extends State { ); } + /// A plain icon beside the composer. Compact on purpose: three full-width + /// buttons would squeeze the field, which is the part that carries the width. + Widget _composerIcon({ + required IconData icon, + required String label, + required VoidCallback? onPressed, + String? tooltip, + }) { + final button = IconButton( + icon: Icon(icon), + iconSize: 22, + padding: EdgeInsets.zero, + visualDensity: VisualDensity.compact, + constraints: const BoxConstraints.tightFor(width: 40, height: 44), + tooltip: tooltip, + onPressed: onPressed, + ); + return tooltip == null + ? Semantics(button: true, label: label, child: button) + : button; + } + /// The round action beside the composer, filled with the chat's colour. It /// takes the row's height, so it is a circle while the field has one line. Widget _composerButton({Widget? child, VoidCallback? onPressed}) { From ed7f86ff08cb57b751896a55ba47d69a435b3018 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 03:17:50 +0100 Subject: [PATCH 167/181] feat(app): put the attach and camera icons back inside the composer field --- lib/pages/chat_page.dart | 45 ++++++++++++++++++++++------------------ 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index b62592b..e306968 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1553,13 +1553,6 @@ class _ChatPageState extends State { child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - _composerIcon( - icon: Icons.attach_file, - label: 'attachButton'.tr(), - tooltip: 'attachButton'.tr(), - onPressed: _isSending ? null : _showAttachSheet, - ), - const SizedBox(width: 2), Expanded( child: TextField( controller: _controllerMessage, @@ -1582,6 +1575,30 @@ class _ChatPageState extends State { hintText: 'yourMessage'.tr(), isDense: true, contentPadding: const EdgeInsets.symmetric(vertical: 12), + prefixIconConstraints: + const BoxConstraints(minWidth: 40, minHeight: 40), + suffixIconConstraints: + const BoxConstraints(minWidth: 40, minHeight: 40), + prefixIcon: _composerIcon( + icon: Icons.attach_file, + label: 'attachButton'.tr(), + tooltip: 'attachButton'.tr(), + onPressed: _isSending ? null : _showAttachSheet, + ), + // Holding the camera records a round note: the pointer + // listener is used because a long-press recognizer loses to the + // field's own gestures. + suffixIcon: Listener( + onPointerDown: _onCameraPressStart, + onPointerMove: _onCameraPressMove, + onPointerUp: _onCameraPressEnd, + onPointerCancel: _onCameraPressEnd, + child: _composerIcon( + icon: Icons.photo_camera_outlined, + label: 'attachCamera'.tr(), + onPressed: _isSending ? null : _captureFromCamera, + ), + ), filled: true, fillColor: chatTheme.brightness == Brightness.dark ? chatTheme.colorScheme.surfaceBright @@ -1597,19 +1614,7 @@ class _ChatPageState extends State { // releasing sends it. The raw pointer listener is here because a // long-press recognizer loses to the keyboard's own gestures when it // sits inside the field. - const SizedBox(width: 2), - Listener( - onPointerDown: _onCameraPressStart, - onPointerMove: _onCameraPressMove, - onPointerUp: _onCameraPressEnd, - onPointerCancel: _onCameraPressEnd, - child: _composerIcon( - icon: Icons.photo_camera_outlined, - label: 'attachCamera'.tr(), - onPressed: _isSending ? null : _captureFromCamera, - ), - ), - const SizedBox(width: 6), + const SizedBox(width: 8), ValueListenableBuilder( valueListenable: _controllerMessage, builder: (context, value, _) { From f779bac86cb46bfb7744610317d2456346d79045 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 03:21:41 +0100 Subject: [PATCH 168/181] fix(app): keep the composer icons out of the field's tap region --- lib/pages/chat_page.dart | 123 ++++++++++++++++++++++----------------- 1 file changed, 69 insertions(+), 54 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index e306968..3ce29ec 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1554,66 +1554,81 @@ class _ChatPageState extends State { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( - child: TextField( - controller: _controllerMessage, - minLines: 1, - maxLines: 5, - textInputAction: TextInputAction.newline, - onChanged: (value) { - // The receiver clears the indicator on its own; this only - // throttles the frames and stays silent when the user opted - // out. - if (value.trim().isNotEmpty) { - utils.Utils.sendTypingHint(widget.user.id); - } - }, - contentInsertionConfiguration: ContentInsertionConfiguration( - allowedMimeTypes: const ['image/gif', 'image/webp'], - onContentInserted: _onKeyboardContentInserted, - ), - decoration: InputDecoration( - hintText: 'yourMessage'.tr(), - isDense: true, - contentPadding: const EdgeInsets.symmetric(vertical: 12), - prefixIconConstraints: - const BoxConstraints(minWidth: 40, minHeight: 40), - suffixIconConstraints: - const BoxConstraints(minWidth: 40, minHeight: 40), - prefixIcon: _composerIcon( - icon: Icons.attach_file, - label: 'attachButton'.tr(), - tooltip: 'attachButton'.tr(), - onPressed: _isSending ? null : _showAttachSheet, + child: Stack( + children: [ + TextField( + controller: _controllerMessage, + minLines: 1, + maxLines: 5, + textInputAction: TextInputAction.newline, + onChanged: (value) { + // The receiver clears the indicator on its own; this only + // throttles the frames and stays silent when the user opted + // out. + if (value.trim().isNotEmpty) { + utils.Utils.sendTypingHint(widget.user.id); + } + }, + contentInsertionConfiguration: + ContentInsertionConfiguration( + allowedMimeTypes: const ['image/gif', 'image/webp'], + onContentInserted: _onKeyboardContentInserted, + ), + decoration: InputDecoration( + hintText: 'yourMessage'.tr(), + isDense: true, + contentPadding: const EdgeInsets.symmetric(vertical: 12), + // Room for the buttons that float above the field. + prefixIcon: const SizedBox(width: 40), + suffixIcon: const SizedBox(width: 40), + filled: true, + fillColor: chatTheme.brightness == Brightness.dark + ? chatTheme.colorScheme.surfaceBright + : chatTheme.colorScheme.surfaceDim, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(30), + borderSide: BorderSide.none, + ), + ), ), - // Holding the camera records a round note: the pointer - // listener is used because a long-press recognizer loses to the - // field's own gestures. - suffixIcon: Listener( - onPointerDown: _onCameraPressStart, - onPointerMove: _onCameraPressMove, - onPointerUp: _onCameraPressEnd, - onPointerCancel: _onCameraPressEnd, - child: _composerIcon( - icon: Icons.photo_camera_outlined, - label: 'attachCamera'.tr(), - onPressed: _isSending ? null : _captureFromCamera, + // The paperclip and the camera sit above the field, not in + // it: a press inside the TextField's tap region focuses it and + // flashes the keyboard, which must not happen while a round + // note is recording. + Positioned( + left: 0, + top: 0, + bottom: 0, + child: Center( + child: _composerIcon( + icon: Icons.attach_file, + label: 'attachButton'.tr(), + tooltip: 'attachButton'.tr(), + onPressed: _isSending ? null : _showAttachSheet, + ), ), ), - filled: true, - fillColor: chatTheme.brightness == Brightness.dark - ? chatTheme.colorScheme.surfaceBright - : chatTheme.colorScheme.surfaceDim, - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(30), - borderSide: BorderSide.none, + Positioned( + right: 0, + top: 0, + bottom: 0, + child: Center( + child: Listener( + onPointerDown: _onCameraPressStart, + onPointerMove: _onCameraPressMove, + onPointerUp: _onCameraPressEnd, + onPointerCancel: _onCameraPressEnd, + child: _composerIcon( + icon: Icons.photo_camera_outlined, + label: 'attachCamera'.tr(), + onPressed: _isSending ? null : _captureFromCamera, + ), + ), + ), ), - ), + ], ), ), - // Tap opens the camera, holding it records a round note and - // releasing sends it. The raw pointer listener is here because a - // long-press recognizer loses to the keyboard's own gestures when it - // sits inside the field. const SizedBox(width: 8), ValueListenableBuilder( valueListenable: _controllerMessage, From 52adacffe2736e41ff710b7f895a9fb025d6f98e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 03:29:42 +0100 Subject: [PATCH 169/181] fix(app): do not open the camera when a round note is released --- lib/pages/chat_page.dart | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 3ce29ec..9a4c121 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -105,6 +105,10 @@ class _ChatPageState extends State { /// the gesture arena and the press would never reach us. Timer? _noteHoldTimer; Offset? _notePressOrigin; + + /// The current press was held long enough to start a note, so releasing it + /// must not also count as a tap that opens the camera. + bool _noteHoldFired = false; bool _cancelRecording = false; MediaRecorderController? _recorderController; Duration _recordDuration = Duration.zero; @@ -1081,6 +1085,15 @@ class _ChatPageState extends State { type == MediaType.video ? MediaType.video : MediaType.image); } + /// The tap that ends a hold must not open the camera: the button sees the + /// release as a tap as well. + void _openCameraUnlessNote() { + if (_noteHoldFired || _isRecordingNote || _noteStarting) { + return; + } + _captureFromCamera(); + } + /// A press on the camera button starts the hold timer; a tap still opens the /// camera through the button itself. void _onCameraPressStart(PointerDownEvent event) { @@ -1088,9 +1101,11 @@ class _ChatPageState extends State { // raise the keyboard over the note preview. FocusScope.of(context).unfocus(); _notePressOrigin = event.position; + _noteHoldFired = false; _noteHoldTimer?.cancel(); _noteHoldTimer = Timer(const Duration(milliseconds: 400), () { _noteHoldTimer = null; + _noteHoldFired = true; _startRoundNote(); }); } @@ -1621,7 +1636,7 @@ class _ChatPageState extends State { child: _composerIcon( icon: Icons.photo_camera_outlined, label: 'attachCamera'.tr(), - onPressed: _isSending ? null : _captureFromCamera, + onPressed: _isSending ? null : _openCameraUnlessNote, ), ), ), From 03ed94446ec70c5f94f062cbf0c03114b8a725a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 03:32:40 +0100 Subject: [PATCH 170/181] feat(app): show the round note's minute as a filling ring --- lib/pages/chat_page.dart | 62 +++++++++++++++++++++++++++++----------- 1 file changed, 46 insertions(+), 16 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 9a4c121..5bb5eec 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1223,23 +1223,53 @@ class _ChatPageState extends State { child: Column( mainAxisSize: MainAxisSize.min, children: [ - ClipOval( - child: SizedBox( - width: 150, - height: 150, - child: ready - ? FittedBox( - fit: BoxFit.cover, - child: SizedBox( - width: controller.value.previewSize?.height ?? 150, - height: controller.value.previewSize?.width ?? 150, - child: CameraPreview(controller), - ), - ) - : const ColoredBox( - color: Colors.black26, - child: Center(child: CircularProgressIndicator()), + SizedBox( + width: 162, + height: 162, + child: Stack( + alignment: Alignment.center, + children: [ + // A minute of recording fills the ring around the preview, so + // the limit is visible without reading the timer. + SizedBox.expand( + child: TweenAnimationBuilder( + tween: Tween( + begin: 0, + end: (_noteElapsed.inMilliseconds / + RoundVideoRecorder.maxLength.inMilliseconds) + .clamp(0.0, 1.0)), + duration: const Duration(seconds: 1), + builder: (context, value, _) => CircularProgressIndicator( + value: value, + strokeWidth: 4, + strokeCap: StrokeCap.round, + backgroundColor: color.withValues(alpha: 0.25), + valueColor: AlwaysStoppedAnimation(color), ), + ), + ), + ClipOval( + child: SizedBox( + width: 150, + height: 150, + child: ready + ? FittedBox( + fit: BoxFit.cover, + child: SizedBox( + width: + controller.value.previewSize?.height ?? 150, + height: + controller.value.previewSize?.width ?? 150, + child: CameraPreview(controller), + ), + ) + : const ColoredBox( + color: Colors.black26, + child: Center(child: CircularProgressIndicator()), + ), + ), + ), + ], ), ), const SizedBox(height: 4), From e09d2db4a7232f3da3bcb308a19086e3e65707ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 03:37:41 +0100 Subject: [PATCH 171/181] feat(app): play a round note inline with a progress ring and its time --- lib/widgets/media_bubble.dart | 18 ++- lib/widgets/round_video_note.dart | 225 ++++++++++++++++++++++++++++++ 2 files changed, 237 insertions(+), 6 deletions(-) create mode 100644 lib/widgets/round_video_note.dart diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 3d4dfe1..e7cc5f1 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -16,6 +16,7 @@ import '../utils/media_utils.dart'; import '../utils/message_actions.dart'; import '../utils/singleton.dart'; import 'view_once_frame.dart'; +import 'round_video_note.dart'; import 'voice_player.dart'; /// Renders a media attachment inside a chat bubble: image/gif thumbnail, video @@ -325,15 +326,20 @@ class _MediaBubbleState extends State { ); } - // A round video note keeps its circle whatever state it is in. + // A round note plays right here: opening a circle in the full-screen + // viewer loses the shape and the ring it was recorded with. if (type == MediaType.video && widget.message.isVideoNote) { + final path = widget.message.localPath; + if (path != null) { + return _withCaption( + RoundVideoNote(path: path), + hasCaption, + ); + } + // Still downloading, or gone: the circle keeps its shape either way. return _withCaption( ClipOval( - child: SizedBox( - width: 200, - height: 200, - child: media, - ), + child: SizedBox(width: 200, height: 200, child: media), ), hasCaption, ); diff --git a/lib/widgets/round_video_note.dart b/lib/widgets/round_video_note.dart new file mode 100644 index 0000000..5c46254 --- /dev/null +++ b/lib/widgets/round_video_note.dart @@ -0,0 +1,225 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:video_player/video_player.dart'; + +import '../utils/media_utils.dart'; +import '../utils/playback_lock.dart'; + +/// A round video note, played in the chat instead of opening the viewer. +/// +/// The circle is the note itself: a filling ring runs around it as it plays and +/// the time sits under the picture, the way it looked while recording. +class RoundVideoNote extends StatefulWidget { + const RoundVideoNote({ + required this.path, + this.size = 200, + super.key, + }); + + /// The encrypted-at-rest file of the note. + final String path; + + final double size; + + @override + State createState() => _RoundVideoNoteState(); +} + +class _RoundVideoNoteState extends State + with WidgetsBindingObserver { + VideoPlayerController? _controller; + File? _tempFile; + bool _failed = false; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + PlaybackLock.owner.addListener(_onLockChanged); + _prepare(); + } + + Future _prepare() async { + try { + final temp = await MediaUtils.materializeTempFile(widget.path, '.mp4'); + final controller = VideoPlayerController.file(temp); + await controller.initialize(); + await controller.setLooping(false); + await controller.setVolume(1); + if (!mounted) { + await controller.dispose(); + MediaUtils.deleteLocalFile(temp.path); + return; + } + controller.addListener(_onPlayerValue); + setState(() { + _tempFile = temp; + _controller = controller; + }); + } catch (_) { + if (mounted) { + setState(() => _failed = true); + } + } + } + + /// Playback ends on its own: park the note at its start so a second tap + /// replays it, and release the playback lock. + void _onPlayerValue() { + final value = _controller?.value; + if (value == null) { + return; + } + if (value.position >= value.duration && value.duration > Duration.zero) { + _controller?.pause(); + _controller?.seekTo(Duration.zero); + PlaybackLock.release(this); + } + } + + void _onLockChanged() { + final other = PlaybackLock.owner.value; + if (other != null && + !identical(other, this) && + (_controller?.value.isPlaying ?? false)) { + _controller?.pause(); + } + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state != AppLifecycleState.resumed) { + _controller?.pause(); + } + } + + Future _toggle() async { + final controller = _controller; + if (controller == null || !controller.value.isInitialized) { + return; + } + if (controller.value.isPlaying) { + await controller.pause(); + PlaybackLock.release(this); + return; + } + PlaybackLock.claim(this); + if (controller.value.position >= controller.value.duration) { + await controller.seekTo(Duration.zero); + } + await controller.play(); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + PlaybackLock.owner.removeListener(_onLockChanged); + PlaybackLock.release(this); + _controller?.removeListener(_onPlayerValue); + _controller?.dispose(); + final temp = _tempFile; + if (temp != null) { + MediaUtils.deleteLocalFile(temp.path); + } + super.dispose(); + } + + String _format(Duration duration) { + final minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0'); + final seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0'); + return '$minutes:$seconds'; + } + + @override + Widget build(BuildContext context) { + final controller = _controller; + final ring = Theme.of(context).colorScheme.primary; + if (_failed) { + return SizedBox( + width: widget.size, + height: widget.size, + child: Center( + child: Text('mediaError'.tr(), + style: TextStyle(color: ring, fontSize: 12)), + ), + ); + } + if (controller == null || !controller.value.isInitialized) { + return SizedBox( + width: widget.size, + height: widget.size, + child: const Center(child: CircularProgressIndicator()), + ); + } + return ValueListenableBuilder( + valueListenable: controller, + builder: (context, value, _) { + final total = value.duration.inMilliseconds; + final played = value.position.inMilliseconds.clamp(0, total); + final progress = total == 0 ? 0.0 : played / total; + return GestureDetector( + onTap: _toggle, + child: SizedBox( + width: widget.size, + height: widget.size, + child: Stack( + alignment: Alignment.center, + children: [ + ClipOval( + child: SizedBox.expand( + child: FittedBox( + fit: BoxFit.cover, + child: SizedBox( + width: controller.value.size.width, + height: controller.value.size.height, + child: VideoPlayer(controller), + ), + ), + ), + ), + // How much of the note is left, as a ring that fills as it plays. + SizedBox.expand( + child: CircularProgressIndicator( + value: progress, + strokeWidth: 4, + strokeCap: StrokeCap.round, + backgroundColor: Colors.black.withValues(alpha: 0.25), + valueColor: AlwaysStoppedAnimation(ring), + ), + ), + if (!value.isPlaying) + Container( + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.35), + shape: BoxShape.circle, + ), + padding: const EdgeInsets.all(8), + child: const Icon(Icons.play_arrow, + color: Colors.white, size: 30), + ), + Positioned( + bottom: widget.size * 0.16, + child: Container( + padding: + const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.45), + borderRadius: BorderRadius.circular(10), + ), + child: Text( + _format(Duration(milliseconds: played)), + style: const TextStyle(color: Colors.white, fontSize: 11), + ), + ), + ), + ], + ), + ), + ); + }, + ); + } +} From 391188d4f641b6bf3529c77f9bf063bfe40a53f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 18:28:18 +0100 Subject: [PATCH 172/181] style(app): format the chat bubble after the media changes --- lib/widgets/chat_bubble.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 93a6e76..717ac51 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -326,7 +326,6 @@ class _ChatBubbleState extends State { } } - /// Gesture handling: select in selection mode, otherwise tooltip + reply. void onTap() { if (widget.selectionMode) { From 8b6bbbf40df8d4d8bb4dbf32115fa8a9839c3f2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 18:32:14 +0100 Subject: [PATCH 173/181] fix(app): start the share inbox after unlock and accept shared links A share that arrives while the app is locked must not open a contact picker over the password screen, so the inbox starts with Home instead of at launch. Text and URL shares are sent as text messages rather than being read as file paths, and text/plain is an explicit share target. --- android/app/src/main/AndroidManifest.xml | 5 ++++ lib/main.dart | 4 --- lib/pages/home_page.dart | 4 +++ lib/utils/share_intent.dart | 35 +++++++++++++++++++++--- 4 files changed, 40 insertions(+), 8 deletions(-) diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index c9f0124..b0e209e 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -66,6 +66,11 @@ + + + + + diff --git a/lib/main.dart b/lib/main.dart index 76b8086..e1801d7 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -21,7 +21,6 @@ import 'models/profile.dart'; import 'models/user.dart'; import 'pages/whisper_page.dart'; import 'utils/media_utils.dart'; -import 'utils/share_intent.dart'; import 'utils/storage_utils.dart'; import 'utils/notification_service.dart'; import 'utils/singleton.dart'; @@ -89,9 +88,6 @@ void main() async { // Same for attachments the user asked to drop after a while. await StorageUtils.purgeIfDue(); - // Pictures and files shared from other apps arrive here. - SharedInbox.start(); - // Default theme Singleton().appTheme = await CacheUtils.getTheme() ?? AppTheme.fromValues(ThemeMode.system, Colors.blue); diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index d3304eb..a7bf7ae 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -24,6 +24,7 @@ import '../models/user.dart'; import '../utils/admin_format.dart'; import '../utils/singleton.dart'; import '../utils/screen_guard.dart'; +import '../utils/share_intent.dart'; import '../utils/utils.dart'; import '../widgets/admin_user_list_item.dart'; @@ -98,6 +99,9 @@ class _HomePageState extends State Utils.onConnected = _sendPendingFid; // Open the chat a notification tap pointed at (after unlocking) _openPendingChat(); + // Pictures, videos and links shared from other apps. Started here rather + // than at launch, so a share can never open over the password screen. + SharedInbox.start(); // Taps arriving while Home is alive open the chat right away NotificationService.onChatSelected = _openChat; // Start checking WebSocket connection diff --git a/lib/utils/share_intent.dart b/lib/utils/share_intent.dart index 060919e..afb20c9 100644 --- a/lib/utils/share_intent.dart +++ b/lib/utils/share_intent.dart @@ -23,9 +23,18 @@ class SharedInbox { /// How many shared files one message may carry. static const int maxFiles = 10; + static bool _started = false; + /// Starts listening for inbound shares: once for a cold start, and then for /// every share while the app runs. + /// + /// Called from Home, never from [main]: a share that arrives while the app is + /// still locked must not open a contact picker over the password screen. static Future start() async { + if (_started) { + return; + } + _started = true; try { final initial = await ReceiveSharingIntent.instance.getInitialMedia(); if (initial.isNotEmpty) { @@ -86,8 +95,26 @@ class SharedInbox { static Future _send(User target, List shared) async { try { - if (shared.length == 1) { - final file = File(shared.single.path); + // A shared link or a line of text arrives as its own item and is a plain + // message; only real files go through the media pipeline. + final texts = shared + .where((item) => + item.type == SharedMediaType.text || + item.type == SharedMediaType.url) + .map((item) => item.path.trim()) + .where((text) => text.isNotEmpty); + for (final text in texts) { + await ChatSender.sendText(target, text); + } + + final files = shared + .where((item) => + item.type != SharedMediaType.text && + item.type != SharedMediaType.url) + .take(maxFiles) + .toList(); + if (files.length == 1) { + final file = File(files.single.path); final bytes = await file.readAsBytes(); if (!MediaUtils.uploadFits(bytes.length)) { throw Exception('fileTooLarge'.tr()); @@ -95,9 +122,9 @@ class SharedInbox { await ChatSender.sendMedia( target, MediaUtils.detectType(file.path), bytes, fileName: MediaUtils.baseName(file.path)); - } else { + } else if (files.isNotEmpty) { final attachments = []; - for (final item in shared) { + for (final item in files) { final file = File(item.path); final bytes = await file.readAsBytes(); if (!MediaUtils.uploadFits(bytes.length)) { From 5ddb91b8e1f8f1de2e89c3b43a4db584e8b01a42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Mon, 23 Nov 2026 18:32:37 +0100 Subject: [PATCH 174/181] docs(app): note the memory ceiling of a whole-file chunked upload --- lib/utils/media_upload.dart | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/utils/media_upload.dart b/lib/utils/media_upload.dart index 1d10320..41ddecf 100644 --- a/lib/utils/media_upload.dart +++ b/lib/utils/media_upload.dart @@ -37,6 +37,10 @@ class MediaUploader { /// /// [messageKey] and [index] identify the attachment of a stored message; when /// a session is recorded for that pair it is resumed. + /// + /// shortcut: the plaintext and its whole ciphertext are held in memory + /// together, so the 100 MiB cap can still exhaust a low-end phone; upgrade by + /// encrypting and sending one chunk at a time. static Future<(String, TransportEncryption)> upload( Uint8List bytes, { required String receiverId, From 52f240133a404fb5100984431831cbd618da44e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 24 Nov 2026 00:18:29 +0100 Subject: [PATCH 175/181] feat(app): autoplay round notes like voice messages A note that reaches its end now asks for the next one in the chat, the way a finished voice message does. MediaAutoplay (renamed from VoiceAutoplay) owns both chains: it skips the other media type, stops at our own message and at the end of the chat, and skips a note without a local copy. The ring is inset to sit on the video's circle rather than on the bubble's clip edge, where it was shaved flat at all four sides, and the time label moved to the bottom of the note. --- ...oice_autoplay.dart => media_autoplay.dart} | 32 ++-- lib/widgets/media_bubble.dart | 6 +- lib/widgets/round_video_note.dart | 88 ++++++++-- lib/widgets/voice_player.dart | 12 +- test/media_autoplay_test.dart | 166 ++++++++++++++++++ test/voice_autoplay_test.dart | 93 ---------- 6 files changed, 269 insertions(+), 128 deletions(-) rename lib/utils/{voice_autoplay.dart => media_autoplay.dart} (61%) create mode 100644 test/media_autoplay_test.dart delete mode 100644 test/voice_autoplay_test.dart diff --git a/lib/utils/voice_autoplay.dart b/lib/utils/media_autoplay.dart similarity index 61% rename from lib/utils/voice_autoplay.dart rename to lib/utils/media_autoplay.dart index dd93bcf..08da8c0 100644 --- a/lib/utils/voice_autoplay.dart +++ b/lib/utils/media_autoplay.dart @@ -1,38 +1,48 @@ import 'package:flutter/foundation.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import '../models/private_message.dart'; import 'cache_utils.dart'; -/// Chains voice messages: when one finishes, the next one of the same chat -/// starts. +/// Chains messages that play on their own: when one finishes, the next one of +/// the same chat starts. /// /// The request is the key of the message that should play, and only the player /// owning that key picks it up, so no bubble has to reach into another one. -class VoiceAutoplay { - VoiceAutoplay._(); +class MediaAutoplay { + MediaAutoplay._(); /// Key of the message that should start playing, consumed by its player. static final ValueNotifier request = ValueNotifier(null); /// Asks the next voice message after [afterSentAt] in [conversationId] to /// play. - /// - /// The chain is for listening to the other side: it stops at our own voice - /// message instead of playing it back. It also stops at the end of the chat, - /// and skips a message that is not on this device, since that one could not - /// play anyway. + static Future next(String conversationId, DateTime afterSentAt) => + _next(conversationId, afterSentAt, + (message) => message.mediaType == MediaType.voice); + + /// Asks the next round note after [afterSentAt] in [conversationId] to play. + static Future nextRoundNote( + String conversationId, DateTime afterSentAt) => + _next(conversationId, afterSentAt, (message) => message.isVideoNote); + + /// The chain is for listening to the other side: it stops at our own message + /// instead of playing it back. It also stops at the end of the chat, and + /// skips a message that is not on this device, since that one could not play + /// anyway. /// /// shortcut: a player only exists while its bubble is built, so a request for /// an off-screen message is dropped; upgrade by hoisting playback into a /// service that owns the queue. - static Future next(String conversationId, DateTime afterSentAt) async { + static Future _next(String conversationId, DateTime afterSentAt, + bool Function(PrivateMessage message) matches) async { final messages = await CacheUtils.getPrivateMessages(conversationId); messages.sort((a, b) => a.sentAt.compareTo(b.sentAt)); for (final message in messages) { if (!message.sentAt.isAfter(afterSentAt)) { continue; } - if (message.mediaType != MediaType.voice) { + if (!matches(message)) { continue; } // Our own message ends the chain: playback continues only into what the diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index e7cc5f1..064f2ec 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -332,7 +332,11 @@ class _MediaBubbleState extends State { final path = widget.message.localPath; if (path != null) { return _withCaption( - RoundVideoNote(path: path), + RoundVideoNote( + path: path, + conversationId: widget.conversationUserId, + sentAt: widget.message.sentAt, + ), hasCaption, ); } diff --git a/lib/widgets/round_video_note.dart b/lib/widgets/round_video_note.dart index 5c46254..a2b7f9d 100644 --- a/lib/widgets/round_video_note.dart +++ b/lib/widgets/round_video_note.dart @@ -5,6 +5,8 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:video_player/video_player.dart'; +import '../utils/cache_utils.dart'; +import '../utils/media_autoplay.dart'; import '../utils/media_utils.dart'; import '../utils/playback_lock.dart'; @@ -15,6 +17,8 @@ import '../utils/playback_lock.dart'; class RoundVideoNote extends StatefulWidget { const RoundVideoNote({ required this.path, + required this.conversationId, + required this.sentAt, this.size = 200, super.key, }); @@ -22,6 +26,11 @@ class RoundVideoNote extends StatefulWidget { /// The encrypted-at-rest file of the note. final String path; + /// The chat this note lives in, and when it was sent: together they are the + /// key the next-note chain looks for. + final String conversationId; + final DateTime sentAt; + final double size; @override @@ -34,11 +43,19 @@ class _RoundVideoNoteState extends State File? _tempFile; bool _failed = false; + /// Set once the finished note has asked for the next one, so a repeated + /// end-of-playback event does not restart the chain. + bool _chained = false; + + late final String _key = + CacheUtils.messageKey(widget.conversationId, widget.sentAt); + @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); PlaybackLock.owner.addListener(_onLockChanged); + MediaAutoplay.request.addListener(_onAutoplayRequest); _prepare(); } @@ -67,7 +84,7 @@ class _RoundVideoNoteState extends State } /// Playback ends on its own: park the note at its start so a second tap - /// replays it, and release the playback lock. + /// replays it, release the playback lock and ask for the next note. void _onPlayerValue() { final value = _controller?.value; if (value == null) { @@ -77,7 +94,26 @@ class _RoundVideoNoteState extends State _controller?.pause(); _controller?.seekTo(Duration.zero); PlaybackLock.release(this); + if (!_chained) { + _chained = true; + MediaAutoplay.nextRoundNote(widget.conversationId, widget.sentAt); + } + } + } + + /// Starts this note when the previous one finished and asked for it. + void _onAutoplayRequest() { + if (MediaAutoplay.request.value != _key) { + return; } + MediaAutoplay.request.value = null; + final controller = _controller; + if (controller == null || !controller.value.isInitialized) { + return; + } + _chained = false; + PlaybackLock.claim(this); + controller.play(); } void _onLockChanged() { @@ -106,6 +142,9 @@ class _RoundVideoNoteState extends State PlaybackLock.release(this); return; } + // A tap starts the chain again: the note it plays may have been reached by + // autoplay before, and that must not stop the next request. + _chained = false; PlaybackLock.claim(this); if (controller.value.position >= controller.value.duration) { await controller.seekTo(Duration.zero); @@ -117,6 +156,7 @@ class _RoundVideoNoteState extends State void dispose() { WidgetsBinding.instance.removeObserver(this); PlaybackLock.owner.removeListener(_onLockChanged); + MediaAutoplay.request.removeListener(_onAutoplayRequest); PlaybackLock.release(this); _controller?.removeListener(_onPlayerValue); _controller?.dispose(); @@ -165,29 +205,43 @@ class _RoundVideoNoteState extends State child: SizedBox( width: widget.size, height: widget.size, + // The indicator draws its stroke inside the box by default, so its + // outer edge sits 2 dp in. The video is inset by the same 2 dp: the + // two circles then share one edge instead of the picture peeking + // past the ring at all four sides. child: Stack( alignment: Alignment.center, children: [ - ClipOval( - child: SizedBox.expand( - child: FittedBox( - fit: BoxFit.cover, - child: SizedBox( - width: controller.value.size.width, - height: controller.value.size.height, - child: VideoPlayer(controller), + Padding( + padding: const EdgeInsets.all(2), + child: ClipOval( + child: SizedBox.expand( + child: FittedBox( + fit: BoxFit.cover, + child: SizedBox( + width: controller.value.size.width, + height: controller.value.size.height, + child: VideoPlayer(controller), + ), ), ), ), ), // How much of the note is left, as a ring that fills as it plays. - SizedBox.expand( - child: CircularProgressIndicator( - value: progress, - strokeWidth: 4, - strokeCap: StrokeCap.round, - backgroundColor: Colors.black.withValues(alpha: 0.25), - valueColor: AlwaysStoppedAnimation(ring), + // Its stroke is centred on a path inset by 4 dp, so the ring's + // outer edge lands exactly on the video's 98 dp circle: flush + // with the picture and still inside the bubble's clip. + Padding( + padding: const EdgeInsets.all(4), + child: SizedBox.expand( + child: CircularProgressIndicator( + value: progress, + strokeWidth: 4, + strokeAlign: BorderSide.strokeAlignCenter, + strokeCap: StrokeCap.round, + backgroundColor: Colors.black.withValues(alpha: 0.25), + valueColor: AlwaysStoppedAnimation(ring), + ), ), ), if (!value.isPlaying) @@ -201,7 +255,7 @@ class _RoundVideoNoteState extends State color: Colors.white, size: 30), ), Positioned( - bottom: widget.size * 0.16, + bottom: 6, child: Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), diff --git a/lib/widgets/voice_player.dart b/lib/widgets/voice_player.dart index c9a8224..fcba116 100644 --- a/lib/widgets/voice_player.dart +++ b/lib/widgets/voice_player.dart @@ -8,7 +8,7 @@ import '../utils/cache_utils.dart'; import '../utils/media_utils.dart'; import '../utils/playback_lock.dart'; import '../utils/playback_speed.dart'; -import '../utils/voice_autoplay.dart'; +import '../utils/media_autoplay.dart'; /// Inline player for a voice message stored encrypted-at-rest. /// @@ -64,7 +64,7 @@ class _VoicePlayerState extends State with WidgetsBindingObserver { PlaybackLock.release(this); if (!_chained) { _chained = true; - VoiceAutoplay.next(widget.conversationId, widget.sentAt); + MediaAutoplay.next(widget.conversationId, widget.sentAt); } return; } @@ -73,16 +73,16 @@ class _VoicePlayerState extends State with WidgetsBindingObserver { } }); PlaybackLock.owner.addListener(_onLockChanged); - VoiceAutoplay.request.addListener(_onAutoplayRequest); + MediaAutoplay.request.addListener(_onAutoplayRequest); _prepare(); } /// Starts this message when the previous one finished and asked for it. void _onAutoplayRequest() { - if (VoiceAutoplay.request.value != _key) { + if (MediaAutoplay.request.value != _key) { return; } - VoiceAutoplay.request.value = null; + MediaAutoplay.request.value = null; if (_loading || _error) { return; } @@ -130,7 +130,7 @@ class _VoicePlayerState extends State with WidgetsBindingObserver { void dispose() { WidgetsBinding.instance.removeObserver(this); PlaybackLock.owner.removeListener(_onLockChanged); - VoiceAutoplay.request.removeListener(_onAutoplayRequest); + MediaAutoplay.request.removeListener(_onAutoplayRequest); PlaybackLock.release(this); _player.dispose(); MediaUtils.deleteLocalFile(_tempFile?.path); diff --git a/test/media_autoplay_test.dart b/test/media_autoplay_test.dart new file mode 100644 index 0000000..92e6b41 --- /dev/null +++ b/test/media_autoplay_test.dart @@ -0,0 +1,166 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/models/profile.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/singleton.dart'; +import 'package:whisper/utils/cache_utils.dart'; +import 'package:whisper/utils/media_autoplay.dart'; + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_media_autoplay_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + // isMe compares against the signed-in user. + Singleton().profile = + Profile('', User('me', 'me', '', false), '', '', '', '', false); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + MediaAutoplay.request.value = null; + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + PrivateMessage voice(DateTime sentAt, + {String? path = '/tmp/voice', String sender = 'peer'}) => + PrivateMessage(sender, '', sentAt, sentAt, true, + mediaTypeStr: 'voice', localPath: path, durationMs: 1000); + + PrivateMessage note(DateTime sentAt, + {String? path = '/tmp/note', String sender = 'peer'}) => + PrivateMessage(sender, '', sentAt, sentAt, true, + mediaTypeStr: 'video', + localPath: path, + durationMs: 1000, + mediaRefJson: '{"videoNote":true}'); + + test('the next voice message in the chat is requested', () async { + final first = DateTime(2026, 1, 1, 10); + final second = DateTime(2026, 1, 1, 10, 1); + await CacheUtils.addPrivateMessages('1', [voice(first), voice(second)]); + + await MediaAutoplay.next('1', first); + + expect(MediaAutoplay.request.value, CacheUtils.messageKey('1', second)); + }); + + test('a text message between two voice messages is skipped', () async { + final first = DateTime(2026, 1, 1, 10); + final text = DateTime(2026, 1, 1, 10, 1); + final second = DateTime(2026, 1, 1, 10, 2); + await CacheUtils.addPrivateMessages('1', [ + voice(first), + PrivateMessage('1', 'hello', text, text, true), + voice(second), + ]); + + await MediaAutoplay.next('1', first); + + expect(MediaAutoplay.request.value, CacheUtils.messageKey('1', second)); + }); + + test('a voice message without a local copy is skipped and the end stops', + () async { + final first = DateTime(2026, 1, 1, 10); + final missing = DateTime(2026, 1, 1, 10, 1); + await CacheUtils.addPrivateMessages('1', [ + voice(first), + voice(missing, path: null), + ]); + + await MediaAutoplay.next('1', first); + + expect(MediaAutoplay.request.value, isNull); + }); + + test('playback stops instead of playing our own voice message', () async { + final first = DateTime(2026, 1, 1, 10); + final mine = DateTime(2026, 1, 1, 10, 1); + final later = DateTime(2026, 1, 1, 10, 2); + await CacheUtils.addPrivateMessages('1', [ + voice(first), + voice(mine, sender: 'me'), + voice(later), + ]); + + await MediaAutoplay.next('1', first); + + expect(MediaAutoplay.request.value, isNull); + }); + + test('the next round note in the chat is requested', () async { + final first = DateTime(2026, 1, 1, 10); + final second = DateTime(2026, 1, 1, 10, 1); + await CacheUtils.addPrivateMessages('1', [note(first), note(second)]); + + await MediaAutoplay.nextRoundNote('1', first); + + expect(MediaAutoplay.request.value, CacheUtils.messageKey('1', second)); + }); + + test('a plain video between two round notes is skipped', () async { + final first = DateTime(2026, 1, 1, 10); + final plain = DateTime(2026, 1, 1, 10, 1); + final second = DateTime(2026, 1, 1, 10, 2); + await CacheUtils.addPrivateMessages('1', [ + note(first), + PrivateMessage('peer', '', plain, plain, true, + mediaTypeStr: 'video', localPath: '/tmp/video'), + note(second), + ]); + + await MediaAutoplay.nextRoundNote('1', first); + + expect(MediaAutoplay.request.value, CacheUtils.messageKey('1', second)); + }); + + test('a round note without a local copy is skipped and the end stops', + () async { + final first = DateTime(2026, 1, 1, 10); + final missing = DateTime(2026, 1, 1, 10, 1); + await CacheUtils.addPrivateMessages('1', [ + note(first), + note(missing, path: null), + ]); + + await MediaAutoplay.nextRoundNote('1', first); + + expect(MediaAutoplay.request.value, isNull); + }); + + test('the round note chain stops at our own note', () async { + final first = DateTime(2026, 1, 1, 10); + final mine = DateTime(2026, 1, 1, 10, 1); + final later = DateTime(2026, 1, 1, 10, 2); + await CacheUtils.addPrivateMessages('1', [ + note(first), + note(mine, sender: 'me'), + note(later), + ]); + + await MediaAutoplay.nextRoundNote('1', first); + + expect(MediaAutoplay.request.value, isNull); + }); + + test('the voice chain does not pick up a round note', () async { + final first = DateTime(2026, 1, 1, 10); + final round = DateTime(2026, 1, 1, 10, 1); + await CacheUtils.addPrivateMessages('1', [voice(first), note(round)]); + + await MediaAutoplay.next('1', first); + + expect(MediaAutoplay.request.value, isNull); + }); +} diff --git a/test/voice_autoplay_test.dart b/test/voice_autoplay_test.dart deleted file mode 100644 index 411bd2f..0000000 --- a/test/voice_autoplay_test.dart +++ /dev/null @@ -1,93 +0,0 @@ -import 'dart:io'; - -import 'package:flutter_test/flutter_test.dart'; -import 'package:hive/hive.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/models/profile.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/singleton.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper/utils/voice_autoplay.dart'; - -void main() { - late Directory dir; - - setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_voice_autoplay_test'); - Hive.init(dir.path); - Hive.registerAdapter(PrivateMessageAdapter()); - // isMe compares against the signed-in user. - Singleton().profile = - Profile('', User('me', 'me', '', false), '', '', '', '', false); - }); - - setUp(() async { - await Hive.openBox('privateMessages'); - await Hive.box('privateMessages').clear(); - VoiceAutoplay.request.value = null; - }); - - tearDownAll(() async { - await Hive.close(); - dir.deleteSync(recursive: true); - }); - - PrivateMessage voice(DateTime sentAt, - {String? path = '/tmp/voice', String sender = 'peer'}) => - PrivateMessage(sender, '', sentAt, sentAt, true, - mediaTypeStr: 'voice', localPath: path, durationMs: 1000); - - test('the next voice message in the chat is requested', () async { - final first = DateTime(2026, 1, 1, 10); - final second = DateTime(2026, 1, 1, 10, 1); - await CacheUtils.addPrivateMessages('1', [voice(first), voice(second)]); - - await VoiceAutoplay.next('1', first); - - expect(VoiceAutoplay.request.value, CacheUtils.messageKey('1', second)); - }); - - test('a text message between two voice messages is skipped', () async { - final first = DateTime(2026, 1, 1, 10); - final text = DateTime(2026, 1, 1, 10, 1); - final second = DateTime(2026, 1, 1, 10, 2); - await CacheUtils.addPrivateMessages('1', [ - voice(first), - PrivateMessage('1', 'hello', text, text, true), - voice(second), - ]); - - await VoiceAutoplay.next('1', first); - - expect(VoiceAutoplay.request.value, CacheUtils.messageKey('1', second)); - }); - - test('a voice message without a local copy is skipped and the end stops', - () async { - final first = DateTime(2026, 1, 1, 10); - final missing = DateTime(2026, 1, 1, 10, 1); - await CacheUtils.addPrivateMessages('1', [ - voice(first), - voice(missing, path: null), - ]); - - await VoiceAutoplay.next('1', first); - - expect(VoiceAutoplay.request.value, isNull); - }); - - test('playback stops instead of playing our own voice message', () async { - final first = DateTime(2026, 1, 1, 10); - final mine = DateTime(2026, 1, 1, 10, 1); - final later = DateTime(2026, 1, 1, 10, 2); - await CacheUtils.addPrivateMessages('1', [ - voice(first), - voice(mine, sender: 'me'), - voice(later), - ]); - - await VoiceAutoplay.next('1', first); - - expect(VoiceAutoplay.request.value, isNull); - }); -} From 8dd25d82bb904d6ccde46095ad993078d5f8d44b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 24 Nov 2026 01:41:18 +0100 Subject: [PATCH 176/181] feat(app): keep a round note playing in a pinned copy A playing note grows to 230 dp and, once less than half of its circle is in view, keeps playing in a 144 dp copy at the top right, under the pinned-message strip. Tap pauses it, a horizontal swipe throws it away and stops playback. The circle keeps its player, so the inline view and the copy render one video without restarting it, and only one of them builds a VideoPlayer at a time. The bubble reserves the grown size so starting or finishing a note never re-lays the chat out under the user's thumb, and the note stays alive (keep-alive) while it is the live one - without that its player would die the moment it left the viewport. Visibility is measured against the settled list: a rubber-band bounce drags the whole list with the finger, which used to make the copy blink and latch. --- lib/pages/chat_page.dart | 152 ++++++++------ lib/utils/round_note_playback.dart | 213 +++++++++++++++++++ lib/widgets/chat_bubble.dart | 11 +- lib/widgets/media_bubble.dart | 3 +- lib/widgets/pinned_round_note.dart | 47 +++++ lib/widgets/round_note_circle.dart | 115 +++++++++++ lib/widgets/round_video_note.dart | 322 +++++++++++++++-------------- test/round_note_playback_test.dart | 72 +++++++ 8 files changed, 715 insertions(+), 220 deletions(-) create mode 100644 lib/utils/round_note_playback.dart create mode 100644 lib/widgets/pinned_round_note.dart create mode 100644 lib/widgets/round_note_circle.dart create mode 100644 test/round_note_playback_test.dart diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 5bb5eec..9a434fb 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -21,6 +21,7 @@ import '../utils/live_location.dart'; import '../utils/media_utils.dart'; import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; +import '../utils/round_note_playback.dart'; import '../utils/presence.dart'; import '../utils/round_video_recorder.dart'; import '../utils/sticker_store.dart'; @@ -30,6 +31,7 @@ import '../utils/utils.dart' as utils; import '../utils/theme_utils.dart'; import '../widgets/attachment_confirm_sheet.dart'; import '../widgets/chat_bubble.dart'; +import '../widgets/pinned_round_note.dart'; import '../widgets/live_location_bubble.dart'; import '../widgets/typing_dots.dart'; import 'camera_page.dart'; @@ -63,6 +65,9 @@ class _ChatPageState extends State { bool _isSending = false; // ScrollController for content final ScrollController _scrollController = ScrollController(); + // The round note that keeps playing (and floats top right) while its circle + // is out of sight; one per open chat. + final RoundNotePlayback _notePlayback = RoundNotePlayback(); // Indicates whether messages are being load for the first time bool _firstLoad = true; // Guards against overlapping cache reads @@ -2162,6 +2167,7 @@ class _ChatPageState extends State { } _readPublish?.cancel(); _recorderController?.dispose(); + _notePlayback.dispose(); _controllerMessage.dispose(); _scrollController.dispose(); super.dispose(); @@ -2426,81 +2432,97 @@ class _ChatPageState extends State { ), body: Container( decoration: BoxDecoration(image: chatPattern()), - child: Stack( - children: [ - Column( - children: [ - // Messages and avatar list - Expanded( - child: Stack( - children: [ - _firstLoad - ? Center( - child: Transform.scale( - scale: 1.5, - child: CircularProgressIndicator(), + child: RoundNoteScope( + playback: _notePlayback, + child: Stack( + children: [ + Column( + children: [ + // Messages and avatar list + Expanded( + child: Stack( + children: [ + _firstLoad + ? Center( + child: Transform.scale( + scale: 1.5, + child: CircularProgressIndicator(), + ), + ) + : _getContent(_messages), + // Floating "down" button: up whenever the viewport is + // far from the newest message, and carrying the count + // of what arrived while the user was reading above. + Positioned( + right: 16, + bottom: _composerHeight + 16, + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 200), + transitionBuilder: (child, animation) => + FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: Tween(begin: 0.8, end: 1) + .animate(animation), + child: child, ), - ) - : _getContent(_messages), - // Floating "down" button: up whenever the viewport is - // far from the newest message, and carrying the count - // of what arrived while the user was reading above. - Positioned( - right: 16, - bottom: _composerHeight + 16, - child: AnimatedSwitcher( - duration: const Duration(milliseconds: 200), - transitionBuilder: (child, animation) => - FadeTransition( - opacity: animation, - child: ScaleTransition( - scale: Tween(begin: 0.8, end: 1) - .animate(animation), - child: child, ), + child: !_firstLoad && + (_farFromBottom || _unseenCount > 0) + ? FloatingActionButton.small( + key: const ValueKey('jumpToLatest'), + heroTag: 'jumpToBottom', + tooltip: 'jumpToLatest'.tr(), + onPressed: () => + _jumpToBottom(animate: true), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.arrow_downward, + size: 16), + if (_unseenCount > 1) + Padding( + padding: const EdgeInsets.only( + left: 2), + child: Text('$_unseenCount', + style: const TextStyle( + fontSize: 11)), + ), + ], + ), + ) + : const SizedBox.shrink(), ), - child: !_firstLoad && - (_farFromBottom || _unseenCount > 0) - ? FloatingActionButton.small( - key: const ValueKey('jumpToLatest'), - heroTag: 'jumpToBottom', - tooltip: 'jumpToLatest'.tr(), - onPressed: () => - _jumpToBottom(animate: true), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.arrow_downward, - size: 16), - if (_unseenCount > 1) - Padding( - padding: const EdgeInsets.only( - left: 2), - child: Text('$_unseenCount', - style: const TextStyle( - fontSize: 11)), - ), - ], - ), - ) - : const SizedBox.shrink(), ), - ), - ], + ], + ), ), - ), - ], - ), - // Right under the header, over the list: the pin is where the - // eye looks first and the composer stays clean. - if (_pinnedInOrder.isNotEmpty) + ], + ), + // Right under the header, over the list: the pins are where the + // eye looks first and the composer stays clean. Positioned( top: kToolbarHeight + MediaQuery.of(context).padding.top, left: 0, right: 0, - child: _buildPinBar(), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (_pinnedInOrder.isNotEmpty) _buildPinBar(), + // A round note that keeps playing once its circle left + // the viewport: the copy hangs under the strip above. + Padding( + padding: const EdgeInsets.only(top: 8, right: 12), + child: Align( + alignment: Alignment.topRight, + child: PinnedRoundNote(playback: _notePlayback), + ), + ), + ], + ), ), - ], + ], + ), ), ), ), diff --git a/lib/utils/round_note_playback.dart b/lib/utils/round_note_playback.dart new file mode 100644 index 0000000..8e301c6 --- /dev/null +++ b/lib/utils/round_note_playback.dart @@ -0,0 +1,213 @@ +import 'package:flutter/widgets.dart'; +import 'package:video_player/video_player.dart'; + +import 'media_autoplay.dart'; +import 'playback_lock.dart'; + +/// Whether the note needs its floating copy: it is live (playing, or paused +/// from the copy itself) and mostly out of the chat's viewport. +bool shouldPin({required bool active, required double visibleFraction}) => + active && visibleFraction < 0.5; + +/// Share of [note] that is inside [viewport]: 0 when it is fully out of sight, +/// 1 when the whole circle is on screen. +double visibleFraction(Rect note, Rect viewport) { + if (note.height <= 0) { + return 0; + } + final inside = note.intersect(viewport); + if (inside.height <= 0) { + return 0; + } + return (inside.height / note.height).clamp(0.0, 1.0); +} + +/// The note's rect as it will sit once a rubber-band bounce settles: the list +/// follows the finger while stretched, so the stretch is taken out of the +/// measurement and the floating copy does not blink with the bounce. +Rect settledNoteRect( + Rect note, { + required double overscroll, + required bool reversed, +}) => + overscroll == 0 + ? note + : note.shift(Offset(0, reversed ? overscroll : -overscroll)); + +/// The one round note that is live in the open chat. +/// +/// The inline circle keeps owning its player - it is the only thing that can +/// give the note a first frame before it is played - and this holds a reference +/// to it: it says which note is live, how much of it is on screen, and hands +/// the player to the floating copy. The two views therefore never restart the +/// video, and two notes can never play at once. +class RoundNotePlayback extends ChangeNotifier { + String? _key; + String? _conversationId; + DateTime? _sentAt; + VideoPlayerController? _controller; + double _visibleFraction = 1; + bool _active = false; + bool _chained = false; + bool _lastPlaying = false; + bool _disposed = false; + + /// Key of the note that is live, null when nothing is playing any more. + String? get key => _key; + + /// The player of the live note; the floating copy renders this one. + VideoPlayerController? get controller => _controller; + + bool get playing => _controller?.value.isPlaying ?? false; + + /// Started and not finished or dismissed yet: the note is still "the one". + bool get active => _active; + + /// The note is (mostly) out of sight and needs the floating copy. + bool get pinned => + shouldPin(active: _active, visibleFraction: _visibleFraction); + + /// Makes [key] the live note and starts it, resuming a paused one. + Future start({ + required String key, + required String conversationId, + required DateTime sentAt, + required VideoPlayerController controller, + }) async { + if (_key != key || !identical(_controller, controller)) { + final previous = _controller; + if (previous != null && !identical(previous, controller)) { + previous.removeListener(_onValue); + await previous.pause(); + } + _key = key; + _conversationId = conversationId; + _sentAt = sentAt; + _controller = controller; + _visibleFraction = 1; + _chained = false; + controller.addListener(_onValue); + } + _active = true; + PlaybackLock.claim(this); + if (controller.value.position >= controller.value.duration) { + await controller.seekTo(Duration.zero); + } + await controller.play(); + _notify(); + } + + Future pause() async { + await _controller?.pause(); + _notify(); + } + + Future resume() async { + final controller = _controller; + if (controller == null) { + return; + } + _active = true; + PlaybackLock.claim(this); + await controller.play(); + _notify(); + } + + Future toggle() => playing ? pause() : resume(); + + /// The floating copy was swiped away: playback stops and the note is no + /// longer the live one until the user starts it again. + Future dismiss() async { + final controller = _controller; + if (controller == null) { + return; + } + await controller.pause(); + await controller.seekTo(Duration.zero); + PlaybackLock.release(this); + _active = false; + _notify(); + } + + /// How much of [key] is on screen. Only a change of the pin itself is worth a + /// rebuild: this is called on every scroll frame. + void updateVisibility(String key, double fraction) { + if (_key != key) { + return; + } + final wasPinned = pinned; + _visibleFraction = fraction; + if (pinned != wasPinned) { + _notify(); + } + } + + /// The inline circle is gone: forget the player and stop it. + void detach(String key) { + if (_key != key) { + return; + } + final controller = _controller; + controller?.removeListener(_onValue); + controller?.pause(); + _controller = null; + _key = null; + _active = false; + _notify(); + } + + void _onValue() { + final controller = _controller; + if (controller == null) { + return; + } + final value = controller.value; + if (value.position >= value.duration && value.duration > Duration.zero) { + controller.pause(); + controller.seekTo(Duration.zero); + PlaybackLock.release(this); + _active = false; + // One request per playback: a repeated end-of-video event must not restart + // the chain. + if (!_chained) { + _chained = true; + MediaAutoplay.nextRoundNote(_conversationId!, _sentAt!); + } + _notify(); + return; + } + if (value.isPlaying != _lastPlaying) { + _lastPlaying = value.isPlaying; + _notify(); + } + } + + void _notify() { + if (!_disposed) { + notifyListeners(); + } + } + + @override + void dispose() { + _disposed = true; + _controller?.removeListener(_onValue); + PlaybackLock.release(this); + super.dispose(); + } +} + +/// Gives the chat's [RoundNotePlayback] to the circles inside the list. +class RoundNoteScope extends InheritedNotifier { + const RoundNoteScope({ + required RoundNotePlayback playback, + required super.child, + super.key, + }) : super(notifier: playback); + + static RoundNotePlayback of(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()!.notifier!; + + static RoundNotePlayback? maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()?.notifier; +} diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 717ac51..51d5567 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -589,12 +589,17 @@ class _ChatBubbleState extends State { // only stops clipping: toggling Container.clipBehavior adds or drops its // clip widget, which re-mounts the attachment and throws the decoded image // away - the white flash when a reaction was added. + // + // A round note is never clipped either: it is a circle that grows while it + // plays and clips itself, so the rounded rectangle would only cut it at the + // box edges. final clippedBox = ownChrome ? ClipRRect( borderRadius: BorderRadius.circular(20), - clipBehavior: widget.message.reactionEmojis.isEmpty - ? Clip.antiAlias - : Clip.none, + clipBehavior: widget.message.reactionEmojis.isEmpty || + widget.message.isVideoNote + ? Clip.none + : Clip.antiAlias, child: bubbleBox, ) : bubbleBox; diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index 064f2ec..b80da32 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -333,9 +333,8 @@ class _MediaBubbleState extends State { if (path != null) { return _withCaption( RoundVideoNote( - path: path, + message: widget.message, conversationId: widget.conversationUserId, - sentAt: widget.message.sentAt, ), hasCaption, ); diff --git a/lib/widgets/pinned_round_note.dart b/lib/widgets/pinned_round_note.dart new file mode 100644 index 0000000..7e9f8d3 --- /dev/null +++ b/lib/widgets/pinned_round_note.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart'; + +import '../utils/round_note_playback.dart'; +import 'round_note_circle.dart'; + +/// The playing note as it looks once its circle leaves the chat's viewport: +/// the same player, 48 dp, hanging under the pinned-message strip. +/// +/// Tap pauses (and resumes) the note; a horizontal swipe throws the copy away +/// and stops playback. The circle it renders is the same widget the inline note +/// uses, so moving between the two never restarts the video. +class PinnedRoundNote extends StatelessWidget { + const PinnedRoundNote({required this.playback, this.size = 144, super.key}); + + final RoundNotePlayback playback; + final double size; + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: playback, + builder: (context, _) { + final controller = playback.controller; + if (!playback.pinned || + controller == null || + !controller.value.isInitialized) { + return const SizedBox.shrink(); + } + return GestureDetector( + onTap: playback.toggle, + onHorizontalDragEnd: (_) => playback.dismiss(), + child: Material( + elevation: 6, + shape: const CircleBorder(), + clipBehavior: Clip.antiAlias, + color: Colors.black, + child: RoundNoteCircle( + controller: controller, + size: size, + showTime: false, + ), + ), + ); + }, + ); + } +} diff --git a/lib/widgets/round_note_circle.dart b/lib/widgets/round_note_circle.dart new file mode 100644 index 0000000..49137c7 --- /dev/null +++ b/lib/widgets/round_note_circle.dart @@ -0,0 +1,115 @@ +import 'package:flutter/material.dart'; +import 'package:video_player/video_player.dart'; + +/// The circle of a round note: the video, the ring that fills as it plays, the +/// play badge when it is not playing and, inline only, the running time. +/// +/// Shared by the inline note and the floating copy so both keep one geometry: +/// the indicator draws its stroke inside its box by default, so the video is +/// inset by the same 2 dp and the ring's path is inset by its 4 dp stroke - +/// that lands the ring's outer edge exactly on the video's circle instead of on +/// the bubble's clip, which used to shave it flat at all four sides. +class RoundNoteCircle extends StatelessWidget { + const RoundNoteCircle({ + required this.controller, + required this.size, + this.showTime = true, + super.key, + }); + + final VideoPlayerController controller; + final double size; + + /// The inline note shows how far it got; the 48 dp copy has no room for it. + final bool showTime; + + static const double _strokeWidth = 4; + + String _format(Duration duration) { + final minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0'); + final seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0'); + return '$minutes:$seconds'; + } + + @override + Widget build(BuildContext context) { + final ring = Theme.of(context).colorScheme.primary; + return ValueListenableBuilder( + valueListenable: controller, + builder: (context, value, _) { + final total = value.duration.inMilliseconds; + final played = value.position.inMilliseconds.clamp(0, total); + final progress = total == 0 ? 0.0 : played / total; + return SizedBox( + width: size, + height: size, + child: Stack( + alignment: Alignment.center, + children: [ + Padding( + padding: const EdgeInsets.all(2), + child: ClipOval( + child: SizedBox.expand( + child: FittedBox( + fit: BoxFit.cover, + child: SizedBox( + width: controller.value.size.width, + height: controller.value.size.height, + child: VideoPlayer(controller), + ), + ), + ), + ), + ), + // How much of the note is left, as a ring that fills as it plays. + Padding( + padding: const EdgeInsets.all(_strokeWidth), + child: SizedBox.expand( + child: CircularProgressIndicator( + value: progress, + strokeWidth: _strokeWidth, + strokeAlign: BorderSide.strokeAlignCenter, + strokeCap: StrokeCap.round, + backgroundColor: Colors.black.withValues(alpha: 0.25), + valueColor: AlwaysStoppedAnimation(ring), + ), + ), + ), + if (!value.isPlaying) + Container( + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.35), + shape: BoxShape.circle, + ), + padding: EdgeInsets.all(size * 0.04), + child: Icon( + Icons.play_arrow, + color: Colors.white, + size: size * 0.15, + ), + ), + if (showTime) + Positioned( + // Just above the video's rim, low enough to read as part of + // the note rather than as a caption. + bottom: 6, + child: Container( + padding: + const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.45), + borderRadius: BorderRadius.circular(10), + ), + child: Text( + _format(Duration(milliseconds: played)), + style: const TextStyle(color: Colors.white, fontSize: 11), + ), + ), + ), + ], + ), + ); + }, + ); + } +} diff --git a/lib/widgets/round_video_note.dart b/lib/widgets/round_video_note.dart index a2b7f9d..5a0c454 100644 --- a/lib/widgets/round_video_note.dart +++ b/lib/widgets/round_video_note.dart @@ -1,35 +1,36 @@ -import 'dart:async'; import 'dart:io'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:video_player/video_player.dart'; +import '../models/private_message.dart'; import '../utils/cache_utils.dart'; import '../utils/media_autoplay.dart'; import '../utils/media_utils.dart'; -import '../utils/playback_lock.dart'; +import '../utils/round_note_playback.dart'; +import 'round_note_circle.dart'; /// A round video note, played in the chat instead of opening the viewer. /// /// The circle is the note itself: a filling ring runs around it as it plays and -/// the time sits under the picture, the way it looked while recording. +/// the time sits under the picture, the way it looked while recording. The +/// circle keeps the player; while it is the live note it stays alive after it +/// scrolls out of sight, so the floating copy (`PinnedRoundNote`) can keep +/// rendering the same player. class RoundVideoNote extends StatefulWidget { const RoundVideoNote({ - required this.path, + required this.message, required this.conversationId, - required this.sentAt, this.size = 200, super.key, }); - /// The encrypted-at-rest file of the note. - final String path; + final PrivateMessage message; - /// The chat this note lives in, and when it was sent: together they are the - /// key the next-note chain looks for. + /// The chat this note lives in: with the send time it is the key the chain + /// and the floating copy look for. final String conversationId; - final DateTime sentAt; final double size; @@ -38,30 +39,55 @@ class RoundVideoNote extends StatefulWidget { } class _RoundVideoNoteState extends State - with WidgetsBindingObserver { + with WidgetsBindingObserver, AutomaticKeepAliveClientMixin { VideoPlayerController? _controller; File? _tempFile; bool _failed = false; - /// Set once the finished note has asked for the next one, so a repeated - /// end-of-playback event does not restart the chain. - bool _chained = false; + ScrollableState? _scrollable; + RoundNotePlayback? _playback; + bool _reportScheduled = false; late final String _key = - CacheUtils.messageKey(widget.conversationId, widget.sentAt); + CacheUtils.messageKey(widget.conversationId, widget.message.sentAt); + + bool get _live => _playback?.key == _key; + + bool get playing => _controller?.value.isPlaying ?? false; + + /// How much bigger a playing note is than a resting one. The bubble reserves + /// the grown size, and 15 % is all the bubble's 16 dp screen inset allows. + static const double _growth = 1.15; @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); - PlaybackLock.owner.addListener(_onLockChanged); MediaAutoplay.request.addListener(_onAutoplayRequest); _prepare(); } + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _playback = RoundNoteScope.maybeOf(context); + final scrollable = Scrollable.maybeOf(context); + if (!identical(scrollable, _scrollable)) { + _scrollable?.position.removeListener(_scheduleReport); + _scrollable = scrollable; + _scrollable?.position.addListener(_scheduleReport); + } + } + + /// The circle stays mounted while it is the live note: without that its + /// player (and the floating copy) would die the moment it leaves the viewport. + @override + bool get wantKeepAlive => _live && (_playback?.active ?? false); + Future _prepare() async { try { - final temp = await MediaUtils.materializeTempFile(widget.path, '.mp4'); + final temp = await MediaUtils.materializeTempFile( + widget.message.localPath!, '.mp4'); final controller = VideoPlayerController.file(temp); await controller.initialize(); await controller.setLooping(false); @@ -71,11 +97,11 @@ class _RoundVideoNoteState extends State MediaUtils.deleteLocalFile(temp.path); return; } - controller.addListener(_onPlayerValue); setState(() { _tempFile = temp; _controller = controller; }); + _reportVisibility(); } catch (_) { if (mounted) { setState(() => _failed = true); @@ -83,82 +109,115 @@ class _RoundVideoNoteState extends State } } - /// Playback ends on its own: park the note at its start so a second tap - /// replays it, release the playback lock and ask for the next note. - void _onPlayerValue() { - final value = _controller?.value; - if (value == null) { - return; - } - if (value.position >= value.duration && value.duration > Duration.zero) { - _controller?.pause(); - _controller?.seekTo(Duration.zero); - PlaybackLock.release(this); - if (!_chained) { - _chained = true; - MediaAutoplay.nextRoundNote(widget.conversationId, widget.sentAt); - } - } - } - /// Starts this note when the previous one finished and asked for it. void _onAutoplayRequest() { if (MediaAutoplay.request.value != _key) { return; } MediaAutoplay.request.value = null; + _start(); + } + + Future _start() async { final controller = _controller; - if (controller == null || !controller.value.isInitialized) { + final playback = _playback; + if (controller == null || playback == null) { return; } - _chained = false; - PlaybackLock.claim(this); - controller.play(); + await playback.start( + key: _key, + conversationId: widget.conversationId, + sentAt: widget.message.sentAt, + controller: controller, + ); + updateKeepAlive(); } - void _onLockChanged() { - final other = PlaybackLock.owner.value; - if (other != null && - !identical(other, this) && - (_controller?.value.isPlaying ?? false)) { - _controller?.pause(); + Future _toggle() async { + final playback = _playback; + final controller = _controller; + if (playback == null || controller == null) { + return; + } + if (_live && controller.value.isPlaying) { + await playback.pause(); + return; } + await _start(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { - if (state != AppLifecycleState.resumed) { + if (state == AppLifecycleState.resumed) { + return; + } + final playback = _playback; + if (_live && playback != null) { + playback.pause(); + } else { _controller?.pause(); } } - Future _toggle() async { - final controller = _controller; - if (controller == null || !controller.value.isInitialized) { + /// A scroll notification arrives before the frame that moves this note, so + /// measuring right away reads the old (or detached) box and the floating copy + /// would stay up after the note came back into sight. Measure after the + /// frame instead. + void _scheduleReport() { + if (_reportScheduled) { + return; + } + _reportScheduled = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _reportScheduled = false; + if (mounted) { + _reportVisibility(); + } + }); + } + + /// Reports how much of the circle is on screen; the floating copy appears + /// once less than half of it is. + void _reportVisibility() { + final playback = _playback; + if (playback == null || playback.key != _key) { return; } - if (controller.value.isPlaying) { - await controller.pause(); - PlaybackLock.release(this); + final position = _scrollable?.position; + final box = context.findRenderObject() as RenderBox?; + final viewport = _scrollable?.context.findRenderObject() as RenderBox?; + if (box == null || + !box.attached || + viewport == null || + !viewport.attached) { + playback.updateVisibility(_key, 0); return; } - // A tap starts the chain again: the note it plays may have been reached by - // autoplay before, and that must not stop the next request. - _chained = false; - PlaybackLock.claim(this); - if (controller.value.position >= controller.value.duration) { - await controller.seekTo(Duration.zero); + var rect = box.localToGlobal(Offset.zero) & box.size; + final area = viewport.localToGlobal(Offset.zero) & viewport.size; + if (position != null) { + // A rubber band drags the whole list with the finger, so a bounce over the + // note made the floating copy vanish and come back on release. Measure + // where the note will sit once the list settles instead. + final overscroll = position.pixels - + position.pixels + .clamp(position.minScrollExtent, position.maxScrollExtent); + if (overscroll != 0) { + final settled = position.axisDirection == AxisDirection.up + ? overscroll + : -overscroll; + rect = rect.shift(Offset(0, -settled)); + } } - await controller.play(); + playback.updateVisibility(_key, visibleFraction(rect, area)); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); - PlaybackLock.owner.removeListener(_onLockChanged); MediaAutoplay.request.removeListener(_onAutoplayRequest); - PlaybackLock.release(this); - _controller?.removeListener(_onPlayerValue); + _scrollable?.position.removeListener(_scheduleReport); + _playback?.detach(_key); _controller?.dispose(); final temp = _tempFile; if (temp != null) { @@ -167,23 +226,20 @@ class _RoundVideoNoteState extends State super.dispose(); } - String _format(Duration duration) { - final minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0'); - final seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0'); - return '$minutes:$seconds'; - } - @override Widget build(BuildContext context) { + super.build(context); final controller = _controller; - final ring = Theme.of(context).colorScheme.primary; if (_failed) { return SizedBox( width: widget.size, height: widget.size, child: Center( - child: Text('mediaError'.tr(), - style: TextStyle(color: ring, fontSize: 12)), + child: Text( + 'mediaError'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.primary, fontSize: 12), + ), ), ); } @@ -194,86 +250,52 @@ class _RoundVideoNoteState extends State child: const Center(child: CircularProgressIndicator()), ); } - return ValueListenableBuilder( - valueListenable: controller, - builder: (context, value, _) { - final total = value.duration.inMilliseconds; - final played = value.position.inMilliseconds.clamp(0, total); - final progress = total == 0 ? 0.0 : played / total; - return GestureDetector( - onTap: _toggle, - child: SizedBox( - width: widget.size, - height: widget.size, - // The indicator draws its stroke inside the box by default, so its - // outer edge sits 2 dp in. The video is inset by the same 2 dp: the - // two circles then share one edge instead of the picture peeking - // past the ring at all four sides. - child: Stack( - alignment: Alignment.center, - children: [ - Padding( - padding: const EdgeInsets.all(2), - child: ClipOval( - child: SizedBox.expand( - child: FittedBox( - fit: BoxFit.cover, - child: SizedBox( - width: controller.value.size.width, - height: controller.value.size.height, - child: VideoPlayer(controller), - ), + final playback = _playback; + // One VideoPlayer per player: while the floating copy shows the video the + // circle (which is out of sight anyway) keeps only its dark disc. + final pinned = playback != null && _live && playback.pinned; + // Reported after every layout: new messages shift the viewport without a + // scroll event. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _reportVisibility(); + } + }); + return GestureDetector( + onTap: _toggle, + child: SizedBox( + // The bubble always reserves the grown size: a circle that changes the + // item's height would re-lay the list out under the user's thumb every + // time a note starts or ends. + width: widget.size * _growth, + height: widget.size * _growth, + child: Center( + child: TweenAnimationBuilder( + // The video is a texture: it paints only inside its own layout box, + // so the growth has to be a real size (a Transform or OverflowBox + // leaves the picture at 200 dp while the ring moves out). + tween: Tween(end: _live && playing ? 1 : 1 / _growth), + duration: const Duration(milliseconds: 180), + curve: Curves.easeOut, + builder: (context, factor, _) { + final side = widget.size * _growth * factor; + return pinned + ? ClipOval( + child: Container( + width: side, + height: side, + color: Colors.black, ), - ), - ), - ), - // How much of the note is left, as a ring that fills as it plays. - // Its stroke is centred on a path inset by 4 dp, so the ring's - // outer edge lands exactly on the video's 98 dp circle: flush - // with the picture and still inside the bubble's clip. - Padding( - padding: const EdgeInsets.all(4), - child: SizedBox.expand( - child: CircularProgressIndicator( - value: progress, - strokeWidth: 4, - strokeAlign: BorderSide.strokeAlignCenter, - strokeCap: StrokeCap.round, - backgroundColor: Colors.black.withValues(alpha: 0.25), - valueColor: AlwaysStoppedAnimation(ring), - ), - ), - ), - if (!value.isPlaying) - Container( - decoration: BoxDecoration( - color: Colors.black.withValues(alpha: 0.35), - shape: BoxShape.circle, - ), - padding: const EdgeInsets.all(8), - child: const Icon(Icons.play_arrow, - color: Colors.white, size: 30), - ), - Positioned( - bottom: 6, - child: Container( - padding: - const EdgeInsets.symmetric(horizontal: 8, vertical: 2), - decoration: BoxDecoration( - color: Colors.black.withValues(alpha: 0.45), - borderRadius: BorderRadius.circular(10), - ), - child: Text( - _format(Duration(milliseconds: played)), - style: const TextStyle(color: Colors.white, fontSize: 11), - ), - ), - ), - ], - ), + ) + : RoundNoteCircle( + controller: controller, + size: side, + showTime: side >= 100, + ); + }, ), - ); - }, + ), + ), ); } } diff --git a/test/round_note_playback_test.dart b/test/round_note_playback_test.dart new file mode 100644 index 0000000..12dfb83 --- /dev/null +++ b/test/round_note_playback_test.dart @@ -0,0 +1,72 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/round_note_playback.dart'; + +void main() { + group('the floating copy of a round note', () { + test('appears for a live note that is mostly out of sight', () { + expect(shouldPin(active: true, visibleFraction: 0.4), isTrue); + expect(shouldPin(active: true, visibleFraction: 0), isTrue); + }); + + test('stays away while the circle is on screen', () { + expect(shouldPin(active: true, visibleFraction: 0.5), isFalse); + expect(shouldPin(active: true, visibleFraction: 1), isFalse); + }); + + test('is gone when the note finished or was dismissed', () { + expect(shouldPin(active: false, visibleFraction: 0), isFalse); + expect(shouldPin(active: false, visibleFraction: 0.9), isFalse); + }); + }); + + group('a rubber-band bounce', () { + const viewport = Rect.fromLTWH(0, 0, 400, 800); + + test('measures as if the list had settled', () { + // Dragging down at the top of a reversed chat pulls the note 120 dp + // lower than it will sit once released. + const pulled = Rect.fromLTRB(0, 700, 230, 930); + final settled = settledNoteRect(pulled, overscroll: -120, reversed: true); + expect(settled, const Rect.fromLTRB(0, 580, 230, 810)); + expect(visibleFraction(pulled, viewport), lessThan(0.5)); + expect(visibleFraction(settled, viewport), greaterThan(0.9)); + }); + + test('is ignored when the list is inside its range', () { + const note = Rect.fromLTRB(0, 300, 230, 530); + expect(settledNoteRect(note, overscroll: 0, reversed: true), note); + }); + + test('the shift follows the list direction', () { + const note = Rect.fromLTRB(0, 600, 230, 830); + expect( + settledNoteRect(note, overscroll: 120, reversed: true), + const Rect.fromLTRB(0, 720, 230, 950), + ); + expect( + settledNoteRect(note, overscroll: 120, reversed: false), + const Rect.fromLTRB(0, 480, 230, 710), + ); + }); + }); + + group('the share of the note on screen', () { + const note = Rect.fromLTWH(0, 0, 200, 200); + + test('is 1 when the whole circle is inside the viewport', () { + expect(visibleFraction(note, const Rect.fromLTWH(0, 0, 400, 800)), 1); + }); + + test('is the covered part when the circle is half way out', () { + expect(visibleFraction(note, const Rect.fromLTWH(0, 100, 400, 800)), 0.5); + expect( + visibleFraction(note, const Rect.fromLTWH(0, 150, 400, 800)), 0.25); + }); + + test('is 0 when the circle is out of sight', () { + expect(visibleFraction(note, const Rect.fromLTWH(0, 300, 400, 800)), 0); + expect(visibleFraction(note, const Rect.fromLTWH(0, -400, 400, 300)), 0); + }); + }); +} From d734ce3c6c6bdf8dd7468b1c617647205512c119 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 27 Nov 2026 00:09:37 +0100 Subject: [PATCH 177/181] refactor(app): rename whisper to shept --- .github/workflows/build_and_release.yml | 4 +-- .github/workflows/flutter-e2e.yml | 6 ++-- .vscode/launch.json | 6 ++-- AGENTS.md | 10 +++---- README.md | 28 +++++++++--------- android/app/build.gradle.kts | 8 ++--- android/app/src/main/AndroidManifest.xml | 4 +-- .../josefraz/shept}/MainActivity.kt | 4 +-- ...{ic_stat_whisper.png => ic_stat_shept.png} | Bin ...{ic_stat_whisper.png => ic_stat_shept.png} | Bin ...{ic_stat_whisper.png => ic_stat_shept.png} | Bin ...{ic_stat_whisper.png => ic_stat_shept.png} | Bin ...{ic_stat_whisper.png => ic_stat_shept.png} | Bin android/app/src/main/res/values/strings.xml | 2 +- android/key.properties.example | 8 ++--- assets/translations/cs.json | 2 +- assets/translations/en.json | 2 +- integration_test/app_e2e_test.dart | 20 ++++++------- ios/Runner.xcodeproj/project.pbxproj | 12 ++++---- ios/Runner/Info.plist | 12 ++++---- lib/main.dart | 4 +-- lib/models/private_message.dart | 6 ++-- lib/models/user.dart | 2 +- lib/pages/chat_media_page.dart | 2 +- lib/pages/chat_page.dart | 4 +-- lib/pages/devices_page.dart | 2 +- lib/pages/home_page.dart | 2 +- lib/pages/media_viewer_page.dart | 2 +- lib/pages/password_page.dart | 2 +- lib/pages/register_page.dart | 4 +-- lib/pages/settings_page.dart | 6 ++-- .../{whisper_page.dart => shept_page.dart} | 4 +-- lib/utils/auto_download.dart | 4 +-- lib/utils/biometric_auth.dart | 2 +- lib/utils/cache_utils.dart | 4 +-- lib/utils/chat_sender.dart | 8 ++--- lib/utils/dialog_utils.dart | 2 +- lib/utils/media_autoplay.dart | 2 +- lib/utils/media_upload.dart | 2 +- lib/utils/media_utils.dart | 20 ++++++------- lib/utils/message_actions.dart | 8 ++--- lib/utils/message_notifier.dart | 8 ++--- lib/utils/notification_service.dart | 20 ++++++------- lib/utils/screen_guard.dart | 2 +- lib/utils/singleton.dart | 4 +-- lib/utils/text_envelope.dart | 8 ++--- lib/utils/utils.dart | 26 ++++++++-------- lib/widgets/invite_list_item.dart | 2 +- lib/widgets/media_bubble.dart | 2 +- linux/CMakeLists.txt | 4 +-- linux/runner/my_application.cc | 4 +-- pubspec.lock | 28 +++++++++--------- pubspec.yaml | 12 ++++---- test/admin_format_test.dart | 4 +-- test/admin_user_list_item_test.dart | 4 +-- test/api_client_test.dart | 2 +- test/attachment_confirm_sheet_test.dart | 2 +- test/auth_refresh_fallback_test.dart | 16 +++++----- test/auto_download_test.dart | 10 +++---- test/avatar_rule_test.dart | 10 +++---- test/batch_decrypt_test.dart | 4 +-- test/chat_bubble_test.dart | 16 +++++----- test/chat_date_test.dart | 2 +- test/chat_info_media_test.dart | 6 ++-- test/chat_list_item_test.dart | 10 +++---- test/chat_media_page_test.dart | 12 ++++---- test/chat_scroll_test.dart | 2 +- test/chat_theme_dialog_test.dart | 4 +-- test/chat_theme_test.dart | 4 +-- test/conversation_meta_test.dart | 6 ++-- test/crypto_test.dart | 2 +- test/delete_message_test.dart | 6 ++-- test/deleted_bubble_test.dart | 12 ++++---- test/device_and_sync_test.dart | 4 +-- test/disappearing_test.dart | 18 +++++------ test/edit_dialog_test.dart | 10 +++---- test/file_media_test.dart | 14 ++++----- test/link_utils_test.dart | 2 +- test/live_location_bubble_test.dart | 8 ++--- test/location_test.dart | 4 +-- test/media_album_test.dart | 18 +++++------ test/media_autoplay_test.dart | 14 ++++----- test/media_cache_test.dart | 6 ++-- test/media_guard_test.dart | 8 ++--- test/media_rekey_test.dart | 2 +- test/media_upload_test.dart | 2 +- test/message_actions_test.dart | 14 ++++----- test/message_format_test.dart | 2 +- test/message_lifecycle_test.dart | 10 +++---- test/message_search_test.dart | 4 +-- test/message_store_test.dart | 8 ++--- test/pbkdf2_salt_test.dart | 2 +- test/playback_lock_test.dart | 2 +- test/playback_speed_test.dart | 2 +- test/presence_test.dart | 4 +-- test/reaction_list_test.dart | 2 +- test/reaction_picker_test.dart | 10 +++---- test/reaction_rebuild_test.dart | 18 +++++------ test/reaction_store_test.dart | 6 ++-- test/read_receipt_test.dart | 12 ++++---- test/reconnect_backoff_test.dart | 2 +- test/round_note_playback_test.dart | 2 +- test/search_user_test.dart | 4 +-- test/server_url_and_temp_test.dart | 10 +++---- test/settings_tile_test.dart | 2 +- test/storage_utils_test.dart | 8 ++--- test/text_envelope_test.dart | 14 ++++----- test/theme_dialog_test.dart | 10 +++---- test/token_expiry_test.dart | 2 +- test/typing_dots_test.dart | 2 +- test/undecryptable_message_test.dart | 2 +- test/user_list_item_test.dart | 6 ++-- test/video_note_test.dart | 6 ++-- test/view_once_location_test.dart | 14 ++++----- test/view_once_preview_test.dart | 8 ++--- test/view_once_test.dart | 10 +++---- 116 files changed, 391 insertions(+), 391 deletions(-) rename android/app/src/main/kotlin/{com/example/whisper => cz/josefraz/shept}/MainActivity.kt (97%) rename android/app/src/main/res/drawable-hdpi/{ic_stat_whisper.png => ic_stat_shept.png} (100%) rename android/app/src/main/res/drawable-mdpi/{ic_stat_whisper.png => ic_stat_shept.png} (100%) rename android/app/src/main/res/drawable-xhdpi/{ic_stat_whisper.png => ic_stat_shept.png} (100%) rename android/app/src/main/res/drawable-xxhdpi/{ic_stat_whisper.png => ic_stat_shept.png} (100%) rename android/app/src/main/res/drawable-xxxhdpi/{ic_stat_whisper.png => ic_stat_shept.png} (100%) rename lib/pages/{whisper_page.dart => shept_page.dart} (97%) diff --git a/.github/workflows/build_and_release.yml b/.github/workflows/build_and_release.yml index 324a4da..f6804af 100644 --- a/.github/workflows/build_and_release.yml +++ b/.github/workflows/build_and_release.yml @@ -88,7 +88,7 @@ jobs: # Rename APK file - name: Rename APK run: | - mv build/app/outputs/flutter-apk/app-release.apk build/app/outputs/flutter-apk/whisper_v${{ steps.version.outputs.version }}.apk + mv build/app/outputs/flutter-apk/app-release.apk build/app/outputs/flutter-apk/shept_v${{ steps.version.outputs.version }}.apk # Creating GitHub release - name: Create Release @@ -102,4 +102,4 @@ jobs: draft: false prerelease: false files: | - build/app/outputs/flutter-apk/whisper_v${{ steps.version.outputs.version }}.apk \ No newline at end of file + build/app/outputs/flutter-apk/shept_v${{ steps.version.outputs.version }}.apk \ No newline at end of file diff --git a/.github/workflows/flutter-e2e.yml b/.github/workflows/flutter-e2e.yml index 66abf1c..8633bff 100644 --- a/.github/workflows/flutter-e2e.yml +++ b/.github/workflows/flutter-e2e.yml @@ -17,7 +17,7 @@ jobs: - name: Checkout app uses: actions/checkout@v7 with: - path: whisper + path: shept # Both Dart clients come from their release tags (pubspec.yaml), so no # sibling checkouts are needed. @@ -34,11 +34,11 @@ jobs: cache: true - name: Get dependencies - working-directory: whisper + working-directory: shept run: | flutter config --enable-linux-desktop flutter pub get - name: Run E2E - working-directory: whisper + working-directory: shept run: xvfb-run -a flutter test integration_test -d linux diff --git a/.vscode/launch.json b/.vscode/launch.json index dc95bd7..eb80aeb 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -2,18 +2,18 @@ "version": "0.2.0", "configurations": [ { - "name": "whisper", + "name": "shept", "request": "launch", "type": "dart" }, { - "name": "whisper (profile mode)", + "name": "shept (profile mode)", "request": "launch", "type": "dart", "flutterMode": "profile" }, { - "name": "whisper (release mode)", + "name": "shept (release mode)", "request": "launch", "type": "dart", "flutterMode": "release" diff --git a/AGENTS.md b/AGENTS.md index 21e9b90..718a270 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ -# whisper — agent contract +# shept — agent contract -Flutter 3.47 / Dart 3.13 client for Whisper. Talks to `whisper-server` over HTTP (generated `whisper_openapi_client_dart`) -and WebSocket (`whisper_websocket_client_dart`). +Flutter 3.47 / Dart 3.13 client for Shept. Talks to `shept-server` over HTTP (generated `shept_openapi_client_dart`) +and WebSocket (`shept_websocket_client_dart`). ## Commands @@ -22,7 +22,7 @@ not in this repository). Use them for the fast loop, but the shell gates below s | `dart` | `analyze_files`, symbol resolution, `run_tests`, `pub`, hot reload/restart, DTD connection, widget inspector | | `flutter-mcp-toolkit` | screenshots, semantic snapshot, tap/type, recent logs — UI verification of a running debug build | -1. At session start register roots: `whisper`, `../whisper_openapi_client_dart`, `../whisper_websocket_client_dart`. +1. At session start register roots: `shept`, `../shept_openapi_client_dart`, `../shept_websocket_client_dart`. 2. MCP-driven runs use a fixed port so the toolkit can attach: `flutter run -d linux --device-vmservice-port=8181`. One running instance only. 3. UI work: `fmt_semantic_snapshot` → `ref` → `fmt_tap_widget`/`fmt_enter_text`, then hot reload after every widget change. Pixel capture is unsupported on Linux desktop (needs the app permission bridge), so use `fmt_hot_reload_flutter`, not `fmt_hot_reload_and_capture`. 4. Never call `fmt_evaluate_dart_expression`; it is denied in the OpenCode `permissions` config and there is no server-side flag for it. @@ -33,7 +33,7 @@ not in this repository). Use them for the fast loop, but the shell gates below s ## Hard rules 1. Never commit secrets, keys, `.env*`, `firebase_options.dart`, `google-services.json` or `firebase.json`. -2. Do not edit `whisper_openapi_client_dart/lib` or `whisper_websocket_client_dart/lib` by hand. Contract changes go through `whisper-server` and regeneration (skill `contract-change`). +2. Do not edit `shept_openapi_client_dart/lib` or `shept_websocket_client_dart/lib` by hand. Contract changes go through `shept-server` and regeneration (skill `contract-change`). 3. `lib/media_download.dart` is a hand-written extension of the generated client — when the download changes, edit this file, not the generated `downloadMedia`. 4. Crypto: never lower RSA 4096, AES-256-GCM or PBKDF2 parameters. No key may leave the device in plaintext and no seed may be constant. 5. Do not weaken the app lock (password, biometrics), not even "temporarily for debugging". diff --git a/README.md b/README.md index 15c66cc..20e255e 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ -# whisper +# shept Secure private self-hosted end-to-end encryption messaging app. -For Whisper server, see [whisper-server](https://github.com/jsfraz/whisper-server) repository. +For Shept server, see [shept-server](https://github.com/jsfraz/shept-server) repository. -Also see [Wiki](https://github.com/jsfraz/whisper/wiki)! +Also see [Wiki](https://github.com/jsfraz/shept/wiki)! | | | | |---|---|---| @@ -33,7 +33,7 @@ to sign in to a server that requires a newer client. ## Download -You can download the app [here in the releases](https://github.com/jsfraz/whisper/releases). +You can download the app [here in the releases](https://github.com/jsfraz/shept/releases). ## AI / MCP tooling @@ -124,10 +124,10 @@ Known limitations (Linux desktop, verified): - used for launching URLs - [vibration](https://pub.dev/packages/vibration) - used for device vibration feedback -- [whisper_openapi_client_dart](https://github.com/jsfraz/whisper_openapi_client_dart) - - used for API communication with Whisper server -- [whisper_websocket_client_dart](https://github.com/jsfraz/whisper_websocket_client_dart) - - used for real-time WebSocket communication with Whisper server +- [shept_openapi_client_dart](https://github.com/jsfraz/shept_openapi_client_dart) + - used for API communication with Shept server +- [shept_websocket_client_dart](https://github.com/jsfraz/shept_websocket_client_dart) + - used for real-time WebSocket communication with Shept server ### Dev dependencies @@ -155,7 +155,7 @@ Known limitations (Linux desktop, verified): - [Firebase](https://firebase.google.com/) - used for push notifications when user is offline - see [Firebase setup for Flutter](https://firebase.google.com/docs/flutter/setup) and [Firebase Cloud Messaging for Flutter](https://firebase.google.com/docs/cloud-messaging/flutter/client) for more details how to implement this - - app specific configuration files [are not included](.gitignore) in the repository, you need to create them yourself if you plan self host Whisper (refer to [whisper-server](https://github.com/jsfraz/whisper-server) repository for more details) + - app specific configuration files [are not included](.gitignore) in the repository, you need to create them yourself if you plan self host Shept (refer to [shept-server](https://github.com/jsfraz/shept-server) repository for more details) ### Development @@ -169,8 +169,8 @@ Or run this for the development environment: ```bash flutterfire configure \ - --android-package-name cz.josefraz.whisper.debug \ - --ios-bundle-id cz.josefraz.whisper.debug + --android-package-name cz.josefraz.shept.debug \ + --ios-bundle-id cz.josefraz.shept.debug ``` Then select your Firebase project. This will generate the necessary `firebase.json` and `lib/firebase_options.dart` files. @@ -198,8 +198,8 @@ Release builds are signed with the debug key unless `android/key.properties` exists (copy `android/key.properties.example`). A keystore is never committed: ```bash -keytool -genkeypair -v -keystore whisper-release.jks -keyalg RSA -keysize 4096 \ - -validity 10000 -alias whisper +keytool -genkeypair -v -keystore shept-release.jks -keyalg RSA -keysize 4096 \ + -validity 10000 -alias shept cp android/key.properties.example android/key.properties # then fill it in ``` @@ -210,7 +210,7 @@ release workflow fails when the `v` tag for the current (and the build number after `+`) before every release. iOS push notifications need the *Push Notifications* capability on the -`cz.josefraz.whisper` App ID; `ios/Runner/Runner.entitlements` is already wired +`cz.josefraz.shept` App ID; `ios/Runner/Runner.entitlements` is already wired into the project. Pull requests from forks cannot read repository secrets, so CI is skipped for them. diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 8dc7282..8ee24ee 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -22,7 +22,7 @@ if (hasReleaseKeystore) { } android { - namespace = "cz.josefraz.whisper" + namespace = "cz.josefraz.shept" // flutter_local_notifications 23 requires compiling against API 37. compileSdk = 37 ndkVersion = flutter.ndkVersion @@ -37,7 +37,7 @@ android { } defaultConfig { - applicationId = "cz.josefraz.whisper" + applicationId = "cz.josefraz.shept" // You can update the following values to match your application needs. // For more information, see: https://flutter.dev/to/review-gradle-config. minSdk = flutter.minSdkVersion @@ -62,7 +62,7 @@ android { // Different applicationId for debug version applicationIdSuffix = ".debug" // Add suffix - resValue("string", "app_name", "Whisper Debug") + resValue("string", "app_name", "Shept Debug") } release { signingConfig = if (hasReleaseKeystore) { @@ -71,7 +71,7 @@ android { logger.warn("key.properties not found, the release APK is signed with the debug key") signingConfigs.getByName("debug") } - resValue("string", "app_name", "Whisper") + resValue("string", "app_name", "Shept") } } } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index b0e209e..0dc541c 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -28,10 +28,10 @@ + android:resource="@drawable/ic_stat_shept" /> + android:value="shept_firebase_messages" /> diff --git a/android/app/src/main/kotlin/com/example/whisper/MainActivity.kt b/android/app/src/main/kotlin/cz/josefraz/shept/MainActivity.kt similarity index 97% rename from android/app/src/main/kotlin/com/example/whisper/MainActivity.kt rename to android/app/src/main/kotlin/cz/josefraz/shept/MainActivity.kt index 9f2e64b..bf77f84 100644 --- a/android/app/src/main/kotlin/com/example/whisper/MainActivity.kt +++ b/android/app/src/main/kotlin/cz/josefraz/shept/MainActivity.kt @@ -1,4 +1,4 @@ -package cz.josefraz.whisper +package cz.josefraz.shept import android.database.ContentObserver import android.net.Uri @@ -21,7 +21,7 @@ class MainActivity : FlutterFragmentActivity() { override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) val methodChannel = - MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "whisper/secure_screen") + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "shept/secure_screen") channel = methodChannel methodChannel.setMethodCallHandler { call, result -> when (call.method) { diff --git a/android/app/src/main/res/drawable-hdpi/ic_stat_whisper.png b/android/app/src/main/res/drawable-hdpi/ic_stat_shept.png similarity index 100% rename from android/app/src/main/res/drawable-hdpi/ic_stat_whisper.png rename to android/app/src/main/res/drawable-hdpi/ic_stat_shept.png diff --git a/android/app/src/main/res/drawable-mdpi/ic_stat_whisper.png b/android/app/src/main/res/drawable-mdpi/ic_stat_shept.png similarity index 100% rename from android/app/src/main/res/drawable-mdpi/ic_stat_whisper.png rename to android/app/src/main/res/drawable-mdpi/ic_stat_shept.png diff --git a/android/app/src/main/res/drawable-xhdpi/ic_stat_whisper.png b/android/app/src/main/res/drawable-xhdpi/ic_stat_shept.png similarity index 100% rename from android/app/src/main/res/drawable-xhdpi/ic_stat_whisper.png rename to android/app/src/main/res/drawable-xhdpi/ic_stat_shept.png diff --git a/android/app/src/main/res/drawable-xxhdpi/ic_stat_whisper.png b/android/app/src/main/res/drawable-xxhdpi/ic_stat_shept.png similarity index 100% rename from android/app/src/main/res/drawable-xxhdpi/ic_stat_whisper.png rename to android/app/src/main/res/drawable-xxhdpi/ic_stat_shept.png diff --git a/android/app/src/main/res/drawable-xxxhdpi/ic_stat_whisper.png b/android/app/src/main/res/drawable-xxxhdpi/ic_stat_shept.png similarity index 100% rename from android/app/src/main/res/drawable-xxxhdpi/ic_stat_whisper.png rename to android/app/src/main/res/drawable-xxxhdpi/ic_stat_shept.png diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 3916c4f..f1ffb0e 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -1,4 +1,4 @@ - Whisper + Shept \ No newline at end of file diff --git a/android/key.properties.example b/android/key.properties.example index ce65bec..a5cc517 100644 --- a/android/key.properties.example +++ b/android/key.properties.example @@ -2,11 +2,11 @@ # key.properties is gitignored; never commit the keystore or these values. # # Generate a keystore once: -# keytool -genkeypair -v -keystore whisper-release.jks -keyalg RSA \ -# -keysize 4096 -validity 10000 -alias whisper +# keytool -genkeypair -v -keystore shept-release.jks -keyalg RSA \ +# -keysize 4096 -validity 10000 -alias shept # # storeFile is relative to android/. -storeFile=../whisper-release.jks +storeFile=../shept-release.jks storePassword=CHANGE_ME -keyAlias=whisper +keyAlias=shept keyPassword=CHANGE_ME diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 2dec36b..5a22c96 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -90,7 +90,7 @@ "newMessagesBody": "Máte nové zprávy v chatu", "notificationChannelDesc": "Oznámení pro nové zprávy v chatu", "tickerLocalNotifications": "Nové zprávy v chatu", - "whisperLocalNotificationSingleMessage": "Máte novou zprávu v chatu", + "sheptLocalNotificationSingleMessage": "Máte novou zprávu v chatu", "offlineTrue": "Jste offline :(", "offlineFalse": "Jste zpět online :)", "decryptionFailed": "Dešifrování selhalo", diff --git a/assets/translations/en.json b/assets/translations/en.json index e95231c..6a71477 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -90,7 +90,7 @@ "newMessagesBody": "You have new messages in chat", "notificationChannelDesc": "Notifications for new messages in chat", "tickerLocalNotifications": "New messages in chat", - "whisperLocalNotificationSingleMessage": "You have a new message in chat", + "sheptLocalNotificationSingleMessage": "You have a new message in chat", "offlineTrue": "You are offline :(", "offlineFalse": "You are back online :)", "decryptionFailed": "Decryption failed", diff --git a/integration_test/app_e2e_test.dart b/integration_test/app_e2e_test.dart index a42199b..fc1d4d1 100644 --- a/integration_test/app_e2e_test.dart +++ b/integration_test/app_e2e_test.dart @@ -9,16 +9,16 @@ import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; import 'package:integration_test/integration_test.dart'; import 'package:pointycastle/export.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper/utils/crypto_utils.dart'; -import 'package:whisper/utils/media_utils.dart'; -import 'package:whisper/utils/utils.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; -import 'package:whisper_websocket_client_dart/models/new_private_message.dart'; -import 'package:whisper_websocket_client_dart/models/private_message.dart'; -import 'package:whisper_websocket_client_dart/models/ws_message.dart'; -import 'package:whisper_websocket_client_dart/models/ws_response.dart'; -import 'package:whisper_websocket_client_dart/ws_client.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/crypto_utils.dart'; +import 'package:shept/utils/media_utils.dart'; +import 'package:shept/utils/utils.dart'; +import 'package:shept_openapi_client_dart/api.dart'; +import 'package:shept_websocket_client_dart/models/new_private_message.dart'; +import 'package:shept_websocket_client_dart/models/private_message.dart'; +import 'package:shept_websocket_client_dart/models/ws_message.dart'; +import 'package:shept_websocket_client_dart/models/ws_response.dart'; +import 'package:shept_websocket_client_dart/ws_client.dart'; import 'fake_server.dart'; diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 5832e62..6526cd9 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -372,7 +372,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.whisper; + PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.shept; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; @@ -388,7 +388,7 @@ CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.whisper.RunnerTests; + PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.shept.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -405,7 +405,7 @@ CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.whisper.RunnerTests; + PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.shept.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; @@ -420,7 +420,7 @@ CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.whisper.RunnerTests; + PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.shept.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; @@ -552,7 +552,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.whisper; + PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.shept; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -575,7 +575,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.whisper; + PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.shept; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index e43d49d..a09d74a 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -5,7 +5,7 @@ CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleDisplayName - Whisper + Shept CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier @@ -13,7 +13,7 @@ CFBundleInfoDictionaryVersion 6.0 CFBundleName - whisper + shept CFBundlePackageType APPL CFBundleShortVersionString @@ -42,13 +42,13 @@ UIInterfaceOrientationLandscapeRight NSCameraUsageDescription - Whisper needs camera access to capture photos and videos you send in chats. + Shept needs camera access to capture photos and videos you send in chats. NSMicrophoneUsageDescription - Whisper needs microphone access to record voice messages. + Shept needs microphone access to record voice messages. NSPhotoLibraryUsageDescription - Whisper needs photo library access to attach images and videos to your messages. + Shept needs photo library access to attach images and videos to your messages. NSFaceIDUsageDescription - Whisper uses Face ID to unlock your encrypted messages. + Shept uses Face ID to unlock your encrypted messages. LSApplicationQueriesSchemes https diff --git a/lib/main.dart b/lib/main.dart index e1801d7..caee3f8 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -19,7 +19,7 @@ import 'models/app_theme.dart'; import 'models/private_message.dart'; import 'models/profile.dart'; import 'models/user.dart'; -import 'pages/whisper_page.dart'; +import 'pages/shept_page.dart'; import 'utils/media_utils.dart'; import 'utils/storage_utils.dart'; import 'utils/notification_service.dart'; @@ -107,7 +107,7 @@ void main() async { supportedLocales: const [Locale('en'), Locale('cs')], path: 'assets/translations', fallbackLocale: const Locale('en'), - child: WhisperPage(), + child: SheptPage(), ), ), ); diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index cd5555d..4a58b21 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -2,8 +2,8 @@ import 'dart:convert'; import 'package:easy_localization/easy_localization.dart'; import 'package:hive/hive.dart'; -import 'package:whisper_websocket_client_dart/models/media_reference.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; import '../utils/singleton.dart'; import '../utils/text_envelope.dart'; @@ -392,7 +392,7 @@ class PrivateMessage extends HiveObject { /// Stored instead of the text when a message cannot be decrypted. It keeps a /// visible gap in the chat, and the receiver only acks what it stored, so the /// server still has the ciphertext. - static const String undecryptableMarker = '\uE000whisper-undecryptable'; + static const String undecryptableMarker = '\uE000shept-undecryptable'; bool get isMe => senderId == Singleton().profile.user.id; diff --git a/lib/models/user.dart b/lib/models/user.dart index 76edb3b..3b92716 100644 --- a/lib/models/user.dart +++ b/lib/models/user.dart @@ -1,7 +1,7 @@ import 'dart:ui'; import 'package:hive/hive.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/api.dart'; import '../utils/color_utils.dart'; diff --git a/lib/pages/chat_media_page.dart b/lib/pages/chat_media_page.dart index 003f74a..f9797b4 100644 --- a/lib/pages/chat_media_page.dart +++ b/lib/pages/chat_media_page.dart @@ -2,7 +2,7 @@ import 'dart:typed_data'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../utils/cache_utils.dart'; import '../utils/media_utils.dart'; diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 9a434fb..b04748f 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -11,7 +11,7 @@ import 'package:path_provider/path_provider.dart'; import 'package:sprintf/sprintf.dart'; import '../utils/dialog_utils.dart'; import '../utils/nav_transitions.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../models/user.dart'; import '../utils/cache_utils.dart'; @@ -1309,7 +1309,7 @@ class _ChatPageState extends State { } final dir = await getTemporaryDirectory(); final path = - '${dir.path}/whisper_edited_${DateTime.now().microsecondsSinceEpoch}.png'; + '${dir.path}/shept_edited_${DateTime.now().microsecondsSinceEpoch}.png'; return File(path)..writeAsBytesSync(edited, flush: true); } if (!mounted) { diff --git a/lib/pages/devices_page.dart b/lib/pages/devices_page.dart index 6f93fa8..add49f2 100644 --- a/lib/pages/devices_page.dart +++ b/lib/pages/devices_page.dart @@ -1,7 +1,7 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/api.dart'; import '../utils/singleton.dart'; import '../utils/utils.dart'; diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index a7bf7ae..be52b90 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -19,7 +19,7 @@ import 'search_user_page.dart'; import 'settings_page.dart'; import '../utils/dialog_utils.dart'; import '../widgets/invite_list_item.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/api.dart'; import '../models/user.dart'; import '../utils/admin_format.dart'; import '../utils/singleton.dart'; diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index de16848..280247e 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -5,7 +5,7 @@ import 'package:chewie/chewie.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:video_player/video_player.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../utils/cache_utils.dart'; diff --git a/lib/pages/password_page.dart b/lib/pages/password_page.dart index 02a7ed4..6ef6a85 100644 --- a/lib/pages/password_page.dart +++ b/lib/pages/password_page.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:whisper_websocket_client_dart/ws_client.dart'; +import 'package:shept_websocket_client_dart/ws_client.dart'; import '../utils/biometric_auth.dart'; import '../utils/cache_utils.dart'; import '../utils/crypto_utils.dart'; diff --git a/lib/pages/register_page.dart b/lib/pages/register_page.dart index eddfeba..c9e8677 100644 --- a/lib/pages/register_page.dart +++ b/lib/pages/register_page.dart @@ -2,11 +2,11 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:whisper_websocket_client_dart/ws_client.dart'; +import 'package:shept_websocket_client_dart/ws_client.dart'; import '../models/invite_data.dart'; import '../models/profile.dart'; import '../models/user.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/api.dart'; import '../utils/biometric_auth.dart'; import '../utils/cache_utils.dart'; import '../utils/crypto_utils.dart'; diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index c4ab3f7..6adc6d8 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -6,7 +6,7 @@ import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:sprintf/sprintf.dart'; import 'package:url_launcher/url_launcher.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/api.dart'; import '../utils/auto_download.dart'; import '../utils/biometric_auth.dart'; import '../utils/cache_utils.dart'; @@ -343,12 +343,12 @@ class _SettingsPageState extends State { icon: Icons.help, label: 'wikiLink'.tr(), onPressed: () => - _openUrl('https://github.com/jsfraz/whisper/wiki'), + _openUrl('https://github.com/jsfraz/shept/wiki'), ), _settingsTile( icon: Icons.code, label: 'repoLink'.tr(), - onPressed: () => _openUrl('https://github.com/jsfraz/whisper'), + onPressed: () => _openUrl('https://github.com/jsfraz/shept'), ), const Divider(thickness: 1, indent: 10, endIndent: 10), _settingsTile( diff --git a/lib/pages/whisper_page.dart b/lib/pages/shept_page.dart similarity index 97% rename from lib/pages/whisper_page.dart rename to lib/pages/shept_page.dart index 2076572..62e8e82 100644 --- a/lib/pages/whisper_page.dart +++ b/lib/pages/shept_page.dart @@ -9,8 +9,8 @@ import '../pages/scan_invite_button_page.dart'; import 'password_page.dart'; import '../utils/cache_utils.dart'; -class WhisperPage extends StatelessWidget { - const WhisperPage({super.key}); +class SheptPage extends StatelessWidget { + const SheptPage({super.key}); /// Fade-through everywhere so `MaterialPageRoute` pushes (forward, search, /// registration) use the same timing as the rest of the app. diff --git a/lib/utils/auto_download.dart b/lib/utils/auto_download.dart index a8d3a7d..1a0c969 100644 --- a/lib/utils/auto_download.dart +++ b/lib/utils/auto_download.dart @@ -1,6 +1,6 @@ import 'package:connectivity_plus/connectivity_plus.dart'; -import 'package:whisper_websocket_client_dart/models/media_reference.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; import 'cache_utils.dart'; diff --git a/lib/utils/biometric_auth.dart b/lib/utils/biometric_auth.dart index 236f3bd..1fb4aa2 100644 --- a/lib/utils/biometric_auth.dart +++ b/lib/utils/biometric_auth.dart @@ -10,7 +10,7 @@ import 'cache_utils.dart'; class BiometricAuth { static final LocalAuthentication _auth = LocalAuthentication(); static const FlutterSecureStorage _secureStorage = FlutterSecureStorage(); - static const String _biometricKeyStorageKey = 'whisper_secure_key'; + static const String _biometricKeyStorageKey = 'shept_secure_key'; /// Checks if biometric authentication is available on the device static Future isBiometricAvailable() async { diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 1b64b7e..adbb85b 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -33,8 +33,8 @@ class CacheUtils { static const _presenceKey = 'presence'; static const _biometry = 'biometry'; static const _playbackSpeed = 'playbackSpeed'; - static const String _saltStorageKey = 'whisper_pbkdf2_salt'; - static const String _deviceIdKey = 'whisper_device_id'; + static const String _saltStorageKey = 'shept_pbkdf2_salt'; + static const String _deviceIdKey = 'shept_device_id'; static const String _syncSeqKey = 'syncSeq'; static const String _syncEventSeqKey = 'syncEventSeq'; static const FlutterSecureStorage _secureStorage = FlutterSecureStorage(); diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index 02c5e23..9e173c5 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -5,10 +5,10 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:whisper_websocket_client_dart/models/media_reference.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; -import 'package:whisper_websocket_client_dart/models/new_private_message.dart'; -import 'package:whisper_websocket_client_dart/models/ws_message.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; +import 'package:shept_websocket_client_dart/models/new_private_message.dart'; +import 'package:shept_websocket_client_dart/models/ws_message.dart'; import '../models/private_message.dart'; import '../models/user.dart'; diff --git a/lib/utils/dialog_utils.dart b/lib/utils/dialog_utils.dart index 1aa7bd3..24be7d3 100644 --- a/lib/utils/dialog_utils.dart +++ b/lib/utils/dialog_utils.dart @@ -6,7 +6,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_colorpicker/flutter_colorpicker.dart'; import 'package:provider/provider.dart'; import '../utils/cache_utils.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/api.dart'; import '../widgets/theme_palette.dart'; import 'color_utils.dart'; import 'singleton.dart'; diff --git a/lib/utils/media_autoplay.dart b/lib/utils/media_autoplay.dart index 08da8c0..094f3a3 100644 --- a/lib/utils/media_autoplay.dart +++ b/lib/utils/media_autoplay.dart @@ -1,5 +1,5 @@ import 'package:flutter/foundation.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import 'cache_utils.dart'; diff --git a/lib/utils/media_upload.dart b/lib/utils/media_upload.dart index 41ddecf..0fb4274 100644 --- a/lib/utils/media_upload.dart +++ b/lib/utils/media_upload.dart @@ -4,7 +4,7 @@ import 'dart:typed_data'; import 'package:easy_localization/easy_localization.dart'; import 'package:http/http.dart' as http; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/api.dart'; import 'cache_utils.dart'; import 'media_utils.dart'; diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 58807b7..53d161b 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -14,8 +14,8 @@ import 'package:path_provider/path_provider.dart'; import 'package:record/record.dart'; import 'package:uuid/uuid.dart'; import 'package:video_player/video_player.dart'; -import 'package:whisper_websocket_client_dart/models/media_reference.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; import 'singleton.dart'; import 'utils.dart'; @@ -301,7 +301,7 @@ class MediaUtils { static Future materializeTempFile(String path, String extension) async { final bytes = await decryptAtRest(path); final tmpDir = await getTemporaryDirectory(); - final file = File('${tmpDir.path}/whisper_media_${_uuid.v4()}$extension'); + final file = File('${tmpDir.path}/shept_media_${_uuid.v4()}$extension'); await file.writeAsBytes(bytes, flush: true); return file; } @@ -322,14 +322,14 @@ class MediaUtils { /// which must only hold encrypted files. static Future writeTempBytes(Uint8List bytes, String extension) async { final tmpDir = await getTemporaryDirectory(); - final file = File('${tmpDir.path}/whisper_send_${_uuid.v4()}.$extension'); + final file = File('${tmpDir.path}/shept_send_${_uuid.v4()}.$extension'); await file.writeAsBytes(bytes, flush: true); return file; } /// Whether a file name belongs to the app's plaintext temp files. static bool isTempMediaName(String name) => - name.startsWith('whisper_media_') || name.startsWith('whisper_send_'); + name.startsWith('shept_media_') || name.startsWith('shept_send_'); /// Remove plaintext media left in the temp directory. /// @@ -585,7 +585,7 @@ class MediaUtils { static Uint8List buildMediaEnvelope(MediaReference reference, String caption, {bool forwarded = false, bool viewOnce = false}) { final map = { - 'whisperMsg': envelopeVersion, + 'sheptMsg': envelopeVersion, 'kind': 'media', 'caption': caption, 'media': reference.toJson(), @@ -601,7 +601,7 @@ class MediaUtils { List references, String caption, {bool forwarded = false, bool viewOnce = false}) { final map = { - 'whisperMsg': envelopeVersionAlbum, + 'sheptMsg': envelopeVersionAlbum, 'kind': 'media', 'caption': caption, 'media': references.map((reference) => reference.toJson()).toList(), @@ -620,14 +620,14 @@ class MediaUtils { final caption = (decoded['caption'] as String?) ?? ''; final forwarded = decoded['forwarded'] == true; final viewOnce = decoded['viewOnce'] == true; - if (decoded['whisperMsg'] == envelopeVersion && + if (decoded['sheptMsg'] == envelopeVersion && decoded['media'] is Map) { final reference = MediaReference.fromJson( Map.from(decoded['media'] as Map)); return ParsedMediaEnvelope([reference], caption, forwarded: forwarded, viewOnce: viewOnce); } - if (decoded['whisperMsg'] == envelopeVersionAlbum && + if (decoded['sheptMsg'] == envelopeVersionAlbum && decoded['media'] is List) { final references = (decoded['media'] as List) .whereType() @@ -721,7 +721,7 @@ class MediaRecorderController { /// Start recording to a temporary .m4a file. Future start() async { final dir = await getTemporaryDirectory(); - _path = '${dir.path}/whisper_voice_${const Uuid().v4()}.m4a'; + _path = '${dir.path}/shept_voice_${const Uuid().v4()}.m4a'; await _recorder.start( const RecordConfig(encoder: AudioEncoder.aacLc, numChannels: 1), path: _path!, diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 13b8e3c..0407320 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -10,8 +10,8 @@ import 'package:fluttertoast/fluttertoast.dart'; import 'package:path_provider/path_provider.dart'; import 'package:share_plus/share_plus.dart'; import 'package:url_launcher/url_launcher.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; +import 'package:shept_openapi_client_dart/api.dart'; import '../models/private_message.dart'; import '../pages/forward_page.dart'; @@ -482,7 +482,7 @@ class MessageActions { final bytes = await MediaUtils.decryptAtRest(path); final dir = await getTemporaryDirectory(); final file = File( - '${dir.path}/whisper_send_share_${message.sentAt.microsecondsSinceEpoch}${MediaUtils.extensionForType(message.mediaType ?? MediaType.file)}'); + '${dir.path}/shept_send_share_${message.sentAt.microsecondsSinceEpoch}${MediaUtils.extensionForType(message.mediaType ?? MediaType.file)}'); await file.writeAsBytes(bytes, flush: true); await SharePlus.instance.share(ShareParams( files: [XFile(file.path)], @@ -507,7 +507,7 @@ class MessageActions { final saved = await FilePicker.saveFile( dialogTitle: 'saveAttachment'.tr(), fileName: message.fileName ?? - 'whisper_${message.sentAt.millisecondsSinceEpoch}${MediaUtils.extensionForType(type)}', + 'shept_${message.sentAt.millisecondsSinceEpoch}${MediaUtils.extensionForType(type)}', bytes: bytes, ); if (saved == null) { diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index 42c8608..03c08b1 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -1,10 +1,10 @@ import 'dart:convert'; import 'package:flutter/material.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; -import 'package:whisper_openapi_client_dart/media_download.dart'; -import 'package:whisper_websocket_client_dart/models/media_reference.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/media_download.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; import '../utils/notification_service.dart'; import '../models/private_message.dart'; diff --git a/lib/utils/notification_service.dart b/lib/utils/notification_service.dart index 4141826..57a5e93 100644 --- a/lib/utils/notification_service.dart +++ b/lib/utils/notification_service.dart @@ -19,10 +19,10 @@ class NotificationService { /// Init notification settings Future init() async { const AndroidInitializationSettings initializationSettingsAndroid = - AndroidInitializationSettings('ic_stat_whisper'); + AndroidInitializationSettings('ic_stat_shept'); final LinuxInitializationSettings initializationSettingsLinux = LinuxInitializationSettings( - defaultActionName: 'whisper_message', + defaultActionName: 'shept_message', defaultIcon: ThemeLinuxIcon('mail-unread'), ); // Asks for alert/badge/sound permission on iOS and macOS. @@ -55,8 +55,8 @@ class NotificationService { .resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(AndroidNotificationChannel( - 'whisper_firebase_messages', - 'Whisper', + 'shept_firebase_messages', + 'Shept', description: 'notificationChannelDesc'.tr(), importance: Importance.max, sound: const RawResourceAndroidNotificationSound('notification'), @@ -146,8 +146,8 @@ class NotificationService { 'xMessagesFromYChats'.tr(), [totalMessageCount, chatCount])); AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails( - 'whisperLocalNotificationMultipleMessages', - 'whisperLocalNotificationMultipleMessages'.tr(), + 'sheptLocalNotificationMultipleMessages', + 'sheptLocalNotificationMultipleMessages'.tr(), groupKey: 'cz.josefraz.flutter_push_notifications_multiple_messages', channelDescription: 'notificationChannelDesc'.tr(), setAsGroupSummary: true, @@ -176,8 +176,8 @@ class NotificationService { AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails( - 'whisperLocalNotificationSingleMessage', - 'whisperLocalNotificationSingleMessage'.tr(), + 'sheptLocalNotificationSingleMessage', + 'sheptLocalNotificationSingleMessage'.tr(), groupKey: 'cz.josefraz.flutter_push_notifications_single_message', channelDescription: 'notificationChannelDesc'.tr(), importance: Importance.max, @@ -207,8 +207,8 @@ class NotificationService { Future showSecurityNotification(String title, String body) async { AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails( - 'whisperLocalNotificationSecurity', - 'whisperLocalNotificationSecurity'.tr(), + 'sheptLocalNotificationSecurity', + 'sheptLocalNotificationSecurity'.tr(), channelDescription: 'notificationChannelDesc'.tr(), importance: Importance.high, priority: Priority.high, diff --git a/lib/utils/screen_guard.dart b/lib/utils/screen_guard.dart index 063cb6d..c461ee7 100644 --- a/lib/utils/screen_guard.dart +++ b/lib/utils/screen_guard.dart @@ -6,7 +6,7 @@ import 'package:flutter/services.dart'; /// target where the block is enforceable, so on every other platform both calls /// are a no-op. class ScreenGuard { - static const MethodChannel _channel = MethodChannel('whisper/secure_screen'); + static const MethodChannel _channel = MethodChannel('shept/secure_screen'); /// Called when the platform noticed a screenshot. static VoidCallback? onScreenshot; diff --git a/lib/utils/singleton.dart b/lib/utils/singleton.dart index da125b1..e65f175 100644 --- a/lib/utils/singleton.dart +++ b/lib/utils/singleton.dart @@ -4,8 +4,8 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:http/io_client.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; -import 'package:whisper_websocket_client_dart/ws_client.dart'; +import 'package:shept_openapi_client_dart/api.dart'; +import 'package:shept_websocket_client_dart/ws_client.dart'; import '../models/app_theme.dart'; import 'version.dart'; import '../models/profile.dart'; diff --git a/lib/utils/text_envelope.dart b/lib/utils/text_envelope.dart index 84abeb7..691ba96 100644 --- a/lib/utils/text_envelope.dart +++ b/lib/utils/text_envelope.dart @@ -118,7 +118,7 @@ const int textEnvelopeVersion = 3; Uint8List buildTextEnvelope(String body, ReplyRef? reply, {bool forwarded = false, LocationRef? location, bool viewOnce = false}) { final map = { - 'whisperMsg': textEnvelopeVersion, + 'sheptMsg': textEnvelopeVersion, 'kind': 'text', 'body': body, if (reply != null) 'replyTo': reply.toJson(), @@ -136,7 +136,7 @@ ParsedTextEnvelope? tryParseTextEnvelope(Uint8List plaintext) { final decoded = jsonDecode(utf8.decode(plaintext)); if (decoded is Map && decoded['kind'] == 'text' && - decoded['whisperMsg'] == textEnvelopeVersion) { + decoded['sheptMsg'] == textEnvelopeVersion) { final body = decoded['body']; if (body is! String) { return null; @@ -178,7 +178,7 @@ class ParsedSystemEnvelope { /// acceptance or a refusal. Uint8List buildSystemEnvelope(String state, int seconds) { final map = { - 'whisperMsg': systemEnvelopeVersion, + 'sheptMsg': systemEnvelopeVersion, 'kind': 'system', 'action': systemActionDisappearing, 'state': state, @@ -193,7 +193,7 @@ ParsedSystemEnvelope? tryParseSystemEnvelope(Uint8List plaintext) { final decoded = jsonDecode(utf8.decode(plaintext)); if (decoded is! Map || decoded['kind'] != 'system' || - decoded['whisperMsg'] != systemEnvelopeVersion || + decoded['sheptMsg'] != systemEnvelopeVersion || decoded['action'] != systemActionDisappearing) { return null; } diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 8813ac4..f7f5001 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -11,19 +11,19 @@ import 'package:path_provider/path_provider.dart'; import 'package:vibration/vibration.dart'; import '../utils/notification_service.dart'; import '../pages/chat_page.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/api.dart'; import 'package:basic_utils/basic_utils.dart' as bu; -import 'package:whisper_websocket_client_dart/models/delivery_ack.dart'; -import 'package:whisper_websocket_client_dart/models/live_location.dart'; -import 'package:whisper_websocket_client_dart/models/message_event.dart'; -import 'package:whisper_websocket_client_dart/models/presence.dart'; -import 'package:whisper_websocket_client_dart/models/read_receipt.dart'; -import 'package:whisper_websocket_client_dart/models/synced.dart'; -import 'package:whisper_websocket_client_dart/models/typing.dart'; -import 'package:whisper_websocket_client_dart/models/media_reference.dart'; -import 'package:whisper_websocket_client_dart/models/private_message.dart'; -import 'package:whisper_websocket_client_dart/models/ws_response.dart'; -import 'package:whisper_websocket_client_dart/models/ws_response_type.dart'; +import 'package:shept_websocket_client_dart/models/delivery_ack.dart'; +import 'package:shept_websocket_client_dart/models/live_location.dart'; +import 'package:shept_websocket_client_dart/models/message_event.dart'; +import 'package:shept_websocket_client_dart/models/presence.dart'; +import 'package:shept_websocket_client_dart/models/read_receipt.dart'; +import 'package:shept_websocket_client_dart/models/synced.dart'; +import 'package:shept_websocket_client_dart/models/typing.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/private_message.dart'; +import 'package:shept_websocket_client_dart/models/ws_response.dart'; +import 'package:shept_websocket_client_dart/models/ws_response_type.dart'; import 'auto_download.dart'; import 'cache_utils.dart'; import 'chat_sender.dart'; @@ -117,7 +117,7 @@ class Utils { /// Gets cache directory path static Future getCacheDir() async { Directory dir = await getApplicationDocumentsDirectory(); - return '${dir.path}/whisper'; + return '${dir.path}/shept'; } /// In-flight token renewal. Concurrent callers (a resume fires several API diff --git a/lib/widgets/invite_list_item.dart b/lib/widgets/invite_list_item.dart index 7f7b77f..d9de47b 100644 --- a/lib/widgets/invite_list_item.dart +++ b/lib/widgets/invite_list_item.dart @@ -3,7 +3,7 @@ import 'dart:async'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:sprintf/sprintf.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/api.dart'; import '../utils/admin_format.dart'; diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart index b80da32..92223d4 100644 --- a/lib/widgets/media_bubble.dart +++ b/lib/widgets/media_bubble.dart @@ -7,7 +7,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import '../utils/nav_transitions.dart'; import 'package:video_player/video_player.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../pages/media_viewer_page.dart'; diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt index a886388..2584b5c 100644 --- a/linux/CMakeLists.txt +++ b/linux/CMakeLists.txt @@ -4,10 +4,10 @@ project(runner LANGUAGES CXX) # The name of the executable created for the application. Change this to change # the on-disk name of your application. -set(BINARY_NAME "whisper") +set(BINARY_NAME "shept") # The unique GTK application identifier for this application. See: # https://wiki.gnome.org/HowDoI/ChooseApplicationID -set(APPLICATION_ID "cz.josefraz.whisper") +set(APPLICATION_ID "cz.josefraz.shept") # Explicitly opt in to modern CMake behaviors to avoid warnings with recent # versions of CMake. diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc index 99c7a7f..7a69f32 100644 --- a/linux/runner/my_application.cc +++ b/linux/runner/my_application.cc @@ -45,11 +45,11 @@ static void my_application_activate(GApplication* application) { if (use_header_bar) { GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); gtk_widget_show(GTK_WIDGET(header_bar)); - gtk_header_bar_set_title(header_bar, "whisper"); + gtk_header_bar_set_title(header_bar, "shept"); gtk_header_bar_set_show_close_button(header_bar, TRUE); gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); } else { - gtk_window_set_title(window, "whisper"); + gtk_window_set_title(window, "shept"); } gtk_window_set_default_size(window, 1280, 720); diff --git a/pubspec.lock b/pubspec.lock index 52dfc79..031829b 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1588,6 +1588,20 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.1" + shept_openapi_client_dart: + dependency: "direct main" + description: + path: "../shept_openapi_client_dart" + relative: true + source: path + version: "0.5.0" + shept_websocket_client_dart: + dependency: "direct main" + description: + path: "../shept_websocket_client_dart" + relative: true + source: path + version: "0.5.0" sky_engine: dependency: transitive description: flutter @@ -1929,20 +1943,6 @@ packages: url: "https://pub.dev" source: hosted version: "3.2.0" - whisper_openapi_client_dart: - dependency: "direct main" - description: - path: "../whisper_openapi_client_dart" - relative: true - source: path - version: "0.5.0" - whisper_websocket_client_dart: - dependency: "direct main" - description: - path: "../whisper_websocket_client_dart" - relative: true - source: path - version: "0.7.0" win32: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index ee8c52a..3ce625f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,4 +1,4 @@ -name: whisper +name: shept description: "Secure private self-hosted end-to-end encryption messaging app." publish_to: 'none' # Remove this line if you wish to publish to pub.dev # Bump before every release; the release workflow tags v and fails if @@ -55,14 +55,14 @@ dependencies: video_player: ^2.11.1 # Clients are pinned by release tag: the app records which contract it was # built against. Local development overrides the paths at the bottom. - whisper_openapi_client_dart: + shept_openapi_client_dart: git: - url: https://github.com/jsfraz/whisper_openapi_client_dart.git + url: https://github.com/jsfraz/shept_openapi_client_dart.git ref: v0.5.0 - whisper_websocket_client_dart: + shept_websocket_client_dart: git: - url: https://github.com/jsfraz/whisper_websocket_client_dart.git - ref: v0.7.0 + url: https://github.com/jsfraz/shept_websocket_client_dart.git + ref: v0.5.0 dev_dependencies: flutter_test: diff --git a/test/admin_format_test.dart b/test/admin_format_test.dart index ae7b561..1e04adf 100644 --- a/test/admin_format_test.dart +++ b/test/admin_format_test.dart @@ -1,6 +1,6 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/admin_format.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/admin_format.dart'; User user(String name) => User(name, name, 'public-key', false); diff --git a/test/admin_user_list_item_test.dart b/test/admin_user_list_item_test.dart index e8967ca..c1f8b19 100644 --- a/test/admin_user_list_item_test.dart +++ b/test/admin_user_list_item_test.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/widgets/admin_user_list_item.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/widgets/admin_user_list_item.dart'; Widget app(User user, VoidCallback onDelete) { return MaterialApp( diff --git a/test/api_client_test.dart b/test/api_client_test.dart index 4ef219a..d89a2f7 100644 --- a/test/api_client_test.dart +++ b/test/api_client_test.dart @@ -1,6 +1,6 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:http/io_client.dart'; -import 'package:whisper/utils/singleton.dart'; +import 'package:shept/utils/singleton.dart'; void main() { // The generated client has no timeout of its own; the app has to install a diff --git a/test/attachment_confirm_sheet_test.dart b/test/attachment_confirm_sheet_test.dart index a85c45d..0957d35 100644 --- a/test/attachment_confirm_sheet_test.dart +++ b/test/attachment_confirm_sheet_test.dart @@ -1,7 +1,7 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/widgets/attachment_confirm_sheet.dart'; +import 'package:shept/widgets/attachment_confirm_sheet.dart'; // easy_localization reads the locale from shared_preferences, its transitive dep // ignore: depend_on_referenced_packages import 'package:shared_preferences/shared_preferences.dart'; diff --git a/test/auth_refresh_fallback_test.dart b/test/auth_refresh_fallback_test.dart index 6d6a2db..de8b492 100644 --- a/test/auth_refresh_fallback_test.dart +++ b/test/auth_refresh_fallback_test.dart @@ -6,13 +6,13 @@ import 'package:pointycastle/export.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/models/profile.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper/utils/singleton.dart'; -import 'package:whisper/utils/utils.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/utils/utils.dart'; +import 'package:shept_openapi_client_dart/api.dart'; /// flutter_test replaces HttpClient with one that answers 400 and never touches /// the network; this test serves its own backend on loopback. @@ -40,7 +40,7 @@ void main() { const challenge = 'test-challenge-1'; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_auth_fallback_test'); + dir = Directory.systemTemp.createTempSync('shept_auth_fallback_test'); Hive.init(dir.path); Hive.registerAdapter(ProfileAdapter()); Hive.registerAdapter(UserAdapter()); diff --git a/test/auto_download_test.dart b/test/auto_download_test.dart index c8b212d..f032e95 100644 --- a/test/auto_download_test.dart +++ b/test/auto_download_test.dart @@ -3,16 +3,16 @@ import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/utils/auto_download.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper_websocket_client_dart/models/media_reference.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept/utils/auto_download.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; void main() { late Directory dir; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_auto_download_test'); + dir = Directory.systemTemp.createTempSync('shept_auto_download_test'); Hive.init(dir.path); }); diff --git a/test/avatar_rule_test.dart b/test/avatar_rule_test.dart index 05b396a..00ca8ea 100644 --- a/test/avatar_rule_test.dart +++ b/test/avatar_rule_test.dart @@ -4,11 +4,11 @@ import 'package:flutter_test/flutter_test.dart'; // easy_localization reads the locale from shared_preferences, its transitive dep // ignore: depend_on_referenced_packages import 'package:shared_preferences/shared_preferences.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/models/profile.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/singleton.dart'; -import 'package:whisper/widgets/chat_bubble.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/widgets/chat_bubble.dart'; void main() { final peer = User('2', 'peer', '', false); diff --git a/test/batch_decrypt_test.dart b/test/batch_decrypt_test.dart index 7b732fb..11f590c 100644 --- a/test/batch_decrypt_test.dart +++ b/test/batch_decrypt_test.dart @@ -3,8 +3,8 @@ import 'dart:typed_data'; import 'package:basic_utils/basic_utils.dart' as bu; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/crypto_utils.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/crypto_utils.dart'; void main() { test('album is decoded once per stored json', () { diff --git a/test/chat_bubble_test.dart b/test/chat_bubble_test.dart index c0f4069..c36d12c 100644 --- a/test/chat_bubble_test.dart +++ b/test/chat_bubble_test.dart @@ -4,14 +4,14 @@ import 'package:flutter_test/flutter_test.dart'; // easy_localization reads the locale from shared_preferences, its transitive dep // ignore: depend_on_referenced_packages import 'package:shared_preferences/shared_preferences.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/models/profile.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/singleton.dart'; -import 'package:whisper/utils/text_envelope.dart'; -import 'package:whisper/widgets/chat_bubble.dart'; -import 'package:whisper/widgets/media_bubble.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/utils/text_envelope.dart'; +import 'package:shept/widgets/chat_bubble.dart'; +import 'package:shept/widgets/media_bubble.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; /// Plain text of everything the bubble rendered, spans included. String renderedText(WidgetTester tester) => tester diff --git a/test/chat_date_test.dart b/test/chat_date_test.dart index 14928ee..5dbb886 100644 --- a/test/chat_date_test.dart +++ b/test/chat_date_test.dart @@ -3,7 +3,7 @@ import 'package:easy_localization/easy_localization.dart'; // ignore: depend_on_referenced_packages import 'package:intl/date_symbol_data_local.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/chat_date.dart'; +import 'package:shept/utils/chat_date.dart'; void main() { final now = DateTime(2026, 6, 10, 12); diff --git a/test/chat_info_media_test.dart b/test/chat_info_media_test.dart index f1b79f3..0f1fc6b 100644 --- a/test/chat_info_media_test.dart +++ b/test/chat_info_media_test.dart @@ -1,7 +1,7 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/message_notifier.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/message_notifier.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; PrivateMessage message(String? type, String? path, DateTime sentAt, {int? downloadStatus}) { diff --git a/test/chat_list_item_test.dart b/test/chat_list_item_test.dart index 2be1bc6..096e5a8 100644 --- a/test/chat_list_item_test.dart +++ b/test/chat_list_item_test.dart @@ -1,10 +1,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/models/profile.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/singleton.dart'; -import 'package:whisper/widgets/chat_list_item.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/widgets/chat_list_item.dart'; Widget app(PrivateMessage last, {DateTime? peerReadAt}) { return MaterialApp( diff --git a/test/chat_media_page_test.dart b/test/chat_media_page_test.dart index bf4226d..7694a37 100644 --- a/test/chat_media_page_test.dart +++ b/test/chat_media_page_test.dart @@ -7,16 +7,16 @@ import 'package:hive/hive.dart'; // easy_localization reads the locale from shared_preferences, its transitive dep // ignore: depend_on_referenced_packages import 'package:shared_preferences/shared_preferences.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/pages/chat_media_page.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/pages/chat_media_page.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; void main() { late Directory dir; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_chat_media_page'); + dir = Directory.systemTemp.createTempSync('shept_chat_media_page'); Hive.init(dir.path); Hive.registerAdapter(PrivateMessageAdapter()); SharedPreferences.setMockInitialValues({}); @@ -62,7 +62,7 @@ void main() { // wait on them forever. await tester.runAsync(() => CacheUtils.addPrivateMessages('peer', [ PrivateMessage('peer', '', sentAt, sentAt, true, - localPath: '/tmp/whisper_test_report.pdf', + localPath: '/tmp/shept_test_report.pdf', mediaTypeStr: MediaType.file.name, fileName: 'report.pdf'), ])); diff --git a/test/chat_scroll_test.dart b/test/chat_scroll_test.dart index 3106b9a..0a0062d 100644 --- a/test/chat_scroll_test.dart +++ b/test/chat_scroll_test.dart @@ -1,5 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/chat_scroll.dart'; +import 'package:shept/utils/chat_scroll.dart'; void main() { group('windowForAddition', () { diff --git a/test/chat_theme_dialog_test.dart b/test/chat_theme_dialog_test.dart index a6d37d1..b42e108 100644 --- a/test/chat_theme_dialog_test.dart +++ b/test/chat_theme_dialog_test.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/dialog_utils.dart'; -import 'package:whisper/widgets/theme_palette.dart'; +import 'package:shept/utils/dialog_utils.dart'; +import 'package:shept/widgets/theme_palette.dart'; /// The per-chat dialog shares the app theme's palette, and adds the one choice /// that only a chat has: fall back to the global color. diff --git a/test/chat_theme_test.dart b/test/chat_theme_test.dart index e7a7e3e..43682c6 100644 --- a/test/chat_theme_test.dart +++ b/test/chat_theme_test.dart @@ -3,13 +3,13 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/utils/cache_utils.dart'; +import 'package:shept/utils/cache_utils.dart'; void main() { late Directory dir; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_chat_theme_test'); + dir = Directory.systemTemp.createTempSync('shept_chat_theme_test'); Hive.init(dir.path); }); diff --git a/test/conversation_meta_test.dart b/test/conversation_meta_test.dart index 7142043..a336afe 100644 --- a/test/conversation_meta_test.dart +++ b/test/conversation_meta_test.dart @@ -2,8 +2,8 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/cache_utils.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; PrivateMessage message(String senderId, DateTime sentAt, {bool read = false}) { return PrivateMessage(senderId, 'text', sentAt, sentAt, read); @@ -13,7 +13,7 @@ void main() { late Directory dir; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_conversation_test'); + dir = Directory.systemTemp.createTempSync('shept_conversation_test'); Hive.init(dir.path); Hive.registerAdapter(PrivateMessageAdapter()); }); diff --git a/test/crypto_test.dart b/test/crypto_test.dart index d8e007d..a4c0958 100644 --- a/test/crypto_test.dart +++ b/test/crypto_test.dart @@ -3,7 +3,7 @@ import 'dart:convert'; import 'package:basic_utils/basic_utils.dart' as bu; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/foundation.dart'; -import 'package:whisper/utils/crypto_utils.dart'; +import 'package:shept/utils/crypto_utils.dart'; void main() async { test('generate RSA keypair asynchronously', () async { diff --git a/test/delete_message_test.dart b/test/delete_message_test.dart index 47ba079..480e5a9 100644 --- a/test/delete_message_test.dart +++ b/test/delete_message_test.dart @@ -2,8 +2,8 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/cache_utils.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; void main() { late Directory dir; @@ -11,7 +11,7 @@ void main() { late PrivateMessage drop; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_delete_message_test'); + dir = Directory.systemTemp.createTempSync('shept_delete_message_test'); Hive.init(dir.path); Hive.registerAdapter(PrivateMessageAdapter()); }); diff --git a/test/deleted_bubble_test.dart b/test/deleted_bubble_test.dart index d75d0fb..c795e3d 100644 --- a/test/deleted_bubble_test.dart +++ b/test/deleted_bubble_test.dart @@ -4,12 +4,12 @@ import 'package:flutter_test/flutter_test.dart'; // easy_localization reads the locale from shared_preferences, its transitive dep // ignore: depend_on_referenced_packages import 'package:shared_preferences/shared_preferences.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/models/profile.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/singleton.dart'; -import 'package:whisper/widgets/chat_bubble.dart'; -import 'package:whisper/widgets/media_bubble.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/widgets/chat_bubble.dart'; +import 'package:shept/widgets/media_bubble.dart'; void main() { final peer = User('2', 'peer', '', false); diff --git a/test/device_and_sync_test.dart b/test/device_and_sync_test.dart index 9012568..069edb8 100644 --- a/test/device_and_sync_test.dart +++ b/test/device_and_sync_test.dart @@ -3,14 +3,14 @@ import 'dart:io'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/utils/cache_utils.dart'; +import 'package:shept/utils/cache_utils.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); late Directory dir; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_device_sync_test'); + dir = Directory.systemTemp.createTempSync('shept_device_sync_test'); Hive.init(dir.path); // The device id lives in secure storage, which a unit test has to fake. final secureStorage = {}; diff --git a/test/disappearing_test.dart b/test/disappearing_test.dart index 3c471ce..6b088fa 100644 --- a/test/disappearing_test.dart +++ b/test/disappearing_test.dart @@ -4,14 +4,14 @@ import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper/utils/disappearing.dart'; -import 'package:whisper/utils/media_utils.dart'; -import 'package:whisper/utils/message_actions.dart'; -import 'package:whisper/utils/text_envelope.dart'; -import 'package:whisper_websocket_client_dart/models/media_reference.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/disappearing.dart'; +import 'package:shept/utils/media_utils.dart'; +import 'package:shept/utils/message_actions.dart'; +import 'package:shept/utils/text_envelope.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; PrivateMessage message(String senderId, DateTime sentAt, {DateTime? expiresAt, bool viewOnce = false}) { @@ -23,7 +23,7 @@ void main() { late Directory dir; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_disappearing_test'); + dir = Directory.systemTemp.createTempSync('shept_disappearing_test'); Hive.init(dir.path); Hive.registerAdapter(PrivateMessageAdapter()); }); diff --git a/test/edit_dialog_test.dart b/test/edit_dialog_test.dart index 026cf45..c809d88 100644 --- a/test/edit_dialog_test.dart +++ b/test/edit_dialog_test.dart @@ -4,11 +4,11 @@ import 'package:flutter_test/flutter_test.dart'; // easy_localization reads the locale from shared_preferences, its transitive dep // ignore: depend_on_referenced_packages import 'package:shared_preferences/shared_preferences.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/models/profile.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/message_actions.dart'; -import 'package:whisper/utils/singleton.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/message_actions.dart'; +import 'package:shept/utils/singleton.dart'; /// Closing the edit dialog used to dispose its controller while the route was /// still animating out; that trips `InheritedElement.debugDeactivated` on a diff --git a/test/file_media_test.dart b/test/file_media_test.dart index e1faf62..840f32e 100644 --- a/test/file_media_test.dart +++ b/test/file_media_test.dart @@ -3,12 +3,12 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper/utils/media_utils.dart'; -import 'package:whisper/utils/message_notifier.dart'; -import 'package:whisper/widgets/media_bubble.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/media_utils.dart'; +import 'package:shept/utils/message_notifier.dart'; +import 'package:shept/widgets/media_bubble.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; PrivateMessage media(String type, String? path, DateTime sentAt, {String? fileName, int size = 1024}) { @@ -75,7 +75,7 @@ void main() { }); test('the file name survives a Hive round trip', () async { - final dir = Directory.systemTemp.createTempSync('whisper_file_media_test'); + final dir = Directory.systemTemp.createTempSync('shept_file_media_test'); Hive.init(dir.path); Hive.registerAdapter(PrivateMessageAdapter()); diff --git a/test/link_utils_test.dart b/test/link_utils_test.dart index 0744aa9..0304bf0 100644 --- a/test/link_utils_test.dart +++ b/test/link_utils_test.dart @@ -1,5 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/link_utils.dart'; +import 'package:shept/utils/link_utils.dart'; void main() { test('text without a link stays plain', () { diff --git a/test/live_location_bubble_test.dart b/test/live_location_bubble_test.dart index 9d264e7..f5b7c86 100644 --- a/test/live_location_bubble_test.dart +++ b/test/live_location_bubble_test.dart @@ -1,9 +1,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/live_location.dart'; -import 'package:whisper/utils/presence.dart'; -import 'package:whisper/widgets/live_location_bubble.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/live_location.dart'; +import 'package:shept/utils/presence.dart'; +import 'package:shept/widgets/live_location_bubble.dart'; void main() { final peer = User('2', 'peer', '', false); diff --git a/test/location_test.dart b/test/location_test.dart index 0526e4f..b76f09f 100644 --- a/test/location_test.dart +++ b/test/location_test.dart @@ -2,8 +2,8 @@ import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/live_location.dart'; -import 'package:whisper/utils/text_envelope.dart'; +import 'package:shept/utils/live_location.dart'; +import 'package:shept/utils/text_envelope.dart'; void main() { // A location is a text message with one optional key, so an older client diff --git a/test/media_album_test.dart b/test/media_album_test.dart index c44e31f..17eb1f6 100644 --- a/test/media_album_test.dart +++ b/test/media_album_test.dart @@ -4,12 +4,12 @@ import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper/utils/media_utils.dart'; -import 'package:whisper/utils/message_notifier.dart'; -import 'package:whisper_websocket_client_dart/models/media_reference.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/media_utils.dart'; +import 'package:shept/utils/message_notifier.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; MediaReference _reference(String id, {MediaType type = MediaType.image}) => MediaReference( @@ -38,7 +38,7 @@ void main() { 'album caption', ); final decoded = jsonDecode(utf8.decode(envelope)) as Map; - expect(decoded['whisperMsg'], MediaUtils.envelopeVersionAlbum); + expect(decoded['sheptMsg'], MediaUtils.envelopeVersionAlbum); final parsed = MediaUtils.tryParseMediaEnvelope(envelope); expect(parsed, isNotNull); @@ -65,7 +65,7 @@ void main() { test('an unknown envelope version is not parsed', () { final parsed = MediaUtils.tryParseMediaEnvelope(Uint8List.fromList( - utf8.encode('{"whisperMsg":99,"kind":"media","media":[]}'))); + utf8.encode('{"sheptMsg":99,"kind":"media","media":[]}'))); expect(parsed, isNull); }); }); @@ -147,7 +147,7 @@ void main() { late Directory dir; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_album_test'); + dir = Directory.systemTemp.createTempSync('shept_album_test'); Hive.init(dir.path); Hive.registerAdapter(PrivateMessageAdapter()); await Hive.openBox('privateMessages'); diff --git a/test/media_autoplay_test.dart b/test/media_autoplay_test.dart index 92e6b41..c1d8eac 100644 --- a/test/media_autoplay_test.dart +++ b/test/media_autoplay_test.dart @@ -2,18 +2,18 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/models/profile.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/singleton.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper/utils/media_autoplay.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/media_autoplay.dart'; void main() { late Directory dir; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_media_autoplay_test'); + dir = Directory.systemTemp.createTempSync('shept_media_autoplay_test'); Hive.init(dir.path); Hive.registerAdapter(PrivateMessageAdapter()); // isMe compares against the signed-in user. diff --git a/test/media_cache_test.dart b/test/media_cache_test.dart index 385e09e..05b8e92 100644 --- a/test/media_cache_test.dart +++ b/test/media_cache_test.dart @@ -2,8 +2,8 @@ import 'dart:io'; import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/media_utils.dart'; -import 'package:whisper/utils/singleton.dart'; +import 'package:shept/utils/media_utils.dart'; +import 'package:shept/utils/singleton.dart'; /// A chat list disposes the rows that leave the viewport, so a photo scrolling /// back into view used to be decrypted again from disk: the spinner stayed up @@ -14,7 +14,7 @@ void main() { late Directory dir; setUpAll(() { - dir = Directory.systemTemp.createTempSync('whisper_media_cache_test'); + dir = Directory.systemTemp.createTempSync('shept_media_cache_test'); Singleton().boxCollectionKey = key; }); diff --git a/test/media_guard_test.dart b/test/media_guard_test.dart index ae93427..8a0ee00 100644 --- a/test/media_guard_test.dart +++ b/test/media_guard_test.dart @@ -2,9 +2,9 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; PrivateMessage media(DateTime sentAt, {String? mediaId, String? localPath, String? albumItemPath}) { @@ -28,7 +28,7 @@ void main() { late Directory dir; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_media_guard_test'); + dir = Directory.systemTemp.createTempSync('shept_media_guard_test'); Hive.init(dir.path); Hive.registerAdapter(PrivateMessageAdapter()); }); diff --git a/test/media_rekey_test.dart b/test/media_rekey_test.dart index 33e66f6..7ac704c 100644 --- a/test/media_rekey_test.dart +++ b/test/media_rekey_test.dart @@ -1,7 +1,7 @@ import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/media_utils.dart'; +import 'package:shept/utils/media_utils.dart'; void main() { test('re-encrypted media only decrypts with the new key', () async { diff --git a/test/media_upload_test.dart b/test/media_upload_test.dart index b11dd82..10acda8 100644 --- a/test/media_upload_test.dart +++ b/test/media_upload_test.dart @@ -1,7 +1,7 @@ import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/media_utils.dart'; +import 'package:shept/utils/media_utils.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); diff --git a/test/message_actions_test.dart b/test/message_actions_test.dart index 578b62e..7c1e185 100644 --- a/test/message_actions_test.dart +++ b/test/message_actions_test.dart @@ -4,11 +4,11 @@ import 'package:flutter_test/flutter_test.dart'; // easy_localization reads the locale from shared_preferences, its transitive dep // ignore: depend_on_referenced_packages import 'package:shared_preferences/shared_preferences.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/models/profile.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/message_actions.dart'; -import 'package:whisper/utils/singleton.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/message_actions.dart'; +import 'package:shept/utils/singleton.dart'; void main() { setUpAll(() async { @@ -66,7 +66,7 @@ void main() { // Attachment on disk without a caption: save, forward, delete, no copy. message = PrivateMessage('2', '', DateTime(2026), DateTime(2026), true, - localPath: '/tmp/whisper_media_test', mediaTypeStr: 'image'); + localPath: '/tmp/shept_media_test', mediaTypeStr: 'image'); await tester.tap(find.text('open')); await tester.pumpAndSettle(); expect(find.text('Save attachment'), findsOneWidget); @@ -127,7 +127,7 @@ void main() { // An own attachment offers the caption edit too. message = PrivateMessage( '1', 'caption', DateTime(2026), DateTime(2026), true, - localPath: '/tmp/whisper_media_test', mediaTypeStr: 'image') + localPath: '/tmp/shept_media_test', mediaTypeStr: 'image') ..id = '00000000-0000-4000-8000-000000000000'; await tester.tap(find.text('open')); await tester.pumpAndSettle(); diff --git a/test/message_format_test.dart b/test/message_format_test.dart index f18dace..389685c 100644 --- a/test/message_format_test.dart +++ b/test/message_format_test.dart @@ -1,5 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/message_format.dart'; +import 'package:shept/utils/message_format.dart'; /// Renders the parsed pieces back as text, so a test can assert on the whole /// message without caring how the parser grouped it. diff --git a/test/message_lifecycle_test.dart b/test/message_lifecycle_test.dart index 3f80419..db7a30e 100644 --- a/test/message_lifecycle_test.dart +++ b/test/message_lifecycle_test.dart @@ -4,10 +4,10 @@ import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper_websocket_client_dart/models/media_reference.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; /// The local side of the lifecycle: an edit rewrites the stored text, a /// reaction is a per-user map, a pin lives on the chat, and the mutation cursor @@ -17,7 +17,7 @@ void main() { const peer = 'peer-id'; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_lifecycle_test'); + dir = Directory.systemTemp.createTempSync('shept_lifecycle_test'); Hive.init(dir.path); if (!Hive.isAdapterRegistered(3)) { Hive.registerAdapter(PrivateMessageAdapter()); diff --git a/test/message_search_test.dart b/test/message_search_test.dart index 3909b60..cbe9668 100644 --- a/test/message_search_test.dart +++ b/test/message_search_test.dart @@ -1,6 +1,6 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/message_search.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/message_search.dart'; PrivateMessage text(String body, DateTime sentAt, {String? fileName}) { return PrivateMessage('peer', body, sentAt, sentAt, true, fileName: fileName); diff --git a/test/message_store_test.dart b/test/message_store_test.dart index fa43b12..e44f7db 100644 --- a/test/message_store_test.dart +++ b/test/message_store_test.dart @@ -2,9 +2,9 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; PrivateMessage message(String senderId, String text, DateTime sentAt, {int sendStatus = SendStatus.sent}) { @@ -18,7 +18,7 @@ void main() { late Directory dir; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_message_store_test'); + dir = Directory.systemTemp.createTempSync('shept_message_store_test'); Hive.init(dir.path); Hive.registerAdapter(PrivateMessageAdapter()); }); diff --git a/test/pbkdf2_salt_test.dart b/test/pbkdf2_salt_test.dart index c3642f8..909067c 100644 --- a/test/pbkdf2_salt_test.dart +++ b/test/pbkdf2_salt_test.dart @@ -1,5 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/crypto_utils.dart'; +import 'package:shept/utils/crypto_utils.dart'; void main() { test('same password and salt derive the same key', () async { diff --git a/test/playback_lock_test.dart b/test/playback_lock_test.dart index 384bf06..aa44389 100644 --- a/test/playback_lock_test.dart +++ b/test/playback_lock_test.dart @@ -1,5 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/playback_lock.dart'; +import 'package:shept/utils/playback_lock.dart'; void main() { test('claim hands the lock to the newest source', () { diff --git a/test/playback_speed_test.dart b/test/playback_speed_test.dart index e70bfd9..a064df4 100644 --- a/test/playback_speed_test.dart +++ b/test/playback_speed_test.dart @@ -1,5 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/playback_speed.dart'; +import 'package:shept/utils/playback_speed.dart'; void main() { test('cycles through 1x, 1.5x, 2x and back', () { diff --git a/test/presence_test.dart b/test/presence_test.dart index 174ac87..dc4cc7b 100644 --- a/test/presence_test.dart +++ b/test/presence_test.dart @@ -1,6 +1,6 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/live_location.dart'; -import 'package:whisper/utils/presence.dart'; +import 'package:shept/utils/live_location.dart'; +import 'package:shept/utils/presence.dart'; void main() { final presence = PresenceNotifier.instance; diff --git a/test/reaction_list_test.dart b/test/reaction_list_test.dart index ca0ee69..dd2f24c 100644 --- a/test/reaction_list_test.dart +++ b/test/reaction_list_test.dart @@ -1,5 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/message_actions.dart'; +import 'package:shept/utils/message_actions.dart'; /// The reaction list groups by emoji, so one emoji with several participants is /// one row with their names, and the busiest row is on top. diff --git a/test/reaction_picker_test.dart b/test/reaction_picker_test.dart index 8568e24..e45596b 100644 --- a/test/reaction_picker_test.dart +++ b/test/reaction_picker_test.dart @@ -1,10 +1,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/models/profile.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/message_actions.dart'; -import 'package:whisper/utils/singleton.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/message_actions.dart'; +import 'package:shept/utils/singleton.dart'; /// The reaction row marks the emoji this user already picked, so a second tap /// reads as "take mine back". diff --git a/test/reaction_rebuild_test.dart b/test/reaction_rebuild_test.dart index bb42c3c..03d11aa 100644 --- a/test/reaction_rebuild_test.dart +++ b/test/reaction_rebuild_test.dart @@ -4,14 +4,14 @@ import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/models/profile.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/media_utils.dart'; -import 'package:whisper/utils/singleton.dart'; -import 'package:whisper/widgets/chat_bubble.dart'; -import 'package:whisper/widgets/media_bubble.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/media_utils.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/widgets/chat_bubble.dart'; +import 'package:shept/widgets/media_bubble.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; /// A reaction is toggled on an attachment all the time. When the bubble's clip /// wrapper came and went with it, the attachment was mounted again from @@ -25,7 +25,7 @@ void main() { late Directory dir; setUpAll(() { - dir = Directory.systemTemp.createTempSync('whisper_reaction_rebuild'); + dir = Directory.systemTemp.createTempSync('shept_reaction_rebuild'); Singleton().boxCollectionKey = key; Singleton().profile = Profile('', User('1', 'me', '', false), '', '', '', '', false); diff --git a/test/reaction_store_test.dart b/test/reaction_store_test.dart index c70e5a5..73e67ea 100644 --- a/test/reaction_store_test.dart +++ b/test/reaction_store_test.dart @@ -2,8 +2,8 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/cache_utils.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; /// Giving a reaction is a local write after the server call: if the key does /// not match, the badge never appears even though the server took the request. @@ -11,7 +11,7 @@ void main() { late Directory dir; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_reaction_store'); + dir = Directory.systemTemp.createTempSync('shept_reaction_store'); Hive.init(dir.path); if (!Hive.isAdapterRegistered(3)) { Hive.registerAdapter(PrivateMessageAdapter()); diff --git a/test/read_receipt_test.dart b/test/read_receipt_test.dart index 909c68b..6c2c7f7 100644 --- a/test/read_receipt_test.dart +++ b/test/read_receipt_test.dart @@ -4,11 +4,11 @@ import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper/utils/message_notifier.dart'; -import 'package:whisper/utils/utils.dart'; -import 'package:whisper_websocket_client_dart/models/ws_response.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/message_notifier.dart'; +import 'package:shept/utils/utils.dart'; +import 'package:shept_websocket_client_dart/models/ws_response.dart'; Uint8List frame(Map json) => Uint8List.fromList(utf8.encode(jsonEncode(json))); @@ -20,7 +20,7 @@ void main() { late Directory dir; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_read_receipt_test'); + dir = Directory.systemTemp.createTempSync('shept_read_receipt_test'); Hive.init(dir.path); if (!Hive.isAdapterRegistered(3)) { Hive.registerAdapter(PrivateMessageAdapter()); diff --git a/test/reconnect_backoff_test.dart b/test/reconnect_backoff_test.dart index 52ab7f7..bab142d 100644 --- a/test/reconnect_backoff_test.dart +++ b/test/reconnect_backoff_test.dart @@ -1,5 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/websocket_manager.dart'; +import 'package:shept/utils/websocket_manager.dart'; void main() { test('reconnects back off instead of polling every few seconds', () { diff --git a/test/round_note_playback_test.dart b/test/round_note_playback_test.dart index 12dfb83..95880ef 100644 --- a/test/round_note_playback_test.dart +++ b/test/round_note_playback_test.dart @@ -1,6 +1,6 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/round_note_playback.dart'; +import 'package:shept/utils/round_note_playback.dart'; void main() { group('the floating copy of a round note', () { diff --git a/test/search_user_test.dart b/test/search_user_test.dart index 00fdd89..fc034fd 100644 --- a/test/search_user_test.dart +++ b/test/search_user_test.dart @@ -2,8 +2,8 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/pages/search_user_page.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/pages/search_user_page.dart'; User user(String name) => User(name, name, 'public-key', false); diff --git a/test/server_url_and_temp_test.dart b/test/server_url_and_temp_test.dart index b81bcd8..aff6352 100644 --- a/test/server_url_and_temp_test.dart +++ b/test/server_url_and_temp_test.dart @@ -1,6 +1,6 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/media_utils.dart'; -import 'package:whisper/utils/utils.dart'; +import 'package:shept/utils/media_utils.dart'; +import 'package:shept/utils/utils.dart'; void main() { group('server url policy', () { @@ -25,10 +25,10 @@ void main() { group('plaintext temp media', () { test('only the app temp files are swept', () { - expect(MediaUtils.isTempMediaName('whisper_media_abc.mp4'), isTrue); - expect(MediaUtils.isTempMediaName('whisper_send_abc.gif'), isTrue); + expect(MediaUtils.isTempMediaName('shept_media_abc.mp4'), isTrue); + expect(MediaUtils.isTempMediaName('shept_send_abc.gif'), isTrue); expect(MediaUtils.isTempMediaName('shared_prefs.xml'), isFalse); - expect(MediaUtils.isTempMediaName('whisper.sqlite'), isFalse); + expect(MediaUtils.isTempMediaName('shept.sqlite'), isFalse); }); }); } diff --git a/test/settings_tile_test.dart b/test/settings_tile_test.dart index 0527491..dfcf1e4 100644 --- a/test/settings_tile_test.dart +++ b/test/settings_tile_test.dart @@ -1,6 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/widgets/settings_tile.dart'; +import 'package:shept/widgets/settings_tile.dart'; void main() { testWidgets('row height does not depend on a trailing widget', diff --git a/test/storage_utils_test.dart b/test/storage_utils_test.dart index e298ba3..f510b3e 100644 --- a/test/storage_utils_test.dart +++ b/test/storage_utils_test.dart @@ -2,15 +2,15 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper/utils/storage_utils.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/storage_utils.dart'; void main() { late Directory dir; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_storage_test'); + dir = Directory.systemTemp.createTempSync('shept_storage_test'); Hive.init(dir.path); Hive.registerAdapter(PrivateMessageAdapter()); }); diff --git a/test/text_envelope_test.dart b/test/text_envelope_test.dart index 36f359a..196a621 100644 --- a/test/text_envelope_test.dart +++ b/test/text_envelope_test.dart @@ -2,7 +2,7 @@ import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/text_envelope.dart'; +import 'package:shept/utils/text_envelope.dart'; Uint8List bytes(String text) => Uint8List.fromList(utf8.encode(text)); @@ -30,7 +30,7 @@ void main() { 'x', ReplyRef(senderId: 'a', sentAt: DateTime(2026), preview: 'y')); final decoded = jsonDecode(utf8.decode(envelope)) as Map; expect(decoded['kind'], 'text'); - expect(decoded['whisperMsg'], textEnvelopeVersion); + expect(decoded['sheptMsg'], textEnvelopeVersion); }); test('a forwarded message survives the round trip without a quote', () { @@ -44,7 +44,7 @@ void main() { // The version stays 3: an older reader still opens the body instead of // showing raw JSON. final decoded = jsonDecode(utf8.decode(envelope)) as Map; - expect(decoded['whisperMsg'], textEnvelopeVersion); + expect(decoded['sheptMsg'], textEnvelopeVersion); }); test('an envelope without the flag is not a forward', () { @@ -62,7 +62,7 @@ void main() { expect(parsed.location!.lat, 50.08); // An older reader still opens the body instead of raw JSON. final decoded = jsonDecode(utf8.decode(envelope)) as Map; - expect(decoded['whisperMsg'], textEnvelopeVersion); + expect(decoded['sheptMsg'], textEnvelopeVersion); }); test('plain text is not an envelope', () { @@ -70,18 +70,18 @@ void main() { }); test('a media envelope is not a text envelope', () { - final media = bytes('{"whisperMsg":1,"kind":"media","media":{}}'); + final media = bytes('{"sheptMsg":1,"kind":"media","media":{}}'); expect(tryParseTextEnvelope(media), isNull); }); test('a broken body is not an envelope', () { - final broken = bytes('{"whisperMsg":3,"kind":"text","body":5}'); + final broken = bytes('{"sheptMsg":3,"kind":"text","body":5}'); expect(tryParseTextEnvelope(broken), isNull); }); test('a broken quote is ignored, the body still reads', () { final broken = - bytes('{"whisperMsg":3,"kind":"text","body":"a","replyTo":{"x":1}}'); + bytes('{"sheptMsg":3,"kind":"text","body":"a","replyTo":{"x":1}}'); final parsed = tryParseTextEnvelope(broken); expect(parsed!.body, 'a'); expect(parsed.reply, isNull); diff --git a/test/theme_dialog_test.dart b/test/theme_dialog_test.dart index ce26efe..5176caf 100644 --- a/test/theme_dialog_test.dart +++ b/test/theme_dialog_test.dart @@ -4,10 +4,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hive/hive.dart'; import 'package:provider/provider.dart'; -import 'package:whisper/models/app_theme.dart'; -import 'package:whisper/utils/dialog_utils.dart'; -import 'package:whisper/utils/singleton.dart'; -import 'package:whisper/utils/theme_notifier.dart'; +import 'package:shept/models/app_theme.dart'; +import 'package:shept/utils/dialog_utils.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/utils/theme_notifier.dart'; /// The theme dialog applies on tap, so picking a swatch has to move the seed /// the whole app is seeded with - and show which one is in use. @@ -15,7 +15,7 @@ void main() { late Directory dir; setUpAll(() async { - dir = Directory.systemTemp.createTempSync('whisper_theme_dialog_test'); + dir = Directory.systemTemp.createTempSync('shept_theme_dialog_test'); Hive.init(dir.path); if (!Hive.isAdapterRegistered(2)) { Hive.registerAdapter(AppThemeAdapter()); diff --git a/test/token_expiry_test.dart b/test/token_expiry_test.dart index 41e7212..930311b 100644 --- a/test/token_expiry_test.dart +++ b/test/token_expiry_test.dart @@ -1,7 +1,7 @@ import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/utils/utils.dart'; +import 'package:shept/utils/utils.dart'; String _token(Map payload) { String encode(Map value) => diff --git a/test/typing_dots_test.dart b/test/typing_dots_test.dart index cac0010..9aedc41 100644 --- a/test/typing_dots_test.dart +++ b/test/typing_dots_test.dart @@ -4,7 +4,7 @@ import 'package:flutter_test/flutter_test.dart'; // easy_localization reads the locale from shared_preferences, its transitive dep // ignore: depend_on_referenced_packages import 'package:shared_preferences/shared_preferences.dart'; -import 'package:whisper/widgets/typing_dots.dart'; +import 'package:shept/widgets/typing_dots.dart'; void main() { setUpAll(() async { diff --git a/test/undecryptable_message_test.dart b/test/undecryptable_message_test.dart index d72322c..b44dd51 100644 --- a/test/undecryptable_message_test.dart +++ b/test/undecryptable_message_test.dart @@ -1,5 +1,5 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/models/private_message.dart'; +import 'package:shept/models/private_message.dart'; void main() { final sentAt = DateTime(2026, 5, 1); diff --git a/test/user_list_item_test.dart b/test/user_list_item_test.dart index 3f84ec1..5807d39 100644 --- a/test/user_list_item_test.dart +++ b/test/user_list_item_test.dart @@ -1,8 +1,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/presence.dart'; -import 'package:whisper/widgets/user_list_item.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/presence.dart'; +import 'package:shept/widgets/user_list_item.dart'; Widget app() => MaterialApp( home: Scaffold( diff --git a/test/video_note_test.dart b/test/video_note_test.dart index 028e38c..f614d0d 100644 --- a/test/video_note_test.dart +++ b/test/video_note_test.dart @@ -2,9 +2,9 @@ import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper_websocket_client_dart/models/media_reference.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; void main() { PrivateMessage video({String? referenceJson}) => PrivateMessage( diff --git a/test/view_once_location_test.dart b/test/view_once_location_test.dart index d8c296e..0ed068f 100644 --- a/test/view_once_location_test.dart +++ b/test/view_once_location_test.dart @@ -6,13 +6,13 @@ import 'package:flutter_test/flutter_test.dart'; // easy_localization reads the locale from shared_preferences, its transitive dep // ignore: depend_on_referenced_packages import 'package:shared_preferences/shared_preferences.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/models/profile.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/singleton.dart'; -import 'package:whisper/utils/text_envelope.dart'; -import 'package:whisper/widgets/chat_bubble.dart'; -import 'package:whisper/widgets/view_once_frame.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/utils/text_envelope.dart'; +import 'package:shept/widgets/chat_bubble.dart'; +import 'package:shept/widgets/view_once_frame.dart'; void main() { final peer = User('2', 'peer', '', false); diff --git a/test/view_once_preview_test.dart b/test/view_once_preview_test.dart index 1fc0ff6..6f282a3 100644 --- a/test/view_once_preview_test.dart +++ b/test/view_once_preview_test.dart @@ -7,9 +7,9 @@ import 'package:flutter_test/flutter_test.dart'; // ignore: depend_on_referenced_packages import 'package:shared_preferences/shared_preferences.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/utils/cache_utils.dart'; -import 'package:whisper/utils/text_envelope.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/text_envelope.dart'; void main() { late Directory dir; @@ -19,7 +19,7 @@ void main() { setUpAll(() async { SharedPreferences.setMockInitialValues({}); await EasyLocalization.ensureInitialized(); - dir = Directory.systemTemp.createTempSync('whisper_view_once_test'); + dir = Directory.systemTemp.createTempSync('shept_view_once_test'); Hive.init(dir.path); Hive.registerAdapter(PrivateMessageAdapter()); }); diff --git a/test/view_once_test.dart b/test/view_once_test.dart index e85f458..08c72f0 100644 --- a/test/view_once_test.dart +++ b/test/view_once_test.dart @@ -1,10 +1,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:whisper/models/private_message.dart'; -import 'package:whisper/models/profile.dart'; -import 'package:whisper/models/user.dart'; -import 'package:whisper/utils/singleton.dart'; -import 'package:whisper/widgets/media_bubble.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/widgets/media_bubble.dart'; Widget app(PrivateMessage message, {String peer = 'peer'}) => MaterialApp( home: Scaffold( From 533c823fdd87d49e5e11b002b31203d1e40e6104 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 27 Nov 2026 00:23:19 +0100 Subject: [PATCH 178/181] chore(app): retire firebase dependencies, keep the code commented --- android/app/build.gradle.kts | 2 +- android/settings.gradle.kts | 2 +- lib/main.dart | 15 +++--- lib/pages/home_page.dart | 90 +++++++++++++++++++----------------- pubspec.lock | 56 ---------------------- pubspec.yaml | 6 ++- 6 files changed, 62 insertions(+), 109 deletions(-) diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 8ee24ee..5666403 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -4,7 +4,7 @@ import java.util.Properties plugins { id("com.android.application") // START: FlutterFire Configuration - id("com.google.gms.google-services") + // Firebase retired: id("com.google.gms.google-services") // END: FlutterFire Configuration id("kotlin-android") // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts index 5b15e75..efdf2ab 100644 --- a/android/settings.gradle.kts +++ b/android/settings.gradle.kts @@ -20,7 +20,7 @@ plugins { id("dev.flutter.flutter-plugin-loader") version "1.0.0" id("com.android.application") version "9.5.1" apply false // START: FlutterFire Configuration - id("com.google.gms.google-services") version("4.6.0") apply false + // Firebase retired: id("com.google.gms.google-services") version("4.6.0") apply false // END: FlutterFire Configuration id("org.jetbrains.kotlin.android") version "2.4.21" apply false } diff --git a/lib/main.dart b/lib/main.dart index caee3f8..41c2e44 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -5,14 +5,15 @@ import 'package:easy_localization/easy_localization.dart'; // only duplicate that pin. // ignore: depend_on_referenced_packages import 'package:intl/date_symbol_data_local.dart'; -import 'package:firebase_core/firebase_core.dart'; +// Firebase is retired; dependency and init are commented out on purpose. +// import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:hive/hive.dart'; import 'package:mcp_toolkit/mcp_toolkit.dart'; import 'package:provider/provider.dart'; -import 'firebase_options.dart'; +// import 'firebase_options.dart'; import '../utils/message_notifier.dart'; import '../utils/cache_utils.dart'; import 'models/app_theme.dart'; @@ -43,11 +44,11 @@ void main() async { } } - if (Platform.isAndroid || Platform.isIOS) { - await Firebase.initializeApp( - options: DefaultFirebaseOptions.currentPlatform, - ); - } + // if (Platform.isAndroid || Platform.isIOS) { + // await Firebase.initializeApp( + // options: DefaultFirebaseOptions.currentPlatform, + // ); + // } // Load locale (the notification service needs it for the channel texts) await EasyLocalization.ensureInitialized(); diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index be52b90..09a1755 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -2,7 +2,8 @@ import 'dart:async'; import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; -import 'package:firebase_messaging/firebase_messaging.dart'; +// Firebase is retired; dependency is commented out in pubspec.yaml. +// import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; @@ -107,41 +108,45 @@ class _HomePageState extends State // Start checking WebSocket connection _webSocketManager.startConnectionCheck(); - // Request FCM notification permissions - FirebaseMessaging.instance.requestPermission(provisional: true); - - // FID registration - store FID and send when online - FirebaseMessaging.instance.onRegistered.listen((fid) async { - _pendingFid = fid; - await _sendPushTargetWhenOnline(fid); - }).onError((err) { - if (kDebugMode) { - debugPrint('Error getting FID: $err'); - } - }); - - // Enable FCM notifications - FirebaseMessaging.instance.setAutoInitEnabled(true); - - // A foreground push is not shown by the OS; show it ourselves. - _fcmSubscription = FirebaseMessaging.onMessage.listen((message) { - final notification = message.notification; - if (notification == null) { - return; - } - NotificationService().showSecurityNotification( - notification.title ?? 'newLoginTitle'.tr(), - notification.body ?? '', - ); - }); - - // Register with FCM, the FID arrives via onRegistered - _registerForPush(); + // Firebase is retired: FCM registration is commented out, the app still + // compiles and runs without push. + // // Request FCM notification permissions + // FirebaseMessaging.instance.requestPermission(provisional: true); + // + // // FID registration - store FID and send when online + // FirebaseMessaging.instance.onRegistered.listen((fid) async { + // _pendingFid = fid; + // await _sendPushTargetWhenOnline(fid); + // }).onError((err) { + // if (kDebugMode) { + // debugPrint('Error getting FID: $err'); + // } + // }); + // + // // Enable FCM notifications + // FirebaseMessaging.instance.setAutoInitEnabled(true); + // + // // A foreground push is not shown by the OS; show it ourselves. + // _fcmSubscription = FirebaseMessaging.onMessage.listen((message) { + // final notification = message.notification; + // if (notification == null) { + // return; + // } + // NotificationService().showSecurityNotification( + // notification.title ?? 'newLoginTitle'.tr(), + // notification.body ?? '', + // ); + // }); + // + // // Register with FCM, the FID arrives via onRegistered + // _registerForPush(); } /// Foreground pushes: the server warns the other devices about a new login, /// and a foreground app has to show that itself. - StreamSubscription? _fcmSubscription; + /// Firebase is retired; kept commented so the type reference does not pull + /// the dependency back in. + // StreamSubscription? _fcmSubscription; /// A screenshot of an ordinary message cannot be stopped, only noticed. void _onScreenshot() { @@ -167,7 +172,7 @@ class _HomePageState extends State void dispose() { WidgetsBinding.instance.removeObserver(this); ScreenGuard.onScreenshot = null; - _fcmSubscription?.cancel(); + // _fcmSubscription?.cancel(); _adminTabController.dispose(); MessageNotifier().removeListener(_onMessagesChanged); if (NotificationService.onChatSelected == _openChat) { @@ -197,15 +202,16 @@ class _HomePageState extends State } /// Register with FCM, the FID arrives via onRegistered - Future _registerForPush() async { - try { - await FirebaseMessaging.instance.register(); - } catch (e) { - if (kDebugMode) { - debugPrint('Error registering with FCM: $e'); - } - } - } + /// Firebase is retired; kept commented so the dependency stays out. + // Future _registerForPush() async { + // try { + // await FirebaseMessaging.instance.register(); + // } catch (e) { + // if (kDebugMode) { + // debugPrint('Error registering with FCM: $e'); + // } + // } + // } /// Send FID when online, store when offline Future _sendPushTargetWhenOnline(String fid) async { diff --git a/pubspec.lock b/pubspec.lock index 031829b..4ce704f 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -9,14 +9,6 @@ packages: url: "https://pub.dev" source: hosted version: "67.0.0" - _flutterfire_internals: - dependency: transitive - description: - name: _flutterfire_internals - sha256: e6d8a6eb9da10e65906dda455eca96ee7a6303b835cad74d667b1ff3bedd5d18 - url: "https://pub.dev" - source: hosted - version: "1.3.79" analyzer: dependency: transitive description: @@ -521,54 +513,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.9.3+6" - firebase_core: - dependency: "direct main" - description: - name: firebase_core - sha256: "21551c1205441d9d155660ea0a409530b65a8d66ce88002bab3f38d94a8638fc" - url: "https://pub.dev" - source: hosted - version: "5.1.0" - firebase_core_platform_interface: - dependency: transitive - description: - name: firebase_core_platform_interface - sha256: "9bfbc85faca09346471ac56fbcee00757ebcfd85887c6f602764eff0001902d8" - url: "https://pub.dev" - source: hosted - version: "8.1.1" - firebase_core_web: - dependency: transitive - description: - name: firebase_core_web - sha256: "0ec9832bfec1662629d6d09abd65021357634b2c10964970d3e96ab18c9458db" - url: "https://pub.dev" - source: hosted - version: "4.1.0" - firebase_messaging: - dependency: "direct main" - description: - name: firebase_messaging - sha256: e19c73b369ae83f4580a0676597f9ac3a0cd91e1b18be69ea16299c153dd9310 - url: "https://pub.dev" - source: hosted - version: "17.0.1" - firebase_messaging_platform_interface: - dependency: transitive - description: - name: firebase_messaging_platform_interface - sha256: "1627f161b85bf842cba5227b02aafaad4e4ff9236a0a8490e6ec72b6fde294a5" - url: "https://pub.dev" - source: hosted - version: "4.11.1" - firebase_messaging_web: - dependency: transitive - description: - name: firebase_messaging_web - sha256: "593d73330500896d9dd81680ee6207c69ad80f258712beb6de2e32dc14a9cb26" - url: "https://pub.dev" - source: hosted - version: "4.3.1" fixnum: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 3ce625f..bd404b8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -24,8 +24,10 @@ dependencies: easy_localization: ^3.0.7 email_validator: ^3.0.0 file_picker: ^13.3.3 - firebase_core: ^5.1.0 - firebase_messaging: ^17.0.1 + # Firebase is retired. The code is commented out, not deleted, so it can be + # revived or stripped later. Re-enable both lines to bring push back. + # firebase_core: ^5.1.0 + # firebase_messaging: ^17.0.1 flutter: sdk: flutter flutter_colorpicker: ^1.1.0 From e678fa2bc9cf569fec67d2865ba4c7e24f8a39fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 27 Nov 2026 00:38:27 +0100 Subject: [PATCH 179/181] ci(app): drop the Firebase options step --- .github/workflows/build_and_release.yml | 60 ++++++++++++------------- .github/workflows/flutter-ci.yml | 19 ++++---- AGENTS.md | 6 +-- 3 files changed, 43 insertions(+), 42 deletions(-) diff --git a/.github/workflows/build_and_release.yml b/.github/workflows/build_and_release.yml index f6804af..c1a92c4 100644 --- a/.github/workflows/build_and_release.yml +++ b/.github/workflows/build_and_release.yml @@ -34,36 +34,36 @@ jobs: - name: Get dependencies run: flutter pub get - # Creating Firebase configuration files from base64 encoded secret keys - - name: Create Firebase configuration files - run: | - if [ -n "${{ secrets.FIREBASE_JSON_BASE64 }}" ]; then - echo "${{ secrets.FIREBASE_JSON_BASE64 }}" | base64 -d > firebase.json - else - echo "Error: FIREBASE_JSON_BASE64 secret is required" - exit 1 - fi - - if [ -n "${{ secrets.FIREBASE_OPTIONS_DART_BASE64 }}" ]; then - echo "${{ secrets.FIREBASE_OPTIONS_DART_BASE64 }}" | base64 -d > lib/firebase_options.dart - else - echo "Error: FIREBASE_OPTIONS_DART_BASE64 secret is required" - exit 1 - fi - - if [ -n "${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }}" ]; then - echo "${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }}" | base64 -d > android/app/google-services.json - else - echo "Error: GOOGLE_SERVICES_JSON_BASE64 secret is required" - exit 1 - fi - - # if [ -n "${{ secrets.GOOGLE_SERVICE_INFO_PLIST_BASE64 }}" ]; then - # echo "${{ secrets.GOOGLE_SERVICE_INFO_PLIST_BASE64 }}" | base64 -d > ios/Runner/GoogleService-Info.plist - #else - # echo "Error: GOOGLE_SERVICE_INFO_PLIST_BASE64 secret is required" - # exit 1 - #fi +# # Creating Firebase configuration files from base64 encoded secret keys +# - name: Create Firebase configuration files +# run: | +# if [ -n "${{ secrets.FIREBASE_JSON_BASE64 }}" ]; then +# echo "${{ secrets.FIREBASE_JSON_BASE64 }}" | base64 -d > firebase.json +# else +# echo "Error: FIREBASE_JSON_BASE64 secret is required" +# exit 1 +# fi +# +# if [ -n "${{ secrets.FIREBASE_OPTIONS_DART_BASE64 }}" ]; then +# echo "${{ secrets.FIREBASE_OPTIONS_DART_BASE64 }}" | base64 -d > lib/firebase_options.dart +# else +# echo "Error: FIREBASE_OPTIONS_DART_BASE64 secret is required" +# exit 1 +# fi +# +# if [ -n "${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }}" ]; then +# echo "${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }}" | base64 -d > android/app/google-services.json +# else +# echo "Error: GOOGLE_SERVICES_JSON_BASE64 secret is required" +# exit 1 +# fi +# +# # if [ -n "${{ secrets.GOOGLE_SERVICE_INFO_PLIST_BASE64 }}" ]; then +# # echo "${{ secrets.GOOGLE_SERVICE_INFO_PLIST_BASE64 }}" | base64 -d > ios/Runner/GoogleService-Info.plist +# #else +# # echo "Error: GOOGLE_SERVICE_INFO_PLIST_BASE64 secret is required" +# # exit 1 +# #fi # Fail fast when the version was not bumped for this release - name: Check version bump diff --git a/.github/workflows/flutter-ci.yml b/.github/workflows/flutter-ci.yml index 7e4338b..500fe51 100644 --- a/.github/workflows/flutter-ci.yml +++ b/.github/workflows/flutter-ci.yml @@ -24,15 +24,16 @@ jobs: channel: stable cache: true - - name: Create Firebase options - env: - FIREBASE_OPTIONS_DART_BASE64: ${{ secrets.FIREBASE_OPTIONS_DART_BASE64 }} - run: | - if [ -z "$FIREBASE_OPTIONS_DART_BASE64" ]; then - echo "FIREBASE_OPTIONS_DART_BASE64 secret is required for analysis" - exit 1 - fi - echo "$FIREBASE_OPTIONS_DART_BASE64" | base64 -d > lib/firebase_options.dart + # Firebase is retired: no generated options file is needed any more. + # - name: Create Firebase options + # env: + # FIREBASE_OPTIONS_DART_BASE64: ${{ secrets.FIREBASE_OPTIONS_DART_BASE64 }} + # run: | + # if [ -z "$FIREBASE_OPTIONS_DART_BASE64" ]; then + # echo "FIREBASE_OPTIONS_DART_BASE64 secret is required for analysis" + # exit 1 + # fi + # echo "$FIREBASE_OPTIONS_DART_BASE64" | base64 -d > lib/firebase_options.dart - name: Get dependencies run: flutter pub get diff --git a/AGENTS.md b/AGENTS.md index 718a270..052e0c7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ and WebSocket (`shept_websocket_client_dart`). - format: `dart format` on the files you touched - test: `flutter test` - e2e: `flutter test integration_test -d linux` (needs Linux desktop toolchain) -- build: `flutter build apk --release` (requires `firebase_options.dart`, `google-services.json`, `firebase.json`) +- build: `flutter build apk --release` (no Firebase files needed; Firebase is retired) ## AI / MCP tooling @@ -43,8 +43,8 @@ not in this repository). Use them for the fast loop, but the shell gates below s ## Where it hurts - **Media upload**: `uploadMedia(file, receiverId)` — the argument order comes from the generator, not from logic. Verify call sites after regenerating the client. -- **Pinned clients**: `pubspec.yaml` pulls both Dart clients from their `v0.1.0` tags, so the build records the contract it was made against. `pubspec_overrides.yaml` (gitignored) points at the sibling checkouts for local work; never commit it. -- **Firebase**: analysis fails without `lib/firebase_options.dart`. CI decodes it from a secret. +- **Pinned clients**: `pubspec.yaml` pulls both Dart clients from their `v0.5.0` tags, so the build records the contract it was made against. `pubspec_overrides.yaml` (gitignored) points at the sibling checkouts for local work; never commit it. +- **Firebase**: retired. Dependencies and the Google Services plugin are commented out, FCM code is kept dead in comments; do not re-enable without a new Firebase project. - **Login needs a challenge**: `CryptoUtils.generateRsaJwt` requires a `nonce` fetched from `AuthenticationApi.authChallenge()`; the server spends it on use. A login without it is refused. From 9f3cecfbab430e4f18cec7a1136802ba98980c4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 27 Nov 2026 00:40:35 +0100 Subject: [PATCH 180/181] style(app): format the renamed media helper --- lib/utils/media_utils.dart | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart index 53d161b..df80bcd 100644 --- a/lib/utils/media_utils.dart +++ b/lib/utils/media_utils.dart @@ -620,8 +620,7 @@ class MediaUtils { final caption = (decoded['caption'] as String?) ?? ''; final forwarded = decoded['forwarded'] == true; final viewOnce = decoded['viewOnce'] == true; - if (decoded['sheptMsg'] == envelopeVersion && - decoded['media'] is Map) { + if (decoded['sheptMsg'] == envelopeVersion && decoded['media'] is Map) { final reference = MediaReference.fromJson( Map.from(decoded['media'] as Map)); return ParsedMediaEnvelope([reference], caption, From 5a2c574c7e4b785826375c91becd49787748c755 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Fri, 27 Nov 2026 00:40:46 +0100 Subject: [PATCH 181/181] docs(app): mark Firebase as retired --- README.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 20e255e..669568c 100644 --- a/README.md +++ b/README.md @@ -150,7 +150,12 @@ Known limitations (Linux desktop, verified): - run `dart run flutter_launcher_icons` to generate icons - see configuration file [flutter_launcher_icons.yaml](flutter_launcher_icons.yaml) -## Firebase Messaging +## Firebase Messaging (retired) + +> Firebase has been retired. `firebase_core`/`firebase_messaging` are commented out in +> `pubspec.yaml`, the Google Services Gradle plugin is disabled and the FCM code is kept +> dead in comments. The notes below describe what it took to enable it and are kept for a +> possible revival. - [Firebase](https://firebase.google.com/) - used for push notifications when user is offline @@ -186,10 +191,10 @@ Required repository secrets (Settings > Secrets and variables > Actions): | Secret | Used by | Description | | --- | --- | --- | -| `FIREBASE_OPTIONS_DART_BASE64` | `flutter-ci.yml`, `build_and_release.yml` | base64 of `lib/firebase_options.dart`. Required: analysis fails without it. | -| `FIREBASE_JSON_BASE64` | `build_and_release.yml` | base64 of `firebase.json`. | -| `GOOGLE_SERVICES_JSON_BASE64` | `build_and_release.yml` | base64 of `android/app/google-services.json`. | -| `GOOGLE_SERVICE_INFO_PLIST_BASE64` | not wired yet | base64 of `ios/Runner/GoogleService-Info.plist`. Add it to the build before shipping iOS releases. | +| `FIREBASE_OPTIONS_DART_BASE64` | unused | Retired with Firebase. | +| `FIREBASE_JSON_BASE64` | unused | Retired with Firebase. | +| `GOOGLE_SERVICES_JSON_BASE64` | unused | Retired with Firebase. | +| `GOOGLE_SERVICE_INFO_PLIST_BASE64` | unused | Retired with Firebase. | | `GITHUB_TOKEN` | both | Provided automatically by GitHub. Used by the secret scan. | ### Release signing