From 292a826b8ff468b365a85d791d25f4b2bb931706 Mon Sep 17 00:00:00 2001 From: Jganenokk Date: Sun, 4 Oct 2026 00:50:36 +0700 Subject: [PATCH 01/63] =?UTF-8?q?fix:=20=D0=92=D0=98=D0=A2=D0=90=D0=95?= =?UTF-8?q?=D0=9C=D0=9E=20=D0=A3=D0=A7=D0=95=D0=9D=D0=AC=E2=9D=A4=EF=B8=8F?= =?UTF-8?q?=20=D0=9C=D0=90=D0=9B=D0=90=D0=94i=D0=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .gitignore | 2 + lib/backend/api.dart | 10 + .../auth/code_confirmation_screen.dart | 430 +++++++++--------- lib/frontend/screens/auth/login_screen.dart | 13 +- .../screens/auth/password_2fa_screen.dart | 185 ++++---- .../screens/auth/session_stale_recovery.dart | 1 + lib/frontend/screens/calls/call_controls.dart | 112 +++++ lib/frontend/screens/calls/call_screen.dart | 179 ++------ .../widgets/login_success_screen.dart | 4 +- test/call_controls_test.dart | 129 ++++++ 10 files changed, 631 insertions(+), 434 deletions(-) create mode 100644 lib/frontend/screens/calls/call_controls.dart create mode 100644 test/call_controls_test.dart diff --git a/.gitignore b/.gitignore index d108e960..b0550b5e 100644 --- a/.gitignore +++ b/.gitignore @@ -154,3 +154,5 @@ test/live_server_probe_test.dart pubspec_overrides.yaml .cargo/ third_party/kolibri/ + +komet_debug_*.zip diff --git a/lib/backend/api.dart b/lib/backend/api.dart index 1a6288b1..0cd5676b 100644 --- a/lib/backend/api.dart +++ b/lib/backend/api.dart @@ -871,6 +871,16 @@ class Api { } } + Future reconnectPreLogin({required bool web}) async { + _suppressReconnectLogin = true; + try { + await disconnect(); + await connect(authenticated: false, web: web); + } finally { + _suppressReconnectLogin = false; + } + } + // #***! колбэк автологина ставит аккаунт, api про токены не знает Future Function()? _onReconnectCallback; diff --git a/lib/frontend/screens/auth/code_confirmation_screen.dart b/lib/frontend/screens/auth/code_confirmation_screen.dart index 6d781a4c..265979dc 100644 --- a/lib/frontend/screens/auth/code_confirmation_screen.dart +++ b/lib/frontend/screens/auth/code_confirmation_screen.dart @@ -307,6 +307,7 @@ class _CodeConfirmationScreenState extends State _showError(AppLocalizations.of(context)!.codeErrorInvalid); return; } + stopSessionRecovery(); final spoof = credentials.spoof; if (spoof != null) { @@ -345,6 +346,7 @@ class _CodeConfirmationScreenState extends State _token, ); verified = true; + stopSessionRecovery(); if (!mounted) return; @@ -394,7 +396,6 @@ class _CodeConfirmationScreenState extends State _showError(AppLocalizations.of(context)!.codeConfirmationSmsNoToken); return; } - stopSessionRecovery(); await accountModule.completeWebSmsSocketLogin( phone: widget.rawPhone, accountId: accId, @@ -432,237 +433,244 @@ class _CodeConfirmationScreenState extends State final l10n = AppLocalizations.of(context)!; final hasError = _errorMessage != null; - return Scaffold( - backgroundColor: cs.surface, - appBar: AppBar( - backgroundColor: Colors.transparent, - elevation: 0, - leading: IconButton( - icon: Icon(Symbols.arrow_back, color: cs.onSurfaceVariant), - onPressed: () => Navigator.pop(context), + return PopScope( + canPop: !_verifying, + child: Scaffold( + backgroundColor: cs.surface, + appBar: AppBar( + backgroundColor: Colors.transparent, + elevation: 0, + leading: IconButton( + icon: Icon(Symbols.arrow_back, color: cs.onSurfaceVariant), + onPressed: _verifying ? null : () => Navigator.pop(context), + ), ), - ), - body: SafeArea( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const SizedBox(height: 16), - Text( - widget.phoneNumber, - style: TextStyle( - color: cs.onSurface, - fontSize: 22, - fontWeight: FontWeight.w500, - ), - ), - const SizedBox(height: 12), - Text( - l10n.codeConfirmationSmsSent, - style: TextStyle( - color: cs.outline, - fontSize: 15, - fontWeight: FontWeight.w400, - height: 1.4, + body: SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 16), + Text( + widget.phoneNumber, + style: TextStyle( + color: cs.onSurface, + fontSize: 22, + fontWeight: FontWeight.w500, + ), ), - ), - const SizedBox(height: 12), - AnimatedBuilder( - animation: _shakeAnimation, - builder: (context, child) => Transform.translate( - offset: Offset(_shakeAnimation.value, 0), - child: child, + const SizedBox(height: 12), + Text( + l10n.codeConfirmationSmsSent, + style: TextStyle( + color: cs.outline, + fontSize: 15, + fontWeight: FontWeight.w400, + height: 1.4, + ), ), - child: Stack( - children: [ - Opacity( - opacity: 0, - child: SizedBox( - height: 0, - width: 0, - child: TextField( - controller: _codeController, - focusNode: _focusNode, - keyboardType: TextInputType.number, - autofillHints: const [AutofillHints.oneTimeCode], - inputFormatters: [ - FilteringTextInputFormatter.digitsOnly, - LengthLimitingTextInputFormatter(6), - ], - onChanged: (value) { - if (hasError) setState(() => _errorMessage = null); - setState(() {}); - if (value.length == 6) _verifyCode(); - }, + const SizedBox(height: 12), + AnimatedBuilder( + animation: _shakeAnimation, + builder: (context, child) => Transform.translate( + offset: Offset(_shakeAnimation.value, 0), + child: child, + ), + child: Stack( + children: [ + Opacity( + opacity: 0, + child: SizedBox( + height: 0, + width: 0, + child: TextField( + controller: _codeController, + focusNode: _focusNode, + keyboardType: TextInputType.number, + autofillHints: const [AutofillHints.oneTimeCode], + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, + LengthLimitingTextInputFormatter(6), + ], + onChanged: (value) { + if (hasError) { + setState(() => _errorMessage = null); + } + setState(() {}); + if (value.length == 6) _verifyCode(); + }, + ), ), ), - ), - GestureDetector( - onTap: _openKeyboard, - child: FittedBox( - child: Row( - children: List.generate(6, (index) { - final isFocused = - _codeController.text.length == index && - _focusNode.hasFocus; - final hasValue = - _codeController.text.length > index; - final char = hasValue - ? _codeController.text[index] - : ''; - - Color borderColor; - if (hasError && hasValue) { - borderColor = cs.error; - } else if (isFocused) { - borderColor = cs.primary; - } else if (hasValue) { - borderColor = cs.outlineVariant; - } else { - borderColor = Colors.transparent; - } - - return AnimatedContainer( - duration: const Duration(milliseconds: 200), - width: 44, - height: 54, - margin: EdgeInsets.only( - right: index == 5 ? 0 : 10, - ), - decoration: BoxDecoration( - color: hasError && hasValue - ? cs.error.withValues(alpha: 0.1) - : cs.surfaceContainerHigh, - borderRadius: BorderRadius.circular(8), - border: Border.all( - color: borderColor, - width: 1.5, + GestureDetector( + onTap: _openKeyboard, + child: FittedBox( + child: Row( + children: List.generate(6, (index) { + final isFocused = + _codeController.text.length == index && + _focusNode.hasFocus; + final hasValue = + _codeController.text.length > index; + final char = hasValue + ? _codeController.text[index] + : ''; + + Color borderColor; + if (hasError && hasValue) { + borderColor = cs.error; + } else if (isFocused) { + borderColor = cs.primary; + } else if (hasValue) { + borderColor = cs.outlineVariant; + } else { + borderColor = Colors.transparent; + } + + return AnimatedContainer( + duration: const Duration(milliseconds: 200), + width: 44, + height: 54, + margin: EdgeInsets.only( + right: index == 5 ? 0 : 10, ), - ), - alignment: Alignment.center, - child: AnimatedSwitcher( - duration: const Duration(milliseconds: 100), - transitionBuilder: - ( - Widget child, - Animation animation, - ) { - return ScaleTransition( - scale: animation, - child: FadeTransition( - opacity: animation, - child: child, - ), - ); - }, - child: Text( - char, - key: ValueKey( - char + - index.toString() + - (hasError ? 'e' : ''), + decoration: BoxDecoration( + color: hasError && hasValue + ? cs.error.withValues(alpha: 0.1) + : cs.surfaceContainerHigh, + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: borderColor, + width: 1.5, ), - style: TextStyle( - color: hasError && hasValue - ? cs.error - : cs.onSurface, - fontSize: 20, - fontWeight: FontWeight.w600, + ), + alignment: Alignment.center, + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 100), + transitionBuilder: + ( + Widget child, + Animation animation, + ) { + return ScaleTransition( + scale: animation, + child: FadeTransition( + opacity: animation, + child: child, + ), + ); + }, + child: Text( + char, + key: ValueKey( + char + + index.toString() + + (hasError ? 'e' : ''), + ), + style: TextStyle( + color: hasError && hasValue + ? cs.error + : cs.onSurface, + fontSize: 20, + fontWeight: FontWeight.w600, + ), ), ), - ), - ); - }), + ); + }), + ), ), ), - ), - ], + ], + ), ), - ), - const SizedBox(height: 16), - AnimatedSize( - duration: const Duration(milliseconds: 250), - curve: Curves.easeOutCubic, - alignment: Alignment.topLeft, - child: hasError - ? Padding( - padding: const EdgeInsets.only(bottom: 8), - child: AnimatedOpacity( - opacity: hasError ? 1.0 : 0.0, - duration: const Duration(milliseconds: 200), - child: Text( - _errorMessage!, - style: TextStyle( - color: cs.error, - fontSize: 14, - fontWeight: FontWeight.w500, - height: 1.35, + const SizedBox(height: 16), + AnimatedSize( + duration: const Duration(milliseconds: 250), + curve: Curves.easeOutCubic, + alignment: Alignment.topLeft, + child: hasError + ? Padding( + padding: const EdgeInsets.only(bottom: 8), + child: AnimatedOpacity( + opacity: hasError ? 1.0 : 0.0, + duration: const Duration(milliseconds: 200), + child: Text( + _errorMessage!, + style: TextStyle( + color: cs.error, + fontSize: 14, + fontWeight: FontWeight.w500, + height: 1.35, + ), ), ), - ), - ) - : const SizedBox.shrink(), - ), - if (!widget.reviewAccess) - GestureDetector( - onTap: _resendCode, - child: AnimatedDefaultTextStyle( - duration: const Duration(milliseconds: 200), - style: TextStyle( - color: _timerSeconds > 0 ? cs.outline : cs.tertiary, - fontSize: 14, - fontWeight: FontWeight.w400, - ), - child: Text( - _timerSeconds > 0 - ? l10n.codeResendInSeconds(_timerSeconds) - : l10n.codeResendSms, - ), - ), + ) + : const SizedBox.shrink(), ), - const Spacer(), - Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Expanded( - child: Text( - l10n.codeConfirmation2faWarning, + if (!widget.reviewAccess) + GestureDetector( + onTap: _resendCode, + child: AnimatedDefaultTextStyle( + duration: const Duration(milliseconds: 200), style: TextStyle( - color: cs.error.withValues(alpha: 0.5), - fontSize: 13, + color: _timerSeconds > 0 ? cs.outline : cs.tertiary, + fontSize: 14, fontWeight: FontWeight.w400, - height: 1.35, + ), + child: Text( + _timerSeconds > 0 + ? l10n.codeResendInSeconds(_timerSeconds) + : l10n.codeResendSms, ), ), ), - const SizedBox(width: 16), - FloatingActionButton( - onPressed: (recovering || _verifying) - ? null - : () { - if (_codeController.text.length == 6) _verifyCode(); - }, - backgroundColor: _codeController.text.length == 6 - ? cs.primaryContainer - : cs.surfaceContainerHighest, - elevation: 0, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(50), + const Spacer(), + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + child: Text( + l10n.codeConfirmation2faWarning, + style: TextStyle( + color: cs.error.withValues(alpha: 0.5), + fontSize: 13, + fontWeight: FontWeight.w400, + height: 1.35, + ), + ), ), - child: (recovering || _verifying) - ? SmallSpinner(size: 24, color: cs.onPrimaryContainer) - : Icon( - Symbols.arrow_forward, - color: _codeController.text.length == 6 - ? cs.onPrimaryContainer - : cs.onSurfaceVariant, - ), - ), - ], - ), - const SizedBox(height: 24), - ], + const SizedBox(width: 16), + FloatingActionButton( + onPressed: (recovering || _verifying) + ? null + : () { + if (_codeController.text.length == 6) { + _verifyCode(); + } + }, + backgroundColor: _codeController.text.length == 6 + ? cs.primaryContainer + : cs.surfaceContainerHighest, + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(50), + ), + child: (recovering || _verifying) + ? SmallSpinner(size: 24, color: cs.onPrimaryContainer) + : Icon( + Symbols.arrow_forward, + color: _codeController.text.length == 6 + ? cs.onPrimaryContainer + : cs.onSurfaceVariant, + ), + ), + ], + ), + const SizedBox(height: 24), + ], + ), ), ), ), diff --git a/lib/frontend/screens/auth/login_screen.dart b/lib/frontend/screens/auth/login_screen.dart index 4b0bd596..d0419eb3 100644 --- a/lib/frontend/screens/auth/login_screen.dart +++ b/lib/frontend/screens/auth/login_screen.dart @@ -80,8 +80,7 @@ class _LoginScreenState extends State { _switchingSmsMode = true; }); try { - await api.disconnect(); - await api.connect(authenticated: false, web: value); + await api.reconnectPreLogin(web: value); } catch (e) { if (!mounted) return; showCustomNotification( @@ -93,6 +92,15 @@ class _LoginScreenState extends State { } } + Future _ensurePreLoginSession() async { + final fresh = + !accountModule.isLoggedIn && + !api.isAuthenticatedHandshake && + api.webHandshake == _alwaysSendSms; + if (fresh) return; + await api.reconnectPreLogin(web: _alwaysSendSms); + } + // #***! предупреждение перед эксперим. SMS-входом: true=Принять, false=Отмена, // null=закрыли мимо (галочку не трогаем, но и дальше не идём) Future _showExperimentalSmsWarning() { @@ -637,6 +645,7 @@ class _LoginScreenState extends State { } try { + await _ensurePreLoginSession(); final result = await accountModule.requestCode( fullPhone, ); diff --git a/lib/frontend/screens/auth/password_2fa_screen.dart b/lib/frontend/screens/auth/password_2fa_screen.dart index 22f908bd..30380de7 100644 --- a/lib/frontend/screens/auth/password_2fa_screen.dart +++ b/lib/frontend/screens/auth/password_2fa_screen.dart @@ -81,6 +81,7 @@ class _Password2FAScreenState extends State trackId: widget.trackId, ); passed = true; + stopSessionRecovery(); if (!mounted) return; @@ -88,7 +89,6 @@ class _Password2FAScreenState extends State // #***! эксперим. SMS-вход через веб: пароль пользователя уже есть, добываем // сокетовый токен и перезаходим боевой версией if (api.webHandshake && widget.rawPhone != null) { - stopSessionRecovery(); await accountModule.completeWebSmsSocketLogin( phone: widget.rawPhone!, accountId: result.accountId, @@ -145,108 +145,111 @@ class _Password2FAScreenState extends State Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; final l10n = AppLocalizations.of(context)!; - return Scaffold( - backgroundColor: cs.surface, - appBar: AppBar( - backgroundColor: Colors.transparent, - elevation: 0, - leading: IconButton( - icon: Icon(Symbols.arrow_back, color: cs.onSurfaceVariant), - onPressed: () => Navigator.pop(context), + return PopScope( + canPop: !_isLoading, + child: Scaffold( + backgroundColor: cs.surface, + appBar: AppBar( + backgroundColor: Colors.transparent, + elevation: 0, + leading: IconButton( + icon: Icon(Symbols.arrow_back, color: cs.onSurfaceVariant), + onPressed: _isLoading ? null : () => Navigator.pop(context), + ), ), - ), - body: SafeArea( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const SizedBox(height: 16), - Text( - l10n.passwordEntry2faSubtitle, - style: TextStyle( - color: cs.onSurface, - fontSize: 22, - fontWeight: FontWeight.w500, - ), - ), - const SizedBox(height: 12), - Text( - l10n.password2faEnterPassword, - style: TextStyle( - color: cs.outline, - fontSize: 15, - fontWeight: FontWeight.w400, - height: 1.4, + body: SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 16), + Text( + l10n.passwordEntry2faSubtitle, + style: TextStyle( + color: cs.onSurface, + fontSize: 22, + fontWeight: FontWeight.w500, + ), ), - ), - if (widget.hint != null) ...[ - const SizedBox(height: 8), + const SizedBox(height: 12), Text( - l10n.passwordEntryHintPrefix(widget.hint ?? ''), + l10n.password2faEnterPassword, style: TextStyle( - color: cs.tertiary, - fontSize: 14, + color: cs.outline, + fontSize: 15, fontWeight: FontWeight.w400, + height: 1.4, ), ), - ], - const SizedBox(height: 24), - TextField( - controller: _passwordController, - obscureText: !_isPasswordVisible, - autofocus: true, - enabled: !_isLoading, - decoration: InputDecoration( - hintText: l10n.passwordEntryGenericPasswordHint, - filled: true, - fillColor: cs.surfaceContainerHigh, - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(12), - borderSide: BorderSide.none, + if (widget.hint != null) ...[ + const SizedBox(height: 8), + Text( + l10n.passwordEntryHintPrefix(widget.hint ?? ''), + style: TextStyle( + color: cs.tertiary, + fontSize: 14, + fontWeight: FontWeight.w400, + ), ), - suffixIcon: IconButton( - icon: AnimatedSlashIcon( - icon: Symbols.visibility, - slashedIcon: Symbols.visibility_off, - slashed: _isPasswordVisible, - color: cs.onSurfaceVariant, + ], + const SizedBox(height: 24), + TextField( + controller: _passwordController, + obscureText: !_isPasswordVisible, + autofocus: true, + enabled: !_isLoading, + decoration: InputDecoration( + hintText: l10n.passwordEntryGenericPasswordHint, + filled: true, + fillColor: cs.surfaceContainerHigh, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide.none, + ), + suffixIcon: IconButton( + icon: AnimatedSlashIcon( + icon: Symbols.visibility, + slashedIcon: Symbols.visibility_off, + slashed: _isPasswordVisible, + color: cs.onSurfaceVariant, + ), + onPressed: () { + setState(() { + _isPasswordVisible = !_isPasswordVisible; + }); + }, ), - onPressed: () { - setState(() { - _isPasswordVisible = !_isPasswordVisible; - }); - }, ), + onSubmitted: (_) => _checkPassword(), ), - onSubmitted: (_) => _checkPassword(), - ), - const Spacer(), - Row( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - FloatingActionButton( - onPressed: _isLoading ? null : _checkPassword, - backgroundColor: _passwordController.text.isNotEmpty - ? cs.primaryContainer - : cs.surfaceContainerHighest, - elevation: 0, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(50), + const Spacer(), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + FloatingActionButton( + onPressed: _isLoading ? null : _checkPassword, + backgroundColor: _passwordController.text.isNotEmpty + ? cs.primaryContainer + : cs.surfaceContainerHighest, + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(50), + ), + child: _isLoading + ? SmallSpinner(size: 24, color: cs.onPrimaryContainer) + : Icon( + Symbols.arrow_forward, + color: _passwordController.text.isNotEmpty + ? cs.onPrimaryContainer + : cs.onSurfaceVariant, + ), ), - child: _isLoading - ? SmallSpinner(size: 24, color: cs.onPrimaryContainer) - : Icon( - Symbols.arrow_forward, - color: _passwordController.text.isNotEmpty - ? cs.onPrimaryContainer - : cs.onSurfaceVariant, - ), - ), - ], - ), - const SizedBox(height: 24), - ], + ], + ), + const SizedBox(height: 24), + ], + ), ), ), ), diff --git a/lib/frontend/screens/auth/session_stale_recovery.dart b/lib/frontend/screens/auth/session_stale_recovery.dart index 98964964..b658344d 100644 --- a/lib/frontend/screens/auth/session_stale_recovery.dart +++ b/lib/frontend/screens/auth/session_stale_recovery.dart @@ -24,6 +24,7 @@ mixin SessionStaleRecovery on State { void stopSessionRecovery() { _stateSub?.cancel(); + _stateSub = null; } void _onSessionState(SessionState state) { diff --git a/lib/frontend/screens/calls/call_controls.dart b/lib/frontend/screens/calls/call_controls.dart new file mode 100644 index 00000000..a2a9c0e6 --- /dev/null +++ b/lib/frontend/screens/calls/call_controls.dart @@ -0,0 +1,112 @@ +import 'dart:math' show min; + +import 'package:flutter/material.dart'; + +import '../../widgets/animated_slash_icon.dart'; +import '../../widgets/glossy_pill.dart'; +import '../../widgets/small_spinner.dart'; + +class CallControlBar extends StatelessWidget { + final List children; + + const CallControlBar({super.key, required this.children}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [for (final child in children) Expanded(child: child)], + ), + ); + } +} + +class CallButton extends StatelessWidget { + static const double maxDiameter = 62; + static const double _minGap = 6; + + final IconData icon; + final IconData? slashedIcon; + final bool slashed; + final String label; + final Color background; + final Color foreground; + final VoidCallback onTap; + final VoidCallback? onLongPress; + final bool busy; + + const CallButton({ + super.key, + required this.icon, + required this.label, + required this.background, + required this.foreground, + required this.onTap, + this.onLongPress, + this.slashedIcon, + this.slashed = false, + this.busy = false, + }); + + Widget _buildIcon() { + final crossed = slashedIcon; + if (crossed == null) { + return Icon(icon, color: foreground, size: 26, fill: 1); + } + return AnimatedSlashIcon( + icon: icon, + slashedIcon: crossed, + slashed: slashed, + color: foreground, + size: 26, + fill: 1, + ); + } + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + return LayoutBuilder( + builder: (context, constraints) { + final diameter = min(maxDiameter, constraints.maxWidth - _minGap); + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + width: diameter, + height: diameter, + child: GlossyPill( + color: background, + borderRadius: BorderRadius.circular(diameter / 2), + onTap: busy ? null : onTap, + onLongPress: busy ? null : onLongPress, + depth: 9, + child: Center( + child: busy + ? SmallSpinner(size: 22, color: foreground) + : _buildIcon(), + ), + ), + ), + const SizedBox(height: 8), + FittedBox( + fit: BoxFit.scaleDown, + child: Text( + label, + maxLines: 1, + softWrap: false, + style: TextStyle( + color: cs.onSurfaceVariant, + fontSize: 12, + fontWeight: FontWeight.w500, + ), + ), + ), + ], + ); + }, + ); + } +} diff --git a/lib/frontend/screens/calls/call_screen.dart b/lib/frontend/screens/calls/call_screen.dart index 9b01fbcc..3e1ea0d3 100644 --- a/lib/frontend/screens/calls/call_screen.dart +++ b/lib/frontend/screens/calls/call_screen.dart @@ -22,9 +22,8 @@ import '../../../l10n/app_localizations.dart'; import '../../widgets/call_video_view.dart'; import '../../widgets/custom_notification.dart'; import '../../widgets/glossy_pill.dart'; -import '../../widgets/animated_slash_icon.dart'; import '../../widgets/sheet_helpers.dart'; -import '../../widgets/small_spinner.dart'; +import 'call_controls.dart'; import 'call_mic_sheet.dart'; import 'call_participants_sheet.dart'; import 'komet_hub.dart'; @@ -1259,14 +1258,14 @@ class _CallScreenState extends State with TickerProviderStateMixin { child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - _CallButton( + CallButton( icon: Symbols.call_end, label: l10n.callDecline, background: kDangerRed, foreground: Colors.white, onTap: _decline, ), - _CallButton( + CallButton( icon: Symbols.call, label: l10n.callAccept, background: kSuccessGreen, @@ -1282,57 +1281,53 @@ class _CallScreenState extends State with TickerProviderStateMixin { final l10n = AppLocalizations.of(context)!; final video = _session?.localVideo == true; final screen = _session?.localScreen == true; - return Padding( - padding: const EdgeInsets.symmetric(horizontal: 12), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - _CallButton( - icon: _isSpeaker ? Symbols.volume_up : Symbols.volume_down, - label: l10n.callSpeaker, - background: _isSpeaker ? cs.primary : cs.surfaceContainerHighest, - foreground: _isSpeaker ? cs.onPrimary : cs.onSurface, - onTap: _toggleSpeaker, - ), - _CallButton( - icon: Symbols.videocam, - slashedIcon: Symbols.videocam_off, - slashed: !video, - label: l10n.callVideoLabel, - background: video ? cs.primary : cs.surfaceContainerHighest, - foreground: video ? cs.onPrimary : cs.onSurface, - busy: _videoBusy, - onTap: _toggleVideo, - ), - _CallButton( - icon: Symbols.screen_share, - label: l10n.callScreenLabel, - background: screen ? cs.primary : cs.surfaceContainerHighest, - foreground: screen ? cs.onPrimary : cs.onSurface, - busy: _videoBusy, - onTap: _toggleScreen, - ), - _CallButton( - icon: Symbols.mic, - slashedIcon: Symbols.mic_off, - slashed: _isMuted, - label: _isMuted - ? (CallNoMute.enabled ? l10n.callMicStillLive : l10n.callUnmute) - : l10n.callMute, - background: _isMuted ? cs.primary : cs.surfaceContainerHighest, - foreground: _isMuted ? cs.onPrimary : cs.onSurface, - onTap: _toggleMute, - onLongPress: _showMicrophones, - ), - _CallButton( - icon: Symbols.call_end, - label: l10n.callEndButton, - background: kDangerRed, - foreground: Colors.white, - onTap: _hangup, - ), - ], - ), + return CallControlBar( + children: [ + CallButton( + icon: _isSpeaker ? Symbols.volume_up : Symbols.volume_down, + label: l10n.callSpeaker, + background: _isSpeaker ? cs.primary : cs.surfaceContainerHighest, + foreground: _isSpeaker ? cs.onPrimary : cs.onSurface, + onTap: _toggleSpeaker, + ), + CallButton( + icon: Symbols.videocam, + slashedIcon: Symbols.videocam_off, + slashed: !video, + label: l10n.callVideoLabel, + background: video ? cs.primary : cs.surfaceContainerHighest, + foreground: video ? cs.onPrimary : cs.onSurface, + busy: _videoBusy, + onTap: _toggleVideo, + ), + CallButton( + icon: Symbols.screen_share, + label: l10n.callScreenLabel, + background: screen ? cs.primary : cs.surfaceContainerHighest, + foreground: screen ? cs.onPrimary : cs.onSurface, + busy: _videoBusy, + onTap: _toggleScreen, + ), + CallButton( + icon: Symbols.mic, + slashedIcon: Symbols.mic_off, + slashed: _isMuted, + label: _isMuted + ? (CallNoMute.enabled ? l10n.callMicStillLive : l10n.callUnmute) + : l10n.callMute, + background: _isMuted ? cs.primary : cs.surfaceContainerHighest, + foreground: _isMuted ? cs.onPrimary : cs.onSurface, + onTap: _toggleMute, + onLongPress: _showMicrophones, + ), + CallButton( + icon: Symbols.call_end, + label: l10n.callEndButton, + background: kDangerRed, + foreground: Colors.white, + onTap: _hangup, + ), + ], ); } } @@ -1380,80 +1375,6 @@ class _CallingDots extends StatelessWidget { } } -class _CallButton extends StatelessWidget { - final IconData icon; - final IconData? slashedIcon; - final bool slashed; - final String label; - final Color background; - final Color foreground; - final VoidCallback onTap; - final VoidCallback? onLongPress; - final bool busy; - - const _CallButton({ - required this.icon, - required this.label, - required this.background, - required this.foreground, - required this.onTap, - this.onLongPress, - this.slashedIcon, - this.slashed = false, - this.busy = false, - }); - - Widget _buildIcon() { - final crossed = slashedIcon; - if (crossed == null) { - return Icon(icon, color: foreground, size: 26, fill: 1); - } - return AnimatedSlashIcon( - icon: icon, - slashedIcon: crossed, - slashed: slashed, - color: foreground, - size: 26, - fill: 1, - ); - } - - @override - Widget build(BuildContext context) { - final cs = Theme.of(context).colorScheme; - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - SizedBox( - width: 62, - height: 62, - child: GlossyPill( - color: background, - borderRadius: BorderRadius.circular(31), - onTap: busy ? null : onTap, - onLongPress: busy ? null : onLongPress, - depth: 9, - child: Center( - child: busy - ? SmallSpinner(size: 22, color: foreground) - : _buildIcon(), - ), - ), - ), - const SizedBox(height: 8), - Text( - label, - style: TextStyle( - color: cs.onSurfaceVariant, - fontSize: 12, - fontWeight: FontWeight.w500, - ), - ), - ], - ); - } -} - class _ElapsedText extends StatefulWidget { final CallSession session; final TextStyle style; diff --git a/lib/frontend/widgets/login_success_screen.dart b/lib/frontend/widgets/login_success_screen.dart index b26e0b28..e38bf7c8 100644 --- a/lib/frontend/widgets/login_success_screen.dart +++ b/lib/frontend/widgets/login_success_screen.dart @@ -7,6 +7,8 @@ import '../../core/utils/haptics.dart'; import '../../l10n/app_localizations.dart'; import 'adaptive_shell.dart'; +const _avatarPrecacheTimeout = Duration(seconds: 5); + Future precacheLoginAvatar( BuildContext context, String? url, @@ -14,7 +16,7 @@ Future precacheLoginAvatar( if (url == null || url.isEmpty) return null; final provider = CachedNetworkImageProvider(url); try { - await precacheImage(provider, context); + await precacheImage(provider, context).timeout(_avatarPrecacheTimeout); return provider; } catch (_) { return null; diff --git a/test/call_controls_test.dart b/test/call_controls_test.dart new file mode 100644 index 00000000..e246409b --- /dev/null +++ b/test/call_controls_test.dart @@ -0,0 +1,129 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/frontend/screens/calls/call_controls.dart'; + +const _labels = ['Динамик', 'Видео', 'Экран', 'Выкл. звук', 'Завершить']; + +Widget _controls({required double textScale}) => MaterialApp( + home: MediaQuery( + data: MediaQueryData( + size: const Size(320, 640), + textScaler: TextScaler.linear(textScale), + ), + child: Scaffold( + body: Align( + alignment: Alignment.bottomCenter, + child: CallControlBar( + children: [ + for (final label in _labels) + CallButton( + key: ValueKey(label), + icon: Icons.call_end, + label: label, + background: Colors.red, + foreground: Colors.white, + onTap: () {}, + ), + ], + ), + ), + ), + ), +); + +Future _pumpNarrow(WidgetTester tester, double textScale) async { + tester.view.physicalSize = const Size(960, 1920); + tester.view.devicePixelRatio = 3; + addTearDown(tester.view.reset); + await tester.pumpWidget(_controls(textScale: textScale)); +} + +void main() { + for (final scale in [1.0, 1.6]) { + testWidgets('все кнопки звонка влезают в 320dp при шрифте ×$scale', ( + tester, + ) async { + await _pumpNarrow(tester, scale); + + expect(tester.takeException(), isNull); + for (final label in _labels) { + final rect = tester.getRect(find.byKey(ValueKey(label))); + expect(rect.left, greaterThanOrEqualTo(0), reason: label); + expect(rect.right, lessThanOrEqualTo(320), reason: label); + } + }); + } + + testWidgets('кнопка вне панели сохраняет полный размер', (tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + for (final label in ['Отклонить', 'Принять']) + CallButton( + key: ValueKey(label), + icon: Icons.call, + label: label, + background: Colors.green, + foreground: Colors.white, + onTap: () {}, + ), + ], + ), + ), + ), + ); + + expect(tester.takeException(), isNull); + final circle = find.descendant( + of: find.byKey(const ValueKey('Принять')), + matching: find.byWidgetPredicate( + (w) => w is SizedBox && w.width == CallButton.maxDiameter, + ), + ); + expect(circle, findsOneWidget); + }); + + testWidgets('кнопка «Завершить» нажимается на узком экране', (tester) async { + tester.view.physicalSize = const Size(960, 1920); + tester.view.devicePixelRatio = 3; + addTearDown(tester.view.reset); + var hungUp = false; + await tester.pumpWidget( + MaterialApp( + home: MediaQuery( + data: const MediaQueryData( + size: Size(320, 640), + textScaler: TextScaler.linear(1.6), + ), + child: Scaffold( + body: CallControlBar( + children: [ + for (final label in _labels.take(4)) + CallButton( + icon: Icons.mic, + label: label, + background: Colors.grey, + foreground: Colors.white, + onTap: () {}, + ), + CallButton( + icon: Icons.call_end, + label: 'Завершить', + background: Colors.red, + foreground: Colors.white, + onTap: () => hungUp = true, + ), + ], + ), + ), + ), + ), + ); + + await tester.tap(find.byIcon(Icons.call_end)); + expect(hungUp, isTrue); + }); +} From 2211f1a95f3147b414f692dea90440329c76cb85 Mon Sep 17 00:00:00 2001 From: Jganenokk Date: Sun, 4 Oct 2026 01:19:03 +0700 Subject: [PATCH 02/63] fix: #161, #159, #160. --- lib/core/config/app_colors.dart | 6 +- lib/core/utils/seed_scheme.dart | 16 +++ lib/frontend/screens/calls/call_screen.dart | 6 +- .../screens/profile/appearance_screen.dart | 7 +- .../screens/profile/security_screen.dart | 125 +++++++++--------- lib/l10n/app_en.arb | 2 +- lib/l10n/app_localizations.dart | 6 +- lib/l10n/app_localizations_en.dart | 2 +- lib/l10n/app_localizations_ru.dart | 2 +- lib/l10n/app_ru.arb | 2 +- lib/main.dart | 11 +- pubspec.lock | 2 +- pubspec.yaml | 1 + test/seed_scheme_test.dart | 60 +++++++++ 14 files changed, 155 insertions(+), 93 deletions(-) create mode 100644 lib/core/utils/seed_scheme.dart create mode 100644 test/seed_scheme_test.dart diff --git a/lib/core/config/app_colors.dart b/lib/core/config/app_colors.dart index 0f412533..3525a4f3 100644 --- a/lib/core/config/app_colors.dart +++ b/lib/core/config/app_colors.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import '../utils/seed_scheme.dart'; // #***! доп цвета поверх ColorScheme extension AppColorTokens on ColorScheme { @@ -23,10 +24,7 @@ class MediaAccent { final seed = Theme.of(context).colorScheme.primary; if (_seed != seed || _scheme == null) { _seed = seed; - _scheme = ColorScheme.fromSeed( - seedColor: seed, - brightness: Brightness.dark, - ); + _scheme = schemeFromSeed(seed, Brightness.dark); } return _scheme!; } diff --git a/lib/core/utils/seed_scheme.dart b/lib/core/utils/seed_scheme.dart new file mode 100644 index 00000000..4aeea73a --- /dev/null +++ b/lib/core/utils/seed_scheme.dart @@ -0,0 +1,16 @@ +import 'package:flutter/material.dart'; +import 'package:material_color_utilities/material_color_utilities.dart'; + +const double kAchromaticSeedChroma = 10; + +bool isAchromaticSeed(Color seed) => + Hct.fromInt(seed.toARGB32()).chroma < kAchromaticSeedChroma; + +ColorScheme schemeFromSeed(Color seed, Brightness brightness) => + ColorScheme.fromSeed( + seedColor: seed, + brightness: brightness, + dynamicSchemeVariant: isAchromaticSeed(seed) + ? DynamicSchemeVariant.monochrome + : DynamicSchemeVariant.tonalSpot, + ); diff --git a/lib/frontend/screens/calls/call_screen.dart b/lib/frontend/screens/calls/call_screen.dart index 3e1ea0d3..08386198 100644 --- a/lib/frontend/screens/calls/call_screen.dart +++ b/lib/frontend/screens/calls/call_screen.dart @@ -28,6 +28,7 @@ import 'call_mic_sheet.dart'; import 'call_participants_sheet.dart'; import 'komet_hub.dart'; import '../../../core/config/app_fonts.dart'; +import '../../../core/utils/seed_scheme.dart'; class CallScreen extends StatefulWidget { final String name; @@ -227,10 +228,7 @@ class _CallScreenState extends State with TickerProviderStateMixin { final seed = Theme.of(context).colorScheme.primary; if (_seedKey != seed || _scheme == null) { _seedKey = seed; - _scheme = ColorScheme.fromSeed( - seedColor: seed, - brightness: Brightness.dark, - ); + _scheme = schemeFromSeed(seed, Brightness.dark); } return _scheme!; } diff --git a/lib/frontend/screens/profile/appearance_screen.dart b/lib/frontend/screens/profile/appearance_screen.dart index 1463c450..d0e5211c 100644 --- a/lib/frontend/screens/profile/appearance_screen.dart +++ b/lib/frontend/screens/profile/appearance_screen.dart @@ -21,6 +21,7 @@ import '../../../main.dart'; import '../../widgets/liquid_glass.dart'; import '../../widgets/settings_card.dart'; import '../../../core/config/app_shape.dart'; +import '../../../core/utils/seed_scheme.dart'; class AppearanceScreen extends StatefulWidget { const AppearanceScreen({super.key}); @@ -602,10 +603,7 @@ class _PreviewSectionState extends State<_PreviewSection> { } _cachedColor = color; _cachedBrightness = brightness; - _cachedScheme = ColorScheme.fromSeed( - seedColor: color, - brightness: brightness, - ); + _cachedScheme = schemeFromSeed(color, brightness); return _cachedScheme!; } @@ -1005,4 +1003,3 @@ class _BubbleBehaviorCard extends StatelessWidget { ); } } - diff --git a/lib/frontend/screens/profile/security_screen.dart b/lib/frontend/screens/profile/security_screen.dart index 48ce6ebe..4f9c808e 100644 --- a/lib/frontend/screens/profile/security_screen.dart +++ b/lib/frontend/screens/profile/security_screen.dart @@ -36,6 +36,9 @@ class SecurityScreen extends StatefulWidget { class _SecurityScreenState extends State with SingleTickerProviderStateMixin, ReloadOnReconnect { + static const _contentLevelSafe = 'SAFE'; + static const _contentLevelAll = 'ALL'; + bool _isLoading = true; bool _isSaving = false; bool _is2faEnabled = false; @@ -72,15 +75,8 @@ class _SecurityScreenState extends State final results = await Future.wait([ accountModule.getPrivacyConfig(), accountModule.getBlockedContacts(), - AppDatabase.loadActiveProfile(), ]); - bool is2faEnabled; - try { - is2faEnabled = (await accountModule.get2faStatus()).enabled; - } catch (_) { - final profile = results[2] as ProfileData?; - is2faEnabled = profile?.profileOptions?.contains(2) ?? false; - } + final is2faEnabled = await _fetch2faEnabled(); if (mounted) { setState(() { _privacyConfig = results[0] as PrivacyConfig; @@ -100,6 +96,24 @@ class _SecurityScreenState extends State } } + Future _fetch2faEnabled() async { + try { + return (await accountModule.get2faStatus()).enabled; + } catch (_) { + final profile = await AppDatabase.loadActiveProfile(); + return profile?.profileOptions?.contains(2) ?? false; + } + } + + Future _openPasswordSettings() async { + await Navigator.push( + context, + MaterialPageRoute(builder: (context) => const PasswordEntryScreen()), + ); + final enabled = await _fetch2faEnabled(); + if (mounted) setState(() => _is2faEnabled = enabled); + } + Future _setSafeMode(bool value) async { if (_isSaving) return; if (value && !await _confirmSafeMode()) return; @@ -438,14 +452,7 @@ class _SecurityScreenState extends State Material( color: Colors.transparent, child: InkWell( - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => const PasswordEntryScreen(), - ), - ); - }, + onTap: _openPasswordSettings, borderRadius: BorderRadius.zero, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 17), @@ -483,8 +490,10 @@ class _SecurityScreenState extends State ], ), ), - _buildWarningBadge(cs), - const SizedBox(width: 4), + if (!_is2faEnabled) ...[ + _buildWarningBadge(cs), + const SizedBox(width: 4), + ], Icon( Symbols.chevron_right, color: cs.outline, @@ -580,30 +589,31 @@ class _SecurityScreenState extends State onSelect: (value) => _updateSetting('SEARCH_BY_PHONE', value), ), ), - if (isSafeMode) - _settingsRow( - cs, - icon: Symbols.filter_alt, - label: l10n.securityShowContact, - trailingText: contentLevelAccess - ? l10n.securityContentSafe - : l10n.securityContentAll, - lockedBySafeMode: true, - ) - else - _settingsRow( + _settingsRow( + cs, + icon: Symbols.filter_alt, + label: l10n.securityShowContent, + trailingText: contentLevelAccess + ? l10n.securityContentSafe + : l10n.securityContentAll, + lockedBySafeMode: isSafeMode, + onTap: () => _showOptionSheet( + context, cs, - icon: Symbols.filter_alt, - label: l10n.securityShowContact, - trailingWidget: Switch( - value: contentLevelAccess, - onChanged: (v) => _updateSetting('CONTENT_LEVEL_ACCESS', v), + title: l10n.securityShowContent, + currentValue: contentLevelAccess + ? _contentLevelSafe + : _contentLevelAll, + options: [ + (_contentLevelSafe, l10n.securityContentSafe), + (_contentLevelAll, l10n.securityContentAll), + ], + onSelect: (value) => _updateSetting( + 'CONTENT_LEVEL_ACCESS', + value == _contentLevelSafe, ), - showChevron: false, - verticalPadding: 14, - onTap: () => - _updateSetting('CONTENT_LEVEL_ACCESS', !contentLevelAccess), ), + ), _settingsRow( cs, icon: Symbols.visibility_off, @@ -631,7 +641,8 @@ class _SecurityScreenState extends State ('CONTACTS', l10n.securityPrivacyContacts), ('NOBODY', l10n.securityPrivacyNobody), ], - onSelect: (value) => _updateSetting('PHONE_NUMBER_PRIVACY', value), + onSelect: (value) => + _updateSetting('PHONE_NUMBER_PRIVACY', value), ), ), ], @@ -648,10 +659,7 @@ class _SecurityScreenState extends State child: InkWell( onTap: _isSaving ? null : () => _setSafeMode(!isSafeMode), child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: 20, - vertical: 17, - ), + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 17), child: Row( children: [ Icon( @@ -837,18 +845,13 @@ class _SecurityScreenState extends State label: l10n.securityReadReceipts, trailingWidget: Switch( value: showReadMark, - onChanged: (v) => _updateConfidentialSetting( - 'SHOW_READ_MARK', - v, - ), + onChanged: (v) => _updateConfidentialSetting('SHOW_READ_MARK', v), ), showChevron: false, verticalPadding: 14, isLast: false, - onTap: () => _updateConfidentialSetting( - 'SHOW_READ_MARK', - !showReadMark, - ), + onTap: () => + _updateConfidentialSetting('SHOW_READ_MARK', !showReadMark), ), _settingsRow( cs, @@ -861,10 +864,8 @@ class _SecurityScreenState extends State showChevron: false, verticalPadding: 14, isLast: false, - onTap: () => _updateConfidentialSetting( - 'ALT_KEYBOARD', - !altKeyboard, - ), + onTap: () => + _updateConfidentialSetting('ALT_KEYBOARD', !altKeyboard), ), _settingsRow( cs, @@ -877,10 +878,8 @@ class _SecurityScreenState extends State showChevron: false, verticalPadding: 14, isLast: false, - onTap: () => _updateConfidentialSetting( - 'UNSAFE_FILES', - !unsafeFiles, - ), + onTap: () => + _updateConfidentialSetting('UNSAFE_FILES', !unsafeFiles), ), _settingsRow( cs, @@ -888,10 +887,8 @@ class _SecurityScreenState extends State label: l10n.securityAudioTranscription, trailingWidget: Switch( value: audioTranscription, - onChanged: (v) => _updateConfidentialSetting( - 'AUDIO_TRANSCRIPTION_ENABLED', - v, - ), + onChanged: (v) => + _updateConfidentialSetting('AUDIO_TRANSCRIPTION_ENABLED', v), ), showChevron: false, verticalPadding: 14, diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 950dab59..3a96f24d 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -797,7 +797,7 @@ "securityFindByPhone": "Find me by phone number", "securityWhoCanCall": "Who can call me", "securityWhoCanInvite": "Who can invite me to chats", - "securityShowContact": "Show contact", + "securityShowContent": "Show content", "securityContentSafe": "Safe", "securityContentAll": "All", "securityShowOnlineStatus": "See online status", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index d988be42..f5db1d39 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3764,11 +3764,11 @@ abstract class AppLocalizations { /// **'Who can invite me to chats'** String get securityWhoCanInvite; - /// No description provided for @securityShowContact. + /// No description provided for @securityShowContent. /// /// In en, this message translates to: - /// **'Show contact'** - String get securityShowContact; + /// **'Show content'** + String get securityShowContent; /// No description provided for @securityContentSafe. /// diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index cecc317b..99caf442 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1953,7 +1953,7 @@ class AppLocalizationsEn extends AppLocalizations { String get securityWhoCanInvite => 'Who can invite me to chats'; @override - String get securityShowContact => 'Show contact'; + String get securityShowContent => 'Show content'; @override String get securityContentSafe => 'Safe'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 4b227997..fc8679a5 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1960,7 +1960,7 @@ class AppLocalizationsRu extends AppLocalizations { String get securityWhoCanInvite => 'Кто может приглашать в чаты'; @override - String get securityShowContact => 'Показывать контакт'; + String get securityShowContent => 'Показывать контент'; @override String get securityContentSafe => 'Безопасный'; diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index cbdfacd5..78cb220f 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -625,7 +625,7 @@ "securityFindByPhone": "Найти меня по номеру", "securityWhoCanCall": "Кто может мне звонить", "securityWhoCanInvite": "Кто может приглашать в чаты", - "securityShowContact": "Показывать контакт", + "securityShowContent": "Показывать контент", "securityContentSafe": "Безопасный", "securityContentAll": "Весь", "securityShowOnlineStatus": "Видеть статус «в сети»", diff --git a/lib/main.dart b/lib/main.dart index b82dc1d9..eae1dc8c 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -60,6 +60,7 @@ import 'core/config/app_nav_pill_style.dart'; import 'core/config/app_wallpaper_tint.dart'; import 'core/storage/chat_wallpaper_store.dart'; import 'core/utils/wallpaper_seed.dart'; +import 'core/utils/seed_scheme.dart'; import 'core/config/app_theme_mode.dart'; import 'core/config/app_theme_schedule.dart'; import 'core/config/app_digital_id_mode.dart'; @@ -974,14 +975,8 @@ class KometAppState extends State return (light: _seedCacheLight!, dark: _seedCacheDark!); } _seedCacheKey = seed; - _seedCacheLight = ColorScheme.fromSeed( - seedColor: seed, - brightness: Brightness.light, - ); - _seedCacheDark = ColorScheme.fromSeed( - seedColor: seed, - brightness: Brightness.dark, - ); + _seedCacheLight = schemeFromSeed(seed, Brightness.light); + _seedCacheDark = schemeFromSeed(seed, Brightness.dark); return (light: _seedCacheLight!, dark: _seedCacheDark!); } diff --git a/pubspec.lock b/pubspec.lock index f2b737ca..2f570f25 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1124,7 +1124,7 @@ packages: source: hosted version: "0.12.20" material_color_utilities: - dependency: transitive + dependency: "direct main" description: name: material_color_utilities sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" diff --git a/pubspec.yaml b/pubspec.yaml index e5b6576c..7a2e6536 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -79,6 +79,7 @@ dependencies: m3e_collection: ^0.3.7 material_symbols_icons: ^4.2906.0 dynamic_color: ^1.8.1 + material_color_utilities: ^0.13.0 shared_preferences: ^2.5.4 flutter_secure_storage: ^10.3.1 package_info_plus: ^9.0.1 diff --git a/test/seed_scheme_test.dart b/test/seed_scheme_test.dart new file mode 100644 index 00000000..a966d6bb --- /dev/null +++ b/test/seed_scheme_test.dart @@ -0,0 +1,60 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/config/chat_wallpaper_themes.dart'; +import 'package:komet/core/storage/chat_wallpaper_store.dart'; +import 'package:komet/core/utils/seed_scheme.dart'; +import 'package:komet/core/utils/wallpaper_seed.dart'; +import 'package:material_color_utilities/material_color_utilities.dart'; + +double _chroma(Color color) => Hct.fromInt(color.toARGB32()).chroma; + +bool _isGray(Color color) { + final argb = color.toARGB32(); + final r = (argb >> 16) & 0xFF; + final g = (argb >> 8) & 0xFF; + final b = argb & 0xFF; + return r == g && g == b; +} + +Future _seedOf(String themeId) async { + final seed = await computeWallpaperSeed(ChatWallpaper.theme(themeId)); + expect(seed, isNotNull, reason: themeId); + return seed!; +} + +void main() { + test('серые обои дают серый акцент, а не синий', () async { + final seed = await _seedOf('graphite'); + + expect(isAchromaticSeed(seed), isTrue); + for (final brightness in Brightness.values) { + final scheme = schemeFromSeed(seed, brightness); + expect(_isGray(scheme.primary), isTrue, reason: '$brightness'); + expect( + _isGray(scheme.secondaryContainer), + isTrue, + reason: '$brightness', + ); + } + }); + + test('цветные встроенные обои остаются цветными', () async { + for (final theme in kChatWallpaperThemes) { + if (theme.id == 'graphite') continue; + final seed = await _seedOf(theme.id); + + expect(isAchromaticSeed(seed), isFalse, reason: theme.id); + final primary = schemeFromSeed(seed, Brightness.dark).primary; + expect(_chroma(primary), greaterThan(20), reason: theme.id); + } + }); + + test('схема от монохромного primary не перекрашивается в синий', () async { + final seed = await _seedOf('graphite'); + final primary = schemeFromSeed(seed, Brightness.dark).primary; + + final derived = schemeFromSeed(primary, Brightness.dark); + + expect(_isGray(derived.primary), isTrue); + }); +} From a8b17b511aaa687a2bfc9f2ca74c7e614ec146e9 Mon Sep 17 00:00:00 2001 From: Jganenokk Date: Sun, 11 Oct 2026 00:29:54 +0700 Subject: [PATCH 03/63] =?UTF-8?q?fix/feat/refactor:=20=D1=84=D0=B8=D0=BA?= =?UTF-8?q?=D1=81=D1=8B=20#172=20#165=20#158=20=D0=B8=20PR=20#166=20(?= =?UTF-8?q?=D0=B2=D0=B7=D1=8F=D1=82=D0=BE=20=D0=BD=D0=B5=20=D0=B2=D1=81?= =?UTF-8?q?=D0=B5).=20=D0=A4=D0=BB=D0=B0=D0=B3=D0=B8=20=D0=B7=D0=B0=D0=BF?= =?UTF-8?q?=D1=83=D1=81=D0=BA=D0=B0=20=D0=B2=20=D0=BE=D0=B4=D0=BD=D0=BE?= =?UTF-8?q?=D0=BC=20=D0=BC=D0=B5=D1=81=D1=82=D0=B5,=20=D0=BF=D0=BB=D1=8E?= =?UTF-8?q?=D1=81=20=D1=84=D0=BB=D0=B0=D0=B3=20=D0=B7=D0=B0=D0=BF=D1=83?= =?UTF-8?q?=D1=81=D0=BA=D0=B0=20--debug=20=D0=B8=20=20--dw19p-im-crazy,=20?= =?UTF-8?q?=20=D0=9D=D0=B0=D1=81=D1=82=D1=80=D0=BE=D0=B9=D0=BA=D0=B8=20?= =?UTF-8?q?=E2=86=92=20=D0=AF=D0=B7=D1=8B=D0=BA,=20=D0=BE=D0=BF=D1=86?= =?UTF-8?q?=D0=B8=D1=8F=20=C2=AB=D0=9C=D0=B5=D0=BD=D1=8F=D1=82=D1=8C=20?= =?UTF-8?q?=D1=8F=D0=B7=D1=8B=D0=BA=20=D0=B8=20=D0=B4=D0=BB=D1=8F=20=D1=81?= =?UTF-8?q?=D0=B5=D1=80=D0=B2=D0=B5=D1=80=D0=B0=20=D1=82=D0=BE=D0=B6=D0=B5?= =?UTF-8?q?=C2=BB,=20=D0=B2=D1=85=D0=BE=D0=B4=20=C2=AB=D0=B2=D1=81=D0=B5?= =?UTF-8?q?=D0=B3=D0=B4=D0=B0=20SMS=C2=BB:=20=D1=81=D0=BE=D0=BA=D0=B5?= =?UTF-8?q?=D1=82=20B=20=D0=BF=D0=BE=D0=B4=D0=BD=D0=B8=D0=BC=D0=B0=D0=B5?= =?UTF-8?q?=D1=82=D1=81=D1=8F=20=D0=B7=D0=B0=D1=80=D0=B0=D0=BD=D0=B5=D0=B5?= =?UTF-8?q?,=20=D0=BF=D0=BE=D0=B4=D1=81=D0=BA=D0=B0=D0=B7=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=BE=20=D0=B4=D0=BE=D0=BB=D0=B3=D0=BE=D0=BC=20=D0=B2=D1=85?= =?UTF-8?q?=D0=BE=D0=B4=D0=B5(=D1=85=D0=BE=D1=82=D1=8F=20=D0=BE=D0=BD?= =?UTF-8?q?=D0=B0=20=D0=BD=D0=B0=D0=B2=D0=B5=D1=80=D0=BD=D0=BE=D0=B5=20?= =?UTF-8?q?=D0=B4=D0=B0=D0=B6=D0=B5=20=D0=BF=D0=BE=D0=BA=D0=B0=D0=B7=D0=B0?= =?UTF-8?q?=D1=82=D1=8C=D1=81=D1=8F=20=D0=BD=D0=B5=20=D1=83=D1=81=D0=BF?= =?UTF-8?q?=D0=B5=D0=B5=D1=82=20=D0=BD=D1=83=20=D0=BF=D0=BE=D1=85=D1=83?= =?UTF-8?q?=D0=B9=20=D0=BF=D1=83=D1=81=D1=82=D1=8C=20=D0=B1=D1=83=D0=B4?= =?UTF-8?q?=D0=B5=D1=82),=20=D0=BF=D0=BB=D0=B0=D0=B2=D0=BD=D0=B0=D1=8F=20?= =?UTF-8?q?=D0=B0=D0=B2=D1=82=D0=BE-=D0=B1=D0=BB=D0=BE=D0=BA=D0=B8=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D0=BA=D0=B0,=20=D1=82=D0=B5=D0=BA=D1=81=D1=82=20?= =?UTF-8?q?=D0=BD=D0=B0=20=D1=8D=D0=BA=D1=80=D0=B0=D0=BD=D0=B5=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=B4=D0=B0,=20=D1=82=D1=80=D0=BE=D0=B5=D1=82=D0=BE?= =?UTF-8?q?=D1=87=D0=B8=D0=B5=20=D0=B1=D0=B5=D0=B7=20=D0=B0=D0=B2=D0=B0?= =?UTF-8?q?=D1=82=D0=B0=D1=80=D0=BA=D0=B8=20=D1=81=D0=BA=D1=80=D1=8B=D1=82?= =?UTF-8?q?=D0=BE,=20=D0=BD=D0=B0=D0=B7=D0=B2=D0=B0=D0=BD=D0=B8=D1=8F=20?= =?UTF-8?q?=D0=BF=D0=B0=D0=BF=D0=BE=D0=BA=20=20=20=D0=BD=D0=B5=20=D0=BE?= =?UTF-8?q?=D0=B1=D1=80=D0=B5=D0=B7=D0=B0=D1=8E=D1=82=D1=81=D1=8F.=20Co-au?= =?UTF-8?q?thored-by:=20Kirill=20Kolesnikov=20<99146381+klsnv@users.norepl?= =?UTF-8?q?y.github.com>?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/actions/setup-rust/action.yml | 10 +- .github/workflows/build-ios.yml | 156 ++-- CLAUDE.md | 36 + ios/Runner.xcodeproj/project.pbxproj | 321 +++++++- ios/Runner/AppDelegate.swift | 31 + ios/Runner/Info.plist | 23 +- ios/Runner/KometShareBridge.swift | 119 +++ ios/Runner/Runner.entitlements | 6 +- ios/SHARING.md | 72 ++ ios/ShareExtension/Info.plist | 28 + ios/ShareExtension/KometShareSender.swift | 114 +++ ios/ShareExtension/KometShareTransport.h | 8 + .../ShareExtension-Bridging-Header.h | 1 + .../ShareExtension.entitlements | 6 + ios/ShareExtension/ShareViewController.swift | 777 ++++++++++++++++++ ios/Shared/KometShareAccounts.swift | 205 +++++ ios/Shared/KometShareStore.swift | 443 ++++++++++ lib/backend/api.dart | 83 +- lib/backend/modules/account.dart | 189 ++++- lib/backend/modules/calls.dart | 53 +- lib/backend/modules/contacts.dart | 6 +- lib/backend/modules/share_sender.dart | 105 ++- lib/core/calls/call_session.dart | 4 +- .../config/app_bottom_navigation_style.dart | 26 + lib/core/config/app_chat_chrome.dart | 4 +- lib/core/config/app_language.dart | 63 ++ lib/core/config/app_visual_style.dart | 4 +- lib/core/config/build_profile.dart | 4 +- lib/core/config/call_no_mute.dart | 12 - lib/core/config/debug_test.dart | 48 -- lib/core/config/launch_flags.dart | 104 +++ lib/core/config/review_access.dart | 5 +- lib/core/config/update_config.dart | 6 +- lib/core/media/share_thumbnail.dart | 46 +- lib/core/protocol/chat_cache_fingerprint.dart | 32 +- .../share/native_share_account_channel.dart | 63 ++ lib/core/share/native_share_account_sync.dart | 190 +++++ lib/core/share/share_account_snapshot.dart | 66 ++ lib/core/share/share_inbox.dart | 69 ++ lib/core/share/share_intent_bridge.dart | 56 +- .../share/share_recipient_eligibility.dart | 16 + lib/core/share/shared_file_usage.dart | 37 + lib/core/storage/account_token_store.dart | 54 ++ lib/core/storage/app_instance.dart | 4 +- lib/core/storage/per_chat_json_store.dart | 18 +- lib/core/storage/token_storage.dart | 29 +- lib/core/transport/wire_debug_log.dart | 45 + lib/core/utils/logger.dart | 69 +- lib/core/utils/seed_scheme.dart | 129 +++ .../auth/code_confirmation_screen.dart | 34 +- lib/frontend/screens/auth/login_screen.dart | 23 +- .../screens/auth/password_2fa_screen.dart | 21 +- .../screens/auth/slow_login_hint.dart | 81 ++ .../screens/calls/call_mic_sheet.dart | 4 +- lib/frontend/screens/calls/call_screen.dart | 4 +- lib/frontend/screens/calls/calls_tab.dart | 74 +- .../chats/chat/view/message_row_widgets.dart | 115 --- .../screens/chats/chat_info_screen.dart | 41 +- .../screens/chats/chat_list_screen.dart | 267 ++++-- lib/frontend/screens/chats/chat_screen.dart | 57 +- .../screens/chats/share_composer_bar.dart | 35 +- .../screens/contacts/contacts_tab.dart | 10 +- lib/frontend/screens/lock/app_lock_layer.dart | 26 +- .../screens/profile/appearance_screen.dart | 12 +- .../screens/profile/language_screen.dart | 126 +++ .../screens/profile/settings_tab.dart | 59 +- .../profile/theme_settings_screen.dart | 1 - .../screens/webapp/web_app_bridge.dart | 26 +- .../screens/webapp/web_app_screen.dart | 6 + lib/frontend/widgets/adaptive_shell.dart | 4 +- .../attachment/bubbles/file_bubble.dart | 467 ++++++----- .../attachment/bubbles/photo_bubble.dart | 58 +- .../attachment/bubbles/video_bubble.dart | 3 +- .../attachment/contact_picker_page.dart | 4 +- .../widgets/attachment/photo_hero.dart | 3 +- .../widgets/bottom_navigation_style_card.dart | 60 ++ .../chat_info/shared_content_tabs.dart | 60 +- lib/frontend/widgets/color_wheel_picker.dart | 103 ++- .../compact_bottom_navigation_bar.dart | 144 ++++ lib/frontend/widgets/direct_call.dart | 54 ++ .../widgets/directional_drag_recognizer.dart | 16 +- .../widgets/main_navigation_items.dart | 16 + lib/frontend/widgets/photo_viewer.dart | 282 +++++-- .../widgets/scroll_keyboard_dismiss.dart | 72 ++ lib/frontend/widgets/swipe_to_reply.dart | 150 ++++ lib/l10n/app_en.arb | 11 +- lib/l10n/app_localizations.dart | 54 ++ lib/l10n/app_localizations_en.dart | 31 + lib/l10n/app_localizations_ru.dart | 31 + lib/l10n/app_ru.arb | 11 +- lib/main.dart | 93 ++- lib/models/shared_payload.dart | 35 +- native/komet_share/.gitignore | 1 + native/komet_share/Cargo.lock | 740 +++++++++++++++++ native/komet_share/Cargo.toml | 28 + native/komet_share/src/engine.rs | 472 +++++++++++ native/komet_share/src/engine/tests.rs | 342 ++++++++ native/komet_share/src/lib.rs | 104 +++ native/komet_share/src/transport.rs | 545 ++++++++++++ scripts/build_ios_share.sh | 38 + scripts/pseudo_sign_ios.py | 38 + scripts/sign_ios_appstore.py | 157 ++++ test/account_token_store_test.dart | 175 ++++ test/app_lock_layer_test.dart | 46 ++ test/bottom_navigation_style_test.dart | 250 ++++++ test/call_mic_selection_test.dart | 13 +- test/chat_swipe_gestures_test.dart | 299 +++++++ test/color_wheel_picker_test.dart | 117 +++ test/file_bubble_test.dart | 281 +++++++ test/fixtures/share_fingerprint_vectors.json | 74 ++ test/launch_flags_test.dart | 140 ++++ test/native/ios_share_accounts_test.swift | 77 ++ test/native/ios_share_images_test.swift | 67 ++ test/native/ios_share_store_test.swift | 139 ++++ test/native/komet_share_transport_stub.c | 8 + test/native/test_ios_appstore_signing.py | 172 ++++ test/native/test_ios_share_build.py | 134 +++ test/per_chat_json_store_test.dart | 157 ++++ test/photo_viewer_test.dart | 206 +++++ test/seed_scheme_test.dart | 65 +- test/share_account_snapshot_test.dart | 142 ++++ test/share_fingerprint_test.dart | 59 ++ test/share_inbox_test.dart | 295 +++++++ test/share_recipient_eligibility_test.dart | 51 ++ test/shared_file_usage_test.dart | 75 ++ test/shared_photo_preview_test.dart | 257 ++++++ test/slow_login_hint_test.dart | 36 + test/webapp_bridge_test.dart | 28 +- 128 files changed, 11509 insertions(+), 1098 deletions(-) create mode 100644 ios/Runner/KometShareBridge.swift create mode 100644 ios/SHARING.md create mode 100644 ios/ShareExtension/Info.plist create mode 100644 ios/ShareExtension/KometShareSender.swift create mode 100644 ios/ShareExtension/KometShareTransport.h create mode 100644 ios/ShareExtension/ShareExtension-Bridging-Header.h create mode 100644 ios/ShareExtension/ShareExtension.entitlements create mode 100644 ios/ShareExtension/ShareViewController.swift create mode 100644 ios/Shared/KometShareAccounts.swift create mode 100644 ios/Shared/KometShareStore.swift create mode 100644 lib/core/config/app_bottom_navigation_style.dart create mode 100644 lib/core/config/app_language.dart delete mode 100644 lib/core/config/call_no_mute.dart delete mode 100644 lib/core/config/debug_test.dart create mode 100644 lib/core/config/launch_flags.dart create mode 100644 lib/core/share/native_share_account_channel.dart create mode 100644 lib/core/share/native_share_account_sync.dart create mode 100644 lib/core/share/share_account_snapshot.dart create mode 100644 lib/core/share/share_inbox.dart create mode 100644 lib/core/share/share_recipient_eligibility.dart create mode 100644 lib/core/share/shared_file_usage.dart create mode 100644 lib/core/storage/account_token_store.dart create mode 100644 lib/core/transport/wire_debug_log.dart create mode 100644 lib/frontend/screens/auth/slow_login_hint.dart create mode 100644 lib/frontend/screens/profile/language_screen.dart create mode 100644 lib/frontend/widgets/bottom_navigation_style_card.dart create mode 100644 lib/frontend/widgets/compact_bottom_navigation_bar.dart create mode 100644 lib/frontend/widgets/direct_call.dart create mode 100644 lib/frontend/widgets/main_navigation_items.dart create mode 100644 lib/frontend/widgets/scroll_keyboard_dismiss.dart create mode 100644 lib/frontend/widgets/swipe_to_reply.dart create mode 100644 native/komet_share/.gitignore create mode 100644 native/komet_share/Cargo.lock create mode 100644 native/komet_share/Cargo.toml create mode 100644 native/komet_share/src/engine.rs create mode 100644 native/komet_share/src/engine/tests.rs create mode 100644 native/komet_share/src/lib.rs create mode 100644 native/komet_share/src/transport.rs create mode 100644 scripts/build_ios_share.sh create mode 100644 scripts/pseudo_sign_ios.py create mode 100644 scripts/sign_ios_appstore.py create mode 100644 test/account_token_store_test.dart create mode 100644 test/bottom_navigation_style_test.dart create mode 100644 test/chat_swipe_gestures_test.dart create mode 100644 test/color_wheel_picker_test.dart create mode 100644 test/file_bubble_test.dart create mode 100644 test/fixtures/share_fingerprint_vectors.json create mode 100644 test/launch_flags_test.dart create mode 100644 test/native/ios_share_accounts_test.swift create mode 100644 test/native/ios_share_images_test.swift create mode 100644 test/native/ios_share_store_test.swift create mode 100644 test/native/komet_share_transport_stub.c create mode 100644 test/native/test_ios_appstore_signing.py create mode 100644 test/native/test_ios_share_build.py create mode 100644 test/per_chat_json_store_test.dart create mode 100644 test/share_account_snapshot_test.dart create mode 100644 test/share_fingerprint_test.dart create mode 100644 test/share_inbox_test.dart create mode 100644 test/share_recipient_eligibility_test.dart create mode 100644 test/shared_file_usage_test.dart create mode 100644 test/shared_photo_preview_test.dart create mode 100644 test/slow_login_hint_test.dart diff --git a/.github/actions/setup-rust/action.yml b/.github/actions/setup-rust/action.yml index 2506215d..6d6463a8 100644 --- a/.github/actions/setup-rust/action.yml +++ b/.github/actions/setup-rust/action.yml @@ -3,9 +3,9 @@ description: > Install the Rust toolchain with platform targets and a build cache, so cargokit can compile the native libraries during the Flutter build. kolibri and fjs come from pub.dev; the tlottie wrapper crate lives in - native/komet_tlottie/rust and pulls tlottie by git rev. cargokit builds all - of them into the Flutter build directory, so there is no workspace target to - list; the shared cargo registry and git checkouts are cached anyway. The + native/komet_tlottie/rust and pulls tlottie by git rev. cargokit builds its + artifacts in the Flutter build directory; the shared cargo registry and git + checkouts are cached alongside the native share transport workspace. The message-encryption core is C, not Rust, and is built by CMake from the crypto-core submodule. @@ -24,3 +24,7 @@ runs: - name: Cache Rust build uses: Swatinem/rust-cache@v2 + with: + workspaces: | + native/komet_tlottie/rust + native/komet_share diff --git a/.github/workflows/build-ios.yml b/.github/workflows/build-ios.yml index a948b381..130fcf0b 100644 --- a/.github/workflows/build-ios.yml +++ b/.github/workflows/build-ios.yml @@ -8,15 +8,39 @@ on: - master paths: - 'lib/**' + - 'test/**' + - 'scripts/pseudo_sign_ios.py' + - 'scripts/build_ios_share.sh' + - 'scripts/sign_ios_appstore.py' + - 'native/komet_share/**' + - 'native/komet_tlottie/**' + - 'native/crypto-core' + - 'native/crypto-core/**' - 'ios/**' - 'pubspec.yaml' + - 'pubspec.lock' + - '.gitmodules' - '.github/workflows/build-ios.yml' + - '.github/actions/setup-rust/**' + - '.github/actions/pin-kolibri-crates/**' pull_request: paths: - 'lib/**' + - 'test/**' + - 'scripts/pseudo_sign_ios.py' + - 'scripts/build_ios_share.sh' + - 'scripts/sign_ios_appstore.py' + - 'native/komet_share/**' + - 'native/komet_tlottie/**' + - 'native/crypto-core' + - 'native/crypto-core/**' - 'ios/**' - 'pubspec.yaml' + - 'pubspec.lock' + - '.gitmodules' - '.github/workflows/build-ios.yml' + - '.github/actions/setup-rust/**' + - '.github/actions/pin-kolibri-crates/**' env: FLUTTER_VERSION: '3.47.0' @@ -36,6 +60,7 @@ jobs: with: flutter-version: ${{ env.FLUTTER_VERSION }} channel: 'stable' + cache: true - name: Setup Rust uses: ./.github/actions/setup-rust @@ -45,13 +70,65 @@ jobs: - name: Get dependencies run: flutter pub get + - name: Build crypto core for tests + run: make -C native/crypto-core shared + + - name: Verify native share inbox + run: | + swiftc -suppress-warnings ios/Shared/KometShareStore.swift test/native/ios_share_store_test.swift -o /tmp/ios-share-store-tests + /tmp/ios-share-store-tests + swiftc -suppress-warnings ios/Shared/KometShareStore.swift ios/Shared/KometShareAccounts.swift test/native/ios_share_accounts_test.swift -o /tmp/ios-share-accounts-tests + /tmp/ios-share-accounts-tests + clang -c test/native/komet_share_transport_stub.c -o /tmp/ios-share-transport-stub.o + swiftc -suppress-warnings -import-objc-header ios/ShareExtension/KometShareTransport.h ios/Shared/KometShareStore.swift ios/ShareExtension/KometShareSender.swift test/native/ios_share_images_test.swift /tmp/ios-share-transport-stub.o -o /tmp/ios-share-image-tests + /tmp/ios-share-image-tests + + - name: Verify native share transport + run: | + cargo test --locked --manifest-path native/komet_share/Cargo.toml + python3 -m unittest discover -s test/native -p "test_ios_*.py" -v + + - name: Analyze application + run: flutter analyze lib test tool --no-pub + + - name: Verify sharing and chat interactions + run: >- + flutter test --no-pub + test/share_intent_test.dart + test/share_inbox_test.dart + test/shared_file_usage_test.dart + test/chat_swipe_gestures_test.dart + test/bottom_navigation_style_test.dart + test/file_bubble_test.dart + test/photo_viewer_test.dart + test/photo_hero_test.dart + test/media_viewer_video_test.dart + test/share_composer_bar_test.dart + test/shared_photo_preview_test.dart + test/share_account_snapshot_test.dart + test/share_fingerprint_test.dart + test/share_recipient_eligibility_test.dart + test/account_token_store_test.dart + test/per_chat_json_store_test.dart + - name: Pin kolibri crates uses: ./.github/actions/pin-kolibri-crates - name: Build iOS (no codesign) run: | flutter config --no-enable-swift-package-manager - flutter build ios --release --no-codesign + flutter build ios --release --no-codesign -v > ios-build.log 2>&1 || { + tail -n 180 ios-build.log + exit 1 + } + + - name: Upload build diagnostics + if: failure() + uses: actions/upload-artifact@v4 + with: + name: ios-build-diagnostics + path: ios-build.log + retention-days: 7 - name: Package unsigned IPA run: | @@ -72,36 +149,7 @@ jobs: run: brew install ldid - name: Pseudo-sign with ldid - run: | - set -euo pipefail - APP="build/ios/iphoneos/Runner.app" - ENT="$(mktemp -t ent).plist" - cat > "$ENT" <<'PLIST' - - - - - get-task-allow - application-identifierru.komet.app - keychain-access-groups - ru.komet.app - - - PLIST - if [ -d "$APP/Frameworks" ]; then - find "$APP/Frameworks" -type f -name "*.dylib" -print0 | xargs -0 -I{} ldid -S "{}" - find "$APP/Frameworks" -type d -name "*.framework" | while read -r fw; do - bin="$fw/$(basename "$fw" .framework)" - [ -f "$bin" ] && ldid -S "$bin" - done - fi - if [ -d "$APP/PlugIns" ]; then - find "$APP/PlugIns" -type d -name "*.appex" | while read -r ext; do - bin="$ext/$(basename "$ext" .appex)" - [ -f "$bin" ] && ldid -S"$ENT" "$bin" - done - fi - ldid -S"$ENT" "$APP/Runner" + run: python3 scripts/pseudo_sign_ios.py build/ios/iphoneos/Runner.app - name: Package IPA run: | @@ -166,6 +214,7 @@ jobs: BUILD_CERTIFICATE_BASE64: ${{ secrets.APPSTORE_CERTIFICATE_BASE64 }} P12_PASSWORD: ${{ secrets.APPSTORE_CERTIFICATE_PASSWORD }} BUILD_PROVISION_PROFILE_BASE64: ${{ secrets.APPSTORE_PROVISION_PROFILE_BASE64 }} + SHARE_PROVISION_PROFILE_BASE64: ${{ secrets.APPSTORE_SHARE_PROVISION_PROFILE_BASE64 }} KEYCHAIN_PASSWORD: ${{ secrets.APPSTORE_KEYCHAIN_PASSWORD }} run: | set -euo pipefail @@ -185,6 +234,10 @@ jobs: mkdir -p ~/Library/MobileDevice/Provisioning\ Profiles cp "$PP_PATH" ~/Library/MobileDevice/Provisioning\ Profiles/appstore.mobileprovision + rm -f "$RUNNER_TEMP/appstore-share.mobileprovision" + if [ -n "$SHARE_PROVISION_PROFILE_BASE64" ]; then + printf '%s' "$SHARE_PROVISION_PROFILE_BASE64" | base64 --decode -o "$RUNNER_TEMP/appstore-share.mobileprovision" + fi - name: Build unsigned app if: steps.signing.outputs.enabled == 'true' @@ -217,39 +270,16 @@ jobs: IDENTITY: ${{ steps.identity.outputs.identity }} run: | set -euo pipefail - APP="build/ios/iphoneos/Runner.app" - PP_PATH="$RUNNER_TEMP/appstore.mobileprovision" - BUNDLE_ID="pw.komet.ios" - - # Подменяем bundle id на App Store идентификатор - /usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier $BUNDLE_ID" "$APP/Info.plist" - /usr/libexec/PlistBuddy -c "Set :CFBundleURLTypes:0:CFBundleURLName $BUNDLE_ID" "$APP/Info.plist" || true - - # Кладём сам provisioning profile внутрь бандла - cp "$PP_PATH" "$APP/embedded.mobileprovision" - - # Достаём entitlements прямо из профиля — они уже содержат - # правильный application-identifier для pw.komet.ios - security cms -D -i "$PP_PATH" > "$RUNNER_TEMP/profile.plist" - ENT_PATH="$RUNNER_TEMP/appstore.entitlements" - /usr/libexec/PlistBuddy -x -c "Print :Entitlements" "$RUNNER_TEMP/profile.plist" > "$ENT_PATH" - - # Подписываем вложенные фреймворки (без entitlements) - if [ -d "$APP/Frameworks" ]; then - find "$APP/Frameworks" -depth 1 \( -name "*.framework" -o -name "*.dylib" \) -print0 \ - | xargs -0 -I{} codesign --force --sign "$IDENTITY" --keychain "$KEYCHAIN_PATH" "{}" + args=( + build/ios/iphoneos/Runner.app + --app-profile "$RUNNER_TEMP/appstore.mobileprovision" + --identity "$IDENTITY" + --keychain "$KEYCHAIN_PATH" + ) + if [ -f "$RUNNER_TEMP/appstore-share.mobileprovision" ]; then + args+=(--share-profile "$RUNNER_TEMP/appstore-share.mobileprovision") fi - - # Расширения (если появятся) — с entitlements - if [ -d "$APP/PlugIns" ]; then - find "$APP/PlugIns" -depth 1 -name "*.appex" -print0 \ - | xargs -0 -I{} codesign --force --sign "$IDENTITY" --keychain "$KEYCHAIN_PATH" --entitlements "$ENT_PATH" "{}" - fi - - # Подписываем само приложение последним - codesign --force --sign "$IDENTITY" --keychain "$KEYCHAIN_PATH" --entitlements "$ENT_PATH" "$APP" - - codesign --verify --deep --strict --verbose=2 "$APP" + python3 scripts/sign_ios_appstore.py "${args[@]}" - name: Package IPA if: steps.signing.outputs.enabled == 'true' diff --git a/CLAUDE.md b/CLAUDE.md index 25bb701e..d167ec3c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,6 +32,42 @@ Android builds require **Java 17**. Gradle memory is configured to `-Xmx4096m`. **Never run APK/AAB builds yourself** (`flutter build apk`, `flutter build appbundle`, gradle assemble tasks) — they are slow and the user builds them. Verify changes with the scoped `flutter analyze` above; the build commands are documentation only. Note that `flutter analyze` treats **info**-level lints as fatal by default, so CI fails on any lint. +### Launch flags + +Every launch flag and build-time define is declared in one place, `LaunchFlags` +(`lib/core/config/launch_flags.dart`). `main()` parses the arguments once, logs the active set +as `Флаги запуска: …` and warns about unknown arguments. Add a new flag there, never as a +`String.fromEnvironment` or `args.contains` somewhere else. + +| Argument | dart-define | Effect | +|-----------------------|-----------------------------|-------------------------------------------------------------------------| +| `--debug` | `KOMET_DEBUG=true` | every log level passes; every wire packet is logged with its JSON | +| `--dw19p-im-crazy` | `KOMET_DW19P_IM_CRAZY=true` | same, plus the payload of opcode 19 (`LOGIN`) | +| `--debug-test` | `DEBUG_TEST=true` | fake-data mode: skips login, opens the shell as account `-424242` | +| `--contacts N` | `DEBUG_CONTACTS=N` | implies `--debug-test` and generates N fake contacts | +| `--berserk` | `BERSERK=true` | drops the profile on login to exercise profile recovery | +| `--no-mute` | `NO_MUTE=true` | call audio keeps flowing while the mic is shown as muted | +| — | `KOMET_LOG_LEVEL=…` | minimum log level: `trace`…`fatal`, `off` | +| — | `KOMET_INSTANCE=name` | separate app copy: own prefs, database, media cache and plugins | +| — | `KOMET_UPDATE_BASE_URL=…` | updater manifest base, default `https://cdn.komet.pw`, empty disables | +| — | `KOMET_REVIEW_PHONE` + `_PAYLOAD` | Google Play review account, see *Review account* | +| — | `is_appstore_build=true` | App Store build, trimmed by `BuildProfile` | + +Without `--dw19p-im-crazy` the `LOGIN` payload is replaced by its length in both directions: it +carries the session token and the whole account snapshot. Payloads of every other opcode go out +verbatim — including `AUTH`/`AUTH_REQUEST` responses with their tokens — so a `--debug` log is +not safe to publish as is. + +Packets are logged by `WireDebugLog` from `Api._onWireLog`, tagged `api/`, so +the two parallel sessions of the experimental "always SMS" login stay apart. Extra login +diagnostics are plain `logger.d` calls — release filters them out unless a flag is set. Long +lines are split into ≤900-char chunks so logcat does not truncate them. + +Arguments reach `main()` only on desktop: `flutter run -d linux --dart-entrypoint-args=--debug` +(repeat the option per argument), or `./build/linux/x64/release/bundle/Komet --debug` for a built +bundle. On Android the engine is started by `audio_service` without entrypoint args, so mobile +builds take the dart-define: `flutter run --dart-define=KOMET_DEBUG=true`. + ## Message encryption core `komet_crypto` is a `dart:ffi` plugin over a C core. `KometTeam/crypto-core` is a **git diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 052b39ec..ed81ae4c 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -7,11 +7,20 @@ objects = { /* Begin PBXBuildFile section */ + 08023DAB67DBB860F77BB775 /* KometShareBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B9DFBD85E3205C9ADEB401D /* KometShareBridge.swift */; }; + 08FF3772A2078A4B61170118 /* KometShareSender.swift in Sources */ = {isa = PBXBuildFile; fileRef = E562D26E56EEB9A6420AD72B /* KometShareSender.swift */; }; 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 1FFB85AE0D947E2ADC636611 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 026D2485025695542ED117DB /* SystemConfiguration.framework */; }; + 250163B69AF01F1A321BD151 /* KometShareAccounts.swift in Sources */ = {isa = PBXBuildFile; fileRef = D53D7B6C0957C1CD6DB59B64 /* KometShareAccounts.swift */; }; + 305C0A6BA857D51078A0BBE8 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A63E96B763FA654541020DC2 /* Security.framework */; }; 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 4B1A4BBCD56B3CE42AD0A480 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 789A1AEF2F4FF7DEED202476 /* Pods_Runner.framework */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 75B17B7F1F62BC021A1BE9C0 /* KometShareStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDAACAA16E141CC00CF7D7A6 /* KometShareStore.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; + 84C5FAB35E4A95AA6E2C518F /* ShareExtension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 4D596EC330D2D8F8B8A26AB6 /* ShareExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + 8B650DA70DC4BDFC02F5F1BE /* KometShareAccounts.swift in Sources */ = {isa = PBXBuildFile; fileRef = D53D7B6C0957C1CD6DB59B64 /* KometShareAccounts.swift */; }; AA11BB22CC33DD44EE550101 /* KometVideo.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA11BB22CC33DD44EE550001 /* KometVideo.swift */; }; AA11BB22CC33DD44EE550102 /* KometVideoNote.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA11BB22CC33DD44EE550002 /* KometVideoNote.swift */; }; AA11BB22CC33DD44EE550103 /* KometNotifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA11BB22CC33DD44EE550003 /* KometNotifications.swift */; }; @@ -19,10 +28,14 @@ 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; + 992D92E93FC84DF35C61C032 /* CoreFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F7A1887EA57B6C16B500C901 /* CoreFoundation.framework */; }; + 9BDF85BC70348818AEF10CBA /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A63E96B763FA654541020DC2 /* Security.framework */; }; B1B2C3D41234567890ABCDEF /* MinimalIcon@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = A1B2C3D41234567890ABCDEF /* MinimalIcon@2x.png */; }; B1B2C3D41234567890ABCDF0 /* MinimalIcon@3x.png in Resources */ = {isa = PBXBuildFile; fileRef = A1B2C3D41234567890ABCDF0 /* MinimalIcon@3x.png */; }; + BB80EDFFF111F138D3411790 /* KometShareStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDAACAA16E141CC00CF7D7A6 /* KometShareStore.swift */; }; + D3E790B969E6525B6B35F151 /* ShareViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6792C66B074C477FB31A4F02 /* ShareViewController.swift */; }; E835CC948F2F948DC3BBF405 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2AE8CB2654009FE276CACA4B /* Pods_RunnerTests.framework */; }; - 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; + F2AE94BDADA90981E47049F4 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 86DE3C678446CCFC937C1F0F /* Foundation.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -33,6 +46,13 @@ remoteGlobalIDString = 97C146ED1CF9000F007C117D; remoteInfo = Runner; }; + A9AB19158D90BC8956890954 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 65E58C4DD504F2B8DEB6B857; + remoteInfo = ShareExtension; + }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -46,9 +66,22 @@ name = "Embed Frameworks"; runOnlyForDeploymentPostprocessing = 0; }; + D132AF483A0CFF92DB79020A /* Embed App Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 13; + files = ( + 84C5FAB35E4A95AA6E2C518F /* ShareExtension.appex in Embed App Extensions */, + ); + name = "Embed App Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 026D2485025695542ED117DB /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; }; + 0DFF6CD45C769B95007FA37C /* KometShareTransport.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = KometShareTransport.h; sourceTree = ""; }; 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; 1615A82960D98F780416FDE7 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; @@ -58,6 +91,10 @@ 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 366C243BBAFE3F87FBDF57A1 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 4B9DFBD85E3205C9ADEB401D /* KometShareBridge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = KometShareBridge.swift; sourceTree = ""; }; + 4D596EC330D2D8F8B8A26AB6 /* ShareExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = ShareExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + 5BCC4AC804992BB0EA5A482D /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 6792C66B074C477FB31A4F02 /* ShareViewController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ShareViewController.swift; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; AA11BB22CC33DD44EE550001 /* KometVideo.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KometVideo.swift; sourceTree = ""; }; @@ -67,19 +104,27 @@ AA11BB22CC33DD44EE550004 /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; 782E66FE4E292DCFD0D1B7D2 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; 789A1AEF2F4FF7DEED202476 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 83CE6DC2BACBB6F59AEA57B6 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + 86DE3C678446CCFC937C1F0F /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - A1B2C3D41234567890ABCDEF /* MinimalIcon@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "MinimalIcon@2x.png"; sourceTree = ""; }; - A1B2C3D41234567890ABCDF0 /* MinimalIcon@3x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "MinimalIcon@3x.png"; 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 = ""; }; 9D7B0FFE63E0BD5D67D7758D /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; - 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; + A1B2C3D41234567890ABCDEF /* MinimalIcon@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "MinimalIcon@2x.png"; sourceTree = ""; }; + A1B2C3D41234567890ABCDF0 /* MinimalIcon@3x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "MinimalIcon@3x.png"; sourceTree = ""; }; + A63E96B763FA654541020DC2 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; }; + A92990150F2CFE8F72ACA01D /* ShareExtension-Bridging-Header.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "ShareExtension-Bridging-Header.h"; sourceTree = ""; }; + D53D7B6C0957C1CD6DB59B64 /* KometShareAccounts.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = KometShareAccounts.swift; sourceTree = ""; }; + DD7AE0A574C0096D5FAD78ED /* ShareExtension.entitlements */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.entitlements; path = ShareExtension.entitlements; sourceTree = ""; }; + E562D26E56EEB9A6420AD72B /* KometShareSender.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = KometShareSender.swift; sourceTree = ""; }; + F7A1887EA57B6C16B500C901 /* CoreFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreFoundation.framework; path = System/Library/Frameworks/CoreFoundation.framework; sourceTree = SDKROOT; }; + FDAACAA16E141CC00CF7D7A6 /* KometShareStore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = KometShareStore.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -97,12 +142,32 @@ files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, 4B1A4BBCD56B3CE42AD0A480 /* Pods_Runner.framework in Frameworks */, + 305C0A6BA857D51078A0BBE8 /* Security.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E89D38CE2057ADBFEDB4C260 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + F2AE94BDADA90981E47049F4 /* Foundation.framework in Frameworks */, + 9BDF85BC70348818AEF10CBA /* Security.framework in Frameworks */, + 1FFB85AE0D947E2ADC636611 /* SystemConfiguration.framework in Frameworks */, + 992D92E93FC84DF35C61C032 /* CoreFoundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 273DBF548AF5F861F4ECFA72 /* iOS */ = { + isa = PBXGroup; + children = ( + 86DE3C678446CCFC937C1F0F /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; 331C8082294A63A400263BE5 /* RunnerTests */ = { isa = PBXGroup; children = ( @@ -111,11 +176,25 @@ path = RunnerTests; sourceTree = ""; }; + 3B6D89D717E5C400639FA5B2 /* Shared */ = { + isa = PBXGroup; + children = ( + FDAACAA16E141CC00CF7D7A6 /* KometShareStore.swift */, + D53D7B6C0957C1CD6DB59B64 /* KometShareAccounts.swift */, + ); + name = Shared; + path = Shared; + sourceTree = ""; + }; 3E066142FD515067AADAC58D /* Frameworks */ = { isa = PBXGroup; children = ( 789A1AEF2F4FF7DEED202476 /* Pods_Runner.framework */, 2AE8CB2654009FE276CACA4B /* Pods_RunnerTests.framework */, + 273DBF548AF5F861F4ECFA72 /* iOS */, + A63E96B763FA654541020DC2 /* Security.framework */, + 026D2485025695542ED117DB /* SystemConfiguration.framework */, + F7A1887EA57B6C16B500C901 /* CoreFoundation.framework */, ); name = Frameworks; sourceTree = ""; @@ -141,6 +220,8 @@ 331C8082294A63A400263BE5 /* RunnerTests */, C4C44F130EEB07A77FD05026 /* Pods */, 3E066142FD515067AADAC58D /* Frameworks */, + 3B6D89D717E5C400639FA5B2 /* Shared */, + CB320B2611C838775EBD1952 /* ShareExtension */, ); sourceTree = ""; }; @@ -149,6 +230,7 @@ children = ( 97C146EE1CF9000F007C117D /* Runner.app */, 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + 4D596EC330D2D8F8B8A26AB6 /* ShareExtension.appex */, ); name = Products; sourceTree = ""; @@ -171,6 +253,7 @@ AA11BB22CC33DD44EE550003 /* KometNotifications.swift */, AA11BB22CC33DD44EE550005 /* KometClipboard.swift */, AA11BB22CC33DD44EE550004 /* Runner.entitlements */, + 4B9DFBD85E3205C9ADEB401D /* KometShareBridge.swift */, ); path = Runner; sourceTree = ""; @@ -189,6 +272,20 @@ path = Pods; sourceTree = ""; }; + CB320B2611C838775EBD1952 /* ShareExtension */ = { + isa = PBXGroup; + children = ( + 6792C66B074C477FB31A4F02 /* ShareViewController.swift */, + 5BCC4AC804992BB0EA5A482D /* Info.plist */, + DD7AE0A574C0096D5FAD78ED /* ShareExtension.entitlements */, + E562D26E56EEB9A6420AD72B /* KometShareSender.swift */, + 0DFF6CD45C769B95007FA37C /* KometShareTransport.h */, + A92990150F2CFE8F72ACA01D /* ShareExtension-Bridging-Header.h */, + ); + name = ShareExtension; + path = ShareExtension; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -211,10 +308,25 @@ productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; - 97C146ED1CF9000F007C117D /* Runner */ = { - packageProductDependencies = ( - 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + 65E58C4DD504F2B8DEB6B857 /* ShareExtension */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6822FE34AA51E883AF823E25 /* Build configuration list for PBXNativeTarget "ShareExtension" */; + buildPhases = ( + 8FF0C1E27BC3C7E3DAF66650 /* Build Komet Share Transport */, + 94B926CD9634D1A633E8EAD9 /* Sources */, + E89D38CE2057ADBFEDB4C260 /* Frameworks */, + D8F9BDC0BB3F15064E678827 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( ); + name = ShareExtension; + productName = ShareExtension; + productReference = 4D596EC330D2D8F8B8A26AB6 /* ShareExtension.appex */; + productType = "com.apple.product-type.app-extension"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( @@ -224,14 +336,19 @@ 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, + D132AF483A0CFF92DB79020A /* Embed App Extensions */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, 122816C3E1F98387D8AA58D3 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( + 5D9E3F9CE2BC28BA06590A81 /* PBXTargetDependency */, ); name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); productName = Runner; productReference = 97C146EE1CF9000F007C117D /* Runner.app */; productType = "com.apple.product-type.application"; @@ -240,9 +357,6 @@ /* Begin PBXProject section */ 97C146E61CF9000F007C117D /* Project object */ = { - packageReferences = ( - 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, - ); isa = PBXProject; attributes = { BuildIndependentTargetsInParallel = YES; @@ -253,9 +367,21 @@ CreatedOnToolsVersion = 14.0; TestTargetID = 97C146ED1CF9000F007C117D; }; + 65E58C4DD504F2B8DEB6B857 = { + SystemCapabilities = { + com.apple.ApplicationGroups.iOS = { + enabled = 1; + }; + }; + }; 97C146ED1CF9000F007C117D = { CreatedOnToolsVersion = 7.3.1; LastSwiftMigration = 1100; + SystemCapabilities = { + com.apple.ApplicationGroups.iOS = { + enabled = 1; + }; + }; }; }; }; @@ -268,12 +394,16 @@ Base, ); mainGroup = 97C146E51CF9000F007C117D; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */, + ); productRefGroup = 97C146EF1CF9000F007C117D /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 97C146ED1CF9000F007C117D /* Runner */, 331C8080294A63A400263BE5 /* RunnerTests */, + 65E58C4DD504F2B8DEB6B857 /* ShareExtension */, ); }; /* End PBXProject section */ @@ -299,6 +429,13 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + D8F9BDC0BB3F15064E678827 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ @@ -357,6 +494,26 @@ shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; + 8FF0C1E27BC3C7E3DAF66650 /* Build Komet Share Transport */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + name = "Build Komet Share Transport"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(BUILT_PRODUCTS_DIR)/KometShareTransport/libkomet_share.a", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/bash; + shellScript = "\"$SRCROOT/../scripts/build_ios_share.sh\""; + }; 942752100DC29827FE94D2B2 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -405,6 +562,17 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 94B926CD9634D1A633E8EAD9 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 75B17B7F1F62BC021A1BE9C0 /* KometShareStore.swift in Sources */, + D3E790B969E6525B6B35F151 /* ShareViewController.swift in Sources */, + 250163B69AF01F1A321BD151 /* KometShareAccounts.swift in Sources */, + 08FF3772A2078A4B61170118 /* KometShareSender.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 97C146EA1CF9000F007C117D /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -415,6 +583,9 @@ AA11BB22CC33DD44EE550103 /* KometNotifications.swift in Sources */, AA11BB22CC33DD44EE550105 /* KometClipboard.swift in Sources */, 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + BB80EDFFF111F138D3411790 /* KometShareStore.swift in Sources */, + 08023DAB67DBB860F77BB775 /* KometShareBridge.swift in Sources */, + 8B650DA70DC4BDFC02F5F1BE /* KometShareAccounts.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -426,6 +597,12 @@ target = 97C146ED1CF9000F007C117D /* Runner */; targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; }; + 5D9E3F9CE2BC28BA06590A81 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = ShareExtension; + target = 65E58C4DD504F2B8DEB6B857 /* ShareExtension */; + targetProxy = A9AB19158D90BC8956890954 /* PBXContainerItemProxy */; + }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ @@ -492,6 +669,7 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 13.0; + KOMET_SHARE_APP_GROUP = group.ru.komet.app; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -506,6 +684,7 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; @@ -513,7 +692,6 @@ "$(inherited)", "@executable_path/Frameworks", ); - CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; PRODUCT_BUNDLE_IDENTIFIER = ru.komet.app; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; @@ -572,6 +750,73 @@ }; name = Profile; }; + 422C6F8EBC3520295482128E /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB31CF90195004384FC /* Generated.xcconfig */; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements; + CODE_SIGN_STYLE = Automatic; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = ShareExtension/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + OTHER_LDFLAGS = ( + "$(inherited)", + "-force_load", + "\"$(BUILT_PRODUCTS_DIR)/KometShareTransport/libkomet_share.a\"", + "-liconv", + ); + PRODUCT_BUNDLE_IDENTIFIER = ru.komet.app.ShareExtension; + PRODUCT_NAME = ShareExtension; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OBJC_BRIDGING_HEADER = "ShareExtension/ShareExtension-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 81175A7CD5EAD0C8A8A37B06 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB31CF90195004384FC /* Generated.xcconfig */; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements; + CODE_SIGN_STYLE = Automatic; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = ShareExtension/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + OTHER_LDFLAGS = ( + "$(inherited)", + "-force_load", + "\"$(BUILT_PRODUCTS_DIR)/KometShareTransport/libkomet_share.a\"", + "-liconv", + ); + PRODUCT_BUNDLE_IDENTIFIER = ru.komet.app.ShareExtension; + PRODUCT_NAME = ShareExtension; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OBJC_BRIDGING_HEADER = "ShareExtension/ShareExtension-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; 97C147031CF9000F007C117D /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -622,6 +867,7 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 13.0; + KOMET_SHARE_APP_GROUP = group.ru.komet.app; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -673,6 +919,7 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 13.0; + KOMET_SHARE_APP_GROUP = group.ru.komet.app; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -689,6 +936,7 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; @@ -696,7 +944,6 @@ "$(inherited)", "@executable_path/Frameworks", ); - CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; PRODUCT_BUNDLE_IDENTIFIER = ru.komet.app; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; @@ -712,6 +959,7 @@ buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; @@ -719,7 +967,6 @@ "$(inherited)", "@executable_path/Frameworks", ); - CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; PRODUCT_BUNDLE_IDENTIFIER = ru.komet.app; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; @@ -728,6 +975,40 @@ }; name = Release; }; + FEDED61E67F74842D74FDC3E /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB31CF90195004384FC /* Generated.xcconfig */; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements; + CODE_SIGN_STYLE = Automatic; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = ShareExtension/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + OTHER_LDFLAGS = ( + "$(inherited)", + "-force_load", + "\"$(BUILT_PRODUCTS_DIR)/KometShareTransport/libkomet_share.a\"", + "-liconv", + ); + PRODUCT_BUNDLE_IDENTIFIER = ru.komet.app.ShareExtension; + PRODUCT_NAME = ShareExtension; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_OBJC_BRIDGING_HEADER = "ShareExtension/ShareExtension-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ @@ -741,6 +1022,16 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + 6822FE34AA51E883AF823E25 /* Build configuration list for PBXNativeTarget "ShareExtension" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FEDED61E67F74842D74FDC3E /* Release */, + 81175A7CD5EAD0C8A8A37B06 /* Debug */, + 422C6F8EBC3520295482128E /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( @@ -762,12 +1053,14 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + /* Begin XCLocalSwiftPackageReference section */ - 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */ = { isa = XCLocalSwiftPackageReference; relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; }; /* End XCLocalSwiftPackageReference section */ + /* Begin XCSwiftPackageProductDependency section */ 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { isa = XCSwiftPackageProductDependency; diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index 4c4fc38a..503769dd 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -28,6 +28,7 @@ final class KometStreamHandler: NSObject, FlutterStreamHandler { private var eventChannels: [FlutterEventChannel] = [] private var streamHandlers: [KometStreamHandler] = [] private var videoNote: KometVideoNote? + private let shareBridge = KometShareBridge() override func application( _ application: UIApplication, @@ -43,6 +44,7 @@ final class KometStreamHandler: NSObject, FlutterStreamHandler { registerVideoNote(messenger) registerNotifications(messenger) registerScreen(messenger) + registerShare(messenger) registerClipboard(messenger) } @@ -56,6 +58,35 @@ final class KometStreamHandler: NSObject, FlutterStreamHandler { channels.append(channel) } + override func application( + _ app: UIApplication, + open url: URL, + options: [UIApplication.OpenURLOptionsKey: Any] = [:] + ) -> Bool { + guard url.isFileURL else { + return super.application(app, open: url, options: options) + } + shareBridge.importDocument(url) { [weak self] error in + guard var controller = self?.window?.rootViewController else { return } + while let presented = controller.presentedViewController { controller = presented } + let alert = UIAlertController(title: "Не удалось открыть файл", + message: error.localizedDescription, + preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "ОК", style: .default)) + controller.present(alert, animated: true) + } + return true + } + + private func registerShare(_ messenger: FlutterBinaryMessenger) { + method("ru.komet.app/share", messenger) { [weak self] call, result in + self?.shareBridge.handle(call, result: result) + } + events("ru.komet.app/share_events", messenger) { [weak self] sink in + self?.shareBridge.attach(sink) + } + } + private func events(_ name: String, _ messenger: FlutterBinaryMessenger, _ onSink: @escaping (FlutterEventSink?) -> Void) { let handler = KometStreamHandler(onSink: onSink) diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 00f1ed74..677bb82b 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -82,20 +82,17 @@ NSFaceIDUsageDescription Face ID разблокирует Komet вместо кода-пароля. NSLocationWhenInUseUsageDescription - Геолокация нужна, чтобы отправлять ваше текущее местоположение в чатах. + Геолокация нужна, чтобы вы могли отправить своё местоположение в чат. NSMicrophoneUsageDescription Микрофон нужен для записи голосовых сообщений, видео и звонков. NSPhotoLibraryAddUsageDescription Доступ к галерее нужен, чтобы сохранять полученные фото и видео. NSPhotoLibraryUsageDescription Доступ к галерее нужен, чтобы отправлять фото и видео в чатах. - NSLocationWhenInUseUsageDescription - Геолокация нужна, чтобы вы могли отправить своё местоположение в чат. NSLocationAlwaysAndWhenInUseUsageDescription Геолокация нужна, чтобы вы могли отправить своё местоположение в чат. NSSpeechRecognitionUsageDescription Распознавание речи нужно, чтобы превращать голосовые сообщения в текст. - UIApplicationSupportsIndirectInputEvents UIBackgroundModes @@ -121,5 +118,23 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight + KometShareAppGroup + $(KOMET_SHARE_APP_GROUP) + CFBundleDocumentTypes + + + CFBundleTypeName + Files and media + CFBundleTypeRole + Viewer + LSHandlerRank + Alternate + LSItemContentTypes + + public.data + public.content + + + diff --git a/ios/Runner/KometShareBridge.swift b/ios/Runner/KometShareBridge.swift new file mode 100644 index 00000000..5ff9796e --- /dev/null +++ b/ios/Runner/KometShareBridge.swift @@ -0,0 +1,119 @@ +import Flutter +import UIKit + +final class KometShareBridge { + private let queue = DispatchQueue(label: "ru.komet.app.share", qos: .userInitiated) + private var store: KometShareStore? + private var sink: FlutterEventSink? + private let extensionEnabled = Bundle.main.object(forInfoDictionaryKey: "KometShareExtensionEnabled") as? Bool != false + + func attach(_ sink: FlutterEventSink?) { + self.sink = sink + } + + func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + if !extensionEnabled && ["syncShareAccount", "clearShareAccount", "clearAllShareAccounts", "readShareToken"].contains(call.method) { + result(nil) + return + } + switch call.method { + case "consumeInitialShare": + perform(result) { try $0.nextPayload() } + case "acknowledgeShare": + guard let id = (call.arguments as? [String: Any])?["id"] as? String else { + result(FlutterError(code: "INVALID_SHARE", message: "Missing share ID", details: nil)) + return + } + perform(result) { store in + try store.acknowledge(id: id) + return nil + } + case "releaseShare": + guard let id = (call.arguments as? [String: Any])?["id"] as? String else { + result(FlutterError(code: "INVALID_SHARE", message: "Missing share ID", details: nil)) + return + } + perform(result) { store in + try store.removeCompleted(id: id) + return nil + } + case "syncShareAccount": + guard let arguments = call.arguments as? [String: Any] else { + result(FlutterError(code: "INVALID_SHARE_ACCOUNT", message: "Missing share account", details: nil)) + return + } + perform(result) { _ in + try KometShareAccounts().sync(arguments) + return nil + } + case "clearShareAccount": + guard let id = (call.arguments as? [String: Any])?["accountId"] as? String else { + result(FlutterError(code: "INVALID_SHARE_ACCOUNT", message: "Missing account ID", details: nil)) + return + } + perform(result) { _ in + try KometShareAccounts().clear(accountID: id) + return nil + } + case "clearAllShareAccounts": + perform(result) { _ in + try KometShareAccounts().clear(accountID: nil) + return nil + } + case "readShareToken": + guard let arguments = call.arguments as? [String: Any], + let id = arguments["accountId"] as? String, + let knownToken = arguments["knownToken"] as? String else { + result(FlutterError(code: "INVALID_SHARE_ACCOUNT", message: "Missing account credentials", details: nil)) + return + } + perform(result) { _ in + try KometShareAccounts().refreshedToken(accountID: id, knownToken: knownToken) + } + case "clearCache": + result(nil) + default: + result(FlutterMethodNotImplemented) + } + } + + func importDocument(_ url: URL, onError: @escaping (Error) -> Void) { + let scoped = url.startAccessingSecurityScopedResource() + queue.async { + defer { if scoped { url.stopAccessingSecurityScopedResource() } } + do { + _ = try self.sharedStore().importDocument(documentURL: url) + DispatchQueue.main.async { self.sink?(["changed": true]) } + } catch { + DispatchQueue.main.async { onError(error) } + } + } + } + + private func sharedStore() throws -> KometShareStore { + if let store = store { return store } + let store: KometShareStore + if extensionEnabled { + store = try KometShareStore() + } else { + let container = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) + store = try KometShareStore(containerURL: container) + } + self.store = store + return store + } + + private func perform(_ result: @escaping FlutterResult, + _ action: @escaping (KometShareStore) throws -> Any?) { + queue.async { + do { + let value = try action(self.sharedStore()) + DispatchQueue.main.async { result(value) } + } catch { + DispatchQueue.main.async { + result(FlutterError(code: "SHARE_FAILED", message: error.localizedDescription, details: nil)) + } + } + } + } +} diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements index 44c36226..7b801e1e 100644 --- a/ios/Runner/Runner.entitlements +++ b/ios/Runner/Runner.entitlements @@ -2,9 +2,13 @@ + com.apple.security.application-groups + + $(KOMET_SHARE_APP_GROUP) + keychain-access-groups - $(AppIdentifierPrefix)$(CFBundleIdentifier) + $(AppIdentifierPrefix)$(PRODUCT_BUNDLE_IDENTIFIER) diff --git a/ios/SHARING.md b/ios/SHARING.md new file mode 100644 index 00000000..7760adbe --- /dev/null +++ b/ios/SHARING.md @@ -0,0 +1,72 @@ +# Komet для iOS: отправка из меню «Поделиться» + +Komet доступен в системном меню «Поделиться» для фотографий, видео, документов, текста и ссылок. Расширение показывает собственное окно выбора чата и отправляет сообщения напрямую, без запуска основного приложения. Поддерживается до 30 вложений за одну отправку. + +## Первый запуск и отправка + +1. После установки обновления откройте Komet и дождитесь входа и загрузки чатов. Для нескольких аккаунтов переключитесь на каждый из них один раз: в расширении появляются только аккаунты, для которых приложение сохранило список чатов. +2. В «Фото», «Файлах» или другом приложении нажмите «Поделиться» → Komet. +3. При необходимости смените аккаунт, найдите существующий чат или контакт через поиск и выберите одного получателя. В окне видны миниатюра первого изображения и сведения о вложениях. Текст или подпись можно изменить перед отправкой. +4. Нажмите «Отправить» и дождитесь подтверждения. Процент и полоса показывают фактически загруженные данные. После загрузки 100% расширение ещё ожидает ответ сервера; надпись «Отправлено» появляется только после подтверждения всех сообщений. + +Список получателей берётся из Komet; создание нового чата в расширении не предусмотрено. Если нужного чата нет, обновите список в основном приложении. Зашифрованные чаты и каналы без права публикации отображаются недоступными. Для зашифрованного чата прикрепите вложения и отправьте их из самого Komet: расширение не использует ключи шифрования основного приложения. + +Статические изображения, в том числе HEIC/HEIF, перед отправкой преобразуются в JPEG с длинной стороной не больше 2560 пикселей. Декодирование выполняется с уменьшением размера, чтобы ограничить расход памяти расширения. Анимированные изображения передаются как файлы; документы сохраняют исходные байты. Фотографии одного набора отправляются альбомом, остальные файлы — отдельными сообщениями; подпись добавляется к первому сообщению. + +## Ошибки и повторная отправка + +После подтверждённой ошибки можно нажать «Повторить». Состояние каждого сообщения сохраняется: уже подтверждённые сообщения из этого набора не отправляются повторно. Текст и получатель при таком повторе остаются прежними. + +Если соединение оборвалось после передачи сообщения или расширение было закрыто системой, результат может оказаться неизвестным. В этом случае сначала проверьте чат в Komet. Автоматического повтора нет. Сохранённые попытки доступны через «Неотправленные» в следующем окне отправки; там можно посмотреть результат и удалить локальные вложения. Удаление этой записи не удаляет сообщения из чата. Неизвестный результат не становится новой входящей отправкой при запуске Komet. + +Действие «Открыть в Komet» для документа по-прежнему передаёт файл в основное приложение и открывает его экран выбора получателей. Закрытый экран этого импорта помечается обработанным до завершения фоновой загрузки, а файлы удаляются после освобождения загрузчиками. + +## Удобство чатов + +- Клавиатура скрывается в начале свайпа назад и при прокрутке истории. +- Свайп назад принимает медленное движение; короткий или отменённый жест возвращает экран. Свайп ответа плавно следует за пальцем. +- Нажатие в любой части карточки файла скачивает и открывает его. На карточке видны действие и прогресс. +- Фото закрывается вертикальным свайпом, если оно не увеличено. Горизонтальное перелистывание и масштабирование сохраняются. +- «Настройки → Внешний вид → Нижняя панель → Компактная» включает более низкую панель вкладок. Выбор сохраняется между запусками; исходный вид тоже доступен. + +## Подпись на iPhone + +Артефакт `Komet-ios-pseudosigned.ipa` из сборки Build iOS предназначен для повторной подписи своим сертификатом и профилем, например в ESign. Псевдоподпись сохраняет исходные entitlements и не заменяет подпись Apple. Успешная сборка IPA сама по себе не подтверждает установку и работу на устройстве с конкретной подписью. + +Установщик должен сохранять `PlugIns/ShareExtension.appex` и разрешённую общую App Group в итоговых подписях обоих исполняемых файлов. Профили приложения и расширения должны допускать выбранную группу; одного сертификата недостаточно. + +Исходные идентификаторы: + +- приложение: `ru.komet.app`; +- расширение: `ru.komet.app.ShareExtension`; +- App Group: `group.ru.komet.app`. + +Если при повторной подписи меняется App Group, значение `KometShareAppGroup` в обоих `Info.plist` должно совпадать с группой в `com.apple.security.application-groups` обоих исполняемых файлов. Изменение только Bundle ID не настраивает общий доступ. При самостоятельной сборке задайте `KOMET_SHARE_APP_GROUP` в настройках проекта для своей зарегистрированной группы. + +Токен, параметры сессии и прокси хранятся в общей Keychain. Список аккаунтов и чатов записывается отдельно в защищённый файл общей папки, без токенов. Для Keychain код явно использует ту же App Group: iOS разрешает этот вариант без дополнительного включения группы в `keychain-access-groups`. См. [документацию Apple об общем доступе к Keychain](https://developer.apple.com/documentation/security/sharing-access-to-keychain-items-among-a-collection-of-apps). + +Поэтому при подписи через ESign важны итоговые entitlements и разрешения профилей, а не только наличие расширения в IPA. Смена группы или команды подписи не переносит прежние записи Keychain и общую папку; может потребоваться повторный вход и открытие Komet для обновления списка чатов. Совместимость конкретной повторной подписи нужно проверить на устройстве. + +Если Komet не виден в «Поделиться», проверьте пункт «Ещё» в списке приложений и наличие расширения в установленном IPA. Ошибка общего хранилища указывает на необходимость проверить App Groups. При ошибке доступа к аккаунту откройте Komet для синхронизации; если ошибка сохраняется, проверьте доступ обоих компонентов к общей группе Keychain. + +## Сборка для App Store в CI + +Задача `build-ios-appstore` сохраняет прежние секреты подписи основного приложения. Для включения Share Extension дополнительно задайте `APPSTORE_SHARE_PROVISION_PROFILE_BASE64` — профиль именно расширения, закодированный в Base64. Профили должны принадлежать одной команде, содержать явные идентификаторы приложения и расширения и разрешать хотя бы одну общую App Group. Идентификатор расширения должен начинаться с идентификатора приложения и точки. + +Скрипт `scripts/sign_ios_appstore.py` берёт идентификаторы и entitlements из соответствующих профилей, согласует общую группу в обоих `Info.plist` и подписывает расширение отдельно от приложения. Если дополнительного секрета нет, задача выводит уведомление и собирает прежний вариант без `ShareExtension.appex`. Экспорт аккаунтов в общую Keychain в этом варианте отключён; «Открыть в Komet» использует личное хранилище приложения. Остальные расширения не удаляются. Обычные unsigned и pseudosigned IPA для самостоятельной подписи не меняются. + +## Проверка на устройстве + +1. После обновления войдите в Komet, дождитесь чатов, затем полностью закройте приложение. Из «Фото» передайте фотографию: должны появиться миниатюра, поиск и список получателей без запуска Komet. +2. Измените подпись, выберите чат и отправьте. Проверьте реальный процент загрузки, отдельное ожидание подтверждения и итоговое сообщение в чате. +3. Повторите с несколькими фотографиями, HEIC, видео, PDF, документом с кириллическим именем и текстовой ссылкой. Проверьте также «Открыть в Komet». +4. Отключите сеть до отправки: ошибка должна позволять повтор после восстановления соединения. При обрыве во время подтверждения проверьте чат вручную; неизвестная попытка не должна автоматически отправляться заново или появляться в основном приложении как новый импорт. +5. Проверьте переключение аккаунтов, выход из одного аккаунта и недоступность зашифрованного чата в расширении. В отправленном сообщении должен быть именно выбранный аккаунт-отправитель. +6. На небольшом экране откройте клавиатуру для подписи и поиска: список получателей и кнопка отправки должны оставаться доступны. +7. В основном приложении проверьте скрытие клавиатуры при свайпе назад и средней/быстрой прокрутке истории. Медленная прокрутка должна оставлять клавиатуру открытой. Проверьте короткий и полный свайп ответа, отмену жеста. +8. Откройте фото, закройте вертикальным свайпом; проверьте короткий жест, увеличение двумя пальцами и горизонтальную галерею. Нажмите по названию или свободному месту карточки файла для скачивания/открытия. +9. Включите компактную нижнюю панель и перезапустите приложение: настройка должна сохраниться. + +Очередь, сохранение результатов отправки, обновление токенов, обработка изображений и жесты проверяются автоматизированными тестами с синтетическими данными. Они не заменяют проверку сетевой отправки и окончательно подписанной сборки на реальном iPhone. + +Дополнительные источники Apple: [Share extensions](https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/Share.html), [App Groups](https://developer.apple.com/documentation/xcode/configuring-app-groups). diff --git a/ios/ShareExtension/Info.plist b/ios/ShareExtension/Info.plist new file mode 100644 index 00000000..76928d9e --- /dev/null +++ b/ios/ShareExtension/Info.plist @@ -0,0 +1,28 @@ + + + + CFBundleDevelopmentRegionru + CFBundleDisplayNameKomet + CFBundleExecutable$(EXECUTABLE_NAME) + CFBundleIdentifier$(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion6.0 + CFBundleName$(PRODUCT_NAME) + CFBundlePackageTypeXPC! + CFBundleShortVersionString$(FLUTTER_BUILD_NAME) + CFBundleVersion$(FLUTTER_BUILD_NUMBER) + KometShareAppGroup$(KOMET_SHARE_APP_GROUP) + NSExtension + NSExtensionPointIdentifiercom.apple.share-services + NSExtensionPrincipalClass$(PRODUCT_MODULE_NAME).ShareViewController + NSExtensionAttributes + NSExtensionActivationRule + NSExtensionActivationSupportsImageWithMaxCount30 + NSExtensionActivationSupportsMovieWithMaxCount30 + NSExtensionActivationSupportsFileWithMaxCount30 + NSExtensionActivationSupportsText + NSExtensionActivationSupportsWebURLWithMaxCount30 + NSExtensionActivationUsesStrictMatching0 + + + + diff --git a/ios/ShareExtension/KometShareSender.swift b/ios/ShareExtension/KometShareSender.swift new file mode 100644 index 00000000..0014b0e6 --- /dev/null +++ b/ios/ShareExtension/KometShareSender.swift @@ -0,0 +1,114 @@ +import Foundation +import ImageIO +#if canImport(MobileCoreServices) +import MobileCoreServices +#else +import CoreServices +#endif +import CoreGraphics + +struct KometShareSendResult { + let status: String + let message: String + var refreshedToken: String? = nil +} + +private final class KometShareProgressContext { + let update: (String, Double?, String) -> Void + + init(update: @escaping (String, Double?, String) -> Void) { + self.update = update + } +} + +private let kometShareProgressCallback: @convention(c) (UnsafePointer?, UnsafeMutableRawPointer?) -> Void = { json, context in + guard let json = json, let context = context, + let data = String(cString: json).data(using: .utf8), + let payload = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return } + let receiver = Unmanaged.fromOpaque(context).takeUnretainedValue() + let message = payload["message"] as? String ?? "Отправляем…" + let progress = (payload["progress"] as? Double).map { min(1, max(0, $0)) } + receiver.update(message, progress, payload["phase"] as? String ?? "connecting") +} + +final class KometShareSender { + static func send( + credentials: [String: Any], request: [String: Any], + progress: @escaping (String, Double?, String) -> Void + ) throws -> KometShareSendResult { + var input = credentials + input["request"] = request + let data = try JSONSerialization.data(withJSONObject: input) + guard let json = String(data: data, encoding: .utf8) else { throw KometShareError.invalidRequest } + let context = KometShareProgressContext(update: progress) + let response = withExtendedLifetime(context) { + json.withCString { value in + komet_share_send(value, kometShareProgressCallback, Unmanaged.passUnretained(context).toOpaque()) + } + } + guard let response = response else { + return KometShareSendResult(status: "unknown", message: "Не удалось подтвердить отправку. Проверьте чат в Komet перед повторной отправкой.") + } + defer { komet_share_free(response) } + guard let data = String(cString: response).data(using: .utf8), + let payload = try JSONSerialization.jsonObject(with: data) as? [String: Any], + let status = payload["status"] as? String, ["sent", "failed", "unknown"].contains(status) else { + return KometShareSendResult(status: "unknown", message: "Не удалось подтвердить отправку. Проверьте чат в Komet перед повторной отправкой.") + } + return KometShareSendResult( + status: status, message: payload["message"] as? String ?? "Не удалось подтвердить отправку.", + refreshedToken: payload["refreshed_token"] as? String + ) + } + + static func prepareImages(_ files: [KometSharedFile], in draft: KometShareDraft) throws -> [KometSharedFile] { + try files.map { file in + try autoreleasepool { + let url = draft.directoryURL.appendingPathComponent(file.relativePath) + guard let source = CGImageSourceCreateWithURL(url as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary) else { + if file.mime.hasPrefix("image/") { throw KometShareError.unreadableAttachment } + return file + } + guard let type = CGImageSourceGetType(source), UTTypeConformsTo(type, kUTTypeImage) else { return file } + if CGImageSourceGetCount(source) > 1 { + return KometSharedFile(relativePath: file.relativePath, name: file.name, mime: "application/octet-stream", size: file.size) + } + let options: [CFString: Any] = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: 2560, + kCGImageSourceShouldCacheImmediately: true + ] + guard let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary), + let colorSpace = CGColorSpace(name: CGColorSpace.sRGB), + let context = CGContext(data: nil, width: thumbnail.width, height: thumbnail.height, + bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, + bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { + throw KometShareError.unreadableAttachment + } + let bounds = CGRect(x: 0, y: 0, width: thumbnail.width, height: thumbnail.height) + context.setFillColor(CGColor(gray: 1, alpha: 1)) + context.fill(bounds) + context.draw(thumbnail, in: bounds) + guard let image = context.makeImage() else { throw KometShareError.unreadableAttachment } + let destinationURL = url.deletingLastPathComponent().appendingPathComponent(UUID().uuidString.lowercased() + ".jpg") + guard let destination = CGImageDestinationCreateWithURL(destinationURL as CFURL, kUTTypeJPEG, 1, nil) else { + throw KometShareError.unreadableAttachment + } + CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: 0.9] as CFDictionary) + guard CGImageDestinationFinalize(destination) else { + try? FileManager.default.removeItem(at: destinationURL) + throw KometShareError.unreadableAttachment + } + let attributes = try FileManager.default.attributesOfItem(atPath: destinationURL.path) + guard let size = attributes[.size] as? NSNumber else { throw KometShareError.unreadableAttachment } + try FileManager.default.removeItem(at: url) + return KometSharedFile( + relativePath: "attachments/\(destinationURL.lastPathComponent)", + name: (file.name as NSString).deletingPathExtension + ".jpg", + mime: "image/jpeg", size: size.int64Value + ) + } + } + } +} diff --git a/ios/ShareExtension/KometShareTransport.h b/ios/ShareExtension/KometShareTransport.h new file mode 100644 index 00000000..21a77630 --- /dev/null +++ b/ios/ShareExtension/KometShareTransport.h @@ -0,0 +1,8 @@ +#ifndef KOMET_SHARE_TRANSPORT_H +#define KOMET_SHARE_TRANSPORT_H + +typedef void (*KometShareProgress)(const char *json, void *context); +char *komet_share_send(const char *json, KometShareProgress progress, void *context); +void komet_share_free(char *value); + +#endif diff --git a/ios/ShareExtension/ShareExtension-Bridging-Header.h b/ios/ShareExtension/ShareExtension-Bridging-Header.h new file mode 100644 index 00000000..818ffb24 --- /dev/null +++ b/ios/ShareExtension/ShareExtension-Bridging-Header.h @@ -0,0 +1 @@ +#import "KometShareTransport.h" diff --git a/ios/ShareExtension/ShareExtension.entitlements b/ios/ShareExtension/ShareExtension.entitlements new file mode 100644 index 00000000..544e2a65 --- /dev/null +++ b/ios/ShareExtension/ShareExtension.entitlements @@ -0,0 +1,6 @@ + + + + com.apple.security.application-groups + $(KOMET_SHARE_APP_GROUP) + diff --git a/ios/ShareExtension/ShareViewController.swift b/ios/ShareExtension/ShareViewController.swift new file mode 100644 index 00000000..b277f656 --- /dev/null +++ b/ios/ShareExtension/ShareViewController.swift @@ -0,0 +1,777 @@ +import UIKit +import MobileCoreServices +import ImageIO + +final class ShareViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UITextViewDelegate { + private let worker = DispatchQueue(label: "ru.komet.app.share-extension") + private let titleLabel = UILabel() + private let messageLabel = UILabel() + private let spinner = UIActivityIndicatorView(style: .large) + private let button = UIButton(type: .system) + private let statusStack = UIStackView() + private let pickerStack = UIStackView() + private let accountButton = UIButton(type: .system) + private let outboxButton = UIButton(type: .system) + private let accountRow = UIStackView() + private let summaryRow = UIStackView() + private let summaryLabel = UILabel() + private let thumbnailView = UIImageView() + private let captionView = UITextView() + private let captionPlaceholder = UILabel() + private let searchBar = UISearchBar() + private let tableView = UITableView(frame: .zero, style: .plain) + private let sendButton = UIButton(type: .system) + private let progressView = UIProgressView(progressViewStyle: .default) + private var pickerBottom: NSLayoutConstraint? + private var keyboardOverlap: CGFloat = 0 + private var accountStore: KometShareAccounts? + private var accounts: [KometShareAccount] = [] + private var selectedAccount: KometShareAccount? + private var selectedChat: KometShareChat? + private var outgoing: KometOutgoingShare? + private var previousShares: [KometOutgoingShare] = [] + private var sending = false + private var canRetry = false + private var store: KometShareStore? + private var draft: KometShareDraft? + private var providers: [NSItemProvider] = [] + private var files: [KometSharedFile] = [] + private var texts: [String] = [] + private var subject: String? + private var index = 0 + private var progress: Progress? + private var cancelled = false + private var completed = false + private var started = false + + #if DEBUG + func configurePreview(accounts: [KometShareAccount], files: [KometSharedFile], text: String, image: UIImage?) { + started = true + loadViewIfNeeded() + self.accounts = accounts + self.files = files + selectedAccount = accounts.first + captionView.text = text + captionPlaceholder.isHidden = !text.isEmpty + summaryLabel.text = files.isEmpty ? "Текст или ссылка" : files.count == 1 ? files[0].name : "Вложений: \(files.count)" + thumbnailView.image = image + thumbnailView.isHidden = image == nil + spinner.stopAnimating() + statusStack.isHidden = true + pickerStack.isHidden = false + refreshPicker() + } + #endif + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .systemBackground + titleLabel.text = "Отправить в Komet" + titleLabel.font = .preferredFont(forTextStyle: .title2) + titleLabel.adjustsFontForContentSizeCategory = true + titleLabel.textAlignment = .center + titleLabel.numberOfLines = 0 + messageLabel.font = .preferredFont(forTextStyle: .body) + messageLabel.adjustsFontForContentSizeCategory = true + messageLabel.textAlignment = .center + messageLabel.numberOfLines = 0 + messageLabel.textColor = .secondaryLabel + messageLabel.text = "Подготавливаем вложения…" + button.setTitle("Отмена", for: .normal) + button.titleLabel?.font = .preferredFont(forTextStyle: .headline) + button.addTarget(self, action: #selector(close), for: .touchUpInside) + statusStack.axis = .vertical + statusStack.spacing = 20 + for child in [spinner, titleLabel, messageLabel, progressView, button] { + statusStack.addArrangedSubview(child) + } + statusStack.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(statusStack) + NSLayoutConstraint.activate([ + statusStack.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 28), + statusStack.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -28), + statusStack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), + statusStack.topAnchor.constraint(greaterThanOrEqualTo: view.safeAreaLayoutGuide.topAnchor, constant: 20), + statusStack.bottomAnchor.constraint(lessThanOrEqualTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20), + button.heightAnchor.constraint(greaterThanOrEqualToConstant: 44) + ]) + progressView.isHidden = true + configurePicker() + preferredContentSize = CGSize(width: 420, height: 660) + spinner.startAnimating() + NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) + } + + deinit { + NotificationCenter.default.removeObserver(self) + } + + private func configurePicker() { + let cancelButton = UIButton(type: .system) + cancelButton.setTitle("Отмена", for: .normal) + cancelButton.addTarget(self, action: #selector(close), for: .touchUpInside) + let heading = UILabel() + heading.text = "Отправить в Komet" + heading.font = .preferredFont(forTextStyle: .headline) + heading.textAlignment = .center + let spacer = UIView() + let navigation = UIStackView(arrangedSubviews: [cancelButton, heading, spacer]) + navigation.alignment = .center + navigation.spacing = 8 + spacer.widthAnchor.constraint(equalTo: cancelButton.widthAnchor).isActive = true + navigation.heightAnchor.constraint(greaterThanOrEqualToConstant: 44).isActive = true + accountButton.contentHorizontalAlignment = .leading + accountButton.titleLabel?.font = .preferredFont(forTextStyle: .subheadline) + accountButton.setTitleColor(.secondaryLabel, for: .disabled) + accountButton.addTarget(self, action: #selector(chooseAccount), for: .touchUpInside) + outboxButton.setTitle("Неотправленные", for: .normal) + outboxButton.titleLabel?.font = .preferredFont(forTextStyle: .footnote) + outboxButton.addTarget(self, action: #selector(showOutbox), for: .touchUpInside) + accountRow.addArrangedSubview(accountButton) + accountRow.addArrangedSubview(outboxButton) + accountRow.spacing = 12 + let accountHeight = accountRow.heightAnchor.constraint(greaterThanOrEqualToConstant: 36) + accountHeight.priority = .defaultHigh + accountHeight.isActive = true + accountButton.setContentHuggingPriority(.defaultLow, for: .horizontal) + thumbnailView.contentMode = .scaleAspectFill + thumbnailView.clipsToBounds = true + thumbnailView.layer.cornerRadius = 8 + thumbnailView.widthAnchor.constraint(equalToConstant: 56).isActive = true + let thumbnailHeight = thumbnailView.heightAnchor.constraint(equalToConstant: 56) + thumbnailHeight.priority = .defaultHigh + thumbnailHeight.isActive = true + thumbnailView.isHidden = true + summaryLabel.font = .preferredFont(forTextStyle: .subheadline) + summaryLabel.textColor = .secondaryLabel + summaryLabel.numberOfLines = 2 + summaryRow.addArrangedSubview(thumbnailView) + summaryRow.addArrangedSubview(summaryLabel) + summaryRow.alignment = .center + summaryRow.spacing = 12 + captionView.font = .preferredFont(forTextStyle: .body) + captionView.backgroundColor = .secondarySystemBackground + captionView.layer.cornerRadius = 10 + captionView.textContainerInset = UIEdgeInsets(top: 10, left: 8, bottom: 10, right: 8) + captionView.accessibilityLabel = "Сообщение или подпись" + captionView.delegate = self + let captionHeight = captionView.heightAnchor.constraint(equalToConstant: 74) + captionHeight.priority = .defaultHigh + captionHeight.isActive = true + captionPlaceholder.text = "Сообщение или подпись…" + captionPlaceholder.font = .preferredFont(forTextStyle: .body) + captionPlaceholder.textColor = .placeholderText + captionPlaceholder.translatesAutoresizingMaskIntoConstraints = false + captionPlaceholder.isUserInteractionEnabled = false + captionView.addSubview(captionPlaceholder) + NSLayoutConstraint.activate([ + captionPlaceholder.leadingAnchor.constraint(equalTo: captionView.leadingAnchor, constant: 13), + captionPlaceholder.topAnchor.constraint(equalTo: captionView.topAnchor, constant: 10) + ]) + searchBar.placeholder = "Поиск чата или контакта" + searchBar.searchBarStyle = .minimal + searchBar.delegate = self + let keyboardToolbar = UIToolbar() + keyboardToolbar.items = [ + UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), + UIBarButtonItem(title: "Готово", style: .done, target: self, action: #selector(dismissKeyboard)) + ] + keyboardToolbar.sizeToFit() + captionView.inputAccessoryView = keyboardToolbar + tableView.dataSource = self + tableView.delegate = self + tableView.keyboardDismissMode = .onDrag + tableView.tableFooterView = UIView() + tableView.rowHeight = UITableView.automaticDimension + tableView.estimatedRowHeight = 58 + sendButton.setTitle("Выберите получателя", for: .normal) + sendButton.titleLabel?.font = .preferredFont(forTextStyle: .headline) + sendButton.layer.cornerRadius = 12 + sendButton.backgroundColor = .systemBlue + sendButton.setTitleColor(.white, for: .normal) + sendButton.setTitleColor(.tertiaryLabel, for: .disabled) + sendButton.addTarget(self, action: #selector(sendSelected), for: .touchUpInside) + sendButton.heightAnchor.constraint(greaterThanOrEqualToConstant: 48).isActive = true + sendButton.isEnabled = false + pickerStack.axis = .vertical + pickerStack.spacing = 8 + for child in [navigation, accountRow, summaryRow, captionView, searchBar, tableView, sendButton] { + pickerStack.addArrangedSubview(child) + } + pickerStack.translatesAutoresizingMaskIntoConstraints = false + pickerStack.isHidden = true + view.addSubview(pickerStack) + let bottom = pickerStack.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -12) + pickerBottom = bottom + NSLayoutConstraint.activate([ + pickerStack.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16), + pickerStack.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16), + pickerStack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 4), + bottom + ]) + } + + @objc private func keyboardChanged(_ notification: Notification) { + guard let frame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return } + let local = view.convert(frame, from: nil) + keyboardOverlap = local.maxY >= view.bounds.maxY - 1 + ? max(0, view.bounds.maxY - local.minY - view.safeAreaInsets.bottom) : 0 + pickerBottom?.constant = -12 - keyboardOverlap + updateEditingLayout() + let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double ?? 0.25 + UIView.animate(withDuration: duration) { self.view.layoutIfNeeded() } + } + + private func updateEditingLayout() { + let hasKeyboard = keyboardOverlap > 0 + accountRow.isHidden = hasKeyboard + summaryRow.isHidden = hasKeyboard + captionView.isHidden = hasKeyboard && searchBar.searchTextField.isFirstResponder + searchBar.isHidden = hasKeyboard && captionView.isFirstResponder + } + + @objc private func dismissKeyboard() { + view.endEditing(true) + } + + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + guard !started else { return } + started = true + begin() + } + + private func begin() { + let items = extensionContext?.inputItems.compactMap { $0 as? NSExtensionItem } ?? [] + for item in items { + appendText(item.attributedContentText?.string) + if subject == nil { subject = item.attributedTitle?.string } + providers.append(contentsOf: item.attachments ?? []) + } + guard providers.count <= KometShareStore.maximumAttachments else { + fail(KometShareError.tooManyAttachments) + return + } + worker.async { + let result = Result { () -> (KometShareStore, KometShareDraft) in + let store = try KometShareStore() + return (store, try store.beginRequest()) + } + DispatchQueue.main.async { + switch result { + case .success(let (store, draft)): + self.store = store + self.draft = draft + if self.cancelled { + self.worker.async { store.discard(draft) } + } else { + self.processNext() + } + case .failure(let error): + if !self.cancelled { self.fail(error) } + } + } + } + } + + private func processNext() { + guard !cancelled, let store = store, let draft = draft else { return } + guard index < providers.count else { + preparePicker(store: store, draft: draft) + return + } + let provider = providers[index] + messageLabel.text = "Подготавливаем вложение \(index + 1) из \(providers.count)…" + if provider.hasItemConformingToTypeIdentifier(kUTTypeFileURL as String) { + progress = nil + provider.loadItem(forTypeIdentifier: kUTTypeFileURL as String, options: nil) { item, error in + let result = Result { () -> KometSharedFile in + if let error = error { throw error } + guard let url = item as? URL else { throw KometShareError.unsupportedAttachment } + return try self.worker.sync { + try store.copyFile(at: url, suggestedName: provider.suggestedName, typeIdentifier: nil, into: draft) + } + } + DispatchQueue.main.async { self.receivedFile(result) } + } + return + } + let types = provider.registeredTypeIdentifiers + let fileType = types.first { + Self.conforms($0, to: kUTTypeImage) || Self.conforms($0, to: kUTTypeMovie) || + Self.conforms($0, to: kUTTypeAudio) + } ?? types.first { + Self.conforms($0, to: kUTTypeData) && !Self.conforms($0, to: kUTTypeText) && + !Self.conforms($0, to: kUTTypeURL) + } + if let type = fileType { + loadFile(provider: provider, type: type, store: store, draft: draft) + } else if provider.hasItemConformingToTypeIdentifier(kUTTypeURL as String) { + loadText(provider: provider, type: kUTTypeURL as String) + } else if let textType = types.first(where: { Self.conforms($0, to: kUTTypeText) }) { + if let name = provider.suggestedName, !(name as NSString).pathExtension.isEmpty { + loadFile(provider: provider, type: textType, store: store, draft: draft) + } else { + loadText(provider: provider, type: textType) + } + } else { + fail(KometShareError.unsupportedAttachment) + } + } + + private func loadFile( + provider: NSItemProvider, type: String, store: KometShareStore, draft: KometShareDraft + ) { + progress = provider.loadFileRepresentation(forTypeIdentifier: type) { url, error in + if let url = url { + let result = Result { + try self.worker.sync { + try store.copyFile( + at: url, suggestedName: provider.suggestedName, typeIdentifier: type, into: draft + ) + } + } + DispatchQueue.main.async { self.receivedFile(result) } + } else { + DispatchQueue.main.async { + guard !self.cancelled else { return } + self.loadData(provider: provider, type: type, store: store, draft: draft) + } + } + } + } + + private func loadData( + provider: NSItemProvider, type: String, store: KometShareStore, draft: KometShareDraft + ) { + progress = provider.loadDataRepresentation(forTypeIdentifier: type) { data, error in + if let data = data { + let result = Result { + try self.worker.sync { + try store.saveData(data, suggestedName: provider.suggestedName, typeIdentifier: type, into: draft) + } + } + DispatchQueue.main.async { self.receivedFile(result) } + } else if Self.conforms(type, to: kUTTypeImage) { + DispatchQueue.main.async { + guard !self.cancelled else { return } + self.loadImage(provider: provider, type: type, store: store, draft: draft) + } + } else { + DispatchQueue.main.async { self.fail(error ?? KometShareError.unreadableAttachment) } + } + } + } + + private func loadImage( + provider: NSItemProvider, type: String, store: KometShareStore, draft: KometShareDraft + ) { + progress = nil + provider.loadItem(forTypeIdentifier: type, options: nil) { item, error in + let result = Result { () -> KometSharedFile in + if let error = error { throw error } + guard let image = item as? UIImage, let data = image.pngData() else { + throw KometShareError.unreadableAttachment + } + let name = provider.suggestedName.map { ($0 as NSString).deletingPathExtension + ".png" } + return try self.worker.sync { + try store.saveData(data, suggestedName: name, typeIdentifier: kUTTypePNG as String, into: draft) + } + } + DispatchQueue.main.async { self.receivedFile(result) } + } + } + + private func loadText(provider: NSItemProvider, type: String) { + progress = nil + provider.loadItem(forTypeIdentifier: type, options: nil) { item, error in + let result = Result { () -> String in + if let error = error { throw error } + if let url = item as? URL { return url.absoluteString } + if let text = item as? String { return text } + if let text = item as? NSAttributedString { return text.string } + if let data = item as? Data, let text = String(data: data, encoding: .utf8) { return text } + throw KometShareError.unsupportedAttachment + } + DispatchQueue.main.async { + guard !self.cancelled else { return } + switch result { + case .success(let text): + self.appendText(text) + self.index += 1 + self.processNext() + case .failure(let error): + self.fail(error) + } + } + } + } + + private func receivedFile(_ result: Result) { + guard !cancelled else { return } + switch result { + case .success(let file): + files.append(file) + index += 1 + processNext() + case .failure(let error): + fail(error) + } + } + + private func appendText(_ value: String?) { + guard let text = value?.trimmingCharacters(in: .whitespacesAndNewlines), + !text.isEmpty, !texts.contains(text) else { return } + texts.append(text) + } + + private func preparePicker(store: KometShareStore, draft: KometShareDraft) { + let files = self.files + let text = texts.joined(separator: "\n") + guard !files.isEmpty || !text.isEmpty else { fail(KometShareError.emptyRequest); return } + worker.async { + let result = Result { () -> ([KometSharedFile], KometShareAccounts, [KometShareAccount], [KometOutgoingShare], UIImage?) in + let accounts = try KometShareAccounts() + let saved = try accounts.accounts() + let prepared = try KometShareSender.prepareImages(files, in: draft) + let image = prepared.first.flatMap { self.thumbnail(for: draft.directoryURL.appendingPathComponent($0.relativePath)) } + return (prepared, accounts, saved, try store.outgoingShares(), image) + } + DispatchQueue.main.async { + guard !self.cancelled else { return } + switch result { + case .success(let (files, accountStore, accounts, previous, image)): + self.files = files + self.accountStore = accountStore + self.accounts = accounts + self.previousShares = previous + self.selectedAccount = accounts.first + self.captionView.text = text + self.captionPlaceholder.isHidden = !text.isEmpty + self.summaryLabel.text = files.isEmpty ? "Текст или ссылка" : files.count == 1 ? files[0].name : "Вложений: \(files.count)" + self.thumbnailView.image = image + self.thumbnailView.isHidden = image == nil + self.spinner.stopAnimating() + self.statusStack.isHidden = true + self.pickerStack.isHidden = false + self.refreshPicker() + case .failure(let error): + self.fail(error) + } + } + } + } + + private func thumbnail(for url: URL) -> UIImage? { + guard let source = CGImageSourceCreateWithURL(url as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary), + let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: 168 + ] as CFDictionary) else { return nil } + return UIImage(cgImage: image) + } + + private var visibleChats: [KometShareChat] { + let query = searchBar.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + return selectedAccount?.chats.filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) } ?? [] + } + + private func refreshPicker() { + accountButton.setTitle(selectedAccount.map { $0.name + (accounts.count > 1 ? " ▾" : "") } ?? "Нет аккаунта", for: .normal) + accountButton.isEnabled = accounts.count > 1 + outboxButton.isHidden = previousShares.isEmpty + let hasContent = !files.isEmpty || !captionView.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + sendButton.isEnabled = selectedChat != nil && selectedChat?.disabledReason == nil && hasContent + sendButton.setTitle(selectedChat.map { "Отправить • " + $0.title } ?? "Выберите получателя", for: .normal) + tableView.reloadData() + if visibleChats.isEmpty { + let empty = UILabel() + empty.numberOfLines = 0 + empty.textAlignment = .center + empty.font = .preferredFont(forTextStyle: .body) + empty.textColor = .secondaryLabel + empty.text = accounts.isEmpty + ? "Откройте Komet один раз, чтобы загрузить ваши аккаунты и чаты. Затем вернитесь к отправке." + : selectedAccount?.chats.isEmpty == true ? "В этом аккаунте пока нет доступных чатов. Обновите список в Komet." : "Чаты не найдены" + tableView.backgroundView = empty + } else { + tableView.backgroundView = nil + } + } + + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { visibleChats.count } + + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let chat = visibleChats[indexPath.row] + let cell = tableView.dequeueReusableCell(withIdentifier: "chat") ?? UITableViewCell(style: .subtitle, reuseIdentifier: "chat") + cell.textLabel?.text = chat.title + cell.textLabel?.font = .preferredFont(forTextStyle: .body) + cell.textLabel?.textColor = chat.disabledReason == nil ? .label : .secondaryLabel + cell.detailTextLabel?.text = chat.disabledReason + cell.detailTextLabel?.numberOfLines = 0 + cell.detailTextLabel?.textColor = .secondaryLabel + cell.accessoryType = selectedChat?.id == chat.id ? .checkmark : .none + cell.selectionStyle = chat.disabledReason == nil ? .default : .none + cell.imageView?.image = UIImage(systemName: chat.type.uppercased() == "DIALOG" ? "person.crop.circle" : "person.2.circle") + cell.imageView?.tintColor = .secondaryLabel + cell.accessibilityTraits = chat.disabledReason == nil ? .button : .notEnabled + return cell + } + + func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + tableView.deselectRow(at: indexPath, animated: true) + let chat = visibleChats[indexPath.row] + guard chat.disabledReason == nil else { return } + selectedChat = chat + view.endEditing(true) + refreshPicker() + } + + func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { refreshPicker() } + func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { updateEditingLayout() } + func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } + func textViewDidBeginEditing(_ textView: UITextView) { updateEditingLayout() } + func textViewDidChange(_ textView: UITextView) { + captionPlaceholder.isHidden = !textView.text.isEmpty + let hasContent = !files.isEmpty || !textView.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + sendButton.isEnabled = selectedChat != nil && selectedChat?.disabledReason == nil && hasContent + } + + @objc private func chooseAccount() { + let alert = UIAlertController(title: "Аккаунт", message: nil, preferredStyle: .actionSheet) + for account in accounts { + alert.addAction(UIAlertAction(title: account.name, style: .default) { _ in + self.selectedAccount = account + self.selectedChat = nil + self.searchBar.text = "" + self.refreshPicker() + }) + } + alert.addAction(UIAlertAction(title: "Отмена", style: .cancel)) + presentSheet(alert, source: accountButton) + } + + private func presentSheet(_ alert: UIAlertController, source: UIView) { + alert.popoverPresentationController?.sourceView = source + alert.popoverPresentationController?.sourceRect = source.bounds + present(alert, animated: true) + } + + @objc private func sendSelected() { + guard !sending, let store = store, let draft = draft, + let account = selectedAccount, let chat = selectedChat, chat.disabledReason == nil else { return } + let files = self.files + let text = captionView.text + view.endEditing(true) + showSending() + worker.async { + do { + let outgoing = try store.prepareOutgoing(draft, files: files, text: text, accountID: account.id, chatID: chat.id, chatTitle: chat.title) + DispatchQueue.main.async { + self.draft = nil + self.outgoing = outgoing + self.sendOutgoing(outgoing) + } + } catch { + DispatchQueue.main.async { + self.sending = false + self.fail(error) + } + } + } + } + + private func showSending() { + sending = true + canRetry = false + pickerStack.isHidden = true + statusStack.isHidden = false + titleLabel.text = "Отправляем в Komet" + messageLabel.text = "Подключаемся…" + spinner.startAnimating() + progressView.progress = 0 + progressView.isHidden = false + button.isEnabled = false + button.setTitle("Отправляем…", for: .normal) + isModalInPresentation = true + } + + private func sendOutgoing(_ outgoing: KometOutgoingShare) { + guard let store = store, let accountStore = accountStore else { return } + worker.async { + var attempted = false + do { + let credentials = try accountStore.authorizedCredentials(accountID: outgoing.accountID, chatID: outgoing.chatID) + let request = try store.outgoingRequest(outgoing) + _ = try store.updateOutgoing(outgoing, status: "sending", message: nil) + attempted = true + let result = try KometShareSender.send(credentials: credentials, request: request) { message, progress, phase in + DispatchQueue.main.async { + self.messageLabel.text = phase == "uploading" && progress != nil + ? message + " \(Int((progress! * 100).rounded()))%" : message + self.progressView.isHidden = progress == nil + if let progress = progress { self.progressView.setProgress(Float(progress), animated: true) } + } + } + var message = result.status == "sent" ? "Вложения отправлены в «\(outgoing.chatTitle)»." : result.message + if let token = result.refreshedToken, let oldToken = credentials["token"] as? String { + do { + try accountStore.updateToken(accountID: outgoing.accountID, previousToken: oldToken, refreshedToken: token) + } catch { + message += "\n\nОткройте Komet, чтобы обновить доступ к аккаунту." + } + } + var confirmed = outgoing + confirmed.status = result.status + confirmed.message = message + let updated = (try? store.updateOutgoing(outgoing, status: result.status, message: message)) ?? confirmed + if result.status == "sent" { try? store.removeOutgoing(id: outgoing.id) } + DispatchQueue.main.async { self.finishSending(updated) } + } catch { + let status = attempted ? "unknown" : "failed" + let message = attempted + ? "Не удалось подтвердить отправку. Проверьте чат в Komet перед повторной отправкой." + : error.localizedDescription + var fallback = outgoing + fallback.status = status + fallback.message = message + let updated = (try? store.updateOutgoing(outgoing, status: status, message: message)) ?? fallback + DispatchQueue.main.async { self.finishSending(updated) } + } + } + } + + private func finishSending(_ outgoing: KometOutgoingShare) { + self.outgoing = outgoing + sending = false + isModalInPresentation = false + completed = outgoing.status == "sent" + canRetry = outgoing.status == "failed" || outgoing.status == "prepared" + spinner.stopAnimating() + progressView.isHidden = true + titleLabel.text = completed ? "Отправлено" : canRetry ? "Не удалось отправить" : "Нужна проверка отправки" + messageLabel.text = outgoing.message ?? (completed ? "Вложения отправлены в «\(outgoing.chatTitle)»." : "Проверьте чат в Komet. Вложения сохранены в разделе «Неотправленные»; автоматической повторной отправки не будет.") + if !completed && !canRetry { + messageLabel.text = (messageLabel.text ?? "") + "\n\nАвтоматической повторной отправки не будет." + } + button.isEnabled = true + button.setTitle(canRetry ? "Повторить" : "Готово", for: .normal) + if canRetry { + let closeButton = UIButton(type: .system) + closeButton.setTitle(draft == nil ? "Закрыть" : "К текущей отправке", for: .normal) + closeButton.addTarget(self, action: #selector(closeWithoutRetry), for: .touchUpInside) + closeButton.tag = 901 + statusStack.arrangedSubviews.first(where: { $0.tag == 901 })?.removeFromSuperview() + statusStack.addArrangedSubview(closeButton) + } else { + statusStack.arrangedSubviews.first(where: { $0.tag == 901 })?.removeFromSuperview() + } + UIAccessibility.post(notification: .announcement, argument: titleLabel.text) + } + + @objc private func showOutbox() { + let alert = UIAlertController(title: "Неотправленные", message: "Повтор возможен только после подтверждённой ошибки. При неизвестном результате сначала проверьте чат.", preferredStyle: .actionSheet) + for share in previousShares { + let state = share.status == "failed" || share.status == "prepared" ? "Ошибка" : share.status == "sent" ? "Отправлено" : "Проверьте чат" + alert.addAction(UIAlertAction(title: "\(share.chatTitle) • \(state)", style: .default) { _ in self.showPreviousShare(share) }) + } + alert.addAction(UIAlertAction(title: "Закрыть", style: .cancel)) + presentSheet(alert, source: outboxButton) + } + + private func showPreviousShare(_ share: KometOutgoingShare) { + let message = share.message ?? "Предыдущая отправка была прервана. Проверьте чат в Komet перед повторной отправкой." + let alert = UIAlertController(title: share.chatTitle, message: message, preferredStyle: .alert) + if share.status == "failed" || share.status == "prepared" { + alert.addAction(UIAlertAction(title: "Повторить отправку", style: .default) { _ in + self.outgoing = share + self.showSending() + self.sendOutgoing(share) + }) + } + alert.addAction(UIAlertAction(title: "Удалить сохранённые вложения", style: .destructive) { _ in + guard let store = self.store else { return } + self.worker.async { + do { + try store.removeOutgoing(id: share.id) + let previous = try store.outgoingShares() + DispatchQueue.main.async { self.previousShares = previous; self.refreshPicker() } + } catch { + DispatchQueue.main.async { self.messageAlert(error.localizedDescription) } + } + } + }) + alert.addAction(UIAlertAction(title: "Назад", style: .cancel)) + present(alert, animated: true) + } + + private func messageAlert(_ message: String) { + let alert = UIAlertController(title: "Komet", message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "Готово", style: .default)) + present(alert, animated: true) + } + + private func fail(_ error: Error) { + guard !cancelled else { return } + if let store = store, let draft = draft { + worker.async { store.discard(draft) } + self.draft = nil + } + sending = false + isModalInPresentation = false + pickerStack.isHidden = true + statusStack.isHidden = false + spinner.stopAnimating() + progressView.isHidden = true + titleLabel.text = "Не удалось передать" + messageLabel.text = error.localizedDescription + button.isEnabled = true + button.setTitle("Закрыть", for: .normal) + } + + @objc private func close() { + guard !sending else { return } + if canRetry, let outgoing = outgoing { + statusStack.arrangedSubviews.first(where: { $0.tag == 901 })?.removeFromSuperview() + showSending() + sendOutgoing(outgoing) + return + } + closeWithoutRetry() + } + + @objc private func closeWithoutRetry() { + guard !sending else { return } + if draft != nil, outgoing != nil { + outgoing = nil + completed = false + canRetry = false + statusStack.arrangedSubviews.first(where: { $0.tag == 901 })?.removeFromSuperview() + statusStack.isHidden = true + pickerStack.isHidden = false + if let store = store { + worker.async { + let previous = (try? store.outgoingShares()) ?? [] + DispatchQueue.main.async { self.previousShares = previous; self.refreshPicker() } + } + } + return + } + if completed { + extensionContext?.completeRequest(returningItems: nil, completionHandler: nil) + return + } + cancelled = true + progress?.cancel() + if let store = store, let draft = draft { + worker.async { store.discard(draft) } + self.draft = nil + } + extensionContext?.cancelRequest(withError: NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError)) + } + + private static func conforms(_ type: String, to parent: CFString) -> Bool { + UTTypeConformsTo(type as CFString, parent) + } +} diff --git a/ios/Shared/KometShareAccounts.swift b/ios/Shared/KometShareAccounts.swift new file mode 100644 index 00000000..127ab73e --- /dev/null +++ b/ios/Shared/KometShareAccounts.swift @@ -0,0 +1,205 @@ +import Foundation +import Security +import Darwin + +struct KometShareChat: Codable { + let id: String + let title: String + let type: String + let disabledReason: String? +} + +struct KometShareAccount: Codable { + let id: String + let name: String + let chats: [KometShareChat] +} + +protocol KometShareCredentialStorage { + func read(accountID: String) throws -> Data + func write(_ data: Data, accountID: String) throws + func remove(accountID: String?) throws +} + +private final class KometShareKeychain: KometShareCredentialStorage { + private let group: String + private let service = "ru.komet.app.share.credentials" + + init(group: String) { self.group = group } + + func read(accountID: String) throws -> Data { + var query = query(accountID: accountID) + query[kSecReturnData as String] = true + query[kSecMatchLimit as String] = kSecMatchLimitOne + var item: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &item) + guard status == errSecSuccess else { throw error(status) } + guard let data = item as? Data else { throw KometShareError.invalidRequest } + return data + } + + func write(_ data: Data, accountID: String) throws { + let query = query(accountID: accountID) + let changes: [String: Any] = [ + kSecValueData as String: data, + kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly + ] + var status = SecItemUpdate(query as CFDictionary, changes as CFDictionary) + if status == errSecItemNotFound { + status = SecItemAdd(query.merging(changes) { _, new in new } as CFDictionary, nil) + } + guard status == errSecSuccess else { throw error(status) } + } + + func remove(accountID: String?) throws { + let status = SecItemDelete(query(accountID: accountID) as CFDictionary) + guard status == errSecSuccess || status == errSecItemNotFound else { throw error(status) } + } + + private func query(accountID: String?) -> [String: Any] { + var query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccessGroup as String: group + ] + if let accountID = accountID { query[kSecAttrAccount as String] = accountID } + return query + } + + private func error(_ status: OSStatus) -> NSError { + let message = status == errSecItemNotFound + ? "Откройте Komet один раз, чтобы обновить список чатов и доступ к аккаунту." + : "Не удалось получить доступ к аккаунту Komet. Проверьте поддержку общей группы Keychain в подписи приложения." + return NSError(domain: NSOSStatusErrorDomain, code: Int(status), userInfo: [NSLocalizedDescriptionKey: message]) + } +} + +final class KometShareAccounts { + private let snapshotURL: URL + private let lockURL: URL + private let credentialStore: KometShareCredentialStorage + + convenience init() throws { + let group = Bundle.main.object(forInfoDictionaryKey: "KometShareAppGroup") as? String ?? "group.ru.komet.app" + guard let container = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group) else { + throw KometShareError.unavailableContainer + } + try self.init(containerURL: container, credentialStore: KometShareKeychain(group: group)) + } + + init(containerURL: URL, credentialStore: KometShareCredentialStorage) throws { + let directory = containerURL.appendingPathComponent("KometShare", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + snapshotURL = directory.appendingPathComponent("accounts.json") + lockURL = directory.appendingPathComponent("accounts.lock") + self.credentialStore = credentialStore + } + + func accounts() throws -> [KometShareAccount] { + try withLock { try readAccounts() } + } + + func sync(_ arguments: [String: Any]) throws { + try withLock { + guard let id = arguments["accountId"] as? String, Int64(id) != nil, + let token = arguments["token"] as? String, !token.isEmpty, + let session = arguments["session"] as? [String: Any], + let login = arguments["login"] as? [String: Any], + let rawChats = arguments["chats"] as? [[String: Any]] else { + throw KometShareError.invalidRequest + } + let chats = try rawChats.map { raw -> KometShareChat in + guard let chatID = raw["id"] as? String, Int64(chatID) != nil, + let title = raw["title"] as? String, !title.isEmpty, + let type = raw["type"] as? String else { throw KometShareError.invalidRequest } + return KometShareChat(id: chatID, title: title, type: type, disabledReason: raw["disabledReason"] as? String) + } + let existing = try? readCredentials(accountID: id) + let activeToken = existing?["sourceToken"] as? String == token ? existing?["token"] as? String ?? token : token + let credentials: [String: Any] = [ + "account_id": id, "token": activeToken, "sourceToken": token, "session": session, "login": login + ] + try writeCredentials(credentials, accountID: id) + var saved = try readAccounts().filter { $0.id != id } + let name = arguments["accountName"] as? String ?? "Komet" + saved.insert(KometShareAccount(id: id, name: name, chats: chats), at: 0) + try writeAccounts(saved) + } + } + + func credentials(accountID: String) throws -> [String: Any] { + try withLock { try readCredentials(accountID: accountID) } + } + + func authorizedCredentials(accountID: String, chatID: String) throws -> [String: Any] { + try withLock { + guard let account = try readAccounts().first(where: { $0.id == accountID }), + let chat = account.chats.first(where: { $0.id == chatID }), chat.disabledReason == nil else { + throw NSError(domain: "KometShare", code: 1, userInfo: [ + NSLocalizedDescriptionKey: "Этот чат недоступен для отправки. Обновите список чатов в Komet." + ]) + } + return try readCredentials(accountID: accountID) + } + } + + func clear(accountID: String?) throws { + try withLock { + try credentialStore.remove(accountID: accountID) + let remaining = try readAccounts().filter { accountID != nil && $0.id != accountID } + try writeAccounts(remaining) + } + } + + func updateToken(accountID: String, previousToken: String, refreshedToken: String) throws { + guard !refreshedToken.isEmpty else { return } + try withLock { + var saved = try readCredentials(accountID: accountID) + guard saved["token"] as? String == previousToken else { return } + saved["token"] = refreshedToken + try writeCredentials(saved, accountID: accountID) + } + } + + func refreshedToken(accountID: String, knownToken: String) throws -> String? { + try withLock { + let saved = try readCredentials(accountID: accountID) + guard saved["sourceToken"] as? String == knownToken, + let token = saved["token"] as? String, !token.isEmpty, token != knownToken else { return nil } + return token + } + } + + private func readCredentials(accountID: String) throws -> [String: Any] { + let data = try credentialStore.read(accountID: accountID) + guard let credentials = try JSONSerialization.jsonObject(with: data) as? [String: Any], + credentials["account_id"] as? String == accountID else { throw KometShareError.invalidRequest } + return credentials + } + + private func writeCredentials(_ credentials: [String: Any], accountID: String) throws { + try credentialStore.write(JSONSerialization.data(withJSONObject: credentials), accountID: accountID) + } + + private func readAccounts() throws -> [KometShareAccount] { + guard FileManager.default.fileExists(atPath: snapshotURL.path) else { return [] } + return try JSONDecoder().decode([KometShareAccount].self, from: Data(contentsOf: snapshotURL)) + } + + private func writeAccounts(_ accounts: [KometShareAccount]) throws { + var options: Data.WritingOptions = [.atomic] + #if os(iOS) + options.insert(.completeFileProtectionUntilFirstUserAuthentication) + #endif + try JSONEncoder().encode(accounts).write(to: snapshotURL, options: options) + } + + private func withLock(_ operation: () throws -> T) throws -> T { + let descriptor = open(lockURL.path, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR) + guard descriptor >= 0 else { throw KometShareError.unavailableContainer } + defer { Darwin.close(descriptor) } + guard flock(descriptor, LOCK_EX) == 0 else { throw KometShareError.unavailableContainer } + defer { flock(descriptor, LOCK_UN) } + return try operation() + } +} diff --git a/ios/Shared/KometShareStore.swift b/ios/Shared/KometShareStore.swift new file mode 100644 index 00000000..83fb26de --- /dev/null +++ b/ios/Shared/KometShareStore.swift @@ -0,0 +1,443 @@ +import Foundation +#if canImport(MobileCoreServices) +import MobileCoreServices +#else +import CoreServices +#endif + +enum KometShareError: LocalizedError { + case unavailableContainer + case tooManyAttachments + case unsupportedAttachment + case unreadableAttachment + case emptyRequest + case invalidRequest + + var errorDescription: String? { + switch self { + case .unavailableContainer: + return "Нет доступа к общему хранилищу Komet. Установите приложение с поддержкой App Groups." + case .tooManyAttachments: + return "Можно передать не больше 30 вложений за один раз." + case .unsupportedAttachment: + return "Не удалось прочитать одно из вложений. Попробуйте поделиться им как файлом." + case .unreadableAttachment: + return "Не удалось скопировать одно из вложений. Проверьте, что файл доступен на устройстве." + case .emptyRequest: + return "Не найдено файлов, фотографий или текста для отправки." + case .invalidRequest: + return "Не удалось прочитать сохранённые вложения." + } + } +} + +struct KometSharedFile: Codable { + let relativePath: String + let name: String + let mime: String + let size: Int64 +} + +struct KometShareDraft { + let id: String + let directoryURL: URL + let createdAt: TimeInterval +} + +struct KometOutgoingShare: Codable { + let id: String + let createdAt: TimeInterval + let accountID: String + let chatID: String + let chatTitle: String + let files: [KometSharedFile] + let text: String? + var status: String + var message: String? +} + +final class KometShareStore { + static let maximumAttachments = 30 + + private struct Manifest: Codable { + let id: String + let createdAt: TimeInterval + let files: [KometSharedFile] + let text: String? + let subject: String? + } + + private let manager = FileManager.default + private let stagingURL: URL + private let requestsURL: URL + private let quarantineURL: URL + private let outgoingURL: URL + + convenience init() throws { + let configured = Bundle.main.object(forInfoDictionaryKey: "KometShareAppGroup") as? String + let group = configured?.isEmpty == false ? configured! : "group.ru.komet.app" + guard let container = FileManager.default.containerURL( + forSecurityApplicationGroupIdentifier: group + ) else { + throw KometShareError.unavailableContainer + } + try self.init(containerURL: container) + } + + init(containerURL: URL) throws { + let root = containerURL.appendingPathComponent("KometShare", isDirectory: true) + stagingURL = root.appendingPathComponent("staging", isDirectory: true) + requestsURL = root.appendingPathComponent("requests", isDirectory: true) + quarantineURL = root.appendingPathComponent("quarantine", isDirectory: true) + outgoingURL = root.appendingPathComponent("outgoing", isDirectory: true) + try manager.createDirectory(at: stagingURL, withIntermediateDirectories: true) + try manager.createDirectory(at: requestsURL, withIntermediateDirectories: true) + try manager.createDirectory(at: outgoingURL, withIntermediateDirectories: true) + } + + func beginRequest() throws -> KometShareDraft { + let id = UUID().uuidString.lowercased() + let directory = stagingURL.appendingPathComponent(id, isDirectory: true) + try manager.createDirectory( + at: directory.appendingPathComponent("attachments", isDirectory: true), + withIntermediateDirectories: true + ) + return KometShareDraft(id: id, directoryURL: directory, createdAt: Date().timeIntervalSince1970) + } + + func copyFile( + at source: URL, + suggestedName: String?, + typeIdentifier: String?, + into draft: KometShareDraft + ) throws -> KometSharedFile { + guard source.isFileURL else { throw KometShareError.unsupportedAttachment } + let access = source.startAccessingSecurityScopedResource() + defer { if access { source.stopAccessingSecurityScopedResource() } } + var coordinationError: NSError? + var outcome: Result? + NSFileCoordinator().coordinate( + readingItemAt: source, + options: .withoutChanges, + error: &coordinationError + ) { readableURL in + outcome = Result { + let values = try readableURL.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]) + guard values.isRegularFile == true, values.isSymbolicLink != true else { + throw KometShareError.unsupportedAttachment + } + let type = Self.resolvedType( + typeIdentifier, fileNames: [readableURL.lastPathComponent, suggestedName] + ) + let name = Self.fileName(suggestedName ?? readableURL.lastPathComponent, typeIdentifier: type) + let destination = try self.destination(in: draft, name: name) + do { + try self.manager.copyItem(at: readableURL, to: destination) + return try self.fileMetadata(at: destination, name: name, typeIdentifier: type) + } catch { + try? self.manager.removeItem(at: destination) + throw error + } + } + } + if let error = coordinationError { throw error } + guard let result = outcome else { throw KometShareError.unreadableAttachment } + return try result.get() + } + + func saveData( + _ data: Data, + suggestedName: String?, + typeIdentifier: String, + into draft: KometShareDraft + ) throws -> KometSharedFile { + let typeIdentifier = Self.resolvedType(typeIdentifier, fileNames: [suggestedName]) + let name = Self.fileName(suggestedName ?? "Вложение", typeIdentifier: typeIdentifier) + let destination = try self.destination(in: draft, name: name) + do { + try data.write(to: destination, options: .atomic) + return try fileMetadata(at: destination, name: name, typeIdentifier: typeIdentifier) + } catch { + try? manager.removeItem(at: destination) + throw error + } + } + + @discardableResult + func commit( + _ draft: KometShareDraft, + files: [KometSharedFile], + text: String?, + subject: String? + ) throws -> String { + guard files.count <= Self.maximumAttachments else { throw KometShareError.tooManyAttachments } + let text = Self.nonempty(text) + guard !files.isEmpty || text != nil else { throw KometShareError.emptyRequest } + let manifest = Manifest( + id: draft.id, + createdAt: draft.createdAt, + files: files, + text: text, + subject: Self.nonempty(subject) + ) + try validate(manifest, at: draft.directoryURL) + try JSONEncoder().encode(manifest).write( + to: draft.directoryURL.appendingPathComponent("manifest.json"), options: .atomic + ) + try writeState("pending", at: draft.directoryURL) + try manager.moveItem(at: draft.directoryURL, to: requestURL(id: draft.id)) + return draft.id + } + + func discard(_ draft: KometShareDraft) { + try? manager.removeItem(at: draft.directoryURL) + } + + func prepareOutgoing( + _ draft: KometShareDraft, files: [KometSharedFile], text: String?, + accountID: String, chatID: String, chatTitle: String + ) throws -> KometOutgoingShare { + guard Int64(accountID) != nil, Int64(chatID) != nil else { throw KometShareError.invalidRequest } + let text = Self.nonempty(text) + try validate(Manifest(id: draft.id, createdAt: draft.createdAt, files: files, text: text, subject: nil), at: draft.directoryURL) + let outgoing = KometOutgoingShare( + id: draft.id, createdAt: draft.createdAt, accountID: accountID, chatID: chatID, + chatTitle: chatTitle, files: files, text: text, status: "prepared", message: nil + ) + try writeOutgoing(outgoing, at: draft.directoryURL) + try manager.moveItem(at: draft.directoryURL, to: outgoingDirectory(id: draft.id)) + return outgoing + } + + func outgoingShares() throws -> [KometOutgoingShare] { + let directories = try manager.contentsOfDirectory(at: outgoingURL, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) + var shares: [KometOutgoingShare] = [] + for directory in directories { + guard let data = try? Data(contentsOf: directory.appendingPathComponent("outgoing.json")), + let share = try? JSONDecoder().decode(KometOutgoingShare.self, from: data), + share.id == directory.lastPathComponent, UUID(uuidString: share.id) != nil else { continue } + shares.append(share) + } + return shares.sorted { $0.createdAt > $1.createdAt } + } + + func outgoingRequest(_ share: KometOutgoingShare) throws -> [String: Any] { + let directory = try outgoingDirectory(id: share.id) + try validate(Manifest(id: share.id, createdAt: share.createdAt, files: share.files, text: share.text, subject: nil), at: directory) + return [ + "id": share.id, "chat_id": share.chatID, "text": share.text ?? "", + "state_path": directory.appendingPathComponent("send-state.json").path, + "files": share.files.map { file -> [String: Any] in + ["path": directory.appendingPathComponent(file.relativePath).path, + "name": file.name, "mime": file.mime, "size": file.size] + } + ] + } + + func updateOutgoing(_ share: KometOutgoingShare, status: String, message: String?) throws -> KometOutgoingShare { + guard ["prepared", "sending", "failed", "unknown", "sent"].contains(status) else { + throw KometShareError.invalidRequest + } + var updated = share + updated.status = status + updated.message = message + try writeOutgoing(updated, at: outgoingDirectory(id: share.id)) + return updated + } + + func removeOutgoing(id: String) throws { + let directory = try outgoingDirectory(id: id) + if manager.fileExists(atPath: directory.path) { try manager.removeItem(at: directory) } + } + + private func outgoingDirectory(id: String) throws -> URL { + guard UUID(uuidString: id) != nil, !id.contains("/"), !id.contains("\\") else { throw KometShareError.invalidRequest } + return outgoingURL.appendingPathComponent(id, isDirectory: true) + } + + private func writeOutgoing(_ share: KometOutgoingShare, at directory: URL) throws { + var options: Data.WritingOptions = [.atomic] + #if os(iOS) + options.insert(.completeFileProtectionUntilFirstUserAuthentication) + #endif + try JSONEncoder().encode(share).write(to: directory.appendingPathComponent("outgoing.json"), options: options) + } + + @discardableResult + func importDocument(documentURL: URL) throws -> String { + let draft = try beginRequest() + do { + let file = try copyFile( + at: documentURL, suggestedName: nil, typeIdentifier: nil, into: draft + ) + return try commit(draft, files: [file], text: nil, subject: nil) + } catch { + discard(draft) + throw error + } + } + + func nextPayload() throws -> [String: Any]? { + let directories = try manager.contentsOfDirectory( + at: requestsURL, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles] + ) + var candidates: [(manifest: Manifest, directory: URL, state: String)] = [] + for directory in directories { + do { + guard UUID(uuidString: directory.lastPathComponent) != nil else { + throw KometShareError.invalidRequest + } + let state = try readState(at: directory) + if state == "completed" { continue } + guard state == "pending" || state == "claimed" else { throw KometShareError.invalidRequest } + let manifest = try JSONDecoder().decode( + Manifest.self, from: Data(contentsOf: directory.appendingPathComponent("manifest.json")) + ) + guard manifest.id == directory.lastPathComponent else { throw KometShareError.invalidRequest } + candidates.append((manifest, directory, state)) + } catch { + try quarantine(directory) + throw KometShareError.invalidRequest + } + } + candidates.sort { + if ($0.state == "claimed") != ($1.state == "claimed") { return $0.state == "claimed" } + if $0.manifest.createdAt != $1.manifest.createdAt { + return $0.manifest.createdAt < $1.manifest.createdAt + } + return $0.manifest.id < $1.manifest.id + } + guard let next = candidates.first else { return nil } + do { + try validate(next.manifest, at: next.directory) + } catch { + try quarantine(next.directory) + throw KometShareError.invalidRequest + } + try writeState("claimed", at: next.directory) + var payload: [String: Any] = [ + "id": next.manifest.id, + "files": next.manifest.files.map { file -> [String: Any] in + [ + "path": next.directory.appendingPathComponent(file.relativePath).path, + "name": file.name, + "mime": file.mime, + "size": file.size + ] + } + ] + if let text = next.manifest.text { payload["text"] = text } + if let subject = next.manifest.subject { payload["subject"] = subject } + return payload + } + + func acknowledge(id: String) throws { + let directory = try requestURL(id: id) + guard manager.fileExists(atPath: directory.path) else { return } + let state = try readState(at: directory) + guard state == "claimed" || state == "completed" else { throw KometShareError.invalidRequest } + try writeState("completed", at: directory) + } + + func removeCompleted(id: String) throws { + let directory = try requestURL(id: id) + guard manager.fileExists(atPath: directory.path) else { return } + guard try readState(at: directory) == "completed" else { throw KometShareError.invalidRequest } + try manager.removeItem(at: directory) + } + + private func requestURL(id: String) throws -> URL { + guard UUID(uuidString: id) != nil, !id.contains("/"), !id.contains("\\") else { + throw KometShareError.invalidRequest + } + return requestsURL.appendingPathComponent(id, isDirectory: true) + } + + private func quarantine(_ directory: URL) throws { + try manager.createDirectory(at: quarantineURL, withIntermediateDirectories: true) + try manager.moveItem(at: directory, to: quarantineURL.appendingPathComponent(UUID().uuidString)) + } + + private func destination(in draft: KometShareDraft, name: String) throws -> URL { + let directory = draft.directoryURL.appendingPathComponent("attachments", isDirectory: true) + let existing = try manager.contentsOfDirectory(atPath: directory.path) + guard existing.count < Self.maximumAttachments else { throw KometShareError.tooManyAttachments } + let suffix = (name as NSString).pathExtension + let filename = UUID().uuidString.lowercased() + (suffix.isEmpty ? "" : ".\(suffix)") + return directory.appendingPathComponent(filename) + } + + private func fileMetadata(at url: URL, name: String, typeIdentifier: String) throws -> KometSharedFile { + let attributes = try manager.attributesOfItem(atPath: url.path) + guard let size = attributes[.size] as? NSNumber else { throw KometShareError.unreadableAttachment } + let mime = UTTypeCopyPreferredTagWithClass(typeIdentifier as CFString, kUTTagClassMIMEType)? + .takeRetainedValue() as String? ?? "application/octet-stream" + return KometSharedFile( + relativePath: "attachments/\(url.lastPathComponent)", name: name, mime: mime, size: size.int64Value + ) + } + + private func validate(_ manifest: Manifest, at directory: URL) throws { + guard !manifest.files.isEmpty || Self.nonempty(manifest.text) != nil, + manifest.files.count <= Self.maximumAttachments else { throw KometShareError.invalidRequest } + for file in manifest.files { + let components = file.relativePath.split(separator: "/", omittingEmptySubsequences: false) + guard components.count == 2, components[0] == "attachments", + !components[1].isEmpty, components[1] != ".", components[1] != "..", + !components[1].contains("\\") else { throw KometShareError.invalidRequest } + let url = directory.appendingPathComponent(file.relativePath) + let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) + guard values.isRegularFile == true, values.isSymbolicLink != true, + values.fileSize.map(Int64.init) == file.size else { throw KometShareError.invalidRequest } + } + } + + private func writeState(_ state: String, at directory: URL) throws { + try Data(state.utf8).write(to: directory.appendingPathComponent("state"), options: .atomic) + } + + private func readState(at directory: URL) throws -> String { + try String(contentsOf: directory.appendingPathComponent("state"), encoding: .utf8) + } + + private static func resolvedType(_ advertised: String?, fileNames: [String?]) -> String { + if let advertised = advertised { + let mime = preferredTag(for: advertised, tagClass: kUTTagClassMIMEType) + let suffix = preferredTag(for: advertised, tagClass: kUTTagClassFilenameExtension) + if (mime != nil && mime != "application/octet-stream") || suffix != nil { return advertised } + } + let inferred = fileNames.compactMap { name -> String? in + guard let name = name else { return nil } + let suffix = (name as NSString).pathExtension + guard !suffix.isEmpty else { return nil } + return UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, suffix as CFString, nil)? + .takeRetainedValue() as String? + } + return inferred.first { + let mime = preferredTag(for: $0, tagClass: kUTTagClassMIMEType) + return mime != nil && mime != "application/octet-stream" + } ?? inferred.first ?? advertised ?? "public.data" + } + + private static func preferredTag(for type: String, tagClass: CFString) -> String? { + UTTypeCopyPreferredTagWithClass(type as CFString, tagClass)?.takeRetainedValue() as String? + } + + private static func fileName(_ proposed: String, typeIdentifier: String) -> String { + let last = (proposed.replacingOccurrences(of: "\\", with: "/") as NSString).lastPathComponent + let cleaned = last.components(separatedBy: .controlCharacters).joined() + var name = cleaned.isEmpty || cleaned == "." || cleaned == ".." ? "Вложение" : cleaned + name = String(name.prefix(160)) + if (name as NSString).pathExtension.isEmpty, + let suffix = UTTypeCopyPreferredTagWithClass(typeIdentifier as CFString, kUTTagClassFilenameExtension)? + .takeRetainedValue() as String?, !suffix.isEmpty { + name += ".\(suffix)" + } + return name + } + + private static func nonempty(_ text: String?) -> String? { + guard let value = text?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else { return nil } + return value + } +} diff --git a/lib/backend/api.dart b/lib/backend/api.dart index 0cd5676b..5152c4b3 100644 --- a/lib/backend/api.dart +++ b/lib/backend/api.dart @@ -7,11 +7,14 @@ import 'package:timezone/data/latest_all.dart' as tz; import '../core/cache/self_presence.dart'; import '../core/config/config.dart'; +import '../core/config/app_language.dart'; import '../core/config/countries.dart'; import '../core/config/device_profile.dart'; import '../core/config/komet_settings.dart'; +import '../core/config/launch_flags.dart'; import '../core/config/proxy_config.dart'; import '../core/config/web_client_profile.dart'; +import '../core/protocol/chat_cache_fingerprint.dart'; import '../core/protocol/opcode_map.dart'; import '../core/protocol/packet.dart'; import '../core/storage/device_identity.dart'; @@ -21,6 +24,7 @@ import '../core/transport/session_factory.dart'; import '../core/transport/tls_config.dart'; import '../core/transport/traffic_monitor.dart'; import '../core/transport/vpn_bypass.dart'; +import '../core/transport/wire_debug_log.dart'; import '../core/utils/app_foreground.dart'; import '../core/utils/debug_session_log.dart'; import '../core/utils/device_locale.dart'; @@ -33,6 +37,9 @@ enum SessionState { disconnected, connecting, connected, online } // #***! весь жизненный цикл соединения /// Клиент API class Api { + static int _instanceCount = 0; + final int _instanceNo = ++_instanceCount; + KolibriSession? _session; final PacketDispatcher _dispatcher = PacketDispatcher(); @@ -49,6 +56,9 @@ class Api { Map? _userAgent; Map? get userAgent => _userAgent; + Map? _shareSessionOptions; + Map? get shareSessionOptions => + _sessionState == SessionState.online ? _shareSessionOptions : null; // #***! полезные данные после логина кому то нужные int? _callsSeed; @@ -113,6 +123,15 @@ class Api { /// `true`, когда рукопожатие уходит как у веб-клиента (deviceType `WEB`). bool get webHandshake => _webHandshake; + String get debugTag { + final mode = _webHandshake + ? 'web' + : _willAuthenticate + ? 'auth' + : 'pre'; + return 'api$_instanceNo/$mode'; + } + // #***! тайминги static const Duration _connectWatchdogTimeout = Duration(seconds: 75); static const Duration _shouldArmTimeout = Duration(seconds: 5); @@ -137,6 +156,10 @@ class Api { Future connect({bool? authenticated, bool? web}) async { if (authenticated != null) _willAuthenticate = authenticated; if (web != null) _webHandshake = web; + logger.d( + '[$debugTag] connect(authenticated: $authenticated, web: $web) ' + 'состояние=${_sessionState.name} spoofScope=$spoofScope', + ); if (_sessionState != SessionState.disconnected) { logger.i('connect пропущен: состояние ${_sessionState.name}'); return; @@ -186,6 +209,7 @@ class Api { logger.i( 'connect: endpoint ${endpoint.host}:${endpoint.port}, bypass=$useBypass', ); + logger.d('[$debugTag] connect: userAgent=$_userAgent'); if (useBypass) { try { @@ -228,13 +252,24 @@ class Api { _callsSeed = info.callsSeed?.toInt(); _registrationCountries = _parseRegistrationCountries(info.payloadMap); + logger.d( + '[$debugTag] хэндшейк ок: deviceName=${info.deviceName} ' + 'callsSeed=${_callsSeed != null} ' + 'стран регистрации=${_registrationCountries?.length}', + ); _sessionState = SessionState.online; _sessionEpoch++; _cancelConnectWatchdog(); _startLiveness(); logger.i('Сессия онлайн, хэндшейк ок'); // #***! автологин токеном (подавлен во время reconnectForLogin) - if (_onReconnectCallback != null && !_suppressReconnectLogin) { + final autoLogin = + _onReconnectCallback != null && !_suppressReconnectLogin; + logger.d( + '[$debugTag] автологин: ${autoLogin ? 'запускаю' : 'пропущен'} ' + '(подавлен=$_suppressReconnectLogin)', + ); + if (autoLogin) { try { await _onReconnectCallback!(); } catch (e) { @@ -243,6 +278,11 @@ class Api { } if (gen != _connectGen) return; if (_loginGate.loginUnanswered || _loginGate.loginRejected) { + logger.d( + '[$debugTag] автологин провален: ' + 'без ответа=${_loginGate.loginUnanswered} ' + 'отклонён=${_loginGate.loginRejected}', + ); await _handleConnectFailure( StateError( _loginGate.loginRejected @@ -531,6 +571,9 @@ class Api { if (sClientSession is int) clientSessionId = sClientSession; } + final serverLanguage = AppLanguage.serverLanguageCode; + if (serverLanguage != null) locale = serverLanguage; + // #***! до логина (сокет без токена) прикидываемся прошлой версией целиком, // перекрывая и дефолт, и спуф-профиль; при входе с токеном версию не трогаем if (!_willAuthenticate) { @@ -595,6 +638,39 @@ class Api { final insecureTls = await TlsConfig.isInsecureAllowed(); final proxy = await _buildProxyUrl(); + _shareSessionOptions = Map.unmodifiable({ + 'host': endpoint.host, + 'port': endpoint.port, + 'trust_mincifry_ca': endpoint.trustMincifryCa, + 'device_id': deviceId, + 'instance_id': instanceId, + 'app_version': appVersion, + 'build_number': buildNumber, + 'device_type': deviceType, + 'os_version': osVersion, + 'timezone': timezone, + 'screen': screen, + 'push_device_type': pushDeviceType, + 'arch': architecture, + 'locale': locale, + 'device_name': deviceName, + 'device_locale': deviceLocale, + 'client_session_id': clientSessionId, + 'ping_interval_secs': ServerConfig.pingInterval.inSeconds, + 'ping_interactive': !KometSettings.ghostMode.value, + 'auto_reconnect': false, + 'insecure_tls': insecureTls, + 'proxy': proxy, + 'is_pwa': isPwa, + 'header_user_agent': headerUserAgent, + 'fingerprint_digests': _webHandshake + ? null + : ChatCacheFingerprint.exportDigests( + arch: architecture, + preLogin: !_willAuthenticate, + ), + }); + // #***! тут реально открывается сокет в расте. Ядро само опускает arch при // пустой строке, buildNumber и clientSessionId при нуле, mt_instanceid при // пустом — ровно этих полей и нет в веб-хэндшейке. @@ -718,6 +794,7 @@ class Api { /// лог вёлся вручную из [sendRequest] по локальному счётчику, из-за чего /// хендшейк/пинги в дамп не попадали, а seq был смещён относительно провода. void _onWireLog(WireLogEvent e) { + if (LaunchFlags.debug) WireDebugLog.record(debugTag, e); // #***! в фоне и без монитора не тратим время на разбор if (!AppForeground.value && !TrafficMonitor.instance.enabled) return; final payload = _decodeWireJson(e.json); @@ -861,6 +938,9 @@ class Api { // переподнимаем соединение боевой версией. Автологин-колбэк на это время // подавляем — токен пошлёт вызвавший login(), а не колбэк, иначе войдём дважды. Future reconnectForLogin() async { + logger.d( + '[$debugTag] reconnectForLogin: переподнимаю сокет боевой версией', + ); _suppressReconnectLogin = true; try { await disconnect(); @@ -872,6 +952,7 @@ class Api { } Future reconnectPreLogin({required bool web}) async { + logger.d('[$debugTag] reconnectPreLogin(web: $web)'); _suppressReconnectLogin = true; try { await disconnect(); diff --git a/lib/backend/modules/account.dart b/lib/backend/modules/account.dart index d408ee44..3ddea7a5 100644 --- a/lib/backend/modules/account.dart +++ b/lib/backend/modules/account.dart @@ -2,8 +2,10 @@ import 'dart:async'; import 'dart:convert'; import 'dart:math'; import 'dart:typed_data'; + import '../api.dart'; -import '../../core/config/debug_test.dart'; +import '../../core/config/app_language.dart'; +import '../../core/config/launch_flags.dart'; import '../../core/config/komet_settings.dart'; import '../../core/protocol/chat_cache_fingerprint.dart'; import '../../core/protocol/opcode_map.dart'; @@ -15,6 +17,7 @@ import '../../core/utils/parse.dart'; import '../../core/storage/profile_deletion_store.dart'; import '../../core/storage/spoofing_service.dart'; import '../../core/storage/token_storage.dart'; +import '../../core/utils/device_locale.dart'; import '../../core/utils/logger.dart'; import '../../models/login_info.dart'; import 'banners.dart'; @@ -44,6 +47,9 @@ String _maskPhone(String phone) { return '${phone.substring(0, 3)}***${phone.substring(phone.length - 2)}'; } +String _describeSecret(String? value) => + value == null || value.isEmpty ? 'нет' : 'есть (${value.length} симв.)'; + // #***! аккаунт целиком, вход регистрация мультиаккаунт class AccountModule { final Api _api; @@ -55,6 +61,9 @@ class AccountModule { final _loginStatusController = StreamController.broadcast(); final _noticeController = StreamController.broadcast(); bool _loggedIn = false; + ({Api api, Future connecting})? _smsSocket; + Timer? _smsSocketIdle; + static const Duration _smsSocketIdleTimeout = Duration(minutes: 3); // #***! тяжёлое в подмодулях, тут только оркестрация AccountModule(this._api) { @@ -172,15 +181,11 @@ class AccountModule { _twoFactor.remove2fa(trackId); // #***! запрос кода, первый и повторный отличаются типом - Future requestCode( - String phone, { - String language = 'ru', - }) => _requestCodeInternal(phone, AuthRequestType.startAuth, language); + Future requestCode(String phone, {String? language}) => + _requestCodeInternal(phone, AuthRequestType.startAuth, language); - Future resendCode( - String phone, { - String language = 'ru', - }) => _requestCodeInternal(phone, AuthRequestType.resend, language); + Future resendCode(String phone, {String? language}) => + _requestCodeInternal(phone, AuthRequestType.resend, language); // #***! проверка кода, дальше вход регистрация или 2FA Future verifyCode(String code, String token) async { @@ -203,6 +208,13 @@ class AccountModule { final loginToken = result.loginToken; final verifiedProfile = _profileFromVerifyPayload(result.payload); final accountId = result.accountId ?? verifiedProfile?.id; + logger.d( + '[${_api.debugTag}] verifyCode: нужен пароль=${result.requiresPassword} ' + 'регистрация=${result.isRegistration} ' + 'login-токен ${_describeSecret(loginToken)} accountId=$accountId ' + 'профиль в ответе=${verifiedProfile != null} ' + 'ключи ответа=${data.keys.toList()}', + ); // #***! токен сохраняем сразу и переносим спуф профиль if (loginToken != null && accountId != null) { @@ -303,6 +315,12 @@ class AccountModule { } } + logger.d( + '[${_api.debugTag}] login: accountId=$resolvedAccountId ' + 'токен ${_describeSecret(authToken)} ' + 'боевой сокет=${_api.isAuthenticatedHandshake} ' + 'sync=${syncParams == null ? 'с нуля' : 'по маркерам'}', + ); // #***! сокет мог быть pre-login (прошлая версия): токен шлём только по // боевой версии, поэтому при необходимости переподнимаем соединение if (!_api.isAuthenticatedHandshake) { @@ -339,13 +357,28 @@ class AccountModule { final result = await _processLoginResponse(dataMap, resolvedAccountId); _loggedIn = true; _loginStatusController.add(LoginStatus.success); + logger.d('[${_api.debugTag}] login: успех, accountId=$resolvedAccountId'); return result; - } catch (e) { + } catch (e, st) { + logger.d('[${_api.debugTag}] login: ошибка $e\n$st'); _loginStatusController.add(LoginStatus.error); rethrow; } } + Future refreshServerLanguage() async { + if (_api.state == SessionState.disconnected) return; + logger.i( + 'Язык сервера: ${AppLanguage.serverLanguageCode ?? 'по умолчанию'}, ' + 'переподключаюсь', + ); + final online = await _api.reconnectToEndpoint(); + if (!online || !_loggedIn) return; + final accountId = await TokenStorage.getActiveAccountId(); + if (accountId == null) return; + await FoldersModule.syncFromServer(_api, accountId); + } + Future> getSessions() => _sessions.getSessions(); Future terminateOtherSessions() => _sessions.terminateOtherSessions(); @@ -394,6 +427,10 @@ class AccountModule { chats.resetForAccountSwitch(); await _api.connect(authenticated: true); + logger.d( + '[${_api.debugTag}] loginWithToken: токен ${_describeSecret(token)} ' + 'сессия=${_api.state.name}', + ); if (_api.state != SessionState.online) { throw StateError('loginWithToken: нет соединения с сервером'); } @@ -418,8 +455,14 @@ class AccountModule { required String webToken, String? existingPassword, }) async { + logger.d( + '[${_api.debugTag}] SMS-вход: старт, phone=${_maskPhone(phone)} ' + 'accountId=$accountId веб-токен ${_describeSecret(webToken)} ' + 'пароль пользователя=${existingPassword != null}', + ); // #***! шаг 1: логинимся на веб-сессии (её НЕ закрываем — в неё придёт код) await _bareLogin(webToken); + logger.d('[${_api.debugTag}] SMS-вход: шаг 1 — веб-сессия залогинена'); // #***! шаг 2: пароль. Есть 2FA — помним введённый; нет — ставим свой рандом. // Наш временный пароль ОБЯЗАН быть снят к концу — иначе аккаунт без 2FA @@ -441,16 +484,28 @@ class AccountModule { ); logger.i('SMS-вход: поставлен временный пароль на аккаунт'); } + logger.d( + '[${_api.debugTag}] SMS-вход: шаг 2 — пароль ' + '${weSetPassword ? 'временный' : 'пользователя'}', + ); String? socketToken; int? socketAccountId; // #***! шаг 3: настоящий сокет 26.23.2 — отдельной сессией B - final apiB = Api(); + final smsSocket = _takeSmsSocket(); + final apiB = smsSocket.api; final accountB = AccountModule(apiB); StreamSubscription? codeSub; try { - await apiB.connect(authenticated: false, web: false); + await smsSocket.connecting; + if (apiB.state != SessionState.online) { + await apiB.reconnectToEndpoint(); + } + logger.d( + '[${apiB.debugTag}] SMS-вход: шаг 3 — сокет-сессия B ' + 'состояние=${apiB.state.name}', + ); if (apiB.state != SessionState.online) { throw StateError('SMS-вход: не удалось поднять сокет-сессию'); } @@ -461,6 +516,11 @@ class AccountModule { .where((p) => p.opcode == Opcode.notifMessage) .listen((p) { final code = _extractLoginCode(p.payload); + logger.d( + '[${_api.debugTag}] SMS-вход: шаг 4 — пуш ' + '${Opcode.name(p.opcode)} на веб-сессии, ' + 'код ${code == null ? 'не найден' : 'найден'}', + ); if (code != null && !codeCompleter.isCompleted) { codeCompleter.complete(code); } @@ -468,6 +528,10 @@ class AccountModule { // #***! шаг 5: запрос кода на сокете — сервер шлёт его сообщением в веб final req = await accountB.requestCode(phone); + logger.d( + '[${apiB.debugTag}] SMS-вход: шаг 5 — код запрошен на сокете, ' + 'жду сообщение в веб-сессии', + ); // #***! шаг 6: ждём код из сообщения (opcode 128) на веб-сессии final code = await codeCompleter.future.timeout( @@ -479,6 +543,10 @@ class AccountModule { // #***! шаг 7: код + пароль на сокете → сокетовый токен final verify = await accountB.verifyCode(code, req.token); + logger.d( + '[${apiB.debugTag}] SMS-вход: шаг 7 — код принят, ' + 'нужен пароль=${verify.requiresPassword}', + ); if (verify.requiresPassword) { final trackId = verify.challengeTrackId; if (trackId == null) { @@ -505,6 +573,10 @@ class AccountModule { } final resolvedToken = socketToken; + logger.d( + '[${_api.debugTag}] SMS-вход: сокетовый токен ' + '${_describeSecret(resolvedToken)} accountId=$socketAccountId', + ); if (resolvedToken == null) { throw StateError('SMS-вход: сокетовый токен не получен'); } @@ -514,6 +586,10 @@ class AccountModule { // #***! шаг 8: наш временный пароль снимаем на веб-сессии if (weSetPassword) { passwordCleared = await _removeTempPassword(password); + logger.d( + '[${_api.debugTag}] SMS-вход: шаг 8 — временный пароль ' + '${passwordCleared ? 'снят' : 'НЕ снят'} на веб-сессии', + ); } // #***! шаг 9: серверный выход из веб-сессии и разрыв @@ -524,6 +600,7 @@ class AccountModule { } _loggedIn = false; await _api.disconnect(); + logger.d('[${_api.debugTag}] SMS-вход: шаг 9 — веб-сессия закрыта'); // #***! шаг 10: боевой сокет 26.31.0 + сокетовый токен — финальный вход. // Автологин-колбэк сам выполнит login по активному аккаунту. @@ -531,6 +608,10 @@ class AccountModule { await TokenStorage.setActiveAccount(resolvedAccountId); await SpoofingService.commitPendingSpoof(resolvedAccountId); await _api.connect(authenticated: true, web: false); + logger.d( + '[${_api.debugTag}] SMS-вход: шаг 10 — боевой сокет ' + 'состояние=${_api.state.name} автологин=$_loggedIn', + ); if (_api.state != SessionState.online) { throw StateError('SMS-вход: не удалось поднять боевой сокет'); } @@ -545,7 +626,11 @@ class AccountModule { if (!passwordCleared) { logger.e('SMS-вход: ВРЕМЕННЫЙ ПАРОЛЬ НЕ СНЯТ. Пароль: $password'); } - } catch (e) { + } catch (e, st) { + logger.d( + '[${_api.debugTag}] SMS-вход: сбой $e ' + '(веб-сессия=${_api.state.name})\n$st', + ); // #***! любой сбой после установки пароля — откатываем, пока веб-сессия // ещё жива; если не вышло, пароль хотя бы попадёт в лог if (weSetPassword && !passwordCleared) { @@ -562,6 +647,53 @@ class AccountModule { } } + void prepareWebSmsSocket() { + if (!_api.webHandshake) return; + _smsSocketIdle?.cancel(); + _smsSocketIdle = Timer(_smsSocketIdleTimeout, _releaseSmsSocket); + if (_smsSocket != null) return; + final prepared = _openSmsSocket(); + _smsSocket = prepared; + logger.d( + '[${prepared.api.debugTag}] SMS-вход: сокет B поднимается заранее', + ); + } + + ({Api api, Future connecting}) _takeSmsSocket() { + _smsSocketIdle?.cancel(); + _smsSocketIdle = null; + final prepared = _smsSocket; + _smsSocket = null; + return prepared ?? _openSmsSocket(); + } + + static ({Api api, Future connecting}) _openSmsSocket() { + final socket = Api(); + return ( + api: socket, + connecting: socket.connect(authenticated: false, web: false), + ); + } + + void _releaseSmsSocket() { + _smsSocketIdle?.cancel(); + _smsSocketIdle = null; + final prepared = _smsSocket; + _smsSocket = null; + if (prepared == null) return; + logger.d('[${prepared.api.debugTag}] SMS-вход: заготовленный сокет B закрыт'); + unawaited(_closeSmsSocket(prepared.api)); + } + + static Future _closeSmsSocket(Api socket) async { + try { + await socket.disconnect(); + } catch (_) {} + try { + await socket.dispose(); + } catch (_) {} + } + // #***! снятие временного пароля: панель 2FA → проверка пароля → удаление Future _removeTempPassword(String password) async { try { @@ -726,10 +858,12 @@ class AccountModule { Future logout() async { MediaPlayback.instance.closeAudioFile(); final accountId = await TokenStorage.getActiveAccountId(); - try { - await _logoutOnServer(accountId); - } on SessionExpiredException catch (e) { - logger.w('logout: сервер отклонил сессию: ${e.message}'); + if (accountId != null) { + try { + await _logoutOnServer(accountId); + } on SessionExpiredException catch (e) { + logger.w('logout: сервер отклонил сессию: ${e.message}'); + } } _loggedIn = false; try { @@ -794,6 +928,10 @@ class AccountModule { ); final data = _requireMapPayload(packet, 'checkPassword'); + logger.d( + '[${_api.debugTag}] checkPassword: ключи ответа=${data.keys.toList()} ' + 'ошибка=${data['error']}', + ); if (data['error'] != null) { throw const WrongPasswordException(); @@ -899,7 +1037,7 @@ class AccountModule { ProfileData profile; final profileMap = data['profile']; // #***! берсерк ломает профиль специально чтоб проверить восстановление - if (!DebugTest.berserk && + if (!LaunchFlags.berserk && profileMap is Map && profileMap['contact'] is Map) { profile = ProfileData.fromServerProfile( @@ -965,7 +1103,7 @@ class AccountModule { // #***! профиля нет нигде, тянем через контакт иначе заглушка Future _resurrectProfile(int accountId) async { - if (DebugTest.berserk) { + if (LaunchFlags.berserk) { await AppDatabase.deleteAccount(accountId); logger.w( 'login: [BERSERK] профиль удалён из БД, форсирую регенерацию (id=$accountId)', @@ -1063,7 +1201,7 @@ class AccountModule { Future _requestCodeInternal( String phone, AuthRequestType type, - String language, + String? language, ) async { _ensureOnline(); @@ -1072,7 +1210,8 @@ class AccountModule { final payload = { 'phone': normalizedPhone, 'type': type.value, - 'language': language, + 'language': + language ?? AppLanguage.serverLanguageCode ?? defaultLanguageCode, }; final callsSeed = _api.callsSeed; @@ -1091,6 +1230,11 @@ class AccountModule { logger.i( 'Запрос OTP-кода: phone=${_maskPhone(normalizedPhone)} type=${type.value}', ); + logger.d( + '[${_api.debugTag}] requestCode: mode-отпечаток=' + '${payload.containsKey('mode')} callsSeed=${callsSeed != null} ' + 'deviceId=${deviceId != null} язык=$language', + ); final packet = await _api.sendRequest(Opcode.authRequest, payload); @@ -1102,6 +1246,9 @@ class AccountModule { } logger.i('OTP-код запрошен, получен временный токен'); + logger.d( + '[${_api.debugTag}] requestCode: ключи ответа=${data.keys.toList()}', + ); return RequestCodeResult(token: token); } diff --git a/lib/backend/modules/calls.dart b/lib/backend/modules/calls.dart index 14309284..0653217b 100644 --- a/lib/backend/modules/calls.dart +++ b/lib/backend/modules/calls.dart @@ -1,12 +1,15 @@ import 'dart:convert'; import 'contacts.dart'; +import 'messages.dart' show ContactCache; import '../api.dart'; +import '../../core/cache/info_cache.dart'; import '../../core/calls/call_link.dart'; import '../../core/calls/ws2_signaling.dart'; import '../../core/protocol/opcode_map.dart'; import '../../core/utils/ids.dart'; import '../../core/utils/logger.dart'; +import '../../models/contact_info.dart'; // #***! как звонок выглядит в истории enum CallStatus { missed, canceled, outgoing, incoming } @@ -74,6 +77,7 @@ class CallLogEntry { final int time; final int count; final bool isGroup; + final bool isBot; const CallLogEntry({ required this.id, @@ -85,7 +89,32 @@ class CallLogEntry { required this.time, this.count = 1, this.isGroup = false, + this.isBot = false, }); + + bool get canCallBack => !isGroup && !isBot; + + CallLogEntry withCount(int count) => CallLogEntry( + id: id, + accountId: accountId, + peerId: peerId, + name: name, + avatarUrl: avatarUrl, + status: status, + time: time, + count: count, + isGroup: isGroup, + isBot: isBot, + ); +} + +class CallPeerIsBotException implements Exception { + final int peerId; + + const CallPeerIsBotException(this.peerId); + + @override + String toString() => 'CallPeerIsBotException: $peerId'; } class _CallerEndpointMissingException implements Exception { @@ -135,6 +164,8 @@ class CallsModule { int calleeId, { bool isVideo = false, }) async { + if (await _isBotPeer(calleeId)) throw CallPeerIsBotException(calleeId); + final conversationId = uuidV4(); final payload = await _api.sendRequestMap(Opcode.videoChatStartActive, { @@ -161,6 +192,16 @@ class CallsModule { ); } + static Future _isBotPeer(int userId) async { + if (_isCachedBot(userId)) return true; + final info = await ContactInfoFetch.get(userId); + return info?.isBot ?? false; + } + + static bool _isCachedBot(int userId) => + (ContactCache.getOptions(userId)?.contains('BOT') ?? false) || + (ContactInfoFetch.peek(userId)?.isBot ?? false); + // #***! конференция со ссылкой Future createConference() async { final conversationId = uuidV4(); @@ -387,6 +428,7 @@ class CallsModule { final List extractedCalls = []; for (final e in parsed) { final contact = contactsMap[e.peerId]; + final info = fetched[e.peerId]; String name; String? avatarUrl; bool isGroup = false; @@ -394,7 +436,6 @@ class CallsModule { name = '${contact.firstName} ${contact.lastName ?? ''}'.trim(); avatarUrl = contact.baseUrl; } else { - final info = fetched[e.peerId]; final resolved = _nameFromInfo(info); if (resolved != null) { name = resolved; @@ -416,6 +457,7 @@ class CallsModule { status: e.status, time: e.time, isGroup: isGroup, + isBot: !isGroup && _isHistoryPeerBot(e.peerId, contact, info), ), ); } @@ -423,6 +465,15 @@ class CallsModule { return extractedCalls; } + static bool _isHistoryPeerBot( + int peerId, + CachedContact? contact, + Map? info, + ) => + (contact?.isBot ?? false) || + (info != null && ContactInfo.fromMap(info).isBot) || + _isCachedBot(peerId); + static String? _nameFromInfo(Map? info) { if (info == null) return null; final names = info['names']; diff --git a/lib/backend/modules/contacts.dart b/lib/backend/modules/contacts.dart index 7e0eceef..ab6f5c81 100644 --- a/lib/backend/modules/contacts.dart +++ b/lib/backend/modules/contacts.dart @@ -1,7 +1,7 @@ import 'package:flutter/foundation.dart'; import '../../core/cache/info_cache.dart'; -import '../../core/config/debug_test.dart'; +import '../../core/config/launch_flags.dart'; import '../../core/protocol/opcode_map.dart'; import '../../core/protocol/packet.dart'; import '../../core/storage/app_database.dart'; @@ -653,7 +653,7 @@ class ContactsModule { ]; static List debugContacts() { - final count = DebugTest.contactCount; + final count = LaunchFlags.contactCount; final out = []; for (var i = 0; i < count; i++) { final first = _debugFirstNames[i % _debugFirstNames.length]; @@ -663,7 +663,7 @@ class ContactsModule { out.add( CachedContact( id: 900000000 + i, - accountId: DebugTest.debugAccountId, + accountId: LaunchFlags.debugTestAccountId, firstName: '$first ${i + 1}', lastName: last, phone: 79000000000 + i, diff --git a/lib/backend/modules/share_sender.dart b/lib/backend/modules/share_sender.dart index 49354d71..f40ffdef 100644 --- a/lib/backend/modules/share_sender.dart +++ b/lib/backend/modules/share_sender.dart @@ -4,6 +4,7 @@ import 'dart:io'; import '../../core/media/gallery_source.dart'; import '../../core/media/share_thumbnail.dart'; import '../../core/media/video_transcoder.dart'; +import '../../core/share/shared_file_usage.dart'; import '../../core/storage/app_database.dart'; import '../../core/utils/logger.dart'; import '../../models/attachment.dart'; @@ -53,12 +54,17 @@ class PreparedShare { bool get isTextOnly => files.isEmpty; // #***! миниатюры и размеры считаем один раз а не на каждый чат - static Future prepare(SharedPayload payload) async { - final prepared = []; - for (final source in payload.files) { - prepared.add(await _prepareOne(source)); - } - return PreparedShare(files: prepared, text: payload.text); + static Future prepare(SharedPayload payload) { + return SharedFileUsage.instance.use( + payload.files.map((file) => file.path), + () async { + final prepared = []; + for (final source in payload.files) { + prepared.add(await _prepareOne(source)); + } + return PreparedShare(files: prepared, text: payload.text); + }, + ); } // #***! у фото размеры из файла, у видео через probe @@ -163,20 +169,28 @@ class ShareSender { required List chatIds, required PreparedShare share, required String caption, - }) async { - var messages = 0; - for (final chatId in chatIds) { - messages += await _sendToChat( - accountId: accountId, - chatId: chatId, - share: share, - caption: caption, - ); - } - logger.i( - 'Поделиться: отправлено $messages сообщений в ${chatIds.length} чатов', + }) { + return SharedFileUsage.instance.use( + share.files.map((file) => file.source.path), + () async { + var messages = 0; + for (final chatId in chatIds) { + messages += await _sendToChat( + accountId: accountId, + chatId: chatId, + share: share, + caption: caption, + ); + } + logger.i( + 'Поделиться: отправлено $messages сообщений в ${chatIds.length} чатов', + ); + return ShareSendResult( + chatCount: chatIds.length, + messageCount: messages, + ); + }, ); - return ShareSendResult(chatCount: chatIds.length, messageCount: messages); } // #***! фото альбомом, видео и документы по одному @@ -361,13 +375,16 @@ class ShareSender { // #***! загрузку не ждём, экран закрывается сразу дальше UploadService unawaited( - UploadService.instance.sendPhotos( - accountId: accountId, - chatId: chatId, - tempId: tempId, - jobs: jobs, - caption: caption, - placeholder: placeholder, + SharedFileUsage.instance.use( + photos.map((photo) => photo.source.path), + () => UploadService.instance.sendPhotos( + accountId: accountId, + chatId: chatId, + tempId: tempId, + jobs: jobs, + caption: caption, + placeholder: placeholder, + ), ), ); } @@ -427,13 +444,16 @@ class ShareSender { ); unawaited( - UploadService.instance.sendVideo( - accountId: accountId, - chatId: chatId, - tempId: tempId, - file: video.file, - caption: caption, - placeholder: placeholder, + SharedFileUsage.instance.use( + [video.source.path], + () => UploadService.instance.sendVideo( + accountId: accountId, + chatId: chatId, + tempId: tempId, + file: video.file, + caption: caption, + placeholder: placeholder, + ), ), ); } @@ -487,14 +507,17 @@ class ShareSender { ); unawaited( - UploadService.instance.sendFile( - accountId: accountId, - chatId: chatId, - tempId: tempId, - source: document.file, - filename: name, - size: size, - placeholder: placeholder, + SharedFileUsage.instance.use( + [document.source.path], + () => UploadService.instance.sendFile( + accountId: accountId, + chatId: chatId, + tempId: tempId, + source: document.file, + filename: name, + size: size, + placeholder: placeholder, + ), ), ); } diff --git a/lib/core/calls/call_session.dart b/lib/core/calls/call_session.dart index cd125c95..7b2ecb84 100644 --- a/lib/core/calls/call_session.dart +++ b/lib/core/calls/call_session.dart @@ -8,7 +8,7 @@ import 'package:flutter_webrtc/flutter_webrtc.dart'; import '../config/app_camera.dart'; import '../config/app_microphone.dart'; import '../config/app_pulse_source.dart'; -import '../config/call_no_mute.dart'; +import '../config/launch_flags.dart'; import '../utils/logger.dart'; import '../utils/parse.dart'; import 'audio_devices.dart'; @@ -238,7 +238,7 @@ class CallSession { bool get peerIsKomet => _peerIsKomet; bool get isMuted => _muted; - bool get audioTransmitting => !_muted || CallNoMute.enabled; + bool get audioTransmitting => !_muted || LaunchFlags.noMute; String? get micDeviceId => _micDeviceId; String? get pulseSource => _pulseSource; bool get isSpeaker => _speakerOn; diff --git a/lib/core/config/app_bottom_navigation_style.dart b/lib/core/config/app_bottom_navigation_style.dart new file mode 100644 index 00000000..59dc1b1f --- /dev/null +++ b/lib/core/config/app_bottom_navigation_style.dart @@ -0,0 +1,26 @@ +import 'package:flutter/foundation.dart'; + +import 'persisted_setting.dart'; + +enum BottomNavigationStyle { floating, compact } + +class AppBottomNavigationStyle { + static const prefKey = 'app_bottom_navigation_style'; + + static final _setting = PersistedEnum( + prefKey: prefKey, + defaultValue: BottomNavigationStyle.floating, + encode: (value) => value.name, + decode: (value) => enumFromName( + BottomNavigationStyle.values, + value, + BottomNavigationStyle.floating, + ), + ); + + static ValueNotifier get current => _setting.current; + + static Future load() => _setting.load(); + + static Future save(BottomNavigationStyle value) => _setting.save(value); +} diff --git a/lib/core/config/app_chat_chrome.dart b/lib/core/config/app_chat_chrome.dart index dfa6066e..b09f1b38 100644 --- a/lib/core/config/app_chat_chrome.dart +++ b/lib/core/config/app_chat_chrome.dart @@ -18,7 +18,7 @@ class AppChatChrome { static final _setting = PersistedEnum( prefKey: prefKey, - defaultValue: ChatChromeStyle.color, + defaultValue: ChatChromeStyle.none, encode: _encode, decode: _parse, ); @@ -26,7 +26,7 @@ class AppChatChrome { static ValueNotifier get current => _setting.current; static ChatChromeStyle _parse(String? value) => - enumFromName(ChatChromeStyle.values, value, ChatChromeStyle.color); + enumFromName(ChatChromeStyle.values, value, ChatChromeStyle.none); static String _encode(ChatChromeStyle value) => value.name; diff --git a/lib/core/config/app_language.dart b/lib/core/config/app_language.dart new file mode 100644 index 00000000..7de2d5c6 --- /dev/null +++ b/lib/core/config/app_language.dart @@ -0,0 +1,63 @@ +import 'package:flutter/widgets.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../l10n/app_localizations.dart'; +import '../utils/device_locale.dart'; +import 'persisted_setting.dart'; + +class AppLanguage { + AppLanguage._(); + + static const prefKey = 'app_locale'; + static const serverPrefKey = 'app_server_language'; + + static final ValueNotifier current = ValueNotifier( + const Locale(defaultLanguageCode), + ); + + static final _appliesToServer = PersistedSetting( + prefKey: serverPrefKey, + defaultValue: false, + read: (prefs, key) => prefs.getBool(key), + write: (prefs, key, value) async { + await prefs.setBool(key, value); + }, + ); + + static ValueNotifier get appliesToServer => _appliesToServer.current; + + static String? get serverLanguageCode => + appliesToServer.value ? current.value.languageCode : null; + + static bool isSupported(String code) => + AppLocalizations.supportedLocales.any((l) => l.languageCode == code); + + static Locale resolve({String? saved, required String platformCode}) { + if (saved != null && isSupported(saved)) return Locale(saved); + if (isSupported(platformCode)) return Locale(platformCode); + return const Locale(defaultLanguageCode); + } + + static Future load() async { + final prefs = await SharedPreferences.getInstance(); + final locale = resolve( + saved: prefs.getString(prefKey), + platformCode: + WidgetsBinding.instance.platformDispatcher.locale.languageCode, + ); + current.value = locale; + await _appliesToServer.load(); + return locale; + } + + static Future save(Locale locale) async { + if (!isSupported(locale.languageCode)) return false; + current.value = Locale(locale.languageCode); + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(prefKey, locale.languageCode); + return true; + } + + static Future setAppliesToServer(bool value) => + _appliesToServer.save(value); +} diff --git a/lib/core/config/app_visual_style.dart b/lib/core/config/app_visual_style.dart index 39f19e47..ffc98b4e 100644 --- a/lib/core/config/app_visual_style.dart +++ b/lib/core/config/app_visual_style.dart @@ -16,7 +16,7 @@ class AppVisualStyle { static final _setting = PersistedEnum( prefKey: prefKey, - defaultValue: VisualStyle.materialYou, + defaultValue: VisualStyle.glossy, encode: _encode, decode: _parse, ); @@ -30,5 +30,5 @@ class AppVisualStyle { static String _encode(VisualStyle value) => value.name; static VisualStyle _parse(String? val) => - enumFromName(VisualStyle.values, val, VisualStyle.materialYou); + enumFromName(VisualStyle.values, val, VisualStyle.glossy); } diff --git a/lib/core/config/build_profile.dart b/lib/core/config/build_profile.dart index b8421fee..2086ca4d 100644 --- a/lib/core/config/build_profile.dart +++ b/lib/core/config/build_profile.dart @@ -1,5 +1,7 @@ import 'package:flutter/services.dart' show appFlavor; +import 'launch_flags.dart'; + // #***! что включено в сборке, всё считается на компиляции из flavor abstract final class BuildProfile { static const String storeFlavor = 'store'; @@ -17,7 +19,7 @@ abstract final class BuildProfile { /// /// The gates below are const, so the compiler drops the disabled code /// from App Store builds. - static const bool isAppStoreBuild = bool.fromEnvironment('is_appstore_build'); + static const bool isAppStoreBuild = LaunchFlags.appStoreBuild; /// Plugins and their settings; built-in slash commands stay either way. static const bool plugins = !isAppStoreBuild; diff --git a/lib/core/config/call_no_mute.dart b/lib/core/config/call_no_mute.dart deleted file mode 100644 index 5f407135..00000000 --- a/lib/core/config/call_no_mute.dart +++ /dev/null @@ -1,12 +0,0 @@ -// #***! аргумент --no-mute, не глушить микрофон на старте звонка -class CallNoMute { - CallNoMute._(); - - static const String flag = '--no-mute'; - - static bool enabled = const bool.fromEnvironment('NO_MUTE'); - - static void parse(List args) { - if (args.contains(flag)) enabled = true; - } -} diff --git a/lib/core/config/debug_test.dart b/lib/core/config/debug_test.dart deleted file mode 100644 index 97109193..00000000 --- a/lib/core/config/debug_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// #***! режим отладки с фейковыми данными -class DebugTest { - static bool enabled = false; - static int contactCount = 0; - static bool berserk = false; - - // #***! отрицательный id чтоб фейк не совпал с настоящим - static const int debugAccountId = -424242; - - static const bool _envEnabled = bool.fromEnvironment('DEBUG_TEST'); - static const bool _envBerserk = bool.fromEnvironment('BERSERK'); - static const int _envContacts = int.fromEnvironment( - 'DEBUG_CONTACTS', - defaultValue: -1, - ); - - static const String _flag = '--debug-test'; - static const String _berserkFlag = '--berserk'; - static const String _contactsFlag = '--contacts'; - - // #***! читаем и dart-define и аргументы, аргументы важнее - static void parse(List args) { - if (_envEnabled) enabled = true; - if (_envBerserk) berserk = true; - if (_envContacts >= 0) { - enabled = true; - contactCount = _envContacts; - } - - for (var i = 0; i < args.length; i++) { - final arg = args[i]; - if (arg == _flag) { - enabled = true; - } else if (arg == _berserkFlag) { - berserk = true; - } else if (arg.startsWith('$_contactsFlag=')) { - enabled = true; - contactCount = - int.tryParse(arg.substring(_contactsFlag.length + 1)) ?? - contactCount; - } else if (arg == _contactsFlag && i + 1 < args.length) { - enabled = true; - contactCount = int.tryParse(args[i + 1]) ?? contactCount; - i++; - } - } - } -} diff --git a/lib/core/config/launch_flags.dart b/lib/core/config/launch_flags.dart new file mode 100644 index 00000000..9caf6cb6 --- /dev/null +++ b/lib/core/config/launch_flags.dart @@ -0,0 +1,104 @@ +import 'package:flutter/foundation.dart'; + +abstract final class LaunchFlags { + static const String debugFlag = '--debug'; + static const String loginPayloadFlag = '--dw19p-im-crazy'; + static const String debugTestFlag = '--debug-test'; + static const String contactsFlag = '--contacts'; + static const String berserkFlag = '--berserk'; + static const String noMuteFlag = '--no-mute'; + + static const bool _envDebug = bool.fromEnvironment('KOMET_DEBUG'); + static const bool _envLoginPayload = bool.fromEnvironment( + 'KOMET_DW19P_IM_CRAZY', + ); + static const bool _envDebugTest = bool.fromEnvironment('DEBUG_TEST'); + static const int _envContacts = int.fromEnvironment( + 'DEBUG_CONTACTS', + defaultValue: -1, + ); + static const bool _envBerserk = bool.fromEnvironment('BERSERK'); + static const bool _envNoMute = bool.fromEnvironment('NO_MUTE'); + + static const String logLevel = String.fromEnvironment('KOMET_LOG_LEVEL'); + static const String instance = String.fromEnvironment('KOMET_INSTANCE'); + static const String updateBaseUrl = String.fromEnvironment( + 'KOMET_UPDATE_BASE_URL', + defaultValue: 'https://cdn.komet.pw', + ); + static const String reviewPhone = String.fromEnvironment( + 'KOMET_REVIEW_PHONE', + ); + static const String reviewPayload = String.fromEnvironment( + 'KOMET_REVIEW_PAYLOAD', + ); + static const bool appStoreBuild = bool.fromEnvironment('is_appstore_build'); + + static const int debugTestAccountId = -424242; + + static bool debug = _envDebug || _envLoginPayload; + static bool revealLoginPayload = _envLoginPayload; + static bool debugTest = _envDebugTest || _envContacts >= 0; + static int contactCount = _envContacts >= 0 ? _envContacts : 0; + static bool berserk = _envBerserk; + static bool noMute = _envNoMute; + static List unknown = const []; + + static void parse(List args) { + final unknownArgs = []; + for (var i = 0; i < args.length; i++) { + final arg = args[i]; + switch (arg) { + case debugFlag: + debug = true; + case loginPayloadFlag: + debug = true; + revealLoginPayload = true; + case debugTestFlag: + debugTest = true; + case berserkFlag: + berserk = true; + case noMuteFlag: + noMute = true; + case contactsFlag when i + 1 < args.length: + _setContacts(args[++i]); + case _ when arg.startsWith('$contactsFlag='): + _setContacts(arg.substring(contactsFlag.length + 1)); + default: + unknownArgs.add(arg); + } + } + unknown = List.unmodifiable(unknownArgs); + } + + static void _setContacts(String raw) { + debugTest = true; + contactCount = int.tryParse(raw) ?? contactCount; + } + + static String get activeDebugFlag => + revealLoginPayload ? loginPayloadFlag : debugFlag; + + static List get summary => [ + if (debug) activeDebugFlag, + if (debugTest) debugTestFlag, + if (debugTest && contactCount > 0) '$contactsFlag=$contactCount', + if (berserk) berserkFlag, + if (noMute) noMuteFlag, + if (logLevel.isNotEmpty) 'KOMET_LOG_LEVEL=$logLevel', + if (instance.isNotEmpty) 'KOMET_INSTANCE=$instance', + if (reviewPhone.isNotEmpty || reviewPayload.isNotEmpty) 'KOMET_REVIEW_*', + if (appStoreBuild) 'is_appstore_build', + ]; + + @visibleForTesting + static void reset() { + debug = _envDebug || _envLoginPayload; + revealLoginPayload = _envLoginPayload; + debugTest = _envDebugTest || _envContacts >= 0; + contactCount = _envContacts >= 0 ? _envContacts : 0; + berserk = _envBerserk; + noMute = _envNoMute; + unknown = const []; + } +} diff --git a/lib/core/config/review_access.dart b/lib/core/config/review_access.dart index 078e0cbb..b0c8e6c5 100644 --- a/lib/core/config/review_access.dart +++ b/lib/core/config/review_access.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import '../../models/spoof_profile.dart'; import '../crypto/chat_crypto_service.dart'; +import 'launch_flags.dart'; class ReviewCredentials { final String token; @@ -11,8 +12,8 @@ class ReviewCredentials { } abstract final class ReviewAccess { - static const String _phone = String.fromEnvironment('KOMET_REVIEW_PHONE'); - static const String _payload = String.fromEnvironment('KOMET_REVIEW_PAYLOAD'); + static const String _phone = LaunchFlags.reviewPhone; + static const String _payload = LaunchFlags.reviewPayload; static bool get enabled => _phone.isNotEmpty && _payload.isNotEmpty; diff --git a/lib/core/config/update_config.dart b/lib/core/config/update_config.dart index 9bfdcb21..51226051 100644 --- a/lib/core/config/update_config.dart +++ b/lib/core/config/update_config.dart @@ -1,11 +1,9 @@ import 'build_profile.dart'; +import 'launch_flags.dart'; // #***! откуда берём обновления, адрес зашит через --dart-define abstract final class UpdateConfig { - static const String baseUrl = String.fromEnvironment( - 'KOMET_UPDATE_BASE_URL', - defaultValue: 'https://cdn.komet.pw', - ); + static const String baseUrl = LaunchFlags.updateBaseUrl; // #***! пустой адрес значит обновления выключены, в App Store сборке их нет вовсе static bool get isConfigured => diff --git a/lib/core/media/share_thumbnail.dart b/lib/core/media/share_thumbnail.dart index a0294ce6..710be817 100644 --- a/lib/core/media/share_thumbnail.dart +++ b/lib/core/media/share_thumbnail.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:io'; +import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart' show ImageProvider, MemoryImage; @@ -28,15 +29,46 @@ Future sharedThumbnailDataUri(SharedFile source) async { // #***! декодируем в изоляте иначе список подвисает Future _photoThumb(File file) async { - Uint8List bytes; try { - bytes = await file.readAsBytes(); + final png = await _platformPhotoThumb(file); + if (png != null) return _asDataUri(png, mime: 'image/png'); + } catch (_) {} + try { + final bytes = await file.readAsBytes(); + final jpeg = await compute(_encodeThumbIsolate, bytes); + return _asDataUri(jpeg); } catch (e) { - logger.w('Поделиться: не прочитать ${file.path}: $e'); + logger.w('Поделиться: не создать превью ${file.path}: $e'); return null; } - final jpeg = await compute(_encodeThumbIsolate, bytes); - return _asDataUri(jpeg); +} + +Future _platformPhotoThumb(File file) async { + ui.ImmutableBuffer? buffer; + ui.ImageDescriptor? descriptor; + ui.Codec? codec; + ui.Image? image; + try { + buffer = await ui.ImmutableBuffer.fromFilePath(file.path); + descriptor = await ui.ImageDescriptor.encoded(buffer); + final landscape = descriptor.width >= descriptor.height; + codec = await descriptor.instantiateCodec( + targetWidth: landscape && descriptor.width > _thumbMaxDimension + ? _thumbMaxDimension + : null, + targetHeight: !landscape && descriptor.height > _thumbMaxDimension + ? _thumbMaxDimension + : null, + ); + image = (await codec.getNextFrame()).image; + final png = await image.toByteData(format: ui.ImageByteFormat.png); + return png?.buffer.asUint8List(png.offsetInBytes, png.lengthInBytes); + } finally { + image?.dispose(); + codec?.dispose(); + descriptor?.dispose(); + buffer?.dispose(); + } } // #***! плагина кадров может не быть, тогда просто без превью @@ -55,9 +87,9 @@ Future _videoThumb(File file) async { } } -String? _asDataUri(Uint8List? bytes) { +String? _asDataUri(Uint8List? bytes, {String mime = 'image/jpeg'}) { if (bytes == null || bytes.isEmpty) return null; - return 'data:image/jpeg;base64,${base64Encode(bytes)}'; + return 'data:$mime;base64,${base64Encode(bytes)}'; } // #***! уважаем EXIF поворот иначе миниатюра на боку diff --git a/lib/core/protocol/chat_cache_fingerprint.dart b/lib/core/protocol/chat_cache_fingerprint.dart index 4c61c9c8..f1d1dc61 100644 --- a/lib/core/protocol/chat_cache_fingerprint.dart +++ b/lib/core/protocol/chat_cache_fingerprint.dart @@ -47,17 +47,37 @@ class ChatCacheFingerprint { }) { final seed = _int64BigEndian(callsSeed); final device = Uint8List.fromList(utf8.encode(deviceId)); - final dexDigest = preLogin ? _preLoginDexDigest : _dexDigest; - final soDigest = preLogin - ? _preLoginSoDigest - : (_soDigests[arch] ?? _soDigests[defaultArch]!); + final digests = _digests(arch, preLogin); final result = BytesBuilder(); result.add(_sha256(_signatureDigest, seed, device)); - result.add(_sha256(dexDigest, seed, device)); - result.add(_sha256(soDigest, seed, device)); + result.add(_sha256(digests.dex, seed, device)); + result.add(_sha256(digests.so, seed, device)); return result.toBytes(); } + static Map exportDigests({ + String arch = defaultArch, + bool preLogin = false, + }) { + final digests = _digests(arch, preLogin); + return { + 'signature': _encodeHex(_signatureDigest), + 'dex': _encodeHex(digests.dex), + 'so': _encodeHex(digests.so), + }; + } + + static ({Uint8List dex, Uint8List so}) _digests(String arch, bool preLogin) => + ( + dex: preLogin ? _preLoginDexDigest : _dexDigest, + so: preLogin + ? _preLoginSoDigest + : (_soDigests[arch] ?? _soDigests[defaultArch]!), + ); + + static String _encodeHex(Uint8List bytes) => + bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join(); + static List _sha256(Uint8List a, Uint8List b, Uint8List c) { final builder = BytesBuilder() ..add(a) diff --git a/lib/core/share/native_share_account_channel.dart b/lib/core/share/native_share_account_channel.dart new file mode 100644 index 00000000..8a5b22a1 --- /dev/null +++ b/lib/core/share/native_share_account_channel.dart @@ -0,0 +1,63 @@ +import 'dart:io'; + +import 'package:flutter/foundation.dart' show kIsWeb; +import 'package:flutter/services.dart'; + +import '../utils/logger.dart'; +import 'share_account_snapshot.dart'; + +class NativeShareAccountChannel { + NativeShareAccountChannel({ + this.channel = const MethodChannel('ru.komet.app/share'), + bool? enabled, + }) : enabled = enabled ?? (!kIsWeb && Platform.isIOS); + + static final instance = NativeShareAccountChannel(); + + final MethodChannel channel; + final bool enabled; + final Map _generations = {}; + Future _tail = Future.value(); + + int generation(int accountId) => _generations[accountId] ?? 0; + + Future renewedToken(int accountId, String knownToken) async { + if (!enabled) return null; + try { + return await channel.invokeMethod('readShareToken', { + 'accountId': accountId.toString(), + 'knownToken': knownToken, + }); + } on PlatformException { + return null; + } on MissingPluginException { + return null; + } + } + + Future publish(ShareAccountSnapshot snapshot, int generation) { + if (!enabled) return Future.value(); + return _enqueue(() async { + if (this.generation(snapshot.accountId) != generation) return; + await channel.invokeMethod('syncShareAccount', snapshot.toMap()); + }); + } + + Future remove(int accountId) { + _generations[accountId] = generation(accountId) + 1; + if (!enabled) return Future.value(); + return _enqueue(() async { + await channel.invokeMethod('clearShareAccount', { + 'accountId': accountId.toString(), + }); + }).catchError((Object error) { + logger.w('Share account removal failed: ${error.runtimeType}'); + }); + } + + Future _enqueue(Future Function() action) { + final next = _tail.then((_) => action()); + _tail = next.then((_) {}, onError: (Object _, StackTrace _) {}); + return next; + } +} diff --git a/lib/core/share/native_share_account_sync.dart b/lib/core/share/native_share_account_sync.dart new file mode 100644 index 00000000..001830c0 --- /dev/null +++ b/lib/core/share/native_share_account_sync.dart @@ -0,0 +1,190 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/widgets.dart'; + +import '../../backend/api.dart'; +import '../../backend/modules/account.dart'; +import '../../backend/modules/chats.dart'; +import '../../backend/modules/contacts.dart'; +import '../../backend/modules/messages.dart'; +import '../config/komet_settings.dart'; +import '../crypto/e2ee_service.dart'; +import '../storage/app_database.dart'; +import '../storage/chat_encryption_store.dart'; +import '../storage/token_storage.dart'; +import '../utils/logger.dart'; +import 'native_share_account_channel.dart'; +import 'share_account_snapshot.dart'; +import 'share_recipient_eligibility.dart'; + +class NativeShareAccountSync with WidgetsBindingObserver { + NativeShareAccountSync._(); + + static final instance = NativeShareAccountSync._(); + Api? _api; + AccountModule? _account; + ChatsModule? _chats; + Timer? _timer; + StreamSubscription? _loginSubscription; + Future? _operation; + bool _refreshRequested = false; + + void init(Api api, AccountModule account, ChatsModule chats) { + if (!Platform.isIOS || _api != null) return; + _api = api; + _account = account; + _chats = chats; + _loginSubscription = account.loginStatusStream.listen((status) { + if (status == LoginStatus.success) unawaited(refresh()); + }); + chats.chatsChanged.addListener(_schedule); + ContactsModule.revision.addListener(_schedule); + ChatEncryptionStore.instance.revision.addListener(_refreshPrivacy); + E2eeService.instance.revision.addListener(_refreshPrivacy); + KometSettings.ghostMode.addListener(_schedule); + WidgetsBinding.instance.addObserver(this); + unawaited(refresh()); + } + + void _schedule() { + _timer ??= Timer(const Duration(milliseconds: 400), () { + _timer = null; + unawaited(refresh()); + }); + } + + void _refreshPrivacy() => unawaited(refresh()); + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.inactive || + state == AppLifecycleState.resumed) { + unawaited(refresh()); + } + } + + Future refresh() { + if (_api == null) return Future.value(); + _timer?.cancel(); + _timer = null; + _refreshRequested = true; + return _operation ??= _drain().whenComplete(() => _operation = null); + } + + Future _drain() async { + while (_refreshRequested) { + _refreshRequested = false; + try { + await _publishActiveAccount(); + } catch (error) { + logger.w('Share account sync failed: ${error.runtimeType}'); + } + } + } + + Future _publishActiveAccount() async { + final api = _api; + final account = _account; + final chats = _chats; + if (api == null || + account == null || + chats == null || + !account.isLoggedIn || + api.state != SessionState.online) { + return; + } + final options = api.shareSessionOptions; + if (options == null) return; + final epoch = api.sessionEpoch; + final accountId = await TokenStorage.getActiveAccountId(); + if (accountId == null) return; + final channel = NativeShareAccountChannel.instance; + final generation = channel.generation(accountId); + final token = await TokenStorage.readToken(accountId); + final profile = await AppDatabase.loadProfile(accountId); + if (token == null || profile == null) return; + await ChatEncryptionStore.instance.load(); + await E2eeService.instance.ensureLoaded(accountId); + final privacyRevision = ChatEncryptionStore.instance.revision.value; + final e2eeRevision = E2eeService.instance.revision.value; + final cachedChats = await chats.getChats(accountId); + if (await TokenStorage.getActiveAccountId() != accountId || + api.sessionEpoch != epoch || + api.state != SessionState.online || + !account.isLoggedIn || + !identical(_api, api) || + !identical(_account, account)) { + return; + } + if (privacyRevision != ChatEncryptionStore.instance.revision.value || + e2eeRevision != E2eeService.instance.revision.value || + !E2eeService.instance.isLoaded(accountId)) { + _refreshRequested = true; + return; + } + final recipients = []; + for (final chat in cachedChats) { + var title = chat.title?.trim() ?? ''; + if (chat.id == 0) { + title = 'Избранное'; + } else if (chat.type == 'DIALOG') { + for (final participant in chat.participants.keys) { + if (participant != accountId) { + title = ContactCache.get(participant) ?? title; + break; + } + } + } + final disabledReason = shareRecipientDisabledReason( + legacyEncryptionEnabled: ChatEncryptionStore.instance.isEnabled( + accountId, + chat.id, + ), + e2eePhase: E2eeService.instance.phaseOf(accountId, chat.id), + isChannel: chat.type == 'CHANNEL', + canPostToChannel: chat.iAmAdmin(accountId), + ); + recipients.add( + ShareRecipientSnapshot( + id: chat.id, + title: title.isEmpty ? 'Чат' : title, + type: chat.type, + disabledReason: disabledReason, + ), + ); + } + final name = '${profile.firstName} ${profile.lastName ?? ''}'.trim(); + await channel.publish( + ShareAccountSnapshot( + accountId: accountId, + accountName: name.isEmpty ? 'Komet' : name, + token: token, + session: { + ...options, + 'ping_interactive': !KometSettings.ghostMode.value, + }, + login: account.buildLoginPayload(token), + chats: recipients, + ), + generation, + ); + } + + void dispose() { + _timer?.cancel(); + _timer = null; + unawaited(_loginSubscription?.cancel()); + _loginSubscription = null; + _chats?.chatsChanged.removeListener(_schedule); + ContactsModule.revision.removeListener(_schedule); + ChatEncryptionStore.instance.revision.removeListener(_refreshPrivacy); + E2eeService.instance.revision.removeListener(_refreshPrivacy); + KometSettings.ghostMode.removeListener(_schedule); + WidgetsBinding.instance.removeObserver(this); + _api = null; + _account = null; + _chats = null; + _refreshRequested = false; + } +} diff --git a/lib/core/share/share_account_snapshot.dart b/lib/core/share/share_account_snapshot.dart new file mode 100644 index 00000000..9dac9c46 --- /dev/null +++ b/lib/core/share/share_account_snapshot.dart @@ -0,0 +1,66 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +class ShareRecipientSnapshot { + const ShareRecipientSnapshot({ + required this.id, + required this.title, + required this.type, + this.disabledReason, + }); + + final int id; + final String title; + final String type; + final String? disabledReason; + + Map toMap() => { + 'id': id.toString(), + 'title': title, + 'type': type, + if (disabledReason != null) 'disabledReason': disabledReason, + }; +} + +class ShareAccountSnapshot { + const ShareAccountSnapshot({ + required this.accountId, + required this.accountName, + required this.token, + required this.session, + required this.login, + required this.chats, + }); + + final int accountId; + final String accountName; + final String token; + final Map session; + final Map login; + final List chats; + + Map toMap() { + final loginOptions = Map.from(login) + ..remove('token') + ..remove('chatCacheFingerprint'); + return { + 'accountId': accountId.toString(), + 'accountName': accountName, + 'token': token, + 'session': session, + 'login': _encode(loginOptions), + 'chats': chats.map((chat) => chat.toMap()).toList(growable: false), + }; + } + + static Object? _encode(Object? value) { + if (value is Uint8List) return {r'$bin': base64Encode(value)}; + if (value is Map) { + return value.map( + (key, item) => MapEntry(key is int ? '\$int:$key' : key, _encode(item)), + ); + } + if (value is List) return value.map(_encode).toList(growable: false); + return value; + } +} diff --git a/lib/core/share/share_inbox.dart b/lib/core/share/share_inbox.dart new file mode 100644 index 00000000..a7ba995c --- /dev/null +++ b/lib/core/share/share_inbox.dart @@ -0,0 +1,69 @@ +import '../../models/shared_payload.dart'; + +class ShareInbox { + ShareInbox({ + required this.consume, + required this.acknowledge, + required this.onShare, + this.release, + }); + + final Future Function() consume; + final Future Function(String id) acknowledge; + final void Function(SharedPayload payload) onShare; + final Future Function(String id)? release; + + String? _activeId; + bool _completed = false; + bool _acknowledged = false; + Future Function()? _waitForRelease; + bool _checkRequested = false; + Future? _operation; + + Future check() { + _checkRequested = true; + return _operation ??= _drain().whenComplete(() => _operation = null); + } + + Future complete({Future Function()? waitForRelease}) { + if (_activeId == null) return Future.value(); + _completed = true; + _waitForRelease ??= waitForRelease; + return check(); + } + + Future _drain() async { + while (_checkRequested) { + _checkRequested = false; + final activeId = _activeId; + if (activeId != null) { + if (!_completed) return; + if (!_acknowledged) { + await acknowledge(activeId); + _acknowledged = true; + } + await _waitForRelease?.call(); + await release?.call(activeId); + _activeId = null; + _completed = false; + _acknowledged = false; + _waitForRelease = null; + } + + _checkRequested = false; + final raw = await consume(); + if (raw is! Map) continue; + final id = raw['id']; + if (id is! String || id.isEmpty) continue; + final payload = SharedPayload.fromMap(raw); + if (payload == null) { + await acknowledge(id); + await release?.call(id); + _checkRequested = true; + continue; + } + _activeId = id; + onShare(payload); + } + } +} diff --git a/lib/core/share/share_intent_bridge.dart b/lib/core/share/share_intent_bridge.dart index cdca1915..824207e9 100644 --- a/lib/core/share/share_intent_bridge.dart +++ b/lib/core/share/share_intent_bridge.dart @@ -9,6 +9,8 @@ import '../../frontend/widgets/swipe_route.dart'; import '../../main.dart'; import '../../models/shared_payload.dart'; import '../utils/logger.dart'; +import 'share_inbox.dart'; +import 'shared_file_usage.dart'; // #***! системное поделиться, файлы с натива class ShareIntentBridge { @@ -27,10 +29,17 @@ class ShareIntentBridge { SharedPayload? _pending; int _retriesLeft = 0; Timer? _retry; + late final _inbox = ShareInbox( + consume: () => _method.invokeMethod('consumeInitialShare'), + acknowledge: (id) => + _method.invokeMethod('acknowledgeShare', {'id': id}), + release: (id) => _method.invokeMethod('releaseShare', {'id': id}), + onShare: _receivePayload, + ); bool get _native { try { - return Platform.isAndroid; + return Platform.isAndroid || Platform.isIOS; } catch (_) { return false; } @@ -59,7 +68,11 @@ class ShareIntentBridge { Future checkInitialShare() async { if (!_native) return; try { - _onEvent(await _method.invokeMethod('consumeInitialShare')); + if (Platform.isIOS) { + await _inbox.check(); + } else { + _onEvent(await _method.invokeMethod('consumeInitialShare')); + } } catch (e) { logger.w('ShareIntentBridge.checkInitialShare: $e'); } @@ -76,8 +89,16 @@ class ShareIntentBridge { // #***! полученное откладываем и пробуем показать void _onEvent(Object? event) { + if (Platform.isIOS) { + unawaited(checkInitialShare()); + return; + } final payload = SharedPayload.fromMap(event); if (payload == null) return; + _receivePayload(payload); + } + + void _receivePayload(SharedPayload payload) { logger.i( 'Поделиться: получено ${payload.files.length} файлов' '${payload.text != null ? ' и текст' : ''}', @@ -94,7 +115,10 @@ class ShareIntentBridge { final context = KometApp.overlayContext; if (!_ready || context == null || api.state != SessionState.online) { - if (_retriesLeft <= 0) { + if (Platform.isIOS && (!_ready || api.state != SessionState.online)) { + return; + } + if (!Platform.isIOS && _retriesLeft <= 0) { _pending = null; return; } @@ -108,15 +132,33 @@ class ShareIntentBridge { // #***! кэш натива чистим после закрытия _pending = null; + _retry?.cancel(); + _retry = null; _presenting = true; unawaited( pushSwipeable( context, (_) => ChatListScreen(sharePayload: payload), - ).whenComplete(() { - _presenting = false; - unawaited(clearCache()); - }), + ).whenComplete(() => _finishShare(payload)), ); } + + Future _finishShare(SharedPayload payload) async { + Future waitForFiles() => SharedFileUsage.instance.waitUntilUnused( + payload.files.map((file) => file.path), + ); + try { + if (Platform.isIOS) { + await _inbox.complete(waitForRelease: waitForFiles); + } else { + await waitForFiles(); + if (_pending == null) await clearCache(); + } + } catch (e) { + logger.w('ShareIntentBridge.complete: $e'); + } finally { + _presenting = false; + _flushPending(); + } + } } diff --git a/lib/core/share/share_recipient_eligibility.dart b/lib/core/share/share_recipient_eligibility.dart new file mode 100644 index 00000000..aaa5de65 --- /dev/null +++ b/lib/core/share/share_recipient_eligibility.dart @@ -0,0 +1,16 @@ +import '../crypto/e2ee_service.dart'; + +String? shareRecipientDisabledReason({ + required bool legacyEncryptionEnabled, + required E2eePhase e2eePhase, + required bool isChannel, + required bool canPostToChannel, +}) { + if (legacyEncryptionEnabled || e2eePhase != E2eePhase.none) { + return 'Зашифрованный чат — отправляйте из Komet'; + } + if (isChannel && !canPostToChannel) { + return 'Нет права отправлять сообщения в этот канал'; + } + return null; +} diff --git a/lib/core/share/shared_file_usage.dart b/lib/core/share/shared_file_usage.dart new file mode 100644 index 00000000..69f1f560 --- /dev/null +++ b/lib/core/share/shared_file_usage.dart @@ -0,0 +1,37 @@ +import 'dart:async'; + +class SharedFileUsage { + static final instance = SharedFileUsage(); + + final Map>> _readers = {}; + + Future use( + Iterable filePaths, + Future Function() operation, + ) async { + final paths = filePaths.toSet(); + final released = Completer(); + for (final path in paths) { + (_readers[path] ??= {}).add(released.future); + } + try { + return await operation(); + } finally { + for (final path in paths) { + final readers = _readers[path]; + readers?.remove(released.future); + if (readers?.isEmpty ?? false) _readers.remove(path); + } + released.complete(); + } + } + + Future waitUntilUnused(Iterable filePaths) async { + final paths = filePaths.toSet(); + while (true) { + final readers = {for (final path in paths) ...?_readers[path]}; + if (readers.isEmpty) return; + await Future.wait(readers); + } + } +} diff --git a/lib/core/storage/account_token_store.dart b/lib/core/storage/account_token_store.dart new file mode 100644 index 00000000..32c3dccc --- /dev/null +++ b/lib/core/storage/account_token_store.dart @@ -0,0 +1,54 @@ +import 'dart:async'; + +class AccountTokenStore { + AccountTokenStore({ + required this.readStored, + required this.writeStored, + required this.deleteStored, + required this.readRenewed, + required this.clearShared, + }); + + final Future Function(int accountId) readStored; + final Future Function(int accountId, String token) writeStored; + final Future Function(int accountId) deleteStored; + final Future Function(int accountId, String token) readRenewed; + final Future Function(int accountId) clearShared; + final Map> _operations = {}; + + Future read(int accountId) => _run(accountId, () async { + final stored = await readStored(accountId); + if (stored == null) return null; + final renewed = await readRenewed(accountId, stored); + if (renewed == null || renewed.isEmpty || renewed == stored) return stored; + await writeStored(accountId, renewed); + return renewed; + }); + + Future save(int accountId, String token) => + _run(accountId, () => writeStored(accountId, token)); + + Future delete(int accountId) => _run(accountId, () async { + await clearShared(accountId); + await deleteStored(accountId); + }); + + Future _run(int accountId, Future Function() action) { + final result = (_operations[accountId] ?? Future.value()).then( + (_) => action(), + ); + final tail = result.then( + (_) {}, + onError: (Object _, StackTrace _) {}, + ); + _operations[accountId] = tail; + unawaited( + tail.then((_) { + if (identical(_operations[accountId], tail)) { + _operations.remove(accountId); + } + }), + ); + return result; + } +} diff --git a/lib/core/storage/app_instance.dart b/lib/core/storage/app_instance.dart index 519caefa..93335435 100644 --- a/lib/core/storage/app_instance.dart +++ b/lib/core/storage/app_instance.dart @@ -1,8 +1,10 @@ +import '../config/launch_flags.dart'; + // #***! имя копии приложения из --dart-define, чтоб держать несколько установок раздельно class AppInstance { AppInstance._(); - static const String id = String.fromEnvironment('KOMET_INSTANCE'); + static const String id = LaunchFlags.instance; static bool get isNamed => id.isNotEmpty; diff --git a/lib/core/storage/per_chat_json_store.dart b/lib/core/storage/per_chat_json_store.dart index 818ce68e..e8ed81b8 100644 --- a/lib/core/storage/per_chat_json_store.dart +++ b/lib/core/storage/per_chat_json_store.dart @@ -21,6 +21,7 @@ abstract class PerChatJsonStore { // #***! revision на каждую запись, списки подписаны final ValueNotifier revision = ValueNotifier(0); bool _loaded = false; + Future? _loading; String _buildKey(int accountId, int chatId) => '$accountId/$chatId'; @@ -32,13 +33,16 @@ abstract class PerChatJsonStore { void onBeforeWrite(String key, T? previous, T? next) {} // #***! читаем один раз, битый джейсон молча игнорим чтоб не блокировать старт - Future load() async { - if (_loaded) return; - _loaded = true; + Future load() { + if (_loaded) return Future.value(); + return _loading ??= _load().whenComplete(() => _loading = null); + } + + Future _load() async { final prefs = await SharedPreferences.getInstance(); final raw = prefs.getString(_prefsKey); - if (raw == null) return; try { + if (raw == null) return; final map = jsonDecode(raw); if (map is Map) { map.forEach((k, v) { @@ -47,7 +51,10 @@ abstract class PerChatJsonStore { if (value != null) _values[k] = value; }); } - } catch (_) {} + } catch (_) { + } finally { + _loaded = true; + } } @protected @@ -60,6 +67,7 @@ abstract class PerChatJsonStore { @protected Future write(int accountId, int chatId, T? value) async { if (accountId == 0) return; + await load(); final key = _buildKey(accountId, chatId); final previous = _values[key]; onBeforeWrite(key, previous, value); diff --git a/lib/core/storage/token_storage.dart b/lib/core/storage/token_storage.dart index dd2fd95c..25fcb661 100644 --- a/lib/core/storage/token_storage.dart +++ b/lib/core/storage/token_storage.dart @@ -2,6 +2,9 @@ import 'package:flutter/services.dart' show PlatformException; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import '../share/native_share_account_channel.dart'; +import 'account_token_store.dart'; + // #***! токены и активный аккаунт class TokenStorage { static const _tokenPrefix = 'auth_token_'; @@ -9,7 +12,6 @@ class TokenStorage { // #***! на иосе ключ только после первой разблокировки и без синхры в айклауд static const _secure = FlutterSecureStorage( - aOptions: AndroidOptions(), iOptions: IOSOptions( accessibility: KeychainAccessibility.first_unlock_this_device, synchronizable: false, @@ -19,6 +21,18 @@ class TokenStorage { // #***! иос иногда даёт дубликат вместо перезаписи, удаляем и пишем заново static const int _duplicateKeychainItem = -25299; + static final _tokens = AccountTokenStore( + readStored: _readStoredToken, + writeStored: (accountId, token) => _write('$_tokenPrefix$accountId', token), + deleteStored: (accountId) async { + final key = '$_tokenPrefix$accountId'; + await _secure.delete(key: key); + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(key); + }, + readRenewed: NativeShareAccountChannel.instance.renewedToken, + clearShared: NativeShareAccountChannel.instance.remove, + ); static bool _isDuplicateItem(PlatformException error) => error.details == _duplicateKeychainItem || @@ -52,10 +66,12 @@ class TokenStorage { } static Future saveToken(String token, int accountId) => - _write('$_tokenPrefix$accountId', token); + _tokens.save(accountId, token); + + static Future readToken(int accountId) => _tokens.read(accountId); // #***! токены раньше лежали в открытых prefs, переносим и стираем - static Future readToken(int accountId) async { + static Future _readStoredToken(int accountId) async { final key = '$_tokenPrefix$accountId'; final secured = await _secure.read(key: key); if (secured != null) return secured; @@ -78,12 +94,7 @@ class TokenStorage { } } - static Future deleteToken(int accountId) async { - final key = '$_tokenPrefix$accountId'; - await _secure.delete(key: key); - final prefs = await SharedPreferences.getInstance(); - await prefs.remove(key); - } + static Future deleteToken(int accountId) => _tokens.delete(accountId); // #***! активный аккаунт в обычных prefs, это не секрет static Future setActiveAccount(int accountId) async { diff --git a/lib/core/transport/wire_debug_log.dart b/lib/core/transport/wire_debug_log.dart new file mode 100644 index 00000000..15c932f1 --- /dev/null +++ b/lib/core/transport/wire_debug_log.dart @@ -0,0 +1,45 @@ +import 'package:kolibri/kolibri.dart' show WireLogEvent; + +import '../config/launch_flags.dart'; +import '../protocol/opcode_map.dart'; +import '../utils/logger.dart'; + +class WireDebugLog { + WireDebugLog._(); + + static void record(String session, WireLogEvent event) { + logger.d( + describe( + session: session, + event: event, + revealLoginPayload: LaunchFlags.revealLoginPayload, + ), + ); + } + + static String describe({ + required String session, + required WireLogEvent event, + required bool revealLoginPayload, + }) { + final arrow = event.direction == 'out' ? '>>' : '<<'; + final head = + 'WIRE [$session] $arrow ${event.cmd} ' + '${Opcode.name(event.opcode)}(${event.opcode}) seq=${event.seq}'; + final hidden = event.opcode == Opcode.login && !revealLoginPayload; + final payload = hidden + ? '' + : maskPasswords(event.json); + return '$head $payload'; + } + + static final RegExp _passwordField = RegExp( + r'"(\w*[Pp]assword)"\s*:\s*"(?:[^"\\]|\\.)*"', + ); + + static String maskPasswords(String json) => json.replaceAllMapped( + _passwordField, + (match) => '"${match[1]}":"***"', + ); +} diff --git a/lib/core/utils/logger.dart b/lib/core/utils/logger.dart index 0749f846..2f2b41bf 100644 --- a/lib/core/utils/logger.dart +++ b/lib/core/utils/logger.dart @@ -3,12 +3,12 @@ import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:logger/logger.dart'; +import '../config/launch_flags.dart'; import 'debug_session_log.dart'; // #***! уровень логов задаётся при сборке Level _minimumLogLevel() { - const raw = String.fromEnvironment('KOMET_LOG_LEVEL', defaultValue: ''); - switch (raw.toLowerCase()) { + switch (LaunchFlags.logLevel.toLowerCase()) { case 'trace': return Level.trace; case 'debug': @@ -36,9 +36,31 @@ Level _minimumLogLevel() { LogFilter _logFilter() { if (kReleaseMode) { - return ProductionFilter(); + return LaunchDebugFilter(ProductionFilter()); } - return DevelopmentFilter(); + return LaunchDebugFilter(DevelopmentFilter()); +} + +class LaunchDebugFilter extends LogFilter { + LaunchDebugFilter(this._base); + + final LogFilter _base; + + @override + Level? get level => _base.level; + + @override + set level(Level? value) => _base.level = value; + + @override + Future init() => _base.init(); + + @override + bool shouldLog(LogEvent event) => + LaunchFlags.debug || _base.shouldLog(event); + + @override + Future destroy() => _base.destroy(); } // #***! единый логгер, консоль плюс лог сессии @@ -127,6 +149,9 @@ class KometLogPrinter extends LogPrinter { final bool colors; + static const int maxLineLength = 900; + static const String continuationPrefix = ' | '; + @override List log(LogEvent event) { final lines = []; @@ -136,22 +161,50 @@ class KometLogPrinter extends LogPrinter { final ord = _importanceSortKey(event.level).toString().padLeft(2, '0'); final letter = _levelLetter(event.level); final label = colors ? _levelColor(event.level)(letter) : letter; - final msg = _stringifyMessage(event.message); - lines.add('$ord|$timeStr $label $msg'); + final msgLines = splitForConsole(_stringifyMessage(event.message)); + lines.add('$ord|$timeStr $label ${msgLines.first}'); + for (final line in msgLines.skip(1)) { + lines.add('$continuationPrefix$line'); + } if (event.error != null) { - lines.add('${' ' * 3}| ${event.error}'); + lines.add('$continuationPrefix${event.error}'); } // #***! стек только для ошибок и не длиннее 12 строк if (event.stackTrace != null && event.level.value >= 5000) { final st = event.stackTrace.toString().split('\n'); const limit = 12; for (var i = 0; i < st.length && i < limit; i++) { - lines.add('${' ' * 3}| ${st[i]}'); + lines.add('$continuationPrefix${st[i]}'); } } return lines; } + static List splitForConsole(String message) { + final out = []; + for (final line in message.split('\n')) { + if (line.length <= maxLineLength) { + out.add(line); + continue; + } + var start = 0; + while (start < line.length) { + var end = start + maxLineLength; + if (end >= line.length) { + end = line.length; + } else if (_isHighSurrogate(line.codeUnitAt(end - 1))) { + end--; + } + out.add(line.substring(start, end)); + start = end; + } + } + return out; + } + + static bool _isHighSurrogate(int codeUnit) => + codeUnit >= 0xD800 && codeUnit <= 0xDBFF; + // #***! карты и списки печатаем джейсоном String _stringifyMessage(dynamic message) { final finalMessage = message is Function ? message() : message; diff --git a/lib/core/utils/seed_scheme.dart b/lib/core/utils/seed_scheme.dart index 4aeea73a..1942099c 100644 --- a/lib/core/utils/seed_scheme.dart +++ b/lib/core/utils/seed_scheme.dart @@ -3,6 +3,22 @@ import 'package:material_color_utilities/material_color_utilities.dart'; const double kAchromaticSeedChroma = 10; +const double kAccentMinBrightness = 0.2; + +const ({double accent, double container}) _lightAccentToneFloors = ( + accent: 20, + container: 60, +); + +const ({double accent, double container}) _darkAccentToneFloors = ( + accent: 65, + container: 15, +); + +const double _accentForegroundContrast = 7; + +const double _containerForegroundContrast = 4.5; + bool isAchromaticSeed(Color seed) => Hct.fromInt(seed.toARGB32()).chroma < kAchromaticSeedChroma; @@ -14,3 +30,116 @@ ColorScheme schemeFromSeed(Color seed, Brightness brightness) => ? DynamicSchemeVariant.monochrome : DynamicSchemeVariant.tonalSpot, ); + +double accentDepth(Color seed) { + final brightness = HSVColor.fromColor(seed).value; + return ((1 - brightness) / (1 - kAccentMinBrightness)).clamp(0.0, 1.0); +} + +ColorScheme accentSchemeFromSeed(Color seed, Brightness brightness) { + final hueSource = HSVColor.fromColor(seed).withValue(1).toColor(); + final base = schemeFromSeed(hueSource, brightness); + final depth = accentDepth(seed); + if (depth == 0) return base; + + final scheme = _dynamicSchemeFor(hueSource, brightness); + final floors = scheme.isDark ? _darkAccentToneFloors : _lightAccentToneFloors; + + _TonePair deepen( + TonalPalette palette, + DynamicColor fill, + DynamicColor onFill, + double floor, + double contrast, + ) { + final fillTone = fill.getTone(scheme); + final tone = fillTone > floor + ? fillTone - (fillTone - floor) * depth + : fillTone; + final onTone = onFill.getTone(scheme); + final readableOnTone = Contrast.ratioOfTones(onTone, tone) >= contrast + ? onTone + : DynamicColor.foregroundTone(tone, contrast); + return ( + fill: Color(palette.getHct(tone).toInt()), + onFill: Color(palette.getHct(readableOnTone).toInt()), + ); + } + + final primary = deepen( + scheme.primaryPalette, + MaterialDynamicColors.primary, + MaterialDynamicColors.onPrimary, + floors.accent, + _accentForegroundContrast, + ); + final primaryContainer = deepen( + scheme.primaryPalette, + MaterialDynamicColors.primaryContainer, + MaterialDynamicColors.onPrimaryContainer, + floors.container, + _containerForegroundContrast, + ); + final secondary = deepen( + scheme.secondaryPalette, + MaterialDynamicColors.secondary, + MaterialDynamicColors.onSecondary, + floors.accent, + _accentForegroundContrast, + ); + final secondaryContainer = deepen( + scheme.secondaryPalette, + MaterialDynamicColors.secondaryContainer, + MaterialDynamicColors.onSecondaryContainer, + floors.container, + _containerForegroundContrast, + ); + final tertiary = deepen( + scheme.tertiaryPalette, + MaterialDynamicColors.tertiary, + MaterialDynamicColors.onTertiary, + floors.accent, + _accentForegroundContrast, + ); + final tertiaryContainer = deepen( + scheme.tertiaryPalette, + MaterialDynamicColors.tertiaryContainer, + MaterialDynamicColors.onTertiaryContainer, + floors.container, + _containerForegroundContrast, + ); + + return base.copyWith( + primary: primary.fill, + onPrimary: primary.onFill, + primaryContainer: primaryContainer.fill, + onPrimaryContainer: primaryContainer.onFill, + secondary: secondary.fill, + onSecondary: secondary.onFill, + secondaryContainer: secondaryContainer.fill, + onSecondaryContainer: secondaryContainer.onFill, + tertiary: tertiary.fill, + onTertiary: tertiary.onFill, + tertiaryContainer: tertiaryContainer.fill, + onTertiaryContainer: tertiaryContainer.onFill, + surfaceTint: primary.fill, + ); +} + +typedef _TonePair = ({Color fill, Color onFill}); + +DynamicScheme _dynamicSchemeFor(Color seed, Brightness brightness) { + final source = Hct.fromInt(seed.toARGB32()); + final isDark = brightness == Brightness.dark; + return isAchromaticSeed(seed) + ? SchemeMonochrome( + sourceColorHct: source, + isDark: isDark, + contrastLevel: 0, + ) + : SchemeTonalSpot( + sourceColorHct: source, + isDark: isDark, + contrastLevel: 0, + ); +} diff --git a/lib/frontend/screens/auth/code_confirmation_screen.dart b/lib/frontend/screens/auth/code_confirmation_screen.dart index 265979dc..7b81e8d3 100644 --- a/lib/frontend/screens/auth/code_confirmation_screen.dart +++ b/lib/frontend/screens/auth/code_confirmation_screen.dart @@ -6,10 +6,12 @@ import 'package:material_symbols_icons/symbols.dart'; import 'password_2fa_screen.dart'; import 'registration_screen.dart'; import 'session_stale_recovery.dart'; +import 'slow_login_hint.dart'; import '../../../backend/api.dart'; import '../../../core/config/review_access.dart'; import '../../../core/protocol/packet.dart'; import '../../../core/storage/spoofing_service.dart'; +import '../../../core/utils/logger.dart'; import '../../../core/utils/sms_code_listener.dart'; import '../../../main.dart'; import '../../widgets/auth_limits_sheet.dart'; @@ -73,6 +75,7 @@ class _CodeConfirmationScreenState extends State if (!widget.reviewAccess) { _startTimer(); _listenForSmsCode(); + accountModule.prepareWebSmsSocket(); } _shakeController = AnimationController( @@ -388,6 +391,10 @@ class _CodeConfirmationScreenState extends State return; } + logger.d( + '[${api.debugTag}] код подтверждён: ' + '${api.webHandshake ? 'SMS-вход через веб' : 'обычный вход'}', + ); // #***! эксперим. SMS-вход через веб: получаем сокетовый токен хитрой схемой if (api.webHandshake) { final token = result.loginToken; @@ -409,7 +416,11 @@ class _CodeConfirmationScreenState extends State final loginResult = await accountModule.login(); await _completeLogin(loginResult.profile.baseUrl); - } catch (e) { + } catch (e, st) { + logger.d( + '[${api.debugTag}] подтверждение кода упало ' + '(код принят=$verified): $e\n$st', + ); if (!mounted) return; if (verified) { _showError(e.toString()); @@ -462,7 +473,9 @@ class _CodeConfirmationScreenState extends State ), const SizedBox(height: 12), Text( - l10n.codeConfirmationSmsSent, + api.webHandshake + ? l10n.codeConfirmationSmsSent + : l10n.codeConfirmationCheckMaxChat, style: TextStyle( color: cs.outline, fontSize: 15, @@ -631,13 +644,16 @@ class _CodeConfirmationScreenState extends State crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( - child: Text( - l10n.codeConfirmation2faWarning, - style: TextStyle( - color: cs.error.withValues(alpha: 0.5), - fontSize: 13, - fontWeight: FontWeight.w400, - height: 1.35, + child: SlowLoginHint( + active: _verifying && api.webHandshake, + idle: Text( + l10n.codeConfirmation2faWarning, + style: TextStyle( + color: cs.error.withValues(alpha: 0.5), + fontSize: 13, + fontWeight: FontWeight.w400, + height: 1.35, + ), ), ), ), diff --git a/lib/frontend/screens/auth/login_screen.dart b/lib/frontend/screens/auth/login_screen.dart index d0419eb3..95d60f1c 100644 --- a/lib/frontend/screens/auth/login_screen.dart +++ b/lib/frontend/screens/auth/login_screen.dart @@ -60,6 +60,10 @@ class _LoginScreenState extends State { void initState() { super.initState(); _sessionState = api.state; + logger.d( + '[${api.debugTag}] экран входа: сессия=${api.state.name} ' + 'всегда SMS=$_alwaysSendSms', + ); if (api.state == SessionState.disconnected) { // #***! экран входа по телефону — сокет без токена, прошлая версия unawaited(api.connect(authenticated: false, web: _alwaysSendSms)); @@ -79,9 +83,15 @@ class _LoginScreenState extends State { _alwaysSendSms = value; _switchingSmsMode = true; }); + logger.d('[${api.debugTag}] всегда SMS: переключаю на $value'); try { await api.reconnectPreLogin(web: value); + logger.d( + '[${api.debugTag}] всегда SMS: сессия переподнята, ' + 'состояние=${api.state.name}', + ); } catch (e) { + logger.d('[${api.debugTag}] всегда SMS: переподнять не вышло: $e'); if (!mounted) return; showCustomNotification( context, @@ -97,6 +107,13 @@ class _LoginScreenState extends State { !accountModule.isLoggedIn && !api.isAuthenticatedHandshake && api.webHandshake == _alwaysSendSms; + logger.d( + '[${api.debugTag}] pre-login сессия: ' + '${fresh ? 'годится' : 'переподнимаю'} ' + '(залогинен=${accountModule.isLoggedIn} ' + 'боевой сокет=${api.isAuthenticatedHandshake} ' + 'веб=${api.webHandshake} нужен веб=$_alwaysSendSms)', + ); if (fresh) return; await api.reconnectPreLogin(web: _alwaysSendSms); } @@ -636,6 +653,7 @@ class _LoginScreenState extends State { // сессий, Отмена снимает галочку и не пускает дальше if (_alwaysSendSms) { final choice = await _showExperimentalSmsWarning(); + logger.d('всегда SMS: предупреждение — $choice'); if (choice == false) { await _setAlwaysSendSms(false); return; @@ -662,7 +680,10 @@ class _LoginScreenState extends State { ), ), ); - } catch (e) { + } catch (e, st) { + logger.d( + '[${api.debugTag}] запрос кода упал: $e\n$st', + ); if (!screenContext.mounted) return; _showPhoneError( isSessionStateError(e) diff --git a/lib/frontend/screens/auth/password_2fa_screen.dart b/lib/frontend/screens/auth/password_2fa_screen.dart index 30380de7..646f3cdf 100644 --- a/lib/frontend/screens/auth/password_2fa_screen.dart +++ b/lib/frontend/screens/auth/password_2fa_screen.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:material_symbols_icons/symbols.dart'; import '../../../backend/modules/account/account_models.dart'; import '../../../core/protocol/packet.dart'; +import '../../../core/utils/logger.dart'; import '../../../l10n/app_localizations.dart'; import '../../../main.dart'; import '../../widgets/animated_slash_icon.dart'; @@ -10,6 +11,7 @@ import '../../widgets/custom_notification.dart'; import '../../widgets/login_success_screen.dart'; import '../../widgets/small_spinner.dart'; import 'session_stale_recovery.dart'; +import 'slow_login_hint.dart'; class Password2FAScreen extends StatefulWidget { final String trackId; @@ -38,10 +40,13 @@ class _Password2FAScreenState extends State String get connectionDroppedMessage => AppLocalizations.of(context)!.password2faConnectionDropped; + bool get _webSmsLogin => api.webHandshake && widget.rawPhone != null; + @override void initState() { super.initState(); startSessionRecovery(); + if (_webSmsLogin) accountModule.prepareWebSmsSocket(); } @override @@ -86,9 +91,13 @@ class _Password2FAScreenState extends State if (!mounted) return; String? avatarUrl; + logger.d( + '[${api.debugTag}] 2FA пройдена, SMS-вход через веб=' + '$_webSmsLogin', + ); // #***! эксперим. SMS-вход через веб: пароль пользователя уже есть, добываем // сокетовый токен и перезаходим боевой версией - if (api.webHandshake && widget.rawPhone != null) { + if (_webSmsLogin) { await accountModule.completeWebSmsSocketLogin( phone: widget.rawPhone!, accountId: result.accountId, @@ -123,7 +132,10 @@ class _Password2FAScreenState extends State ), (route) => false, ); - } catch (e) { + } catch (e, st) { + logger.d( + '[${api.debugTag}] 2FA-вход упал (пароль принят=$passed): $e\n$st', + ); if (!mounted) return; setState(() { @@ -225,8 +237,11 @@ class _Password2FAScreenState extends State ), const Spacer(), Row( - mainAxisAlignment: MainAxisAlignment.end, children: [ + Expanded( + child: SlowLoginHint(active: _isLoading && _webSmsLogin), + ), + const SizedBox(width: 16), FloatingActionButton( onPressed: _isLoading ? null : _checkPassword, backgroundColor: _passwordController.text.isNotEmpty diff --git a/lib/frontend/screens/auth/slow_login_hint.dart b/lib/frontend/screens/auth/slow_login_hint.dart new file mode 100644 index 00000000..498f08e7 --- /dev/null +++ b/lib/frontend/screens/auth/slow_login_hint.dart @@ -0,0 +1,81 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../../../l10n/app_localizations.dart'; + +class SlowLoginHint extends StatefulWidget { + const SlowLoginHint({ + super.key, + required this.active, + this.idle = const SizedBox.shrink(), + }); + + static const Duration delay = Duration(seconds: 2); + + final bool active; + final Widget idle; + + @override + State createState() => _SlowLoginHintState(); +} + +class _SlowLoginHintState extends State { + Timer? _timer; + bool _shown = false; + + @override + void initState() { + super.initState(); + _sync(); + } + + @override + void didUpdateWidget(SlowLoginHint oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.active != widget.active) _sync(); + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + void _sync() { + _timer?.cancel(); + if (!widget.active) { + _shown = false; + return; + } + _timer = Timer(SlowLoginHint.delay, () { + if (mounted) setState(() => _shown = true); + }); + } + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + return AnimatedSwitcher( + duration: const Duration(milliseconds: 450), + switchInCurve: Curves.easeOutCubic, + switchOutCurve: Curves.easeInCubic, + layoutBuilder: (current, previous) => Stack( + alignment: AlignmentDirectional.centerStart, + children: [...previous, ?current], + ), + child: _shown + ? Text( + AppLocalizations.of(context)!.loginSlowSmsHint, + key: const ValueKey('slow'), + style: TextStyle( + color: cs.onSurfaceVariant, + fontSize: 13, + fontWeight: FontWeight.w500, + height: 1.35, + ), + ) + : KeyedSubtree(key: const ValueKey('idle'), child: widget.idle), + ); + } +} diff --git a/lib/frontend/screens/calls/call_mic_sheet.dart b/lib/frontend/screens/calls/call_mic_sheet.dart index 84020b84..148071e8 100644 --- a/lib/frontend/screens/calls/call_mic_sheet.dart +++ b/lib/frontend/screens/calls/call_mic_sheet.dart @@ -5,7 +5,7 @@ import '../../../core/calls/audio_devices.dart'; import '../../../core/calls/call_session.dart'; import '../../../core/calls/pulse_audio.dart'; import '../../../core/config/app_fonts.dart'; -import '../../../core/config/call_no_mute.dart'; +import '../../../core/config/launch_flags.dart'; import '../../../l10n/app_localizations.dart'; import '../../widgets/custom_notification.dart'; import '../../widgets/sheet_helpers.dart'; @@ -135,7 +135,7 @@ class _MicrophoneSheetState extends State<_MicrophoneSheet> { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ _header(cs, l10n), - if (CallNoMute.enabled) _noMuteHint(cs, l10n), + if (LaunchFlags.noMute) _noMuteHint(cs, l10n), if (options == null) const Padding( padding: EdgeInsets.symmetric(vertical: 24), diff --git a/lib/frontend/screens/calls/call_screen.dart b/lib/frontend/screens/calls/call_screen.dart index 08386198..74f68ac0 100644 --- a/lib/frontend/screens/calls/call_screen.dart +++ b/lib/frontend/screens/calls/call_screen.dart @@ -15,7 +15,7 @@ import '../../../core/calls/call_controller.dart'; import '../../../core/calls/call_info.dart'; import '../../../core/calls/call_session.dart'; import '../../../core/config/app_colors.dart'; -import '../../../core/config/call_no_mute.dart'; +import '../../../core/config/launch_flags.dart'; import '../../../core/utils/format.dart'; import '../../../core/utils/screen_wake.dart'; import '../../../l10n/app_localizations.dart'; @@ -1311,7 +1311,7 @@ class _CallScreenState extends State with TickerProviderStateMixin { slashedIcon: Symbols.mic_off, slashed: _isMuted, label: _isMuted - ? (CallNoMute.enabled ? l10n.callMicStillLive : l10n.callUnmute) + ? (LaunchFlags.noMute ? l10n.callMicStillLive : l10n.callUnmute) : l10n.callMute, background: _isMuted ? cs.primary : cs.surfaceContainerHighest, foreground: _isMuted ? cs.onPrimary : cs.onSurface, diff --git a/lib/frontend/screens/calls/calls_tab.dart b/lib/frontend/screens/calls/calls_tab.dart index e66cdf26..4885648b 100644 --- a/lib/frontend/screens/calls/calls_tab.dart +++ b/lib/frontend/screens/calls/calls_tab.dart @@ -16,6 +16,7 @@ import '../../widgets/chat_menu_overlay.dart'; import '../../widgets/small_spinner.dart'; import '../../widgets/prompt_dialog.dart'; import '../../widgets/call_link_handler.dart'; +import '../../widgets/direct_call.dart'; import '../../widgets/spectrum_tint.dart'; import '../../../l10n/app_localizations.dart'; import 'call_link_sheet.dart'; @@ -23,7 +24,9 @@ import 'call_screen.dart'; import '../../../core/config/app_fonts.dart'; class CallsTab extends StatefulWidget { - const CallsTab({super.key}); + const CallsTab({super.key, this.bottomPadding = 120}); + + final double bottomPadding; @override State createState() => _CallsTabState(); @@ -87,19 +90,7 @@ class _CallsTabState extends State grouped.last.status == call.status && _isSameDay(grouped.last.time, call.time)) { final last = grouped.removeLast(); - grouped.add( - CallLogEntry( - id: last.id, - accountId: last.accountId, - peerId: last.peerId, - name: last.name, - avatarUrl: last.avatarUrl, - status: last.status, - time: last.time, - count: last.count + 1, - isGroup: last.isGroup, - ), - ); + grouped.add(last.withCount(last.count + 1)); } else { grouped.add(call); } @@ -161,7 +152,7 @@ class _CallsTabState extends State return Material( color: Colors.transparent, child: InkWell( - onTap: call.isGroup ? null : () => _callBack(call), + onTap: call.canCallBack ? () => _callBack(call) : null, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12), child: Row( @@ -271,7 +262,7 @@ class _CallsTabState extends State destructive: true, onTap: () => _deleteCall(call), ), - if (!call.isGroup) + if (call.canCallBack) ChatMenuItem( icon: Symbols.call, label: l10n.callsTabCallBack, @@ -299,49 +290,12 @@ class _CallsTabState extends State } Future _callBack(CallLogEntry call) async { - if (call.peerId <= 0) { - showCustomNotification( - context, - AppLocalizations.of(context)!.callsTabPeerUnknown, - ); - return; - } - final navigator = Navigator.of(context); - final avatarUrl = (call.avatarUrl?.isNotEmpty ?? false) - ? call.avatarUrl - : null; - final active = CallController.instance.activeSession; - if (active != null) { - await navigator.push( - MaterialPageRoute( - builder: (_) => CallScreen( - name: call.name, - avatarUrl: avatarUrl, - session: active, - ), - ), - ); - return; - } - try { - final session = await CallController.instance.startOutgoing(call.peerId); - if (!mounted) return; - await navigator.push( - MaterialPageRoute( - builder: (_) => CallScreen( - name: call.name, - avatarUrl: avatarUrl, - session: session, - ), - ), - ); - } catch (_) { - if (!mounted) return; - showCustomNotification( - context, - AppLocalizations.of(context)!.chatInfoCallFailed, - ); - } + await startDirectCall( + context, + peerId: call.peerId, + name: call.name, + avatarUrl: (call.avatarUrl?.isNotEmpty ?? false) ? call.avatarUrl : null, + ); } Widget _buildLinkAction( @@ -556,7 +510,7 @@ class _CallsTabState extends State ) : ListView.builder( physics: const BouncingScrollPhysics(), - padding: const EdgeInsets.only(bottom: 120), + padding: EdgeInsets.only(bottom: widget.bottomPadding), itemCount: filteredCalls.length, itemBuilder: (context, index) { final call = filteredCalls[index]; diff --git a/lib/frontend/screens/chats/chat/view/message_row_widgets.dart b/lib/frontend/screens/chats/chat/view/message_row_widgets.dart index 75950040..56f3ba99 100644 --- a/lib/frontend/screens/chats/chat/view/message_row_widgets.dart +++ b/lib/frontend/screens/chats/chat/view/message_row_widgets.dart @@ -16,7 +16,6 @@ import 'package:komet/core/crypto/message_decryption_cache.dart'; import 'package:komet/core/utils/haptics.dart'; import 'package:komet/core/utils/text_format.dart'; import 'package:komet/frontend/widgets/animated_text_swap.dart'; -import 'package:komet/frontend/widgets/directional_drag_recognizer.dart'; import 'package:komet/frontend/widgets/liquid_glass.dart'; import 'package:komet/frontend/widgets/message_actions_overlay.dart' show @@ -32,120 +31,6 @@ import 'package:komet/main.dart' show animojiModule; import 'package:komet/models/animoji.dart' show Animoji; import 'package:komet/models/chat_reaction_settings.dart'; -class SwipeToReply extends StatefulWidget { - final Widget child; - final bool isMe; - final VoidCallback onReply; - - const SwipeToReply({ - super.key, - required this.child, - required this.isMe, - required this.onReply, - }); - - @override - State createState() => _SwipeToReplyState(); -} - -class _SwipeToReplyState extends State - with SingleTickerProviderStateMixin { - static const double _maxDrag = 72.0; - static const double _triggerThreshold = 56.0; - - late final AnimationController _springBack; - double _dragX = 0.0; - double _springFrom = 0.0; - bool _triggered = false; - - @override - void initState() { - super.initState(); - _springBack = - AnimationController( - vsync: this, - duration: const Duration(milliseconds: 200), - )..addListener(() { - final t = Curves.easeOut.transform(_springBack.value); - setState(() => _dragX = _springFrom * (1 - t)); - }); - } - - @override - void dispose() { - _springBack.dispose(); - super.dispose(); - } - - void _onDragUpdate(DragUpdateDetails d) { - if (_springBack.isAnimating) _springBack.stop(); - var next = _dragX + d.delta.dx; - if (next > 0) next = 0; - if (next < -_maxDrag) next = -_maxDrag; - final wasTriggered = _triggered; - _triggered = next <= -_triggerThreshold; - if (_triggered && !wasTriggered) Haptics.medium(); - setState(() => _dragX = next); - } - - void _onDragEnd(DragEndDetails d) { - if (_triggered) widget.onReply(); - _settle(); - } - - void _onDragCancel() => _settle(); - - void _settle() { - _triggered = false; - _springFrom = _dragX; - _springBack.forward(from: 0); - } - - @override - Widget build(BuildContext context) { - final cs = Theme.of(context).colorScheme; - final progress = (-_dragX / _triggerThreshold).clamp(0.0, 1.0); - return RawGestureDetector( - behavior: HitTestBehavior.opaque, - gestures: { - LeftwardDragRecognizer: - GestureRecognizerFactoryWithHandlers( - () => LeftwardDragRecognizer(debugOwner: this), - (instance) { - instance - ..onUpdate = _onDragUpdate - ..onEnd = _onDragEnd - ..onCancel = _onDragCancel; - }, - ), - }, - child: Stack( - alignment: Alignment.centerRight, - children: [ - Positioned( - right: 16, - child: Opacity( - opacity: progress, - child: Transform.scale( - scale: 0.6 + 0.4 * progress, - child: Container( - padding: const EdgeInsets.all(6), - decoration: BoxDecoration( - color: cs.surfaceContainerHighest, - shape: BoxShape.circle, - ), - child: Icon(Symbols.reply, size: 20, color: cs.primary), - ), - ), - ), - ), - Transform.translate(offset: Offset(_dragX, 0), child: widget.child), - ], - ), - ); - } -} - class PinnedMessageBanner extends StatelessWidget { final String? text; final bool isPreview; diff --git a/lib/frontend/screens/chats/chat_info_screen.dart b/lib/frontend/screens/chats/chat_info_screen.dart index f66dfd51..cdcbbffb 100644 --- a/lib/frontend/screens/chats/chat_info_screen.dart +++ b/lib/frontend/screens/chats/chat_info_screen.dart @@ -15,7 +15,6 @@ import '../../../backend/modules/complaints.dart'; import '../../../backend/modules/contacts.dart'; import '../../../backend/modules/messages.dart' show ContactCache; import '../../../core/cache/info_cache.dart'; -import '../../../core/calls/call_controller.dart'; import '../../../core/config/app_show_extra_info.dart'; import '../../../core/config/app_stories.dart'; import '../../../core/protocol/packet.dart'; @@ -37,6 +36,7 @@ import '../../widgets/photo_viewer.dart'; import '../../widgets/chat_info/shared_content_tabs.dart'; import '../../widgets/connection_status.dart'; import '../../widgets/custom_notification.dart'; +import '../../widgets/direct_call.dart'; import '../../widgets/hint_bubble.dart'; import 'chat_removal_undo.dart'; import '../../widgets/formatted_message_text.dart'; @@ -48,7 +48,6 @@ import '../../widgets/profile_hero.dart'; import '../../widgets/swipe_route.dart'; import '../../widgets/local_avatar_builder.dart'; import '../../../backend/modules/chats.dart'; -import '../calls/call_screen.dart'; import '../contacts/open_contact_profile.dart'; import '../profile/profile_qr_sheet.dart'; import '../stories/story_owner_info.dart'; @@ -1536,38 +1535,12 @@ class _ChatInfoScreenState extends State ); if (!mounted || !choice.confirmed) return; - final navigator = Navigator.of(context); - final avatarUrl = _chatImageUrl.isNotEmpty ? _chatImageUrl : null; - final active = CallController.instance.activeSession; - if (active != null) { - await navigator.push( - MaterialPageRoute( - builder: (_) => CallScreen( - name: _customName, - avatarUrl: avatarUrl, - session: active, - ), - ), - ); - return; - } - - try { - final session = await CallController.instance.startOutgoing(peerId); - if (!mounted) return; - await navigator.push( - MaterialPageRoute( - builder: (_) => CallScreen( - name: _customName, - avatarUrl: avatarUrl, - session: session, - ), - ), - ); - } catch (_) { - if (!mounted) return; - showCustomNotification(context, l10n.chatInfoCallFailed); - } + await startDirectCall( + context, + peerId: peerId, + name: _customName, + avatarUrl: _chatImageUrl.isNotEmpty ? _chatImageUrl : null, + ); } Future _leaveChat() async { diff --git a/lib/frontend/screens/chats/chat_list_screen.dart b/lib/frontend/screens/chats/chat_list_screen.dart index 68c638a5..dacc2a05 100644 --- a/lib/frontend/screens/chats/chat_list_screen.dart +++ b/lib/frontend/screens/chats/chat_list_screen.dart @@ -30,6 +30,7 @@ import '../../widgets/sheet_helpers.dart'; import '../../widgets/swipe_route.dart'; import '../../widgets/toast_placement.dart'; import '../../widgets/sliding_pill_nav.dart'; +import '../../widgets/compact_bottom_navigation_bar.dart'; import '../../widgets/springy_tap.dart'; import '../../widgets/visible_page_tickers.dart'; import '../../widgets/informer_banner_tile.dart'; @@ -71,6 +72,7 @@ import '../../../core/config/app_animations.dart'; import '../../../core/config/app_frost.dart'; import '../../../core/config/app_spectrum_background.dart'; import '../../../core/config/app_nav_pill_style.dart'; +import '../../../core/config/app_bottom_navigation_style.dart'; import '../../../core/cache/info_cache.dart'; import '../../../core/config/app_visual_style.dart'; import '../../../core/config/app_stories.dart'; @@ -1088,7 +1090,7 @@ class _ChatListScreenState extends State void _maybeLoadStories() { if (!AppStories.current.value) return; - if (api.state != SessionState.online) return; + if (api.state != SessionState.online || !accountModule.isLoggedIn) return; unawaited(storiesModule.loadFeed()); } @@ -2222,50 +2224,12 @@ class _ChatListScreenState extends State ), child: _showFoldersShimmer ? FolderStripShimmer(shimmer: _shimmerController) - : LayoutBuilder( - builder: (context, constraints) { - final availableWidth = constraints.maxWidth - 40; - final folderCount = _folders.length; - final minWidthPerFolder = 80.0; - final totalMinWidth = - folderCount * minWidthPerFolder + - (folderCount - 1) * 8; - final needsScroll = totalMinWidth > availableWidth; - - if (needsScroll) { - return ListView( - scrollDirection: Axis.horizontal, - padding: const EdgeInsets.symmetric( - horizontal: 20, - vertical: 2, - ), - physics: const BouncingScrollPhysics(), - children: [ - for (var i = 0; i < _folders.length; i++) ...[ - if (i > 0) const SizedBox(width: 8), - _buildFolderChip(_folders[i], i), - ], - ], - ); - } else { - return Padding( - padding: const EdgeInsets.symmetric( - horizontal: 20, - vertical: 2, - ), - child: Row( - children: [ - for (var i = 0; i < _folders.length; i++) ...[ - if (i > 0) const SizedBox(width: 8), - Expanded( - child: _buildFolderChip(_folders[i], i), - ), - ], - ], - ), - ); - } - }, + : ValueListenableBuilder( + valueListenable: chats.chatsChanged, + builder: (context, _, _) => LayoutBuilder( + builder: (context, constraints) => + _buildFolderStrip(constraints.maxWidth), + ), ), ), ), @@ -2506,10 +2470,23 @@ class _ChatListScreenState extends State }, ), ), - SliverPadding( - padding: EdgeInsets.only( - bottom: MediaQuery.viewPaddingOf(context).bottom + 100, - ), + ValueListenableBuilder( + valueListenable: AppBottomNavigationStyle.current, + builder: (context, style, _) { + final compact = style == BottomNavigationStyle.compact; + final keyboardVisible = + MediaQuery.viewInsetsOf(context).bottom > 0; + final bottom = compact && keyboardVisible + ? 12.0 + : MediaQuery.viewPaddingOf(context).bottom + + (compact + ? CompactBottomNavigationBar.contentHeight( + context, + ) + + 12 + : 100); + return SliverPadding(padding: EdgeInsets.only(bottom: bottom)); + }, ), ], ), @@ -2684,6 +2661,13 @@ class _ChatListScreenState extends State if (widget.archiveMode) { return _buildArchiveScaffold(cs); } + return ValueListenableBuilder( + valueListenable: AppBottomNavigationStyle.current, + builder: (context, style, _) => _buildMainScaffold(cs, style), + ); + } + + Widget _buildMainScaffold(ColorScheme cs, BottomNavigationStyle navStyle) { return Scaffold( backgroundColor: cs.surface, body: SafeArea( @@ -2708,6 +2692,16 @@ class _ChatListScreenState extends State ); } final bottomInset = MediaQuery.viewPaddingOf(context).bottom; + final compactNav = navStyle == BottomNavigationStyle.compact; + final keyboardVisible = MediaQuery.viewInsetsOf(context).bottom > 0; + final compactHeight = CompactBottomNavigationBar.contentHeight( + context, + ); + final contentBottomPadding = compactNav + ? (keyboardVisible ? 12.0 : bottomInset + compactHeight + 12) + : 120.0; + final fabBottom = + bottomInset + (compactNav ? compactHeight + 12 : 90); final pageW = constraints.maxWidth; final pageH = constraints.maxHeight; final navInnerW = pageW - 20; @@ -2789,9 +2783,22 @@ class _ChatListScreenState extends State crossAxisAlignment: CrossAxisAlignment.stretch, children: [ page(0, _getChatsBody()), - page(1, const CallsTab()), - page(2, const ContactsTab()), - page(3, const SettingsTab()), + page( + 1, + CallsTab(bottomPadding: contentBottomPadding), + ), + page( + 2, + ContactsTab( + bottomPadding: contentBottomPadding, + ), + ), + page( + 3, + SettingsTab( + bottomPadding: contentBottomPadding, + ), + ), ], ), builder: (context, child) { @@ -2809,7 +2816,25 @@ class _ChatListScreenState extends State ), ), ), - _buildDockedBottomNav(cs, navInnerW, bottomInset), + if (compactNav) ...[ + if (!_isSelectionMode) + Positioned( + left: 0, + right: 0, + bottom: 0, + child: ToastObstruction( + child: CompactBottomNavigationBar( + items: _chatsNavItems(AppLocalizations.of(context)!), + currentIndex: _currentNavIndex, + onTap: _onNavTabSelected, + onItemLongPress: (index, position) { + if (index == 3) _openAccountSwitcher(position); + }, + ), + ), + ), + ] else + _buildDockedBottomNav(cs, navInnerW, bottomInset), AnimatedBuilder( animation: Listenable.merge([ _fabController, @@ -2822,6 +2847,7 @@ class _ChatListScreenState extends State ); final showChatsFab = !_isSelectionMode && + !(compactNav && keyboardVisible) && (_navDragging || _navPageAnimController.isAnimating ? pageDisplayT < 1.0 : _currentNavIndex == 0); @@ -2847,7 +2873,7 @@ class _ChatListScreenState extends State if (_fabController.value > 0) Positioned( right: 20, - bottom: bottomInset + 90 + 74, + bottom: fabBottom + 74, child: RepaintBoundary( child: Transform.scale( scale: val, @@ -2861,7 +2887,7 @@ class _ChatListScreenState extends State ), Positioned( right: 20, - bottom: bottomInset + 90, + bottom: fabBottom, child: ToastObstruction( child: ValueListenableBuilder( valueListenable: AppVisualStyle.current, @@ -2885,7 +2911,9 @@ class _ChatListScreenState extends State : null, liquid: liquid, backdropKey: _frostBackdrop, - borderRadius: BorderRadius.circular(28), + borderRadius: BorderRadius.circular( + 28, + ), elevated: true, depth: 12, child: child!, @@ -3286,8 +3314,97 @@ class _ChatListScreenState extends State return (total: total, loud: loud); } - Widget _buildFolderChip(ChatFolder folder, int pageIndex) { + static const double _folderStripInset = 20; + static const double _folderChipGap = 8; + static const double _folderChipPadding = 12; + static const double _folderBadgeGap = 6; + static const TextStyle _folderChipTextStyle = TextStyle( + fontSize: 13, + fontWeight: FontWeight.w500, + ); + static const TextStyle _countBadgeTextStyle = TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + height: 1.1, + ); + + Widget _buildFolderStrip(double maxWidth) { + final unread = [ + for (var i = 0; i < _folders.length; i++) + _liveUnread(_chatsForPageIndex(i)), + ]; + final widths = [ + for (var i = 0; i < _folders.length; i++) + _folderChipWidth(_folders[i], _badgeLabel(unread[i].total)), + ]; + final used = + widths.fold(0.0, (sum, w) => sum + w) + + _folderChipGap * (_folders.length - 1) + + _folderStripInset * 2; + final free = maxWidth - used; + const padding = EdgeInsets.symmetric( + horizontal: _folderStripInset, + vertical: 2, + ); + final chips = [ + for (var i = 0; i < _folders.length; i++) ...[ + if (i > 0) const SizedBox(width: _folderChipGap), + free < 0 + ? _buildFolderChip(_folders[i], unread[i]) + : SizedBox( + width: widths[i] + free / _folders.length, + child: _buildFolderChip(_folders[i], unread[i]), + ), + ], + ]; + if (free < 0) { + return ListView( + scrollDirection: Axis.horizontal, + padding: padding, + physics: const BouncingScrollPhysics(), + children: chips, + ); + } + return Padding( + padding: padding, + child: Row(children: chips), + ); + } + + static String? _badgeLabel(int total) => + total <= 0 ? null : (total > 99 ? '99+' : '$total'); + + double _folderChipWidth(ChatFolder folder, String? badge) { + final base = DefaultTextStyle.of(context).style; + final scaler = MediaQuery.textScalerOf(context); + final direction = Directionality.of(context); + double measure(String text, TextStyle style) { + final painter = TextPainter( + text: TextSpan(text: text, style: base.merge(style)), + textDirection: direction, + textScaler: scaler, + maxLines: 1, + )..layout(); + final width = painter.width; + painter.dispose(); + return width.ceilToDouble(); + } + + var width = + _folderChipPadding * 2 + + measure(_folderChipLabel(folder), _folderChipTextStyle) + + 2; + if (badge != null) { + width += + _folderBadgeGap + + max(20.0, measure(badge, _countBadgeTextStyle) + 12); + } + return width; + } + + Widget _buildFolderChip(ChatFolder folder, ({int total, int loud}) unread) { final cs = Theme.of(context).colorScheme; + final badge = _badgeLabel(unread.total); final folderId = folder.id; final isSelected = _selectedFolderId == folderId; return GestureDetector( @@ -3299,7 +3416,10 @@ class _ChatListScreenState extends State child: GlossyPill( color: isSelected ? cs.primaryContainer : cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(50), - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + padding: const EdgeInsets.symmetric( + horizontal: _folderChipPadding, + vertical: 4, + ), depth: 4, child: Center( child: Row( @@ -3310,30 +3430,16 @@ class _ChatListScreenState extends State _folderChipLabel(folder), textAlign: TextAlign.center, overflow: TextOverflow.ellipsis, - style: TextStyle( + style: _folderChipTextStyle.copyWith( color: isSelected ? cs.onPrimaryContainer : cs.primary, - fontSize: 13, - fontWeight: FontWeight.w500, ), ), ), - ValueListenableBuilder( - valueListenable: chats.chatsChanged, - builder: (context, _, _) { - final (:total, :loud) = _liveUnread( - _chatsForPageIndex(pageIndex), - ); - if (total <= 0) return const SizedBox.shrink(); - return Padding( - padding: const EdgeInsets.only(left: 6), - child: _countBadge( - cs, - total > 99 ? '99+' : '$total', - muted: loud == 0, - ), - ); - }, - ), + if (badge != null) + Padding( + padding: const EdgeInsets.only(left: _folderBadgeGap), + child: _countBadge(cs, badge, muted: unread.loud == 0), + ), ], ), ), @@ -3443,11 +3549,8 @@ class _ChatListScreenState extends State child: Text( label, textAlign: TextAlign.center, - style: TextStyle( + style: _countBadgeTextStyle.copyWith( color: muted ? cs.outline : cs.onPrimary, - fontSize: 11, - fontWeight: FontWeight.w600, - height: 1.1, ), ), ); diff --git a/lib/frontend/screens/chats/chat_screen.dart b/lib/frontend/screens/chats/chat_screen.dart index 0468e91f..6f2be225 100644 --- a/lib/frontend/screens/chats/chat_screen.dart +++ b/lib/frontend/screens/chats/chat_screen.dart @@ -40,7 +40,6 @@ import '../../../models/animoji.dart'; import '../../../backend/modules/complaints.dart'; import '../../../core/calls/call_controller.dart'; import '../../../core/media/tlottie/tlottie.dart'; -import '../calls/call_screen.dart'; import '../../../core/protocol/opcode_map.dart'; import '../../../core/protocol/packet.dart'; import '../../../core/push/notification_bridge.dart'; @@ -106,6 +105,7 @@ import '../../widgets/confirm_dialog.dart'; import '../../widgets/rich_message_controller.dart'; import '../../../core/utils/text_format.dart'; import '../../widgets/call_link_handler.dart'; +import '../../widgets/direct_call.dart'; import '../../widgets/connection_status.dart'; import '../../widgets/message_bubble.dart'; import '../../widgets/photo_viewer.dart'; @@ -117,6 +117,8 @@ import '../../widgets/attachment/paste_preview_sheet.dart'; import '../../widgets/sticker_pack_sheet.dart'; import '../../widgets/swipe_to_pop.dart'; import '../../widgets/swipe_route.dart'; +import '../../widgets/swipe_to_reply.dart'; +import '../../widgets/scroll_keyboard_dismiss.dart'; import '../../widgets/reload_on_reconnect.dart'; import '../../widgets/schedule_time_picker.dart'; import '../../widgets/chat_wallpaper_sheet.dart'; @@ -3652,51 +3654,20 @@ class _ChatScreenState extends State } Future _startCall() async { - if (widget.chatType != 'DIALOG' || _peerIsBot) { + if (widget.chatType != 'DIALOG') { showCustomNotification( context, AppLocalizations.of(context)!.chatScreenCallsDialogsOnly, ); return; } - // Звонок уже идёт (возможно, свёрнут) — просто открываем его экран снова. - final navigator = Navigator.of(context); - final active = CallController.instance.activeSession; - if (active != null) { - await navigator.push( - MaterialPageRoute( - builder: (_) => CallScreen( - name: widget.name, - avatarUrl: widget.imageUrl.isNotEmpty ? widget.imageUrl : null, - session: active, - ), - ), - ); - _onCallScreenClosed(); - return; - } - final peerId = widget.chatId ^ _myId; - if (peerId <= 0) return; - try { - final session = await CallController.instance.startOutgoing(peerId); - if (!mounted) return; - await navigator.push( - MaterialPageRoute( - builder: (_) => CallScreen( - name: widget.name, - avatarUrl: widget.imageUrl.isNotEmpty ? widget.imageUrl : null, - session: session, - ), - ), - ); - _onCallScreenClosed(); - } catch (_) { - if (!mounted) return; - showCustomNotification( - context, - AppLocalizations.of(context)!.chatInfoCallFailed, - ); - } + final shown = await startDirectCall( + context, + peerId: widget.chatId ^ _myId, + name: widget.name, + avatarUrl: widget.imageUrl.isNotEmpty ? widget.imageUrl : null, + ); + if (shown) _onCallScreenClosed(); } void _onCallScreenClosed() { @@ -4814,7 +4785,10 @@ class _ChatScreenState extends State } return false; }, - child: _buildMessagesList(), + child: ScrollKeyboardDismiss( + onDismiss: _messageFocusNode.unfocus, + child: _buildMessagesList(), + ), ), ), if (showShimmer) @@ -5126,7 +5100,6 @@ class _ChatScreenState extends State !_canReply) ? pressable : SwipeToReply( - isMe: isMe, onReply: () => _textSend.startReply(message), child: pressable, ); diff --git a/lib/frontend/screens/chats/share_composer_bar.dart b/lib/frontend/screens/chats/share_composer_bar.dart index a6446ffb..66d9a3b9 100644 --- a/lib/frontend/screens/chats/share_composer_bar.dart +++ b/lib/frontend/screens/chats/share_composer_bar.dart @@ -316,16 +316,35 @@ class _ShareThumb extends StatelessWidget { ), clipBehavior: Clip.antiAlias, child: provider != null - ? Image(image: provider, fit: BoxFit.cover) - : Icon( - file.kind == SharedFileKind.video - ? Symbols.movie - : Symbols.description, - size: 20, - color: cs.onSurfaceVariant, - ), + ? Image( + image: provider, + fit: BoxFit.cover, + errorBuilder: (_, _, _) => _localPhotoOrIcon(), + ) + : _localPhotoOrIcon(), + ); + } + + Widget _localPhotoOrIcon() { + if (file.kind != SharedFileKind.photo) return _icon(); + return Image.file( + file.file, + fit: BoxFit.cover, + cacheWidth: 128, + gaplessPlayback: true, + errorBuilder: (_, _, _) => _icon(), ); } + + Widget _icon() => Icon( + switch (file.kind) { + SharedFileKind.photo => Symbols.image, + SharedFileKind.video => Symbols.movie, + SharedFileKind.file => Symbols.description, + }, + size: 20, + color: cs.onSurfaceVariant, + ); } class _SendButton extends StatelessWidget { diff --git a/lib/frontend/screens/contacts/contacts_tab.dart b/lib/frontend/screens/contacts/contacts_tab.dart index efec1137..3c2be909 100644 --- a/lib/frontend/screens/contacts/contacts_tab.dart +++ b/lib/frontend/screens/contacts/contacts_tab.dart @@ -2,7 +2,7 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:material_symbols_icons/symbols.dart'; -import '../../../core/config/debug_test.dart'; +import '../../../core/config/launch_flags.dart'; import '../../../core/config/ios_release.dart'; import '../../../core/contacts/contact_labels.dart'; import '../../../core/contacts/device_contacts_service.dart'; @@ -26,7 +26,9 @@ import '../../../core/config/app_frost.dart'; import '../../../core/config/app_fonts.dart'; class ContactsTab extends StatefulWidget { - const ContactsTab({super.key}); + const ContactsTab({super.key, this.bottomPadding = 120}); + + final double bottomPadding; @override State createState() => _ContactsTabState(); @@ -122,7 +124,7 @@ class _ContactsTabState extends State with SpectrumSurface { } Future _loadContacts() async { - if (DebugTest.enabled) { + if (LaunchFlags.debugTest) { final debug = ContactsModule.debugContacts() ..sort((a, b) => a.firstName.compareTo(b.firstName)); if (mounted) { @@ -440,7 +442,7 @@ class _ContactsTabState extends State with SpectrumSurface { physics: const BouncingScrollPhysics(), keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, - padding: const EdgeInsets.only(bottom: 120), + padding: EdgeInsets.only(bottom: widget.bottomPadding), itemCount: visible.length, itemBuilder: (context, index) => _buildContactItem(context, cs, visible[index]), diff --git a/lib/frontend/screens/lock/app_lock_layer.dart b/lib/frontend/screens/lock/app_lock_layer.dart index c1fdaa67..dac3472c 100644 --- a/lib/frontend/screens/lock/app_lock_layer.dart +++ b/lib/frontend/screens/lock/app_lock_layer.dart @@ -23,6 +23,7 @@ class AppLockLayer extends StatefulWidget { class _AppLockLayerState extends State with TickerProviderStateMixin { static const Duration _enterDuration = Duration(milliseconds: 620); + static const Duration _softEnterDuration = Duration(milliseconds: 450); static const Duration _exitDuration = Duration(milliseconds: 300); static const Duration _openDuration = Duration(milliseconds: 240); @@ -38,6 +39,7 @@ class _AppLockLayerState extends State ); bool _shown = false; bool _covered = false; + bool _animateIn = false; Rect? _origin; @override @@ -66,19 +68,31 @@ class _AppLockLayerState extends State super.dispose(); } + bool get _canAnimateLock { + final state = WidgetsBinding.instance.lifecycleState; + final foreground = state == null || state == AppLifecycleState.resumed; + return foreground && + !(MediaQuery.maybeDisableAnimationsOf(context) ?? false); + } + void _onLockedChanged() { if (_lock.locked.value) { _opening.value = 0; final origin = _lock.takeOrigin(); + final animate = _canAnimateLock; setState(() { _shown = true; - _origin = origin; + _origin = animate ? origin : null; + _animateIn = animate; }); - if (origin == null) { + if (!animate) { _presence.value = 1; _onPresenceStatus(_presence.status); - } else { + } else if (origin != null) { _presence.forward(from: 0); + } else { + _presence.value = 0; + _presence.animateTo(1, duration: _softEnterDuration); } return; } @@ -94,6 +108,7 @@ class _AppLockLayerState extends State setState(() { _shown = false; _origin = null; + _animateIn = false; }); } @@ -118,6 +133,7 @@ class _AppLockLayerState extends State presence: _presence, opening: _opening, origin: _origin, + animateIn: _animateIn, ), ), ], @@ -129,11 +145,13 @@ class _LockScreen extends StatefulWidget { final AnimationController presence; final AnimationController opening; final Rect? origin; + final bool animateIn; const _LockScreen({ required this.presence, required this.opening, required this.origin, + required this.animateIn, }); @override @@ -299,7 +317,7 @@ class _LockScreenState extends State<_LockScreen> with WidgetsBindingObserver { Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; final l10n = AppLocalizations.of(context)!; - final animated = widget.origin != null; + final animated = widget.animateIn; final background = animated ? _interval(0, 0.45) : const AlwaysStoppedAnimation(1); diff --git a/lib/frontend/screens/profile/appearance_screen.dart b/lib/frontend/screens/profile/appearance_screen.dart index d0e5211c..9911b8ff 100644 --- a/lib/frontend/screens/profile/appearance_screen.dart +++ b/lib/frontend/screens/profile/appearance_screen.dart @@ -20,6 +20,7 @@ import '../../../l10n/app_localizations.dart'; import '../../../main.dart'; import '../../widgets/liquid_glass.dart'; import '../../widgets/settings_card.dart'; +import '../../widgets/bottom_navigation_style_card.dart'; import '../../../core/config/app_shape.dart'; import '../../../core/utils/seed_scheme.dart'; @@ -132,6 +133,8 @@ class _AppearanceScreenState extends State { const SizedBox(height: 12), const _ComposerBarCard(), const SizedBox(height: 12), + const BottomNavigationStyleCard(), + const SizedBox(height: 12), const _NavPillStyleCard(), const SizedBox(height: 12), const _GradientToggleCard(), @@ -603,7 +606,7 @@ class _PreviewSectionState extends State<_PreviewSection> { } _cachedColor = color; _cachedBrightness = brightness; - _cachedScheme = schemeFromSeed(color, brightness); + _cachedScheme = accentSchemeFromSeed(color, brightness); return _cachedScheme!; } @@ -850,7 +853,12 @@ class _ColorPickerCard extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ ColorWheelPicker( - color: swatchColor, + color: sys + ? HSVColor.fromColor( + cs.primary, + ).withValue(1).toColor() + : col, + minBrightness: kAccentMinBrightness, onChanged: onColorChanged, ), const SizedBox(height: 20), diff --git a/lib/frontend/screens/profile/language_screen.dart b/lib/frontend/screens/profile/language_screen.dart new file mode 100644 index 00000000..cbcb7250 --- /dev/null +++ b/lib/frontend/screens/profile/language_screen.dart @@ -0,0 +1,126 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:material_symbols_icons/symbols.dart'; + +import '../../../core/config/app_language.dart'; +import '../../../core/utils/haptics.dart'; +import '../../../l10n/app_localizations.dart'; +import '../../../main.dart'; +import '../../widgets/connection_status.dart'; +import '../../widgets/settings_card.dart'; + +class LanguageScreen extends StatelessWidget { + const LanguageScreen({super.key}); + + void _select(BuildContext context, String code) { + if (AppLanguage.current.value.languageCode == code) return; + Haptics.selection(); + unawaited(KometApp.stateOf(context)?.applyLocale(Locale(code))); + } + + Future _setAppliesToServer(bool value) async { + await AppLanguage.setAppliesToServer(value); + await accountModule.refreshServerLanguage(); + } + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + final languages = [ + ('ru', l10n.languageNameRu), + ('en', l10n.languageNameEn), + ]; + + return Scaffold( + backgroundColor: cs.surface, + appBar: ConnectionTitleBar( + titleText: l10n.loginLanguage, + backgroundColor: cs.surface, + ), + body: SafeArea( + top: false, + child: ListView( + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.fromLTRB(16, 12, 16, 120), + children: [ + ValueListenableBuilder( + valueListenable: AppLanguage.current, + builder: (context, locale, _) => SettingsCard( + children: [ + for (final (code, name) in languages) + _LanguageTile( + label: name, + selected: locale.languageCode == code, + onTap: () => _select(context, code), + ), + ], + ), + ), + const SizedBox(height: 20), + ValueListenableBuilder( + valueListenable: AppLanguage.appliesToServer, + builder: (context, value, _) => SettingsCard( + children: [ + SettingsToggleTile( + icon: Symbols.dns, + label: l10n.languageServerTitle, + subtitle: l10n.languageServerSubtitle, + value: value, + onChanged: (v) => unawaited(_setAppliesToServer(v)), + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +class _LanguageTile extends StatelessWidget { + final String label; + final bool selected; + final VoidCallback onTap; + + const _LanguageTile({ + required this.label, + required this.selected, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + return Material( + color: Colors.transparent, + child: InkWell( + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 17), + child: Row( + children: [ + Expanded( + child: Text( + label, + style: TextStyle( + color: cs.onSurface, + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + ), + AnimatedOpacity( + duration: const Duration(milliseconds: 180), + opacity: selected ? 1 : 0, + child: Icon(Symbols.check, color: cs.primary, size: 22), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/frontend/screens/profile/settings_tab.dart b/lib/frontend/screens/profile/settings_tab.dart index 6141113b..e2012d4e 100644 --- a/lib/frontend/screens/profile/settings_tab.dart +++ b/lib/frontend/screens/profile/settings_tab.dart @@ -47,6 +47,7 @@ import '../digital_id/digital_id_web_screen.dart'; import '../webapp/web_app_bridge.dart'; import '../webapp/web_app_screen.dart'; import 'avatar_carousel.dart'; +import 'language_screen.dart'; import 'cloud_storage_screen.dart'; import 'customization_section.dart'; import 'debug_menu_screen.dart'; @@ -64,7 +65,9 @@ import '../../../core/config/app_fonts.dart'; import '../../../core/config/app_shape.dart'; class SettingsTab extends StatefulWidget { - const SettingsTab({super.key}); + const SettingsTab({super.key, this.bottomPadding = 120}); + + final double bottomPadding; @override State createState() => _SettingsTabState(); @@ -100,6 +103,7 @@ class _SettingsTabState extends State Timer? _versionSecretTapResetTimer; StreamSubscription? _profileUpdateSub; bool _avatarsLoading = false; + bool _loggingOut = false; @override void reloadAfterReconnect() { @@ -495,6 +499,7 @@ class _SettingsTabState extends State } Future _confirmLogout() async { + if (_loggingOut) return; final cs = Theme.of(context).colorScheme; final l10n = AppLocalizations.of(context)!; final confirmed = await showModalBottomSheet( @@ -544,8 +549,13 @@ class _SettingsTabState extends State ); }, ); - if (confirmed != true || !mounted) return; - await _doLogout(); + if (confirmed != true || !mounted || _loggingOut) return; + _loggingOut = true; + try { + await _doLogout(); + } finally { + _loggingOut = false; + } } Future _doLogout() async { @@ -562,10 +572,6 @@ class _SettingsTabState extends State return; } await resetDigitalIdSession(); - try { - // #***! вышли из аккаунта — дальше экран входа по телефону, прошлая версия - await api.connect(authenticated: false); - } catch (_) {} if (navState != null) { await navState.pushAndRemoveUntil( MaterialPageRoute(builder: (_) => const LoginScreen()), @@ -717,6 +723,18 @@ class _SettingsTabState extends State ); }, ), + _SettingsItem( + icon: Symbols.translate, + label: l10n.loginLanguage, + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => const LanguageScreen(), + ), + ); + }, + ), _SettingsItem( icon: Symbols.videocam, label: l10n.mediaDevicesTitle, @@ -925,7 +943,9 @@ class _SettingsTabState extends State ), ), ), - const SliverToBoxAdapter(child: SizedBox(height: 120)), + SliverToBoxAdapter( + child: SizedBox(height: widget.bottomPadding), + ), ], ), ), @@ -1084,18 +1104,19 @@ class _SettingsTabState extends State Row( mainAxisSize: MainAxisSize.min, children: [ - IconButton( - key: _avatarMenuKey, - icon: Icon( - Symbols.more_vert, - color: iconColor, - size: 22, - weight: 400, + if (hasPhoto) + IconButton( + key: _avatarMenuKey, + icon: Icon( + Symbols.more_vert, + color: iconColor, + size: 22, + weight: 400, + ), + onPressed: _currentAvatar == null + ? null + : _openAvatarMenu, ), - onPressed: _currentAvatar == null - ? null - : _openAvatarMenu, - ), IconButton( icon: Icon( Symbols.edit, diff --git a/lib/frontend/screens/profile/theme_settings_screen.dart b/lib/frontend/screens/profile/theme_settings_screen.dart index 0b04e879..86b3318b 100644 --- a/lib/frontend/screens/profile/theme_settings_screen.dart +++ b/lib/frontend/screens/profile/theme_settings_screen.dart @@ -486,4 +486,3 @@ class _TimeRow extends StatelessWidget { if (picked != null) onPick(picked); } } - diff --git a/lib/frontend/screens/webapp/web_app_bridge.dart b/lib/frontend/screens/webapp/web_app_bridge.dart index 1ef60f1d..33e21a69 100644 --- a/lib/frontend/screens/webapp/web_app_bridge.dart +++ b/lib/frontend/screens/webapp/web_app_bridge.dart @@ -156,21 +156,28 @@ class WebAppBridge { required this.contextResolver, required this.viewportResolver, required this.onClose, + required this.onRestart, this.privateChannel = false, this.mobileIdVerifier, this.emitter, WebAppBiometry? biometry, - }) : biometry = biometry ?? DeviceWebAppBiometry(contextResolver); + String? Function()? deviceIdResolver, + }) : biometry = biometry ?? DeviceWebAppBiometry(contextResolver), + deviceIdResolver = deviceIdResolver ?? _sessionDeviceId; final int botId; final String entryPoint; final BuildContext? Function() contextResolver; final Size Function() viewportResolver; final VoidCallback onClose; + final VoidCallback onRestart; final bool privateChannel; final WebAppMobileIdVerifier? mobileIdVerifier; final WebAppEmitter? emitter; final WebAppBiometry biometry; + final String? Function() deviceIdResolver; + + static String? _sessionDeviceId() => api.deviceId; InAppWebViewController? _controller; DateTime? _lastGesture; @@ -601,14 +608,15 @@ class WebAppBridge { } Future> _biometryState(int? accountId) async { + final deviceId = deviceIdResolver(); if (accountId == null) { - return const { + return { 'available': false, - 'type': ['unknown'], + 'type': const ['unknown'], 'accessRequested': false, 'accessGranted': false, 'tokenSaved': false, - 'deviceId': null, + 'deviceId': deviceId, }; } final types = await biometry.types(); @@ -623,7 +631,7 @@ class WebAppBridge { 'accessRequested': requested, 'accessGranted': granted, 'tokenSaved': token != null, - 'deviceId': granted ? api.deviceId : null, + 'deviceId': deviceId, }; } @@ -696,11 +704,11 @@ class WebAppBridge { } final token = await WebAppStorage.biometryToken(accountId, botId); if (token == null) { - _fail(method, requestId, 'not_found', private: private); + _fail(method, requestId, 'token_not_found', private: private); return; } if (!await biometry.authenticate(_biometryReason(data))) { - _fail(method, requestId, 'auth_failed', private: private); + _fail(method, requestId, 'access_denied', private: private); return; } _send(method, { @@ -741,7 +749,7 @@ class WebAppBridge { return; } if (!await biometry.authenticate(_biometryReason(data))) { - _fail(method, requestId, 'auth_failed', private: private); + _fail(method, requestId, 'permission_denied', private: private); return; } await WebAppStorage.saveBiometryToken(accountId, botId, token); @@ -775,7 +783,7 @@ class WebAppBridge { granted: allowed, ); _ok(method, requestId, 'opened', private: private); - if (allowed != granted) onClose(); + if (allowed != granted) onRestart(); } Future _impact(String? style) async { diff --git a/lib/frontend/screens/webapp/web_app_screen.dart b/lib/frontend/screens/webapp/web_app_screen.dart index 32819c15..46bd9c53 100644 --- a/lib/frontend/screens/webapp/web_app_screen.dart +++ b/lib/frontend/screens/webapp/web_app_screen.dart @@ -128,6 +128,7 @@ class _WebAppScreenState extends State { contextResolver: () => mounted ? context : null, viewportResolver: () => _viewport, onClose: _closeFromWebApp, + onRestart: _restartFromWebApp, ); void _closeFromWebApp() { @@ -135,6 +136,11 @@ class _WebAppScreenState extends State { Navigator.of(context).pop(); } + void _restartFromWebApp() { + if (!mounted) return; + _load(); + } + Future _closeByUser() async { final bridge = _bridge; if (bridge != null && bridge.needsCloseConfirmation) { diff --git a/lib/frontend/widgets/adaptive_shell.dart b/lib/frontend/widgets/adaptive_shell.dart index ea6f873c..0d943580 100644 --- a/lib/frontend/widgets/adaptive_shell.dart +++ b/lib/frontend/widgets/adaptive_shell.dart @@ -7,7 +7,7 @@ import 'package:shared_preferences/shared_preferences.dart'; import '../../backend/modules/chats.dart'; import '../../core/config/build_profile.dart'; -import '../../core/config/debug_test.dart'; +import '../../core/config/launch_flags.dart'; import '../../core/utils/update_checker.dart'; import '../../l10n/app_localizations.dart'; import '../screens/chats/chat_list_screen.dart'; @@ -81,7 +81,7 @@ class _AdaptiveShellState extends State { Future _maybeCheckUpdate() async { if (!BuildProfile.selfUpdate) return; - if (DebugTest.enabled) return; + if (LaunchFlags.debugTest) return; final update = await UpdateChecker.check(); if (update == null || !mounted) return; await showUpdateDialog(context, update); diff --git a/lib/frontend/widgets/attachment/bubbles/file_bubble.dart b/lib/frontend/widgets/attachment/bubbles/file_bubble.dart index 1f9a7d5c..c4a08330 100644 --- a/lib/frontend/widgets/attachment/bubbles/file_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/file_bubble.dart @@ -27,21 +27,42 @@ import '../../share_unopenable_file.dart'; import '../../upload_progress_ring.dart'; import 'bubble_context.dart'; -class FileBubble extends StatelessWidget { - static const double _previewWidth = 240; - static const double _previewHeight = 160; - +typedef FileBubbleOpener = + Future Function( + String cacheName, + Future Function() resolveUrl, { + void Function(double progress)? onProgress, + void Function()? onReady, + DownloadMetadata? download, + }); + +class FileBubble extends StatefulWidget { final BubbleContext ctx; final FileAttachment file; final bool fill; + final FileBubbleOpener openFile; const FileBubble({ super.key, required this.ctx, required this.file, this.fill = false, + this.openFile = openCachedFile, }); + @override + State createState() => _FileBubbleState(); +} + +class _FileBubbleState extends State { + static const double _previewWidth = 240; + static const double _previewHeight = 160; + + bool _opening = false; + + BubbleContext get ctx => widget.ctx; + FileAttachment get file => widget.file; + @override Widget build(BuildContext context) { final isMe = ctx.isMe; @@ -62,176 +83,209 @@ class FileBubble extends StatelessWidget { encrypted: fileId != null && _isEncryptedImage(name), ); - final inner = Padding( - padding: const EdgeInsets.fromLTRB(14, 10, 14, 4), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - mainAxisSize: MainAxisSize.min, - children: [ - ?previewWidget, - Row( + return ListenableBuilder( + listenable: Listenable.merge([ + MediaCache.presence(cacheName), + MediaDownloadProgress.notifier(cacheName), + if (audioFile) MediaPlayback.instance.audioFile, + if (audioFile && AudioPlaybackController.isInitialized) + AudioPlaybackController.instance.playing, + ]), + builder: (context, _) { + final cached = MediaCache.presence(cacheName).value; + final progress = MediaDownloadProgress.notifier(cacheName).value; + final busy = _opening || progress != null; + final available = fileId != null && ctx.uploadProgress == null; + final status = progress != null + ? 'Загрузка ${(progress * 100).round()}%' + : _opening + ? 'Открытие…' + : cached + ? 'Открыть' + : available + ? 'Скачать' + : ctx.uploadProgress != null + ? 'Отправка…' + : 'Файл недоступен'; + final inner = Padding( + padding: const EdgeInsets.fromLTRB(14, 10, 14, 4), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.center, children: [ - Container( - width: 38, - height: 38, - decoration: BoxDecoration( - color: isMe ? ctx.systemTint : ctx.cs.primaryContainer, - borderRadius: BorderRadius.circular(10), - ), - child: ctx.uploadProgress == null - ? Icon( - audioFile ? Symbols.audio_file : Symbols.description, - color: isMe - ? ctx.cs.onPrimaryContainer - : ctx.cs.primary, - size: 20, - ) - : UploadProgressRing( - progress: ctx.uploadProgress!, - color: isMe - ? ctx.cs.onPrimaryContainer - : ctx.cs.primary, - size: 38, - strokeWidth: 2.4, - iconSize: 14, - padding: const EdgeInsets.all(4), - ), - ), - const SizedBox(width: 10), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Text( - name, - style: TextStyle( - color: ctx.text, - fontSize: 14, - fontWeight: FontWeight.w500, - height: 1.2, - ), - maxLines: 2, - overflow: TextOverflow.ellipsis, + ?previewWidget, + Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Container( + width: 38, + height: 38, + decoration: BoxDecoration( + color: isMe ? ctx.systemTint : ctx.cs.primaryContainer, + borderRadius: BorderRadius.circular(10), ), - const SizedBox(height: 2), - ValueListenableBuilder( - valueListenable: MediaDownloadProgress.notifier( - cacheName, - ), - builder: (context, progress, _) => Text( - progress != null - ? '${(progress * 100).round()}% · $sizeStr' - : sizeStr, - style: TextStyle( - color: ctx.dim, - fontSize: 12, - height: 1.2, - ), - ), - ), - ], - ), - ), - const SizedBox(width: 12), - ValueListenableBuilder( - valueListenable: MediaDownloadProgress.notifier(cacheName), - builder: (context, progress, _) { - final iconColor = isMe - ? ctx.cs.onPrimaryContainer - : ctx.cs.primary; - Widget circle(Widget child, VoidCallback? onTap) { - return GestureDetector( - onTap: onTap, - child: Container( - width: 34, - height: 34, - decoration: BoxDecoration( - color: isMe - ? ctx.systemTint - : ctx.cs.surfaceContainerHighest, - shape: BoxShape.circle, + child: ctx.uploadProgress == null + ? Icon( + audioFile + ? Symbols.audio_file + : Symbols.description, + color: isMe + ? ctx.cs.onPrimaryContainer + : ctx.cs.primary, + size: 20, + ) + : UploadProgressRing( + progress: ctx.uploadProgress!, + color: isMe + ? ctx.cs.onPrimaryContainer + : ctx.cs.primary, + size: 38, + strokeWidth: 2.4, + iconSize: 14, + padding: const EdgeInsets.all(4), + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + name, + style: TextStyle( + color: ctx.text, + fontSize: 14, + fontWeight: FontWeight.w500, + height: 1.2, + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, ), - child: child, - ), - ); - } - - if (progress != null) { - return circle( - Padding( - padding: const EdgeInsets.all(8), - child: CircularProgressIndicator( - strokeWidth: 2, - value: progress > 0 ? progress : null, - color: iconColor, + const SizedBox(height: 2), + Text( + '$status · $sizeStr', + style: TextStyle( + color: ctx.dim, + fontSize: 12, + height: 1.2, + ), ), + ], + ), + ), + const SizedBox(width: 12), + if (available) + Container( + width: 34, + height: 34, + decoration: BoxDecoration( + color: isMe + ? ctx.systemTint + : ctx.cs.surfaceContainerHighest, + shape: BoxShape.circle, ), - null, - ); - } - - return ValueListenableBuilder( - valueListenable: MediaCache.presence(cacheName), - builder: (context, cached, _) { - if (!audioFile) { - return circle( - Icon( - cached ? Symbols.check : Symbols.download, - color: iconColor, - size: 18, - ), - () => _downloadFile(ctx.context, file, name), - ); - } - Widget button(IconData icon) => circle( - Icon(icon, color: iconColor, size: 18, fill: 1), - () => _playAudioFile(ctx.context, file, name), - ); - return ValueListenableBuilder( - valueListenable: MediaPlayback.instance.audioFile, - builder: (context, track, _) { - if (!cached) return button(Symbols.download); - if (track?.cacheName != cacheName || - !AudioPlaybackController.isInitialized) { - return button(Symbols.play_arrow); - } - return ValueListenableBuilder( - valueListenable: - AudioPlaybackController.instance.playing, - builder: (context, playing, _) => button( - playing ? Symbols.pause : Symbols.play_arrow, + child: busy + ? Padding( + padding: const EdgeInsets.all(8), + child: CircularProgressIndicator( + strokeWidth: 2, + value: progress != null && progress > 0 + ? progress + : null, + color: isMe + ? ctx.cs.onPrimaryContainer + : ctx.cs.primary, + ), + ) + : Icon( + !cached + ? Symbols.download + : audioFile + ? MediaPlayback + .instance + .audioFile + .value + ?.cacheName == + cacheName && + AudioPlaybackController + .isInitialized && + AudioPlaybackController + .instance + .playing + .value + ? Symbols.pause + : Symbols.play_arrow + : Symbols.open_in_new, + color: isMe + ? ctx.cs.onPrimaryContainer + : ctx.cs.primary, + size: 18, ), - ); - }, - ); - }, - ); - }, + ), + ], ), + if (audioFile) + _AudioFilePlaybackControl( + cacheName: cacheName, + color: isMe ? ctx.cs.onPrimaryContainer : ctx.cs.primary, + textColor: ctx.dim, + ), + ctx.meta(), ], ), - if (audioFile) - _AudioFilePlaybackControl( - cacheName: cacheName, - color: isMe ? ctx.cs.onPrimaryContainer : ctx.cs.primary, - textColor: ctx.dim, - ), - ctx.meta(), - ], - ), - ); - final body = fill ? inner : IntrinsicWidth(child: inner); - if (!_isViewableImage(name)) return body; - return GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () => _openInViewer(ctx.context, name, cacheName), - child: body, + ); + final body = widget.fill ? inner : IntrinsicWidth(child: inner); + final onTap = available ? () => _activate(name, cacheName) : null; + return Semantics( + button: true, + enabled: available && !busy, + label: name, + value: '$status · $sizeStr', + hint: available && !busy + ? cached + ? 'Открыть файл' + : 'Скачать и открыть файл' + : null, + onTap: busy ? null : onTap, + excludeSemantics: !audioFile, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + excludeFromSemantics: true, + onTap: onTap, + child: body, + ), + ); + }, ); } + Future _activate(String name, String cacheName) async { + if (_opening || MediaDownloadProgress.notifier(cacheName).value != null) { + return; + } + setState(() => _opening = true); + try { + if (downloadKindForName(name) == DownloadKind.audio) { + await _playAudioFile(context, file, name); + } else if (_isViewableImage(name)) { + await _openInViewer(context, name, cacheName); + } else { + await _downloadFile(context, file, name); + } + } catch (_) { + if (mounted) { + showCustomNotification( + context, + AppLocalizations.of(context)!.fileBubbleOpenFailedReason, + ); + } + } finally { + if (mounted) setState(() => _opening = false); + } + } + static const Set _coverExtensions = { '.png', '.jpg', @@ -247,8 +301,9 @@ class FileBubble extends StatelessWidget { name.toLowerCase().endsWith('.png') || name.toLowerCase().endsWith('.kce'); - Uint8List? get _sealedTicket => - ctx.message.e2ee == CachedMessage.e2eeFile ? ctx.message.sealedText : null; + Uint8List? get _sealedTicket => ctx.message.e2ee == CachedMessage.e2eeFile + ? ctx.message.sealedText + : null; static bool _hasCover(String name) { final dot = name.lastIndexOf('.'); @@ -387,17 +442,19 @@ class FileBubble extends StatelessWidget { if (fileId == null) return; Haptics.tap(); - final wasCached = (await MediaCache.existing(cacheName)) != null; + File? local = await MediaCache.existing(cacheName); + final wasCached = local != null; if (!wasCached) MediaDownloadProgress.set(cacheName, 0); - File? local; try { - final url = await _fileUrl(); - if (url != null && url.isNotEmpty) { - local = await MediaCache.getOrDownload( - cacheName, - url, - onProgress: (p) => MediaDownloadProgress.set(cacheName, p), - ); + if (local == null) { + final url = await _fileUrl(); + if (url != null && url.isNotEmpty) { + local = await MediaCache.getOrDownload( + cacheName, + url, + onProgress: (p) => MediaDownloadProgress.set(cacheName, p), + ); + } } } finally { if (!wasCached) MediaDownloadProgress.set(cacheName, null); @@ -435,7 +492,7 @@ class FileBubble extends StatelessWidget { if (!context.mounted || shown == null) return; await Navigator.of(context).push( - MaterialPageRoute( + PhotoViewerRoute( builder: (_) => PhotoViewerScreen( photos: [PhotoAttachment(localPath: shown.path)], chatId: ctx.message.chatId, @@ -505,33 +562,33 @@ class FileBubble extends StatelessWidget { Haptics.tap(); final cacheName = '${fileId}_$name'; - final cached = (await MediaCache.existing(cacheName)) != null; + final cached = MediaCache.presence(cacheName).value; final kind = downloadKindForName(name); if (!cached) MediaDownloadProgress.set(cacheName, 0); - final result = await openCachedFile( - cacheName, - () => messagesModule.getFileUrl( - messageId: ctx.message.id, - chatId: ctx.message.chatId, - fileId: fileId, - ), - onProgress: (p) => MediaDownloadProgress.set(cacheName, p), - onReady: () { - if (!cached) MediaDownloadProgress.set(cacheName, null); - }, - download: DownloadMetadata( - cacheName: cacheName, - name: name, - kind: kind, - sourceName: ctx.chatName ?? '', - thumbnailUrl: _thumbnailUrl, - expectedSize: file.size ?? 0, - chatId: ctx.message.chatId, - messageId: ctx.message.id, - messageTime: ctx.message.time, - ), - ); + final result = await widget + .openFile( + cacheName, + () => messagesModule.getFileUrl( + messageId: ctx.message.id, + chatId: ctx.message.chatId, + fileId: fileId, + ), + onProgress: (p) => MediaDownloadProgress.set(cacheName, p), + onReady: () => MediaDownloadProgress.set(cacheName, null), + download: DownloadMetadata( + cacheName: cacheName, + name: name, + kind: kind, + sourceName: ctx.chatName ?? '', + thumbnailUrl: _thumbnailUrl, + expectedSize: file.size ?? 0, + chatId: ctx.message.chatId, + messageId: ctx.message.id, + messageTime: ctx.message.time, + ), + ) + .whenComplete(() => MediaDownloadProgress.set(cacheName, null)); if (!context.mounted) return; final path = result.path; if (result.noAppToOpen && path != null) { @@ -542,9 +599,7 @@ class FileBubble extends StatelessWidget { final l10n = AppLocalizations.of(context)!; showCustomNotification( context, - l10n.securityLoadError( - result.error ?? l10n.fileBubbleOpenFailedReason, - ), + l10n.securityLoadError(result.error ?? l10n.fileBubbleOpenFailedReason), ); } } @@ -576,9 +631,7 @@ class FileBubble extends StatelessWidget { cacheName, _fileUrl, onProgress: (value) => MediaDownloadProgress.set(cacheName, value), - onReady: () { - if (!cached) MediaDownloadProgress.set(cacheName, null); - }, + onReady: () => MediaDownloadProgress.set(cacheName, null), download: DownloadMetadata( cacheName: cacheName, name: name, @@ -640,7 +693,8 @@ class _AudioFilePlaybackControl extends StatelessWidget { return ValueListenableBuilder( valueListenable: MediaPlayback.instance.audioFile, builder: (context, track, _) => - track?.cacheName != cacheName || !AudioPlaybackController.isInitialized + track?.cacheName != cacheName || + !AudioPlaybackController.isInitialized ? const SizedBox.shrink() : _AudioFileScrubber(color: color, textColor: textColor), ); @@ -669,7 +723,10 @@ class _AudioFileScrubberState extends State<_AudioFileScrubber> { final total = audio.duration.value.inMilliseconds; final elapsed = _dragMilliseconds != null ? _dragMilliseconds!.round() - : audio.position.value.inMilliseconds.clamp(0, total > 0 ? total : 0); + : audio.position.value.inMilliseconds.clamp( + 0, + total > 0 ? total : 0, + ); return Padding( padding: const EdgeInsets.only(top: 4), child: Row( diff --git a/lib/frontend/widgets/attachment/bubbles/photo_bubble.dart b/lib/frontend/widgets/attachment/bubbles/photo_bubble.dart index a386c243..bdb8752e 100644 --- a/lib/frontend/widgets/attachment/bubbles/photo_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/photo_bubble.dart @@ -7,9 +7,9 @@ import 'package:flutter/material.dart'; import 'package:komet/main.dart'; import 'package:material_symbols_icons/symbols.dart'; -import '../../../../core/media/preview_image.dart'; import '../../../../core/utils/format.dart'; import '../../../../models/attachment.dart'; +import '../../../../core/media/preview_image.dart'; import '../../photo_viewer.dart'; import '../photo_hero.dart'; import '../../text_with_meta.dart'; @@ -276,7 +276,6 @@ class PhotoBubble extends StatelessWidget { required int memWidth, required int memHeight, }) { - final embedded = dataUriImage(photo, photo.previewData); final localPath = _localPathOf(photo); if (localPath != null) { return Image.file( @@ -286,14 +285,12 @@ class PhotoBubble extends StatelessWidget { fit: BoxFit.cover, cacheWidth: memWidth, gaplessPlayback: true, - errorBuilder: (_, _, _) => embedded == null - ? _buildPhotoPlaceholder(ctx.cs, width, height) - : Image( - image: embedded, - width: width, - height: height, - fit: BoxFit.cover, - ), + frameBuilder: (_, child, frame, synchronouslyLoaded) => + frame != null || synchronouslyLoaded + ? child + : _buildPreviewImage(ctx, photo, width, height), + errorBuilder: (_, _, _) => + _buildPreviewImage(ctx, photo, width, height), ); } final imageUrl = _previewUrlOf(photo); @@ -307,28 +304,29 @@ class PhotoBubble extends StatelessWidget { memCacheHeight: memHeight, fadeInDuration: Duration.zero, placeholderFadeInDuration: Duration.zero, - errorWidget: (_, _, _) => embedded == null - ? _buildPhotoPlaceholder(ctx.cs, width, height) - : Image( - image: embedded, - width: width, - height: height, - fit: BoxFit.cover, - ), + placeholder: (_, _) => _buildPreviewImage(ctx, photo, width, height), + errorWidget: (_, _, _) => _buildPreviewImage(ctx, photo, width, height), ); } - if (embedded != null) { - return Image( - image: embedded, - width: width, - height: height, - fit: BoxFit.cover, - gaplessPlayback: true, - errorBuilder: (_, _, _) => - _buildPhotoPlaceholder(ctx.cs, width, height), - ); - } - return _buildPhotoPlaceholder(ctx.cs, width, height); + return _buildPreviewImage(ctx, photo, width, height); + } + + Widget _buildPreviewImage( + BubbleContext ctx, + MessageAttachment photo, + double width, + double height, + ) { + final preview = dataUriImage(photo, photo.previewData); + if (preview == null) return _buildPhotoPlaceholder(ctx.cs, width, height); + return Image( + image: preview, + width: width, + height: height, + fit: BoxFit.cover, + gaplessPlayback: true, + errorBuilder: (_, _, _) => _buildPhotoPlaceholder(ctx.cs, width, height), + ); } // #***! плитка видео отличается от фото только кружком плеера и длительностью diff --git a/lib/frontend/widgets/attachment/bubbles/video_bubble.dart b/lib/frontend/widgets/attachment/bubbles/video_bubble.dart index df168550..d0b2fcec 100644 --- a/lib/frontend/widgets/attachment/bubbles/video_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/video_bubble.dart @@ -246,8 +246,7 @@ Future openVideoPlayer(BubbleContext ctx, VideoAttachment video) async { } Navigator.of(context).push( - MaterialPageRoute( - fullscreenDialog: true, + PhotoViewerRoute( builder: (_) => PhotoViewerScreen.video( attachment: video, initialVideoSources: sources, diff --git a/lib/frontend/widgets/attachment/contact_picker_page.dart b/lib/frontend/widgets/attachment/contact_picker_page.dart index e79493b2..a3e86a11 100644 --- a/lib/frontend/widgets/attachment/contact_picker_page.dart +++ b/lib/frontend/widgets/attachment/contact_picker_page.dart @@ -2,7 +2,7 @@ import 'package:flutter/material.dart'; import 'package:material_symbols_icons/symbols.dart'; import 'package:komet/backend/modules/contacts.dart'; -import 'package:komet/core/config/debug_test.dart'; +import 'package:komet/core/config/launch_flags.dart'; import 'package:komet/core/contacts/contact_labels.dart'; import 'package:komet/core/storage/app_database.dart'; import 'package:komet/frontend/widgets/komet_avatar.dart'; @@ -53,7 +53,7 @@ class _ContactPickerPageState extends State { } Future> _fetch() async { - if (DebugTest.enabled) { + if (LaunchFlags.debugTest) { return ContactsModule.debugContacts() ..sort((a, b) => a.firstName.compareTo(b.firstName)); } diff --git a/lib/frontend/widgets/attachment/photo_hero.dart b/lib/frontend/widgets/attachment/photo_hero.dart index 0cd2b0a6..68d353d0 100644 --- a/lib/frontend/widgets/attachment/photo_hero.dart +++ b/lib/frontend/widgets/attachment/photo_hero.dart @@ -68,6 +68,7 @@ class PhotoHeroController { class PhotoHeroRoute extends PageRouteBuilder { PhotoHeroRoute({required this.hero, required WidgetBuilder builder}) : super( + opaque: false, transitionDuration: const Duration(milliseconds: 320), reverseTransitionDuration: const Duration(milliseconds: 280), pageBuilder: (context, animation, secondaryAnimation) => @@ -301,7 +302,7 @@ class _PhotoHeroTransitionState extends State<_PhotoHeroTransition> { } return Stack( children: [ - widget.child, + FadeTransition(opacity: widget.animation, child: widget.child), Positioned.fill( child: IgnorePointer( child: AnimatedBuilder( diff --git a/lib/frontend/widgets/bottom_navigation_style_card.dart b/lib/frontend/widgets/bottom_navigation_style_card.dart new file mode 100644 index 00000000..fccf1333 --- /dev/null +++ b/lib/frontend/widgets/bottom_navigation_style_card.dart @@ -0,0 +1,60 @@ +import 'package:flutter/material.dart'; + +import '../../core/config/app_bottom_navigation_style.dart'; +import '../../core/utils/haptics.dart'; +import '../../l10n/app_localizations.dart'; +import 'settings_card.dart'; + +class BottomNavigationStyleCard extends StatelessWidget { + const BottomNavigationStyleCard({super.key}); + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + return SettingsPanel( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.appearanceBottomNavigationTitle, + style: TextStyle( + color: cs.onSurface, + fontSize: 16, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 4), + Text( + l10n.appearanceBottomNavigationSubtitle, + style: TextStyle(color: cs.onSurfaceVariant, fontSize: 13), + ), + const SizedBox(height: 16), + ValueListenableBuilder( + valueListenable: AppBottomNavigationStyle.current, + builder: (context, current, _) => + SegmentedButton( + showSelectedIcon: false, + segments: [ + ButtonSegment( + value: BottomNavigationStyle.floating, + label: Text(l10n.appearanceBottomNavigationFloating), + ), + ButtonSegment( + value: BottomNavigationStyle.compact, + label: Text(l10n.appearanceBottomNavigationCompact), + ), + ], + selected: {current}, + onSelectionChanged: (selection) { + Haptics.selection(); + AppBottomNavigationStyle.save(selection.first); + }, + ), + ), + ], + ), + ); + } +} diff --git a/lib/frontend/widgets/chat_info/shared_content_tabs.dart b/lib/frontend/widgets/chat_info/shared_content_tabs.dart index e998139c..7799d4e7 100644 --- a/lib/frontend/widgets/chat_info/shared_content_tabs.dart +++ b/lib/frontend/widgets/chat_info/shared_content_tabs.dart @@ -814,23 +814,24 @@ class _MediaTile extends StatelessWidget { ); return; } - pushSwipeable( - context, - (_) => PhotoViewerScreen.video( - attachment: att, - initialVideoSources: sources, - chatId: item.chatId, - message: CachedMessage( - id: item.messageId, - accountId: 0, + Navigator.of(context).push( + PhotoViewerRoute( + builder: (_) => PhotoViewerScreen.video( + attachment: att, + initialVideoSources: sources, chatId: item.chatId, - senderId: item.senderId, - text: item.text, - time: item.time, + message: CachedMessage( + id: item.messageId, + accountId: 0, + chatId: item.chatId, + senderId: item.senderId, + text: item.text, + time: item.time, + ), + actions: PhotoViewerActions(goToMessage: onGoToMessage), + sourceName: sourceName, + videoUserAgentProvider: () => api.session?.userAgent(), ), - actions: PhotoViewerActions(goToMessage: onGoToMessage), - sourceName: sourceName, - videoUserAgentProvider: () => api.session?.userAgent(), ), ); return; @@ -841,22 +842,23 @@ class _MediaTile extends StatelessWidget { final photo = att is PhotoAttachment && (att.baseUrl ?? '').isNotEmpty ? att : PhotoAttachment(baseUrl: url); - pushSwipeable( - context, - (_) => PhotoViewerScreen( - photos: [photo], - chatId: item.chatId, - message: CachedMessage( - id: item.messageId, - accountId: 0, + Navigator.of(context).push( + PhotoViewerRoute( + builder: (_) => PhotoViewerScreen( + photos: [photo], chatId: item.chatId, - senderId: item.senderId, - text: item.text, - time: item.time, + message: CachedMessage( + id: item.messageId, + accountId: 0, + chatId: item.chatId, + senderId: item.senderId, + text: item.text, + time: item.time, + ), + actions: PhotoViewerActions(goToMessage: onGoToMessage), + sourceName: sourceName, + videoUserAgentProvider: () => api.session?.userAgent(), ), - actions: PhotoViewerActions(goToMessage: onGoToMessage), - sourceName: sourceName, - videoUserAgentProvider: () => api.session?.userAgent(), ), ); } diff --git a/lib/frontend/widgets/color_wheel_picker.dart b/lib/frontend/widgets/color_wheel_picker.dart index 0b4a4b20..354c976b 100644 --- a/lib/frontend/widgets/color_wheel_picker.dart +++ b/lib/frontend/widgets/color_wheel_picker.dart @@ -1,12 +1,19 @@ import 'dart:math' as math; +import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; class ColorWheelPicker extends StatefulWidget { final Color color; final ValueChanged onChanged; + final double minBrightness; - const ColorWheelPicker({super.key, required this.color, required this.onChanged}); + const ColorWheelPicker({ + super.key, + required this.color, + required this.onChanged, + this.minBrightness = 0, + }) : assert(minBrightness >= 0 && minBrightness < 1); @override State createState() => _ColorWheelPickerState(); @@ -50,8 +57,8 @@ class _ColorWheelPickerState extends State { } void _handleBrightness(double localY, double height) { - final value = (1 - localY / height).clamp(0.0, 1.0); - _emit(_hsv.withValue(value)); + final fraction = (localY / height).clamp(0.0, 1.0); + _emit(_hsv.withValue(1 - fraction * (1 - widget.minBrightness))); } @override @@ -69,25 +76,28 @@ class _ColorWheelPickerState extends State { mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ - GestureDetector( - behavior: HitTestBehavior.opaque, - onPanDown: (d) => _handleWheel(d.localPosition, wheelSize), - onPanUpdate: (d) => _handleWheel(d.localPosition, wheelSize), + _ClaimingDragArea( + onPosition: (local) => _handleWheel(local, wheelSize), child: SizedBox( width: wheelSize, height: wheelSize, child: CustomPaint(painter: _WheelPainter(hsv: _hsv)), ), ), - const SizedBox(width: spacing), - GestureDetector( - behavior: HitTestBehavior.opaque, - onPanDown: (d) => _handleBrightness(d.localPosition.dy, wheelSize), - onPanUpdate: (d) => _handleBrightness(d.localPosition.dy, wheelSize), - child: SizedBox( - width: barWidth, - height: wheelSize, - child: CustomPaint(painter: _BrightnessBarPainter(hsv: _hsv)), + _ClaimingDragArea( + onPosition: (local) => _handleBrightness(local.dy, wheelSize), + child: Padding( + padding: const EdgeInsets.only(left: spacing), + child: SizedBox( + width: barWidth, + height: wheelSize, + child: CustomPaint( + painter: _BrightnessBarPainter( + hsv: _hsv, + minBrightness: widget.minBrightness, + ), + ), + ), ), ), ], @@ -97,6 +107,43 @@ class _ColorWheelPickerState extends State { } } +class _ClaimingDragArea extends StatelessWidget { + final ValueChanged onPosition; + final Widget child; + + const _ClaimingDragArea({required this.onPosition, required this.child}); + + @override + Widget build(BuildContext context) { + return RawGestureDetector( + behavior: HitTestBehavior.opaque, + gestures: { + _ClaimingPanGestureRecognizer: + GestureRecognizerFactoryWithHandlers<_ClaimingPanGestureRecognizer>( + _ClaimingPanGestureRecognizer.new, + (recognizer) { + recognizer.onDown = (details) => + onPosition(details.localPosition); + recognizer.onUpdate = (details) => + onPosition(details.localPosition); + }, + ), + }, + child: child, + ); + } +} + +class _ClaimingPanGestureRecognizer extends PanGestureRecognizer { + _ClaimingPanGestureRecognizer({super.debugOwner}); + + @override + void addAllowedPointer(PointerDownEvent event) { + super.addAllowedPointer(event); + resolvePointer(event.pointer, GestureDisposition.accepted); + } +} + class _WheelPainter extends CustomPainter { final HSVColor hsv; @@ -134,22 +181,20 @@ class _WheelPainter extends CustomPainter { false, ); canvas.drawCircle(thumb, 13, Paint()..color = Colors.white); - canvas.drawCircle( - thumb, - 10, - Paint()..color = hsv.withValue(1).toColor(), - ); + canvas.drawCircle(thumb, 10, Paint()..color = hsv.withValue(1).toColor()); } @override bool shouldRepaint(_WheelPainter oldDelegate) => - oldDelegate.hsv.hue != hsv.hue || oldDelegate.hsv.saturation != hsv.saturation; + oldDelegate.hsv.hue != hsv.hue || + oldDelegate.hsv.saturation != hsv.saturation; } class _BrightnessBarPainter extends CustomPainter { final HSVColor hsv; + final double minBrightness; - const _BrightnessBarPainter({required this.hsv}); + const _BrightnessBarPainter({required this.hsv, required this.minBrightness}); @override void paint(Canvas canvas, Size size) { @@ -157,16 +202,18 @@ class _BrightnessBarPainter extends CustomPainter { Offset.zero & size, Radius.circular(size.width / 2), ); - final top = hsv.withValue(1).toColor(); final gradient = LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, - colors: [top, Colors.black], + colors: [ + hsv.withValue(1).toColor(), + hsv.withValue(minBrightness).toColor(), + ], ).createShader(Offset.zero & size); canvas.drawRRect(rrect, Paint()..shader = gradient); - final thumbY = (1 - hsv.value) * size.height; - final thumb = Offset(size.width / 2, thumbY.clamp(0.0, size.height)); + final fraction = ((1 - hsv.value) / (1 - minBrightness)).clamp(0.0, 1.0); + final thumb = Offset(size.width / 2, fraction * size.height); canvas.drawShadow( Path()..addOval(Rect.fromCircle(center: thumb, radius: 12)), Colors.black, @@ -179,5 +226,5 @@ class _BrightnessBarPainter extends CustomPainter { @override bool shouldRepaint(_BrightnessBarPainter oldDelegate) => - oldDelegate.hsv != hsv; + oldDelegate.hsv != hsv || oldDelegate.minBrightness != minBrightness; } diff --git a/lib/frontend/widgets/compact_bottom_navigation_bar.dart b/lib/frontend/widgets/compact_bottom_navigation_bar.dart new file mode 100644 index 00000000..1a93a347 --- /dev/null +++ b/lib/frontend/widgets/compact_bottom_navigation_bar.dart @@ -0,0 +1,144 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import 'sliding_pill_nav.dart'; + +class CompactBottomNavigationBar extends StatelessWidget { + const CompactBottomNavigationBar({ + super.key, + required this.items, + required this.currentIndex, + required this.onTap, + this.onItemLongPress, + }); + + final List items; + final int currentIndex; + final ValueChanged onTap; + final void Function(int index, Offset position)? onItemLongPress; + + static double contentHeight(BuildContext context) => + math.max(50, 34 + MediaQuery.textScalerOf(context).scale(10) * 1.2); + + @override + Widget build(BuildContext context) { + if (MediaQuery.viewInsetsOf(context).bottom > 0) { + return const SizedBox.shrink(); + } + final cs = Theme.of(context).colorScheme; + return DecoratedBox( + decoration: BoxDecoration( + color: cs.surface, + border: Border(top: BorderSide(color: cs.outlineVariant, width: 0.5)), + ), + child: SafeArea( + top: false, + child: SizedBox( + height: contentHeight(context), + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (var index = 0; index < items.length; index++) + Expanded( + child: _CompactTab( + item: items[index], + selected: index == currentIndex, + onTap: () => onTap(index), + onLongPress: + items[index].longPressable && onItemLongPress != null + ? (position) => onItemLongPress!(index, position) + : null, + ), + ), + ], + ), + ), + ), + ); + } +} + +class _CompactTab extends StatefulWidget { + const _CompactTab({ + required this.item, + required this.selected, + required this.onTap, + this.onLongPress, + }); + + final PillNavItem item; + final bool selected; + final VoidCallback onTap; + final ValueChanged? onLongPress; + + @override + State<_CompactTab> createState() => _CompactTabState(); +} + +class _CompactTabState extends State<_CompactTab> { + bool _pressed = false; + + void _setPressed(bool value) { + if (_pressed != value) setState(() => _pressed = value); + } + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final color = widget.selected ? cs.primary : cs.onSurfaceVariant; + return Semantics( + button: true, + selected: widget.selected, + label: widget.item.label, + onTap: widget.onTap, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + excludeFromSemantics: true, + onTapDown: (_) => _setPressed(true), + onTapUp: (_) => _setPressed(false), + onTapCancel: () => _setPressed(false), + onTap: widget.onTap, + onLongPressStart: widget.onLongPress == null + ? null + : (details) { + _setPressed(false); + widget.onLongPress!(details.globalPosition); + }, + child: ExcludeSemantics( + child: AnimatedOpacity( + opacity: _pressed ? 0.55 : 1, + duration: const Duration(milliseconds: 100), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 4), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + widget.item.icon, + color: color, + size: 24, + fill: widget.selected ? 1 : 0, + weight: widget.selected ? 500 : 400, + ), + const SizedBox(height: 2), + Text( + widget.item.label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: color, + fontSize: 10, + height: 1.2, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/frontend/widgets/direct_call.dart b/lib/frontend/widgets/direct_call.dart new file mode 100644 index 00000000..6e103ae5 --- /dev/null +++ b/lib/frontend/widgets/direct_call.dart @@ -0,0 +1,54 @@ +import 'package:flutter/material.dart'; + +import '../../backend/modules/calls.dart'; +import '../../core/calls/call_controller.dart'; +import '../../l10n/app_localizations.dart'; +import '../screens/calls/call_screen.dart'; +import 'custom_notification.dart'; + +Future startDirectCall( + BuildContext context, { + required int peerId, + required String name, + String? avatarUrl, +}) async { + final l10n = AppLocalizations.of(context)!; + final navigator = Navigator.of(context); + final controller = CallController.instance; + + final active = controller.activeSession; + if (active != null) { + await navigator.push( + MaterialPageRoute( + builder: (_) => + CallScreen(name: name, avatarUrl: avatarUrl, session: active), + ), + ); + return true; + } + + if (peerId <= 0) { + showCustomNotification(context, l10n.callsTabPeerUnknown); + return false; + } + + try { + final session = await controller.startOutgoing(peerId); + if (!context.mounted) return false; + await navigator.push( + MaterialPageRoute( + builder: (_) => + CallScreen(name: name, avatarUrl: avatarUrl, session: session), + ), + ); + return true; + } on CallPeerIsBotException { + if (context.mounted) showCustomNotification(context, l10n.callPeerIsBot); + return false; + } catch (_) { + if (context.mounted) { + showCustomNotification(context, l10n.chatInfoCallFailed); + } + return false; + } +} diff --git a/lib/frontend/widgets/directional_drag_recognizer.dart b/lib/frontend/widgets/directional_drag_recognizer.dart index e84d6551..45e92190 100644 --- a/lib/frontend/widgets/directional_drag_recognizer.dart +++ b/lib/frontend/widgets/directional_drag_recognizer.dart @@ -17,6 +17,7 @@ class DirectionalDragRecognizer extends HorizontalDragGestureRecognizer { final Map _initialPositions = {}; final Map _velocityTrackers = {}; final Map _currentDeltaX = {}; + bool _accepted = false; @override void addAllowedPointer(PointerDownEvent event) { @@ -36,9 +37,10 @@ class DirectionalDragRecognizer extends HorizontalDragGestureRecognizer { ); final initial = _initialPositions[event.pointer]; if (initial != null) { - final dx = (event.position.dx - initial.dx) * direction; + final delta = event.position - initial; + final dx = delta.dx * direction; _currentDeltaX[event.pointer] = dx; - if (dx < -kTouchSlop) { + if (dx < -kTouchSlop || (!_accepted && _isMostlyVertical(delta))) { stopTrackingPointer(event.pointer); _cleanup(event.pointer); return; @@ -74,6 +76,15 @@ class DirectionalDragRecognizer extends HorizontalDragGestureRecognizer { return false; } + static bool _isMostlyVertical(Offset delta) => + delta.dy.abs() > kTouchSlop && delta.dy.abs() > delta.dx.abs(); + + @override + void acceptGesture(int pointer) { + _accepted = true; + super.acceptGesture(pointer); + } + void _cleanup(int pointer) { _initialPositions.remove(pointer); _velocityTrackers.remove(pointer); @@ -83,6 +94,7 @@ class DirectionalDragRecognizer extends HorizontalDragGestureRecognizer { @override void didStopTrackingLastPointer(int pointer) { _cleanup(pointer); + _accepted = false; super.didStopTrackingLastPointer(pointer); } diff --git a/lib/frontend/widgets/main_navigation_items.dart b/lib/frontend/widgets/main_navigation_items.dart new file mode 100644 index 00000000..24d8710a --- /dev/null +++ b/lib/frontend/widgets/main_navigation_items.dart @@ -0,0 +1,16 @@ +import 'package:material_symbols_icons/symbols.dart'; + +import '../../core/config/app_animations.dart'; +import 'sliding_pill_nav.dart'; + +const mainNavigationItems = [ + PillNavItem(icon: Symbols.chat_bubble, label: 'Чаты'), + PillNavItem(icon: Symbols.call, label: 'Звонки'), + PillNavItem(icon: Symbols.person_pin, label: 'Контакты'), + PillNavItem( + icon: Symbols.settings, + label: 'Настройки', + longPressable: true, + animationAsset: AppAnimations.settings, + ), +]; diff --git a/lib/frontend/widgets/photo_viewer.dart b/lib/frontend/widgets/photo_viewer.dart index 3cdfc693..a5500c65 100644 --- a/lib/frontend/widgets/photo_viewer.dart +++ b/lib/frontend/widgets/photo_viewer.dart @@ -78,6 +78,19 @@ class PhotoViewerActions { viewAllMedia == null; } +class PhotoViewerRoute extends PageRouteBuilder { + PhotoViewerRoute({required WidgetBuilder builder}) + : super( + opaque: false, + transitionDuration: const Duration(milliseconds: 220), + reverseTransitionDuration: const Duration(milliseconds: 200), + pageBuilder: (context, animation, secondaryAnimation) => + builder(context), + transitionsBuilder: (context, animation, secondaryAnimation, child) => + FadeTransition(opacity: animation, child: child), + ); +} + class _ViewerMedia { final String id; final MessageAttachment attachment; @@ -198,7 +211,8 @@ class PhotoViewerScreen extends StatefulWidget { State createState() => _PhotoViewerScreenState(); } -class _PhotoViewerScreenState extends State { +class _PhotoViewerScreenState extends State + with SingleTickerProviderStateMixin { static const int _prefetchThreshold = 3; static const int _maxCachedVideoPlayers = 5; static const double _compactHeight = 480; @@ -216,9 +230,17 @@ class _PhotoViewerScreenState extends State { final Map>> _videoSourceLoads = {}; final TransformationController _heroTransform = TransformationController(); final Map _pageTransforms = {}; - int _pointers = 0; bool _zoomed = false; bool _swipeEnabled = true; + final Set _pointers = {}; + late final AnimationController _dismissReturn; + final ValueNotifier _dismissOffset = ValueNotifier(Offset.zero); + Offset _returnFrom = Offset.zero; + Offset? _pointerOrigin; + VelocityTracker? _velocityTracker; + bool _dismissAllowed = false; + bool _draggingToDismiss = false; + bool _closing = false; bool _feedLoaded = false; bool _feedFailed = false; bool _loadingMore = false; @@ -230,6 +252,10 @@ class _PhotoViewerScreenState extends State { @override void initState() { super.initState(); + _dismissReturn = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 240), + )..addListener(_animateDismissReturn); _heroTransform.addListener(_syncHero); _heroTransform.addListener(_syncZoom); _items = _localItems(); @@ -271,14 +297,8 @@ class _PhotoViewerScreenState extends State { _syncSwipe(); } - void _updatePointers(int delta) { - final next = _pointers + delta; - _pointers = next < 0 ? 0 : next; - _syncSwipe(); - } - void _syncSwipe() { - final enabled = _pointers < 2 && !_zoomed; + final enabled = _pointers.length < 2 && !_zoomed; if (enabled == _swipeEnabled) return; setState(() => _swipeEnabled = enabled); } @@ -286,6 +306,8 @@ class _PhotoViewerScreenState extends State { @override void dispose() { _controller.dispose(); + _dismissReturn.dispose(); + _dismissOffset.dispose(); _heroTransform.dispose(); for (final transform in _pageTransforms.values) { transform.dispose(); @@ -296,6 +318,97 @@ class _PhotoViewerScreenState extends State { super.dispose(); } + bool get _canDismiss { + final route = ModalRoute.of(context); + return !_closing && + !_dismissReturn.isAnimating && + route?.isCurrent == true && + route?.popDisposition != RoutePopDisposition.doNotPop && + Navigator.of(context).canPop() && + (!_controller.hasClients || + !_controller.position.isScrollingNotifier.value) && + (_current.isVideo || + _transformFor(_current.id).value.getMaxScaleOnAxis() <= 1.01); + } + + void _onMediaPointerDown(PointerDownEvent event) { + _pointers.add(event.pointer); + _syncSwipe(); + if (_pointers.length != 1) { + _dismissAllowed = false; + _restoreDismiss(); + return; + } + _dismissAllowed = event.kind != PointerDeviceKind.mouse && _canDismiss; + _pointerOrigin = event.position; + _velocityTracker = VelocityTracker.withKind(event.kind) + ..addPosition(event.timeStamp, event.position); + } + + void _onMediaPointerMove(PointerMoveEvent event) { + if (!_dismissAllowed || _pointers.length != 1) return; + _velocityTracker?.addPosition(event.timeStamp, event.position); + final delta = event.position - _pointerOrigin!; + if (!_draggingToDismiss) { + if (delta.distance < kTouchSlop) return; + if (delta.dx.abs() >= delta.dy.abs()) { + _dismissAllowed = false; + return; + } + if (!_current.isVideo && + _transformFor(_current.id).value.getMaxScaleOnAxis() > 1.01) { + _dismissAllowed = false; + return; + } + _draggingToDismiss = true; + } + _dismissOffset.value = Offset(delta.dx * 0.35, delta.dy); + } + + void _onMediaPointerUp(PointerUpEvent event) { + _pointers.remove(event.pointer); + _syncSwipe(); + if (!_draggingToDismiss || !_dismissAllowed) return; + _dismissAllowed = false; + _draggingToDismiss = false; + _velocityTracker?.addPosition(event.timeStamp, event.position); + final velocity = _velocityTracker?.getVelocity().pixelsPerSecond.dy ?? 0; + final distance = _dismissOffset.value.dy; + final threshold = (MediaQuery.sizeOf(context).height * 0.18).clamp(96, 180); + final fling = + distance.abs() >= 32 && + velocity.abs() >= 900 && + velocity.sign == distance.sign; + final route = ModalRoute.of(context); + if ((distance.abs() >= threshold || fling) && + route?.isCurrent == true && + route?.popDisposition != RoutePopDisposition.doNotPop) { + _closing = true; + Navigator.of(context).pop(); + } else { + _restoreDismiss(); + } + } + + void _onMediaPointerCancel(PointerCancelEvent event) { + _pointers.remove(event.pointer); + _syncSwipe(); + _dismissAllowed = false; + _restoreDismiss(); + } + + void _restoreDismiss() { + _draggingToDismiss = false; + if (_closing || _dismissOffset.value == Offset.zero) return; + _returnFrom = _dismissOffset.value; + _dismissReturn.forward(from: 0); + } + + void _animateDismissReturn() { + final value = Curves.easeOutCubic.transform(_dismissReturn.value); + _dismissOffset.value = Offset.lerp(_returnFrom, Offset.zero, value)!; + } + AvatarFeed? get _avatarFeed => widget.avatars; bool get _isAvatars => _avatarFeed != null; @@ -929,9 +1042,11 @@ class _PhotoViewerScreenState extends State { final media = MediaQuery.of(context); final padding = media.padding; final compact = media.size.height < _compactHeight; + double dismissProgress(Offset offset) => + (offset.dy.abs() / (media.size.height * 0.55)).clamp(0.0, 1.0); return Scaffold( - backgroundColor: Colors.black, + backgroundColor: Colors.transparent, body: CallbackShortcuts( bindings: { const SingleActivator(LogicalKeyboardKey.arrowLeft): () => @@ -943,52 +1058,90 @@ class _PhotoViewerScreenState extends State { autofocus: true, child: Stack( children: [ - Positioned.fill(child: _buildPager()), Positioned.fill( - child: IgnorePointer( - ignoring: !_chromeVisible, - child: AnimatedOpacity( - opacity: _chromeVisible ? 1 : 0, - duration: const Duration(milliseconds: 220), - curve: Curves.easeOut, - child: Stack( - children: [ - if (_canStep(_leftStep)) - Align( - alignment: Alignment.centerLeft, - child: Padding( - padding: EdgeInsets.only(left: padding.left), - child: _arrow( - Symbols.chevron_left, - () => _step(_leftStep), - ), + child: ValueListenableBuilder( + valueListenable: _dismissOffset, + builder: (context, offset, _) => ColoredBox( + key: const ValueKey('media-dismiss-backdrop'), + color: Colors.black.withValues( + alpha: 1 - dismissProgress(offset), + ), + ), + ), + ), + Positioned.fill( + child: Listener( + behavior: HitTestBehavior.translucent, + onPointerDown: _onMediaPointerDown, + onPointerMove: _onMediaPointerMove, + onPointerUp: _onMediaPointerUp, + onPointerCancel: _onMediaPointerCancel, + child: ValueListenableBuilder( + valueListenable: _dismissOffset, + child: _buildPager(), + builder: (context, offset, pager) => Transform.translate( + key: const ValueKey('media-dismiss-transform'), + offset: offset, + child: Transform.scale( + scale: 1 - 0.12 * dismissProgress(offset), + child: pager, + ), + ), + ), + ), + ), + Positioned.fill( + child: ValueListenableBuilder( + valueListenable: _dismissOffset, + builder: (context, offset, chrome) => IgnorePointer( + ignoring: !_chromeVisible || offset != Offset.zero, + child: AnimatedOpacity( + opacity: _chromeVisible ? 1 : 0, + duration: const Duration(milliseconds: 220), + curve: Curves.easeOut, + child: Opacity( + opacity: 1 - dismissProgress(offset), + child: chrome, + ), + ), + ), + child: Stack( + children: [ + if (_canStep(_leftStep)) + Align( + alignment: Alignment.centerLeft, + child: Padding( + padding: EdgeInsets.only(left: padding.left), + child: _arrow( + Symbols.chevron_left, + () => _step(_leftStep), ), ), - if (_canStep(-_leftStep)) - Align( - alignment: Alignment.centerRight, - child: Padding( - padding: EdgeInsets.only(right: padding.right), - child: _arrow( - Symbols.chevron_right, - () => _step(-_leftStep), - ), + ), + if (_canStep(-_leftStep)) + Align( + alignment: Alignment.centerRight, + child: Padding( + padding: EdgeInsets.only(right: padding.right), + child: _arrow( + Symbols.chevron_right, + () => _step(-_leftStep), ), ), - Positioned( - top: 0, - left: 0, - right: 0, - child: _buildTopBar(padding, compact: compact), - ), - Positioned( - left: 0, - right: 0, - bottom: 0, - child: _buildBottomBar(padding, compact: compact), ), - ], - ), + Positioned( + top: 0, + left: 0, + right: 0, + child: _buildTopBar(padding, compact: compact), + ), + Positioned( + left: 0, + right: 0, + bottom: 0, + child: _buildBottomBar(padding, compact: compact), + ), + ], ), ), ), @@ -1007,23 +1160,18 @@ class _PhotoViewerScreenState extends State { gestureSettings: DeviceGestureSettings(touchSlop: swipeSlop), ); - return Listener( - onPointerDown: (_) => _updatePointers(1), - onPointerUp: (_) => _updatePointers(-1), - onPointerCancel: (_) => _updatePointers(-1), - child: MediaQuery( - data: swipeMedia, - child: PageView.builder( - key: ValueKey(_pager), - controller: _controller, - reverse: !_isAvatars, - physics: _swipeEnabled ? null : const NeverScrollableScrollPhysics(), - itemCount: _items.length, - onPageChanged: _onPageChanged, - itemBuilder: (_, i) => MediaQuery( - data: _zoomed ? media : swipeMedia, - child: _buildPage(i), - ), + return MediaQuery( + data: swipeMedia, + child: PageView.builder( + key: ValueKey(_pager), + controller: _controller, + reverse: !_isAvatars, + physics: _swipeEnabled ? null : const NeverScrollableScrollPhysics(), + itemCount: _items.length, + onPageChanged: _onPageChanged, + itemBuilder: (_, i) => MediaQuery( + data: _zoomed ? media : swipeMedia, + child: _buildPage(i), ), ), ); diff --git a/lib/frontend/widgets/scroll_keyboard_dismiss.dart b/lib/frontend/widgets/scroll_keyboard_dismiss.dart new file mode 100644 index 00000000..74c2802e --- /dev/null +++ b/lib/frontend/widgets/scroll_keyboard_dismiss.dart @@ -0,0 +1,72 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/widgets.dart'; + +class ScrollKeyboardDismiss extends StatefulWidget { + const ScrollKeyboardDismiss({ + super.key, + required this.onDismiss, + required this.child, + }); + + final VoidCallback onDismiss; + final Widget child; + + @override + State createState() => _ScrollKeyboardDismissState(); +} + +class _ScrollKeyboardDismissState extends State { + static const _minimumSpeed = 300.0; + static const _minimumDistance = 18.0; + VelocityTracker? _tracker; + Offset? _origin; + bool _dismissed = false; + + bool _onScroll(ScrollNotification notification) { + if (notification.depth != 0 || notification.metrics.axis != Axis.vertical) { + return false; + } + if (notification is ScrollStartNotification) { + final details = notification.dragDetails; + _tracker = details == null + ? null + : VelocityTracker.withKind(details.kind ?? PointerDeviceKind.touch); + _origin = details?.globalPosition; + _dismissed = false; + if (details?.sourceTimeStamp case final time?) { + _tracker?.addPosition(time, details!.globalPosition); + } + } else if (notification is ScrollEndNotification) { + _tracker = null; + _origin = null; + } else if (!_dismissed) { + final details = switch (notification) { + ScrollUpdateNotification() => notification.dragDetails, + OverscrollNotification() => notification.dragDetails, + _ => null, + }; + final time = details?.sourceTimeStamp; + final tracker = _tracker; + final origin = _origin; + if (details != null && + time != null && + tracker != null && + origin != null) { + tracker.addPosition(time, details.globalPosition); + if ((details.globalPosition.dy - origin.dy).abs() >= _minimumDistance && + tracker.getVelocity().pixelsPerSecond.dy.abs() >= _minimumSpeed) { + _dismissed = true; + widget.onDismiss(); + } + } + } + return false; + } + + @override + Widget build(BuildContext context) => + NotificationListener( + onNotification: _onScroll, + child: widget.child, + ); +} diff --git a/lib/frontend/widgets/swipe_to_reply.dart b/lib/frontend/widgets/swipe_to_reply.dart new file mode 100644 index 00000000..1c3b10e4 --- /dev/null +++ b/lib/frontend/widgets/swipe_to_reply.dart @@ -0,0 +1,150 @@ +import 'package:flutter/gestures.dart' show DragStartBehavior; +import 'package:flutter/material.dart'; +import 'package:flutter/physics.dart'; +import 'package:material_symbols_icons/symbols.dart'; + +import '../../core/utils/haptics.dart'; +import 'directional_drag_recognizer.dart'; + +class SwipeToReply extends StatefulWidget { + const SwipeToReply({super.key, required this.child, required this.onReply}); + + final Widget child; + final VoidCallback onReply; + + @override + State createState() => _SwipeToReplyState(); +} + +class _SwipeToReplyState extends State + with SingleTickerProviderStateMixin { + static const double _triggerDistance = 56; + static const double _resistanceLength = 32; + static final SpringDescription _spring = SpringDescription.withDampingRatio( + mass: 1, + stiffness: 500, + ratio: 1, + ); + + late final AnimationController _offset; + double _distance = 0; + bool _triggered = false; + bool _hapticSent = false; + + @override + void initState() { + super.initState(); + _offset = AnimationController.unbounded(vsync: this); + } + + @override + void dispose() { + _offset.dispose(); + super.dispose(); + } + + void _onDragStart(DragStartDetails details) { + _offset.stop(); + final visibleDistance = (-_offset.value).clamp(0.0, double.infinity); + final extra = (visibleDistance - _triggerDistance).clamp( + 0.0, + _resistanceLength - 0.01, + ); + _distance = extra == 0 + ? visibleDistance + : _triggerDistance + extra / (1 - extra / _resistanceLength); + _triggered = false; + _hapticSent = false; + } + + void _onDragUpdate(DragUpdateDetails details) { + _distance = (_distance - details.delta.dx).clamp(0.0, double.infinity); + final extra = (_distance - _triggerDistance).clamp(0.0, double.infinity); + _offset.value = extra == 0 + ? -_distance + : -(_triggerDistance + extra / (1 + extra / _resistanceLength)); + _triggered = _distance >= _triggerDistance; + if (_triggered && !_hapticSent) { + _hapticSent = true; + Haptics.medium(); + } + } + + void _onDragEnd(DragEndDetails details) { + final shouldReply = _triggered; + _settle(details.velocity.pixelsPerSecond.dx); + if (shouldReply) widget.onReply(); + } + + void _settle([double velocity = 0]) { + _triggered = false; + final extra = (_distance - _triggerDistance).clamp(0.0, double.infinity); + final resistance = 1 + extra / _resistanceLength; + _offset.animateWith( + SpringSimulation( + _spring, + _offset.value, + 0, + velocity.clamp(-1500.0, 1500.0) / (resistance * resistance), + tolerance: const Tolerance(distance: 0.1, velocity: 0.1), + snapToEnd: true, + ), + ); + } + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + return Listener( + onPointerCancel: (_) => _settle(), + child: RawGestureDetector( + behavior: HitTestBehavior.opaque, + gestures: { + LeftwardDragRecognizer: + GestureRecognizerFactoryWithHandlers( + () => LeftwardDragRecognizer(debugOwner: this), + (instance) { + instance + ..dragStartBehavior = DragStartBehavior.down + ..onStart = _onDragStart + ..onUpdate = _onDragUpdate + ..onEnd = _onDragEnd + ..onCancel = _settle; + }, + ), + }, + child: AnimatedBuilder( + animation: _offset, + child: RepaintBoundary(child: widget.child), + builder: (context, child) { + final offset = _offset.value.clamp(-double.infinity, 0.0); + final progress = (-offset / _triggerDistance).clamp(0.0, 1.0); + return Stack( + alignment: Alignment.centerRight, + children: [ + Positioned( + right: 16, + child: Opacity( + opacity: progress, + child: Transform.scale( + scale: 0.6 + 0.4 * progress, + child: Container( + padding: const EdgeInsets.all(6), + decoration: BoxDecoration( + color: cs.surfaceContainerHighest, + shape: BoxShape.circle, + ), + child: Icon(Symbols.reply, size: 20, color: cs.primary), + ), + ), + ), + ), + Transform.translate(offset: Offset(offset, 0), child: child), + ], + ); + }, + ), + ), + ); + } +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 3a96f24d..812015b4 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -35,9 +35,13 @@ "loginLanguage": "Language", "languageNameRu": "Русский", "languageNameEn": "English", + "languageServerTitle": "Use this language on the server too", + "languageServerSubtitle": "When on, built-in folder names, server error messages and some other built-in elements come in the language you chose. By default they are not translated.", "selectCountryTitle": "Select country", "selectCountrySearchHint": "Search countries…", "codeConfirmationSmsSent": "We sent an SMS with a verification code to your phone number.", + "codeConfirmationCheckMaxChat": "Check the “Verification codes” chat in MAX.", + "loginSlowSmsHint": "Signing in this way takes longer than usual. Please wait and don't leave.", "codeResendInSeconds": "Resend in {seconds} s.", "@codeResendInSeconds": { "placeholders": { @@ -1865,6 +1869,7 @@ "callsTabStatusIncoming": "Incoming", "callsTabCallBack": "Call back", "callsTabPeerUnknown": "Couldn't identify the other person", + "callPeerIsBot": "Bots can't be called", "callsTabAlreadyInCall": "A call is already in progress", "callsTabStartFailed": "Couldn't start the call: {error}", "@callsTabStartFailed": {"placeholders": {"error": {"type": "String"}}}, @@ -2449,5 +2454,9 @@ "avatarEditorSetPhoto": "Set photo", "avatarEditorDraw": "Draw", "avatarPickerFilesTitle": "Pick a photo from files", - "avatarPickerFilesSubtitle": "If the photo you need isn't in the gallery" + "avatarPickerFilesSubtitle": "If the photo you need isn't in the gallery", + "appearanceBottomNavigationTitle": "Bottom navigation", + "appearanceBottomNavigationSubtitle": "The compact bar keeps all four tab labels visible and takes up less space.", + "appearanceBottomNavigationFloating": "Floating", + "appearanceBottomNavigationCompact": "Compact" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index f5db1d39..46f62364 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -308,6 +308,18 @@ abstract class AppLocalizations { /// **'English'** String get languageNameEn; + /// No description provided for @languageServerTitle. + /// + /// In en, this message translates to: + /// **'Use this language on the server too'** + String get languageServerTitle; + + /// No description provided for @languageServerSubtitle. + /// + /// In en, this message translates to: + /// **'When on, built-in folder names, server error messages and some other built-in elements come in the language you chose. By default they are not translated.'** + String get languageServerSubtitle; + /// No description provided for @selectCountryTitle. /// /// In en, this message translates to: @@ -326,6 +338,18 @@ abstract class AppLocalizations { /// **'We sent an SMS with a verification code to your phone number.'** String get codeConfirmationSmsSent; + /// No description provided for @codeConfirmationCheckMaxChat. + /// + /// In en, this message translates to: + /// **'Check the “Verification codes” chat in MAX.'** + String get codeConfirmationCheckMaxChat; + + /// No description provided for @loginSlowSmsHint. + /// + /// In en, this message translates to: + /// **'Signing in this way takes longer than usual. Please wait and don\'t leave.'** + String get loginSlowSmsHint; + /// No description provided for @codeResendInSeconds. /// /// In en, this message translates to: @@ -8408,6 +8432,12 @@ abstract class AppLocalizations { /// **'Couldn\'t identify the other person'** String get callsTabPeerUnknown; + /// No description provided for @callPeerIsBot. + /// + /// In en, this message translates to: + /// **'Bots can\'t be called'** + String get callPeerIsBot; + /// No description provided for @callsTabAlreadyInCall. /// /// In en, this message translates to: @@ -11407,6 +11437,30 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'If the photo you need isn\'t in the gallery'** String get avatarPickerFilesSubtitle; + + /// No description provided for @appearanceBottomNavigationTitle. + /// + /// In en, this message translates to: + /// **'Bottom navigation'** + String get appearanceBottomNavigationTitle; + + /// No description provided for @appearanceBottomNavigationSubtitle. + /// + /// In en, this message translates to: + /// **'The compact bar keeps all four tab labels visible and takes up less space.'** + String get appearanceBottomNavigationSubtitle; + + /// No description provided for @appearanceBottomNavigationFloating. + /// + /// In en, this message translates to: + /// **'Floating'** + String get appearanceBottomNavigationFloating; + + /// No description provided for @appearanceBottomNavigationCompact. + /// + /// In en, this message translates to: + /// **'Compact'** + String get appearanceBottomNavigationCompact; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 99caf442..eb6fd869 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -117,6 +117,13 @@ class AppLocalizationsEn extends AppLocalizations { @override String get languageNameEn => 'English'; + @override + String get languageServerTitle => 'Use this language on the server too'; + + @override + String get languageServerSubtitle => + 'When on, built-in folder names, server error messages and some other built-in elements come in the language you chose. By default they are not translated.'; + @override String get selectCountryTitle => 'Select country'; @@ -127,6 +134,14 @@ class AppLocalizationsEn extends AppLocalizations { String get codeConfirmationSmsSent => 'We sent an SMS with a verification code to your phone number.'; + @override + String get codeConfirmationCheckMaxChat => + 'Check the “Verification codes” chat in MAX.'; + + @override + String get loginSlowSmsHint => + 'Signing in this way takes longer than usual. Please wait and don\'t leave.'; + @override String codeResendInSeconds(int seconds) { return 'Resend in $seconds s.'; @@ -4628,6 +4643,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get callsTabPeerUnknown => 'Couldn\'t identify the other person'; + @override + String get callPeerIsBot => 'Bots can\'t be called'; + @override String get callsTabAlreadyInCall => 'A call is already in progress'; @@ -6421,4 +6439,17 @@ class AppLocalizationsEn extends AppLocalizations { @override String get avatarPickerFilesSubtitle => 'If the photo you need isn\'t in the gallery'; + + @override + String get appearanceBottomNavigationTitle => 'Bottom navigation'; + + @override + String get appearanceBottomNavigationSubtitle => + 'The compact bar keeps all four tab labels visible and takes up less space.'; + + @override + String get appearanceBottomNavigationFloating => 'Floating'; + + @override + String get appearanceBottomNavigationCompact => 'Compact'; } diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index fc8679a5..b360572a 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -118,6 +118,13 @@ class AppLocalizationsRu extends AppLocalizations { @override String get languageNameEn => 'English'; + @override + String get languageServerTitle => 'Менять язык и для сервера тоже'; + + @override + String get languageServerSubtitle => + 'При включении переключателя названия встроенных папок, уведомления о серверных ошибках и некоторые встроенные элементы будут на выбранном вами языке. По умолчанию они не переводятся.'; + @override String get selectCountryTitle => 'Выберите страну'; @@ -128,6 +135,14 @@ class AppLocalizationsRu extends AppLocalizations { String get codeConfirmationSmsSent => 'Мы отправили SMS с кодом подтверждения на ваш номер телефона.'; + @override + String get codeConfirmationCheckMaxChat => + 'Проверьте чат «Коды подтверждения» в МАХ.'; + + @override + String get loginSlowSmsHint => + 'Вход с этим способом дольше обычного. Подождите немного, не выходите.'; + @override String codeResendInSeconds(int seconds) { return 'Отправить повторно через $seconds сек.'; @@ -4667,6 +4682,9 @@ class AppLocalizationsRu extends AppLocalizations { @override String get callsTabPeerUnknown => 'Не удалось определить собеседника'; + @override + String get callPeerIsBot => 'Ботам нельзя звонить'; + @override String get callsTabAlreadyInCall => 'Звонок уже идёт'; @@ -6466,4 +6484,17 @@ class AppLocalizationsRu extends AppLocalizations { @override String get avatarPickerFilesSubtitle => 'Если нужного фото нет в галерее'; + + @override + String get appearanceBottomNavigationTitle => 'Нижняя панель'; + + @override + String get appearanceBottomNavigationSubtitle => + 'Компактная панель занимает меньше места и всегда показывает названия четырёх вкладок.'; + + @override + String get appearanceBottomNavigationFloating => 'Плавающая'; + + @override + String get appearanceBottomNavigationCompact => 'Компактная'; } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 78cb220f..4d05ec48 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -35,9 +35,13 @@ "loginLanguage": "Язык", "languageNameRu": "Русский", "languageNameEn": "English", + "languageServerTitle": "Менять язык и для сервера тоже", + "languageServerSubtitle": "При включении переключателя названия встроенных папок, уведомления о серверных ошибках и некоторые встроенные элементы будут на выбранном вами языке. По умолчанию они не переводятся.", "selectCountryTitle": "Выберите страну", "selectCountrySearchHint": "Поиск страны…", "codeConfirmationSmsSent": "Мы отправили SMS с кодом подтверждения на ваш номер телефона.", + "codeConfirmationCheckMaxChat": "Проверьте чат «Коды подтверждения» в МАХ.", + "loginSlowSmsHint": "Вход с этим способом дольше обычного. Подождите немного, не выходите.", "codeResendInSeconds": "Отправить повторно через {seconds} сек.", "@codeResendInSeconds": { "placeholders": { @@ -1508,6 +1512,7 @@ "callsTabStatusIncoming": "Входящий", "callsTabCallBack": "Перезвонить", "callsTabPeerUnknown": "Не удалось определить собеседника", + "callPeerIsBot": "Ботам нельзя звонить", "callsTabAlreadyInCall": "Звонок уже идёт", "callsTabStartFailed": "Не удалось начать звонок: {error}", "callsTabJoinTitle": "Присоединиться к звонку", @@ -2007,5 +2012,9 @@ "avatarEditorSetPhoto": "Установить фото", "avatarEditorDraw": "Рисовать", "avatarPickerFilesTitle": "Выбрать фото из файлов", - "avatarPickerFilesSubtitle": "Если нужного фото нет в галерее" + "avatarPickerFilesSubtitle": "Если нужного фото нет в галерее", + "appearanceBottomNavigationTitle": "Нижняя панель", + "appearanceBottomNavigationSubtitle": "Компактная панель занимает меньше места и всегда показывает названия четырёх вкладок.", + "appearanceBottomNavigationFloating": "Плавающая", + "appearanceBottomNavigationCompact": "Компактная" } diff --git a/lib/main.dart b/lib/main.dart index eae1dc8c..99b78a7f 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -26,6 +26,7 @@ import 'core/storage/local_contact_avatars.dart'; import 'core/crypto/e2ee_service.dart'; import 'core/storage/chat_encryption_store.dart'; import 'core/config/app_accent.dart'; +import 'core/config/app_language.dart'; import 'core/config/app_amoled.dart'; import 'core/config/app_badge.dart'; import 'core/config/app_show_extra_info.dart'; @@ -34,8 +35,7 @@ import 'core/config/app_bubble_behavior.dart'; import 'core/config/app_camera.dart'; import 'core/config/komet_settings.dart'; import 'core/security/app_lock.dart'; -import 'core/config/call_no_mute.dart'; -import 'core/config/debug_test.dart'; +import 'core/config/launch_flags.dart'; import 'core/config/app_bubble_shape.dart'; import 'core/config/app_cache_extent.dart'; import 'core/config/app_fonts.dart'; @@ -57,6 +57,7 @@ import 'core/config/app_chat_chrome.dart'; import 'core/config/app_composer_background.dart'; import 'core/config/app_composer_style.dart'; import 'core/config/app_nav_pill_style.dart'; +import 'core/config/app_bottom_navigation_style.dart'; import 'core/config/app_wallpaper_tint.dart'; import 'core/storage/chat_wallpaper_store.dart'; import 'core/utils/wallpaper_seed.dart'; @@ -92,6 +93,7 @@ import 'core/push/fkm_controller.dart'; import 'core/push/launcher_badge.dart'; import 'core/push/notification_bridge.dart'; import 'core/share/share_intent_bridge.dart'; +import 'core/share/native_share_account_sync.dart'; import 'core/push/push_service.dart'; import 'core/storage/app_database.dart'; import 'core/transport/tls_config.dart'; @@ -147,19 +149,6 @@ const PageTransitionsTheme _appPageTransitions = PageTransitionsTheme( }, ); -Future _loadInitialLocale() async { - final prefs = await SharedPreferences.getInstance(); - final code = prefs.getString('app_locale'); - if (code != null && (code == 'en' || code == 'ru')) { - return Locale(code); - } - final platform = WidgetsBinding.instance.platformDispatcher.locale; - if (platform.languageCode == 'en' || platform.languageCode == 'ru') { - return Locale(platform.languageCode); - } - return const Locale('ru'); -} - void _installLogCapture() { final previousDebugPrint = debugPrint; debugPrint = (String? message, {int? wrapWidth}) { @@ -200,14 +189,25 @@ void _installLogCapture() { void main(List args) async { WidgetsFlutterBinding.ensureInitialized(); + LaunchFlags.parse(args); trackHintBubblePresses(); debugPrint('KOMET-STARTUP: binding ready'); debugPrint('KOMET-STARTUP: initKolibri...'); await initKolibri(); debugPrint('KOMET-STARTUP: initKolibri done'); - DebugTest.parse(args); - CallNoMute.parse(args); _installLogCapture(); + if (LaunchFlags.summary.isNotEmpty) { + logger.i('Флаги запуска: ${LaunchFlags.summary.join(' ')}'); + } + if (LaunchFlags.unknown.isNotEmpty) { + logger.w('Неизвестные аргументы запуска: ${LaunchFlags.unknown.join(' ')}'); + } + if (LaunchFlags.debug) { + logger.w( + 'Запуск с ${LaunchFlags.activeDebugFlag}: в лог идёт весь трафик с данными' + '${LaunchFlags.revealLoginPayload ? ', включая payload LOGIN (19)' : ''}', + ); + } MediaKitVideoPlatform.registerOnDesktop(); if (AppInstance.isNamed) { SharedPreferences.setPrefix('flutter.${AppInstance.id}.'); @@ -232,7 +232,7 @@ void main(List args) async { unawaited(DeepLinkService.instance.init()); final packageInfoFuture = PackageInfo.fromPlatform(); - final localeFuture = _loadInitialLocale(); + final localeFuture = AppLanguage.load(); final hapticsFuture = Haptics.load(); final prefsFuture = SharedPreferences.getInstance(); final accentFuture = AppAccent.load(); @@ -249,6 +249,7 @@ void main(List args) async { final composerStyleFuture = AppComposerStyle.load(); final composerBackgroundFuture = AppComposerBackground.load(); final navPillStyleFuture = AppNavPillStyle.load(); + final bottomNavigationStyleFuture = AppBottomNavigationStyle.load(); final wallpaperTintFuture = AppWallpaperTint.load(); final themeScheduleFuture = AppThemeSchedule.load(); final messageActionsFuture = AppMessageActionsStyle.load(); @@ -325,6 +326,7 @@ void main(List args) async { composerStyleFuture, composerBackgroundFuture, navPillStyleFuture, + bottomNavigationStyleFuture, wallpaperTintFuture, themeScheduleFuture, messageActionsFuture, @@ -500,6 +502,7 @@ class KometAppState extends State NotificationBridge.instance.init(); unawaited(LauncherBadge.instance.init()); ShareIntentBridge.instance.init(); + NativeShareAccountSync.instance.init(api, accountModule, chats); WidgetsBinding.instance.addPostFrameCallback((_) { CallBridge.instance.checkInitialCall(); unawaited(NotificationBridge.instance.checkInitialChat()); @@ -634,6 +637,7 @@ class KometAppState extends State @override void dispose() { + NativeShareAccountSync.instance.dispose(); _finishReveal(); _sessionExpiredSub?.cancel(); _loginStatusSub?.cancel(); @@ -891,15 +895,13 @@ class KometAppState extends State } Future applyLocale(Locale locale) async { - if (!AppLocalizations.supportedLocales.any( - (l) => l.languageCode == locale.languageCode, - )) { - return; - } - final prefs = await SharedPreferences.getInstance(); - await prefs.setString('app_locale', locale.languageCode); + final serverLanguageBefore = AppLanguage.serverLanguageCode; + if (!await AppLanguage.save(locale)) return; if (mounted) { - setState(() => _locale = locale); + setState(() => _locale = AppLanguage.current.value); + } + if (AppLanguage.serverLanguageCode != serverLanguageBefore) { + unawaited(accountModule.refreshServerLanguage()); } } @@ -964,19 +966,24 @@ class KometAppState extends State ThemeData? _lightTheme; ThemeData? _darkTheme; - Color? _seedCacheKey; + ({Color seed, bool accent})? _seedCacheKey; ColorScheme? _seedCacheLight; ColorScheme? _seedCacheDark; - ({ColorScheme light, ColorScheme dark}) _schemesForSeed(Color seed) { - if (_seedCacheKey == seed && + ({ColorScheme light, ColorScheme dark}) _schemesForSeed( + Color seed, { + required bool accent, + }) { + final key = (seed: seed, accent: accent); + if (_seedCacheKey == key && _seedCacheLight != null && _seedCacheDark != null) { return (light: _seedCacheLight!, dark: _seedCacheDark!); } - _seedCacheKey = seed; - _seedCacheLight = schemeFromSeed(seed, Brightness.light); - _seedCacheDark = schemeFromSeed(seed, Brightness.dark); + final build = accent ? accentSchemeFromSeed : schemeFromSeed; + _seedCacheKey = key; + _seedCacheLight = build(seed, Brightness.light); + _seedCacheDark = build(seed, Brightness.dark); return (light: _seedCacheLight!, dark: _seedCacheDark!); } @@ -1087,21 +1094,25 @@ class KometAppState extends State AppWallpaperTint.current, ]), builder: (context, _) { - final seed = - AppWallpaperTint.current.value && wallpaperSeed.value != null + final tintSeed = AppWallpaperTint.current.value ? wallpaperSeed.value - : accentSeed.value; + : null; + final accentColor = accentSeed.value; + final seeded = tintSeed != null + ? _schemesForSeed(tintSeed, accent: false) + : accentColor != null + ? _schemesForSeed(accentColor, accent: true) + : null; final ColorScheme lightBase; final ColorScheme darkBase; - if (seed != null) { - final s = _schemesForSeed(seed); - lightBase = s.light; - darkBase = s.dark; + if (seeded != null) { + lightBase = seeded.light; + darkBase = seeded.dark; } else if (lightDynamic != null && darkDynamic != null) { lightBase = lightDynamic; darkBase = darkDynamic; } else { - final s = _schemesForSeed(_fallbackSeed); + final s = _schemesForSeed(_fallbackSeed, accent: false); lightBase = lightDynamic ?? s.light; darkBase = darkDynamic ?? s.dark; } @@ -1230,7 +1241,7 @@ class _StartupScreenState extends State<_StartupScreen> { } Future _tryAutoLogin() async { - if (DebugTest.enabled) { + if (LaunchFlags.debugTest) { await Future.delayed(Duration.zero); if (!mounted) return; Navigator.pushReplacement( diff --git a/lib/models/shared_payload.dart b/lib/models/shared_payload.dart index 0af73744..53902e5e 100644 --- a/lib/models/shared_payload.dart +++ b/lib/models/shared_payload.dart @@ -38,10 +38,41 @@ class SharedFile { // #***! тип по mime, svg это документ SharedFileKind get kind { - if (mime.startsWith('image/') && !mime.contains('svg')) { + final type = mime.split(';').first.trim().toLowerCase(); + if (type.startsWith('image/') && !type.contains('svg')) { return SharedFileKind.photo; } - if (mime.startsWith('video/')) return SharedFileKind.video; + if (type.startsWith('video/')) return SharedFileKind.video; + if (type.isEmpty || type == 'application/octet-stream') { + final dot = name.lastIndexOf('.'); + if (dot < 0) return SharedFileKind.file; + final extension = name.substring(dot + 1).toLowerCase(); + if (const { + 'jpg', + 'jpeg', + 'png', + 'gif', + 'webp', + 'heic', + 'heif', + 'bmp', + 'tif', + 'tiff', + 'avif', + }.contains(extension)) { + return SharedFileKind.photo; + } + if (const { + 'mp4', + 'mov', + 'm4v', + 'webm', + 'mkv', + 'avi', + }.contains(extension)) { + return SharedFileKind.video; + } + } return SharedFileKind.file; } diff --git a/native/komet_share/.gitignore b/native/komet_share/.gitignore new file mode 100644 index 00000000..b83d2226 --- /dev/null +++ b/native/komet_share/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/native/komet_share/Cargo.lock b/native/komet_share/Cargo.lock new file mode 100644 index 00000000..17f424a4 --- /dev/null +++ b/native/komet_share/Cargo.lock @@ -0,0 +1,740 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "kolibri-net" +version = "0.1.2" +source = "git+https://github.com/KometTeam/kolibri?tag=dart-v0.1.4#a6cdce9e0e75d33aa0c398988d3b45e25c8908ab" +dependencies = [ + "base64", + "lz4_flex", + "rmpv", + "rustls", + "rustls-pemfile", + "serde_json", + "sha2", + "thiserror", + "tokio", + "tokio-rustls", + "webpki-roots 0.26.11", + "zstd", +] + +[[package]] +name = "komet_share" +version = "0.1.0" +dependencies = [ + "fs2", + "hex", + "kolibri-net", + "rmpv", + "serde", + "serde_json", + "sha2", + "tempfile", + "tokio", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "lz4_flex" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a" +dependencies = [ + "twox-hash", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rmp" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "rmpv" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a4e1d4b9b938a26d2996af33229f0ca0956c652c1375067f0b45291c1df8417" +dependencies = [ + "rmp", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio" +version = "1.53.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "twox-hash" +version = "2.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5283634e518fe9e82c7b20520bb4bc209009fd16c82077c802f8111ecbb0117a" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.9", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.0+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/native/komet_share/Cargo.toml b/native/komet_share/Cargo.toml new file mode 100644 index 00000000..55fb269c --- /dev/null +++ b/native/komet_share/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "komet_share" +version = "0.1.0" +edition = "2021" +license = "MIT" + +[lib] +crate-type = ["staticlib", "rlib"] + +[dependencies] +kolibri-net = { git = "https://github.com/KometTeam/kolibri", tag = "dart-v0.1.4", default-features = false, features = ["transport", "json"] } +tokio = { version = "1", features = ["rt-multi-thread", "time", "macros"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +rmpv = "1" +sha2 = "0.10" +hex = "0.4" +fs2 = "0.4" +tempfile = "3" + +[workspace] + +[profile.release] +opt-level = "z" +lto = true +codegen-units = 1 +strip = true +panic = "unwind" diff --git a/native/komet_share/src/engine.rs b/native/komet_share/src/engine.rs new file mode 100644 index 00000000..3c730597 --- /dev/null +++ b/native/komet_share/src/engine.rs @@ -0,0 +1,472 @@ +use std::fs::{self, File, OpenOptions}; +use std::io::Write; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +use fs2::FileExt; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; + +pub type Progress = Arc; +pub type UploadProgress = Arc; + +#[derive(Serialize)] +pub struct ProgressUpdate { + pub phase: &'static str, + pub message: &'static str, + pub progress: Option, + pub sent: u64, + pub total: u64, +} + +struct UploadCounter { + finished: u64, + total: u64, + current_total: u64, + current_sent: u64, +} + +#[derive(Deserialize)] +pub struct Input { + pub account_id: String, + pub token: String, + pub session: crate::transport::SessionOptions, + #[serde(default)] + pub login: Value, + pub request: ShareRequest, +} + +#[derive(Deserialize, Serialize)] +pub struct ShareRequest { + pub id: String, + pub chat_id: String, + #[serde(default)] + pub files: Vec, + #[serde(default)] + pub text: String, + pub state_path: String, +} + +#[derive(Clone, Deserialize, Serialize)] +pub struct SharedFile { + pub path: String, + pub name: String, + pub mime: String, + pub size: u64, +} + +impl SharedFile { + pub fn is_photo(&self) -> bool { + self.mime.starts_with("image/") && self.mime != "image/gif" && self.mime != "image/svg+xml" + } +} + +impl Input { + pub fn validate_files(&self) -> Result<(), String> { + for file in &self.request.files { + let metadata = fs::symlink_metadata(&file.path) + .map_err(|_| "Файл больше недоступен. Выберите его заново".to_string())?; + if !Path::new(&file.path).is_absolute() + || !metadata.is_file() + || metadata.len() != file.size + || file.name.is_empty() + { + return Err("Файл изменён или недоступен. Выберите его заново".into()); + } + } + Ok(()) + } +} + +#[derive(Serialize, Debug)] +pub struct Outcome { + pub status: String, + pub message: String, + pub sent_count: usize, + pub total_count: usize, + pub message_ids: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub refreshed_token: Option, +} + +impl Outcome { + pub fn failed(message: &str) -> Self { + Self { + status: "failed".into(), + message: message.into(), + sent_count: 0, + total_count: 0, + message_ids: vec![], + refreshed_token: None, + } + } + + pub fn unknown(message: &str) -> Self { + Self { + status: "unknown".into(), + ..Self::failed(message) + } + } +} + +#[derive(Deserialize, Serialize)] +struct SavedState { + version: u32, + identity: String, + entries: Vec, +} + +#[derive(Deserialize, Serialize)] +struct Entry { + files: Vec, + cid: i64, + status: EntryStatus, + payload: Option, + message_id: Option, +} + +#[derive(Clone, Copy, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "snake_case")] +enum EntryStatus { + Pending, + Sending, + Sent, + Failed, + Unknown, +} + +pub struct Journal { + path: String, + state: SavedState, + _lock: File, +} + +impl Journal { + pub fn open(input: &Input) -> Result { + let request = &input.request; + if input.account_id.parse::().is_err() + || request.chat_id.parse::().is_err() + || request.id.is_empty() + || input.token.is_empty() + || request.files.len() > 30 + || (request.files.is_empty() && request.text.trim().is_empty()) + || !Path::new(&request.state_path).is_absolute() + { + return Err(Outcome::failed("Недостаточно данных для отправки")); + } + let lock = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(format!("{}.lock", request.state_path)) + .map_err(|_| Outcome::failed("Не удалось сохранить состояние отправки"))?; + lock.try_lock_exclusive() + .map_err(|_| Outcome::failed("Эта отправка уже выполняется"))?; + let identity = hex::encode(Sha256::digest( + json!({ + "account_id": input.account_id, + "request": request, + }) + .to_string(), + )); + let state = match fs::read(&request.state_path) { + Ok(bytes) => { + let state: SavedState = serde_json::from_slice(&bytes).map_err(|_| { + Outcome::unknown("Состояние отправки повреждено. Проверьте чат") + })?; + if state.version != 1 || state.identity != identity { + return Err(Outcome::unknown( + "Данные отправки изменены. Проверьте чат перед повтором", + )); + } + state + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + let photos: Vec = request + .files + .iter() + .enumerate() + .filter_map(|(index, file)| file.is_photo().then_some(index)) + .collect(); + let mut groups = Vec::new(); + if !photos.is_empty() { + groups.push(photos); + } + groups.extend( + request + .files + .iter() + .enumerate() + .filter_map(|(index, file)| (!file.is_photo()).then_some(vec![index])), + ); + if groups.is_empty() { + groups.push(vec![]); + } + let entries = groups + .into_iter() + .enumerate() + .map(|(index, files)| { + let digest = Sha256::digest(format!( + "{}:{}:{}", + input.account_id, request.id, index + )); + let raw = i64::from_be_bytes(digest[..8].try_into().unwrap()); + Entry { + files, + cid: -(raw & i64::MAX).max(1), + status: EntryStatus::Pending, + payload: None, + message_id: None, + } + }) + .collect(); + SavedState { + version: 1, + identity, + entries, + } + } + Err(_) => { + return Err(Outcome::unknown( + "Не удалось прочитать состояние отправки. Проверьте чат", + )) + } + }; + let journal = Self { + path: request.state_path.clone(), + state, + _lock: lock, + }; + journal + .persist() + .map_err(|_| Outcome::failed("Не удалось сохранить состояние отправки"))?; + Ok(journal) + } + + fn persist(&self) -> Result<(), ()> { + let parent = Path::new(&self.path).parent().ok_or(())?; + let mut file = tempfile::NamedTempFile::new_in(parent).map_err(|_| ())?; + serde_json::to_writer(&mut file, &self.state).map_err(|_| ())?; + file.flush().map_err(|_| ())?; + file.as_file().sync_all().map_err(|_| ())?; + file.persist(&self.path).map_err(|_| ())?; + Ok(()) + } + + pub fn terminal(&self) -> Option { + if self + .state + .entries + .iter() + .all(|entry| entry.status == EntryStatus::Sent) + { + return Some(self.outcome("sent", "Отправлено")); + } + if self + .state + .entries + .iter() + .any(|entry| matches!(entry.status, EntryStatus::Sending | EntryStatus::Unknown)) + { + return Some(self.outcome( + "unknown", + "Сервер мог получить сообщение. Проверьте чат; автоматический повтор остановлен", + )); + } + None + } + + pub fn outcome(&self, status: &str, message: &str) -> Outcome { + Outcome { + status: status.into(), + message: message.into(), + sent_count: self + .state + .entries + .iter() + .filter(|entry| entry.status == EntryStatus::Sent) + .count(), + total_count: self.state.entries.len(), + message_ids: self + .state + .entries + .iter() + .filter_map(|entry| entry.message_id.clone()) + .collect(), + refreshed_token: None, + } + } +} + +pub enum SendError { + Rejected(String), + Unknown, +} + +pub trait Transport { + async fn upload( + &mut self, + file: &SharedFile, + progress: UploadProgress, + ) -> Result; + async fn send(&mut self, payload: &Value) -> Result; +} + +pub async fn deliver( + input: &Input, + journal: &mut Journal, + transport: &mut impl Transport, + progress: Progress, +) -> Outcome { + if let Some(outcome) = journal.terminal() { + return outcome; + } + let count = journal.state.entries.len(); + let counter = Arc::new(Mutex::new(UploadCounter { + total: input.request.files.iter().map(|file| file.size).sum(), + finished: journal + .state + .entries + .iter() + .filter(|entry| entry.payload.is_some()) + .flat_map(|entry| &entry.files) + .map(|index| input.request.files[*index].size) + .sum(), + current_total: 0, + current_sent: 0, + })); + for index in 0..count { + if journal.state.entries[index].status == EntryStatus::Sent { + continue; + } + if journal.state.entries[index].payload.is_none() { + let mut attachments = Vec::new(); + let files = journal.state.entries[index].files.clone(); + for file_index in &files { + let callback = progress.clone(); + { + let mut bytes = counter.lock().unwrap(); + bytes.current_total = input.request.files[*file_index].size; + bytes.current_sent = 0; + } + let bytes = counter.clone(); + let file_progress: UploadProgress = Arc::new(move |sent, total| { + let mut bytes = bytes.lock().unwrap(); + if total > 0 { + bytes.total = bytes + .total + .saturating_sub(bytes.current_total) + .saturating_add(total); + bytes.current_total = total; + } + bytes.current_sent = bytes.current_sent.max(sent.min(bytes.current_total)); + let sent = bytes.finished.saturating_add(bytes.current_sent); + let total = bytes.total; + callback(ProgressUpdate { + phase: "uploading", + message: "Загрузка вложений…", + progress: (total > 0).then(|| (sent as f64 / total as f64).clamp(0.0, 1.0)), + sent, + total, + }); + }); + match transport + .upload(&input.request.files[*file_index], file_progress) + .await + { + Ok(attachment) => { + attachments.push(attachment); + let mut bytes = counter.lock().unwrap(); + bytes.finished = bytes.finished.saturating_add(bytes.current_total); + } + Err(message) => return journal.outcome("failed", &message), + } + } + let mut message = json!({ + "cid": journal.state.entries[index].cid, + "attaches": attachments, + "isLive": false, + "detectShare": false, + "elements": [], + }); + if index == 0 && !input.request.text.trim().is_empty() { + message["text"] = json!(input.request.text); + } + journal.state.entries[index].payload = Some(json!({ + "chatId": input.request.chat_id.parse::().unwrap(), + "message": message, + "notify": true, + })); + if journal.persist().is_err() { + return journal.outcome( + "failed", + "Не удалось сохранить загрузку. Сообщение не отправлено", + ); + } + } + } + for index in 0..count { + if journal.state.entries[index].status == EntryStatus::Sent { + continue; + } + journal.state.entries[index].status = EntryStatus::Sending; + if journal.persist().is_err() { + journal.state.entries[index].status = EntryStatus::Failed; + return journal.outcome( + "failed", + "Не удалось сохранить отправку. Сообщение не отправлено", + ); + } + let total = counter.lock().unwrap().total; + progress(ProgressUpdate { + phase: "sending", + message: "Подтверждение отправки…", + progress: (total > 0).then_some(1.0), + sent: total, + total, + }); + let payload = journal.state.entries[index].payload.as_ref().unwrap(); + match transport.send(payload).await { + Ok(message_id) => { + journal.state.entries[index].status = EntryStatus::Sent; + journal.state.entries[index].message_id = Some(message_id); + if journal.persist().is_err() { + return journal.outcome( + "unknown", + "Сообщение отправлено, но подтверждение не сохранено. Проверьте чат", + ); + } + } + Err(SendError::Rejected(message)) => { + journal.state.entries[index].status = EntryStatus::Failed; + if journal.persist().is_err() { + return journal + .outcome("unknown", "Не удалось сохранить результат. Проверьте чат"); + } + return journal.outcome("failed", &message); + } + Err(SendError::Unknown) => { + journal.state.entries[index].status = EntryStatus::Unknown; + let _ = journal.persist(); + return journal.outcome( + "unknown", + "Соединение прервано после отправки. Проверьте чат; повтор остановлен", + ); + } + } + } + let total = counter.lock().unwrap().total; + progress(ProgressUpdate { + phase: "sent", + message: "Отправлено", + progress: (total > 0).then_some(1.0), + sent: total, + total, + }); + journal.outcome("sent", "Отправлено") +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/native/komet_share/src/engine/tests.rs b/native/komet_share/src/engine/tests.rs new file mode 100644 index 00000000..f74b132c --- /dev/null +++ b/native/komet_share/src/engine/tests.rs @@ -0,0 +1,342 @@ +use super::*; +use std::collections::VecDeque; + +pub(crate) fn input(directory: &Path, files: Vec) -> Input { + serde_json::from_value(json!({ + "account_id": "123", "token": "synthetic-auth-token", + "session": { + "host": "example.test", "port": 443, "device_id": "synthetic-device", + "instance_id": "synthetic-instance", "app_version": "1.0", "build_number": 1, + "device_type": "IOS", "os_version": "18.0", "timezone": "UTC", "screen": "390x844", + "push_device_type": "APNS", "arch": "arm64", "locale": "ru", "device_name": "Synthetic Phone", + "device_locale": "ru_RU", "client_session_id": 321, "ping_interactive": true, + "fingerprint_digests": {"signature": "010203", "dex": "040506", "so": "070809"} + }, + "login": {"chatCacheFingerprint": "stale", "exp": {"chatsCountGroups": {"$bin": "CzI="}}}, + "request": {"id": "synthetic-request", "chat_id": "456", "files": files, + "text": "Synthetic caption", "state_path": directory.join("state.json")} + })).unwrap() +} + +fn file(directory: &Path, name: &str, mime: &str, size: usize) -> SharedFile { + let path = directory.join(name); + fs::write(&path, vec![0_u8; size]).unwrap(); + SharedFile { + path: path.to_str().unwrap().into(), + name: name.into(), + mime: mime.into(), + size: size as u64, + } +} + +#[derive(Default)] +struct FakeTransport { + uploaded: Vec, + sent: Vec, + replies: VecDeque>, + state_path: Option, + upload_failure: bool, + out_of_order_progress: bool, +} + +impl Transport for FakeTransport { + async fn upload( + &mut self, + file: &SharedFile, + progress: UploadProgress, + ) -> Result { + self.uploaded.push(file.name.clone()); + progress(file.size / 2, file.size); + if self.upload_failure { + return Err("Synthetic upload failure".into()); + } + progress(file.size, file.size); + if self.out_of_order_progress { + progress(file.size / 4, file.size); + } + Ok(json!({"_type": if file.is_photo() { "PHOTO" } else { "FILE" }, "token": file.name})) + } + + async fn send(&mut self, payload: &Value) -> Result { + if let Some(path) = &self.state_path { + let state: Value = serde_json::from_slice(&fs::read(path).unwrap()).unwrap(); + assert!(state["entries"].as_array().unwrap().iter().any(|entry| { + entry["cid"] == payload["message"]["cid"] && entry["status"] == "sending" + })); + } + self.sent.push(payload.clone()); + self.replies + .pop_front() + .unwrap_or_else(|| Ok(format!("synthetic-message-{}", self.sent.len()))) + } +} + +fn events() -> (Progress, Arc>>) { + let values = Arc::new(Mutex::new(Vec::new())); + let storage = values.clone(); + ( + Arc::new(move |event| { + storage + .lock() + .unwrap() + .push(serde_json::to_value(event).unwrap()) + }), + values, + ) +} + +#[tokio::test] +async fn photos_form_album_and_caption_is_sent_once() { + let directory = tempfile::tempdir().unwrap(); + let input = input( + directory.path(), + vec![ + file(directory.path(), "doc.pdf", "application/pdf", 100), + file(directory.path(), "first.jpg", "image/jpeg", 200), + file(directory.path(), "second.jpg", "image/jpeg", 300), + file(directory.path(), "animated.gif", "image/gif", 400), + ], + ); + let mut journal = Journal::open(&input).unwrap(); + let mut transport = FakeTransport { + state_path: Some(input.request.state_path.clone()), + ..Default::default() + }; + let (progress, values) = events(); + let outcome = deliver(&input, &mut journal, &mut transport, progress).await; + assert_eq!(outcome.status, "sent"); + assert_eq!(outcome.sent_count, 3); + assert_eq!( + transport.sent[0]["message"]["attaches"] + .as_array() + .unwrap() + .len(), + 2 + ); + assert_eq!(transport.sent[0]["message"]["text"], "Synthetic caption"); + assert!(transport.sent[1]["message"].get("text").is_none()); + assert_eq!(transport.sent[2]["message"]["attaches"][0]["_type"], "FILE"); + let values = values.lock().unwrap(); + let first_sending = values + .iter() + .position(|event| event["phase"] == "sending") + .unwrap(); + assert!(values[first_sending..] + .iter() + .all(|event| event["phase"] != "uploading")); + assert_eq!(values.last().unwrap()["phase"], "sent"); + assert!(!fs::read_to_string(&input.request.state_path) + .unwrap() + .contains(&input.token)); +} + +#[tokio::test] +async fn unknown_send_is_never_repeated_after_restart() { + let directory = tempfile::tempdir().unwrap(); + let input = input(directory.path(), vec![]); + let mut journal = Journal::open(&input).unwrap(); + let mut transport = FakeTransport { + replies: VecDeque::from([Err(SendError::Unknown)]), + state_path: Some(input.request.state_path.clone()), + ..Default::default() + }; + let (progress, values) = events(); + assert_eq!( + deliver(&input, &mut journal, &mut transport, progress) + .await + .status, + "unknown" + ); + assert!(values + .lock() + .unwrap() + .iter() + .all(|event| event["phase"] != "sent")); + drop(journal); + let mut journal = Journal::open(&input).unwrap(); + let mut restarted = FakeTransport::default(); + assert_eq!( + deliver(&input, &mut journal, &mut restarted, events().0) + .await + .status, + "unknown" + ); + assert!(restarted.sent.is_empty()); +} + +#[tokio::test] +async fn crash_with_sending_marker_blocks_duplicate_even_without_unknown_write() { + let directory = tempfile::tempdir().unwrap(); + let input = input(directory.path(), vec![]); + let mut journal = Journal::open(&input).unwrap(); + journal.state.entries[0].status = EntryStatus::Sending; + journal.persist().unwrap(); + drop(journal); + let mut restarted = Journal::open(&input).unwrap(); + let mut transport = FakeTransport::default(); + assert_eq!( + deliver(&input, &mut restarted, &mut transport, events().0) + .await + .status, + "unknown" + ); + assert!(transport.sent.is_empty()); +} + +#[tokio::test] +async fn explicit_retry_skips_sent_messages_and_reuses_cid_and_upload() { + let directory = tempfile::tempdir().unwrap(); + let input = input( + directory.path(), + vec![ + file(directory.path(), "one.pdf", "application/pdf", 100), + file(directory.path(), "two.pdf", "application/pdf", 300), + ], + ); + let mut journal = Journal::open(&input).unwrap(); + let mut transport = FakeTransport { + replies: VecDeque::from([ + Ok("synthetic-first".into()), + Err(SendError::Rejected("Synthetic rejection".into())), + ]), + ..Default::default() + }; + let outcome = deliver(&input, &mut journal, &mut transport, events().0).await; + assert_eq!(outcome.status, "failed"); + assert_eq!(outcome.sent_count, 1); + let failed_cid = transport.sent[1]["message"]["cid"].clone(); + drop(journal); + let mut journal = Journal::open(&input).unwrap(); + let mut retry = FakeTransport::default(); + let outcome = deliver(&input, &mut journal, &mut retry, events().0).await; + assert_eq!(outcome.status, "sent"); + assert_eq!(outcome.sent_count, 2); + assert_eq!(retry.sent.len(), 1); + assert_eq!(retry.sent[0]["message"]["cid"], failed_cid); + assert!(retry.uploaded.is_empty()); + drop(journal); + assert_eq!( + Journal::open(&input).unwrap().terminal().unwrap().status, + "sent" + ); +} + +#[tokio::test] +async fn progress_uses_aggregate_bytes_and_text_remains_indeterminate() { + let directory = tempfile::tempdir().unwrap(); + let input = input( + directory.path(), + vec![ + file(directory.path(), "one.pdf", "application/pdf", 100), + file(directory.path(), "two.pdf", "application/pdf", 300), + ], + ); + let mut journal = Journal::open(&input).unwrap(); + let (progress, values) = events(); + deliver( + &input, + &mut journal, + &mut FakeTransport::default(), + progress, + ) + .await; + let values = values.lock().unwrap(); + let uploading: Vec<_> = values + .iter() + .filter(|event| event["phase"] == "uploading") + .collect(); + assert_eq!( + uploading + .iter() + .map(|value| value["sent"].as_u64().unwrap()) + .collect::>(), + vec![50, 100, 250, 400] + ); + assert_eq!( + uploading + .iter() + .map(|value| value["progress"].as_f64().unwrap()) + .collect::>(), + vec![0.125, 0.25, 0.625, 1.0] + ); + assert!(uploading.iter().all(|event| event["total"] == 400)); + drop(values); + let text_directory = tempfile::tempdir().unwrap(); + let text = self::input(text_directory.path(), vec![]); + let mut journal = Journal::open(&text).unwrap(); + let (progress, values) = events(); + deliver(&text, &mut journal, &mut FakeTransport::default(), progress).await; + assert!(values + .lock() + .unwrap() + .iter() + .all(|event| event["progress"].is_null())); +} + +#[tokio::test] +async fn failed_upload_does_not_attempt_message_send() { + let directory = tempfile::tempdir().unwrap(); + let input = input( + directory.path(), + vec![file(directory.path(), "test.pdf", "application/pdf", 100)], + ); + let mut journal = Journal::open(&input).unwrap(); + let mut transport = FakeTransport { + upload_failure: true, + ..Default::default() + }; + let outcome = deliver(&input, &mut journal, &mut transport, events().0).await; + assert_eq!(outcome.status, "failed"); + assert!(transport.sent.is_empty()); +} + +#[test] +fn exclusive_journal_and_identity_prevent_parallel_or_modified_replay() { + let directory = tempfile::tempdir().unwrap(); + let mut input = input(directory.path(), vec![]); + let journal = Journal::open(&input).unwrap(); + assert_eq!(Journal::open(&input).err().unwrap().status, "failed"); + drop(journal); + input.request.text = "Changed caption".into(); + assert_eq!(Journal::open(&input).err().unwrap().status, "unknown"); +} + +#[test] +fn missing_or_changed_file_is_rejected_before_network() { + let directory = tempfile::tempdir().unwrap(); + let input = input( + directory.path(), + vec![file( + directory.path(), + "name\"with quote.txt", + "text/plain", + 100, + )], + ); + assert!(input.validate_files().is_ok()); + fs::write(&input.request.files[0].path, b"changed").unwrap(); + assert!(input.validate_files().is_err()); +} + +#[tokio::test] +async fn concurrent_video_callback_order_cannot_reduce_sent_bytes() { + let directory = tempfile::tempdir().unwrap(); + let input = input( + directory.path(), + vec![file(directory.path(), "clip.mp4", "video/mp4", 400)], + ); + let mut journal = Journal::open(&input).unwrap(); + let mut transport = FakeTransport { + out_of_order_progress: true, + ..Default::default() + }; + let (progress, values) = events(); + deliver(&input, &mut journal, &mut transport, progress).await; + let values = values.lock().unwrap(); + let sent: Vec<_> = values + .iter() + .filter(|event| event["phase"] == "uploading") + .map(|event| event["sent"].as_u64().unwrap()) + .collect(); + assert_eq!(sent, vec![200, 400, 400]); +} diff --git a/native/komet_share/src/lib.rs b/native/komet_share/src/lib.rs new file mode 100644 index 00000000..8b657cbb --- /dev/null +++ b/native/komet_share/src/lib.rs @@ -0,0 +1,104 @@ +mod engine; +mod transport; + +use std::ffi::{c_char, c_void, CStr, CString}; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use engine::{Input, Journal, Outcome, Progress, ProgressUpdate}; + +static SEND_LOCK: Mutex<()> = Mutex::new(()); + +type ProgressCallback = unsafe extern "C" fn(*const c_char, *mut c_void); + +#[no_mangle] +pub unsafe extern "C" fn komet_share_send( + input: *const c_char, + callback: Option, + context: *mut c_void, +) -> *mut c_char { + let result = catch_unwind(AssertUnwindSafe(|| { + if input.is_null() { + return Outcome::failed("Нет данных для отправки"); + } + let input = + match serde_json::from_slice::(unsafe { CStr::from_ptr(input) }.to_bytes()) { + Ok(input) => input, + Err(_) => return Outcome::failed("Не удалось прочитать данные отправки"), + }; + let context = context as usize; + let last = Mutex::new((Instant::now() - Duration::from_secs(1), "")); + let progress: Progress = Arc::new(move |event| { + let mut last = last.lock().unwrap(); + if event.phase == last.1 + && last.0.elapsed() < Duration::from_millis(80) + && event.progress != Some(1.0) + { + return; + } + *last = (Instant::now(), event.phase); + drop(last); + if let Some(callback) = callback { + let json = serde_json::to_string(&event).unwrap(); + if let Ok(text) = CString::new(json) { + unsafe { callback(text.as_ptr(), context as *mut c_void) }; + } + } + }); + send(input, progress) + })) + .unwrap_or_else(|_| Outcome::unknown("Отправка прервана. Проверьте чат перед повтором")); + CString::new(serde_json::to_string(&result).unwrap_or_else(|_| { + "{\"status\":\"unknown\",\"message\":\"Не удалось подтвердить отправку\"}".into() + })) + .unwrap() + .into_raw() +} + +#[no_mangle] +pub unsafe extern "C" fn komet_share_free(value: *mut c_char) { + if !value.is_null() { + drop(unsafe { CString::from_raw(value) }); + } +} + +fn send(input: Input, progress: Progress) -> Outcome { + let Ok(_guard) = SEND_LOCK.try_lock() else { + return Outcome::failed("Дождитесь завершения текущей отправки"); + }; + let mut journal = match Journal::open(&input) { + Ok(value) => value, + Err(outcome) => return outcome, + }; + if let Some(outcome) = journal.terminal() { + return outcome; + } + if let Err(message) = input.validate_files() { + return journal.outcome("failed", &message); + } + let runtime = match tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(_) => return journal.outcome("failed", "Не удалось запустить отправку"), + }; + runtime.block_on(async { + progress(ProgressUpdate { + phase: "connecting", + message: "Подключение к Komet…", + progress: None, + sent: 0, + total: 0, + }); + let mut transport = match transport::Connection::connect(&input).await { + Ok(transport) => transport, + Err(message) => return journal.outcome("failed", &message), + }; + let mut outcome = engine::deliver(&input, &mut journal, &mut transport, progress).await; + outcome.refreshed_token = transport.refreshed_token.clone(); + outcome + }) +} diff --git a/native/komet_share/src/transport.rs b/native/komet_share/src/transport.rs new file mode 100644 index 00000000..ddbf4312 --- /dev/null +++ b/native/komet_share/src/transport.rs @@ -0,0 +1,545 @@ +use sha2::{Digest, Sha256}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use kolibri_net::{ + media, opcodes, ClientConfig, HandshakeConfig, ProxyConfig, Session, SessionConfig, UserAgent, +}; +use serde::Deserialize; +use serde_json::{json, Value}; + +use crate::engine::{Input, SendError, SharedFile, Transport, UploadProgress}; + +#[derive(Deserialize)] +pub struct SessionOptions { + pub host: String, + pub port: u16, + pub device_id: String, + pub instance_id: String, + pub app_version: String, + pub build_number: i64, + pub device_type: String, + pub os_version: String, + pub timezone: String, + pub screen: String, + pub push_device_type: String, + pub arch: String, + pub locale: String, + pub device_name: String, + pub device_locale: String, + pub client_session_id: i64, + #[serde(default)] + pub ping_interactive: bool, + #[serde(default)] + pub insecure_tls: bool, + #[serde(default)] + pub trust_mincifry_ca: bool, + pub proxy: Option, + pub is_pwa: Option, + pub header_user_agent: Option, + pub fingerprint_digests: Option, +} + +#[derive(Deserialize)] +pub struct FingerprintDigests { + signature: String, + dex: String, + so: String, +} + +impl FingerprintDigests { + fn decode(&self) -> Result<[Vec; 3], String> { + let decode = |value: &str| { + hex::decode(value) + .ok() + .filter(|bytes| !bytes.is_empty() && bytes.len() <= 64) + .ok_or_else(|| "Обновите данные аккаунта в приложении Komet".to_string()) + }; + Ok([ + decode(&self.signature)?, + decode(&self.dex)?, + decode(&self.so)?, + ]) + } +} + +pub struct Connection { + session: Session, + proxy: Option, + insecure_tls: bool, + pub refreshed_token: Option, +} + +struct Response { + ok: bool, + body: Value, +} + +impl Connection { + pub async fn connect(input: &Input) -> Result { + let options = &input.session; + kolibri_net::set_trust_mincifry_ca(options.trust_mincifry_ca); + let proxy = options + .proxy + .as_deref() + .map(ProxyConfig::parse) + .transpose() + .map_err(|_| "Проверьте настройки прокси в Komet".to_string())?; + let mut client = ClientConfig::new(&options.host, options.port); + client.proxy = proxy.clone(); + client.insecure_tls = options.insecure_tls; + let handshake = HandshakeConfig { + instance_id: options.instance_id.clone(), + device_id: options.device_id.clone(), + client_session_id: fresh_session_id(input), + user_agent: UserAgent { + device_type: options.device_type.clone(), + app_version: options.app_version.clone(), + os_version: options.os_version.clone(), + timezone: options.timezone.clone(), + screen: options.screen.clone(), + push_device_type: options.push_device_type.clone(), + arch: options.arch.clone(), + locale: options.locale.clone(), + build_number: options.build_number, + device_name: options.device_name.clone(), + device_locale: options.device_locale.clone(), + is_pwa: options.is_pwa, + header_user_agent: options.header_user_agent.clone(), + }, + }; + let mut config = SessionConfig::new(client, handshake); + config.auto_reconnect = false; + config.ping_interactive = options.ping_interactive; + let mut connection = Self { + session: Session::new(config), + proxy, + insecure_tls: options.insecure_tls, + refreshed_token: None, + }; + let info = connection + .session + .connect() + .await + .map_err(|_| "Не удалось подключиться к Komet. Проверьте интернет".to_string())?; + let payload = login_payload(input, info.calls_seed)?; + let response = connection + .request(opcodes::LOGIN, &payload) + .await + .map_err(|_| "Не удалось войти в Komet. Откройте приложение и повторите".to_string())?; + if !response.ok { + return Err(server_message( + &response.body, + "Войдите в аккаунт в приложении Komet", + )); + } + connection.refreshed_token = response + .body + .get("token") + .and_then(Value::as_str) + .filter(|token| !token.is_empty()) + .map(str::to_owned); + Ok(connection) + } + + async fn request(&self, opcode: u16, payload: &Value) -> Result { + let mut bytes = Vec::new(); + rmpv::encode::write_value(&mut bytes, &kolibri_net::protocol::json_to_value(payload)) + .map_err(|_| ())?; + let packet = self + .session + .request_raw(opcode, &bytes) + .await + .map_err(|_| ())?; + Ok(Response { + ok: packet.is_ok(), + body: packet.json_tagged().map_err(|_| ())?, + }) + } + + async fn upload_info(&self, opcode: u16, payload: Value) -> Result { + let response = self + .request(opcode, &payload) + .await + .map_err(|_| "Не удалось подготовить загрузку. Проверьте интернет".to_string())?; + if !response.ok { + return Err(server_message( + &response.body, + "Сервер не разрешил загрузку", + )); + } + Ok(response.body) + } +} + +fn fresh_session_id(input: &Input) -> i64 { + if input.session.client_session_id == 0 { + return 0; + } + static NEXT: AtomicU64 = AtomicU64::new(0); + let nonce = NEXT.fetch_add(1, Ordering::Relaxed); + let time = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_nanos(); + let digest = Sha256::digest(format!("{}:{time}:{nonce}", input.request.id)); + let mut id = (u32::from_be_bytes(digest[..4].try_into().unwrap()) & 0x7fff_ffff).max(1) as i64; + if id == input.session.client_session_id { + id = id % 0x7fff_ffff + 1; + } + id +} + +fn upload_filename(name: &str) -> String { + name.chars() + .map(|character| match character { + '\r' | '\n' | '"' | '\\' | ';' => '_', + value if value.is_control() => '_', + value => value, + }) + .collect() +} + +fn login_payload(input: &Input, seed: Option) -> Result { + let mut payload = input.login.as_object().cloned().unwrap_or_default(); + payload.insert("token".into(), json!(input.token)); + payload.remove("chatCacheFingerprint"); + if let (Some(seed), Some(digests)) = (seed, &input.session.fingerprint_digests) { + let [signature, dex, so] = digests.decode()?; + let fingerprint = kolibri_net::auth::chat_cache_fingerprint( + &signature, + &dex, + &so, + seed, + &input.session.device_id, + ); + payload.insert( + "chatCacheFingerprint".into(), + kolibri_net::protocol::value_to_json_tagged(&rmpv::Value::Binary(fingerprint)), + ); + } + payload + .entry("interactive") + .or_insert(json!(input.session.ping_interactive)); + Ok(Value::Object(payload)) +} + +fn server_message(body: &Value, fallback: &str) -> String { + ["localizedMessage", "message", "title"] + .iter() + .find_map(|key| body.get(key).and_then(Value::as_str)) + .unwrap_or(fallback) + .chars() + .take(300) + .collect() +} + +fn required_string<'a>(value: &'a Value, key: &str) -> Result<&'a str, String> { + value + .get(key) + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .ok_or_else(|| "Сервер вернул неполные данные загрузки".into()) +} + +fn photo_token(body: &[u8]) -> Option { + let value: Value = serde_json::from_slice(body).ok()?; + value + .get("photos") + .and_then(Value::as_object) + .and_then(|photos| { + photos + .values() + .find_map(|photo| photo.get("token").and_then(Value::as_str)) + }) + .or_else(|| value.get("photoToken").and_then(Value::as_str)) + .filter(|value| !value.is_empty()) + .map(str::to_owned) +} + +fn send_attempts(payload: &Value) -> usize { + let has_video = payload + .get("message") + .and_then(|message| message.get("attaches")) + .and_then(Value::as_array) + .is_some_and(|attachments| { + attachments + .iter() + .any(|attachment| attachment.get("_type").and_then(Value::as_str) == Some("VIDEO")) + }); + if has_video { + 30 + } else { + 20 + } +} + +impl Transport for Connection { + async fn upload( + &mut self, + file: &SharedFile, + progress: UploadProgress, + ) -> Result { + progress(0, file.size); + let on_progress: media::ProgressFn = Arc::new(move |sent, total| { + progress(sent, total); + }); + let ua = self.session.http_user_agent(); + let filename = upload_filename(&file.name); + if file.is_photo() { + let info = self + .upload_info(opcodes::PHOTO_UPLOAD, json!({"count": 1})) + .await?; + let url = required_string(&info, "url")?; + let response = media::upload_photo_path( + url, + &file.path, + &filename, + self.insecure_tls, + self.proxy.as_ref(), + Some(on_progress), + &ua, + ) + .await + .map_err(|_| "Не удалось загрузить фотографию".to_string())?; + if response.status != 200 { + return Err("Сервер не принял фотографию".into()); + } + let token = photo_token(&response.body) + .ok_or_else(|| "Сервер не подтвердил загрузку фотографии".to_string())?; + return Ok(json!({"_type": "PHOTO", "photoToken": token})); + } + let video = file.mime.starts_with("video/"); + let data = self + .upload_info( + if video { + opcodes::VIDEO_UPLOAD + } else { + opcodes::FILE_UPLOAD + }, + if video { + json!({"count": 1, "uploaderType": 0, "type": 0}) + } else { + json!({"count": 1}) + }, + ) + .await?; + let info = data + .get("info") + .and_then(Value::as_array) + .and_then(|list| list.first()) + .ok_or_else(|| "Сервер вернул неполные данные загрузки".to_string())?; + let url = required_string(info, "url")?; + let token = required_string(info, "token")?; + if video { + let uploaded = media::upload_video_path( + url, + &file.path, + 2 * 1024 * 1024, + 2, + self.insecure_tls, + self.proxy.clone(), + Some(on_progress), + ) + .await + .map_err(|_| "Не удалось загрузить видео".to_string())?; + if !uploaded { + return Err("Сервер не принял видео".into()); + } + Ok(json!({"_type": "VIDEO", "videoType": 0, "token": token})) + } else { + let response = media::upload_file_path( + url, + &file.path, + &filename, + None, + Some("close"), + self.insecure_tls, + self.proxy.as_ref(), + Some(on_progress), + &ua, + ) + .await + .map_err(|_| "Не удалось загрузить файл".to_string())?; + if response.status != 200 { + return Err("Сервер не принял файл".into()); + } + Ok(json!({"_type": "FILE", "token": token})) + } + } + + async fn send(&mut self, payload: &Value) -> Result { + let max_attempts = send_attempts(payload); + for attempt in 0..max_attempts { + let response = self + .request(opcodes::MSG_SEND, payload) + .await + .map_err(|_| SendError::Unknown)?; + if response.ok { + let id = response + .body + .get("message") + .and_then(|message| message.get("id")) + .and_then(|id| match id { + Value::String(value) => Some(value.clone()), + Value::Number(value) => Some(value.to_string()), + _ => None, + }) + .filter(|id| !id.is_empty()) + .ok_or(SendError::Unknown)?; + return Ok(id); + } + let not_ready = response + .body + .get("error") + .and_then(Value::as_str) + .is_some_and(|error| error.contains("not.ready")); + if not_ready && attempt + 1 < max_attempts { + tokio::time::sleep(Duration::from_secs(1)).await; + continue; + } + return Err(SendError::Rejected(server_message( + &response.body, + "Сервер отклонил отправку", + ))); + } + Err(SendError::Unknown) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unsafe_header_characters_do_not_reject_otherwise_valid_names() { + assert_eq!(upload_filename("Фото \"июнь\".jpg"), "Фото _июнь_.jpg"); + assert_eq!( + upload_filename("name\r\nX-Fake: value;.txt"), + "name__X-Fake: value_.txt" + ); + } + + #[test] + fn extension_session_is_distinct_from_host_connection() { + let directory = tempfile::tempdir().unwrap(); + let input = crate::engine::tests::input(directory.path(), vec![]); + let first = fresh_session_id(&input); + let second = fresh_session_id(&input); + assert_ne!(first, input.session.client_session_id); + assert_ne!(first, second); + assert!((1..=0x7fff_ffff).contains(&first)); + } + + #[test] + fn parses_both_photo_upload_response_shapes() { + assert_eq!( + photo_token(br#"{"photos":{"one":{"token":"synthetic-token"}}}"#), + Some("synthetic-token".into()) + ); + assert_eq!( + photo_token(br#"{"photoToken":"synthetic-token"}"#), + Some("synthetic-token".into()) + ); + assert_eq!(photo_token(br#"{"photoToken":""}"#), None); + assert_eq!(photo_token(b"invalid"), None); + } + + #[test] + fn login_replaces_stale_fingerprint_using_fresh_handshake_seed() { + let directory = tempfile::tempdir().unwrap(); + let input = crate::engine::tests::input(directory.path(), vec![]); + let first = login_payload(&input, Some(101)).unwrap(); + let second = login_payload(&input, Some(202)).unwrap(); + assert_ne!( + first["chatCacheFingerprint"], + second["chatCacheFingerprint"] + ); + let wire = kolibri_net::protocol::json_to_value(&first); + let fields = wire.as_map().unwrap(); + let fingerprint = fields + .iter() + .find(|(key, _)| key.as_str() == Some("chatCacheFingerprint")) + .unwrap(); + assert!(matches!(&fingerprint.1, rmpv::Value::Binary(bytes) if bytes.len() == 96)); + let exp = fields + .iter() + .find(|(key, _)| key.as_str() == Some("exp")) + .unwrap(); + assert!( + matches!(&exp.1.as_map().unwrap()[0].1, rmpv::Value::Binary(bytes) if bytes == &[0x0b, 0x32]) + ); + } + + #[test] + fn login_without_seed_omits_stale_fingerprint_and_keeps_options() { + let directory = tempfile::tempdir().unwrap(); + let input = crate::engine::tests::input(directory.path(), vec![]); + let payload = login_payload(&input, None).unwrap(); + assert!(payload.get("chatCacheFingerprint").is_none()); + assert_eq!(payload["token"], input.token); + assert_eq!(payload["exp"], input.login["exp"]); + assert_eq!(payload["interactive"], input.session.ping_interactive); + } + + #[test] + fn exported_host_digests_match_all_architecture_and_prelogin_vectors() { + let vectors: Vec = serde_json::from_str(include_str!( + "../../../test/fixtures/share_fingerprint_vectors.json" + )) + .unwrap(); + let directory = tempfile::tempdir().unwrap(); + let mut input = crate::engine::tests::input(directory.path(), vec![]); + for vector in vectors { + input.session.fingerprint_digests = + Some(serde_json::from_value(vector["digests"].clone()).unwrap()); + input.session.device_id = vector["device_id"].as_str().unwrap().into(); + let payload = login_payload(&input, vector["seed"].as_i64()).unwrap(); + let wire = kolibri_net::protocol::json_to_value(&payload["chatCacheFingerprint"]); + let rmpv::Value::Binary(bytes) = wire else { + panic!("fingerprint must remain binary"); + }; + assert_eq!(hex::encode(bytes), vector["fingerprint"].as_str().unwrap()); + } + } + + #[test] + fn web_options_omit_native_fingerprint_and_session_id() { + let directory = tempfile::tempdir().unwrap(); + let mut input = crate::engine::tests::input(directory.path(), vec![]); + input.session.fingerprint_digests = None; + input.session.client_session_id = 0; + assert!(login_payload(&input, Some(101)) + .unwrap() + .get("chatCacheFingerprint") + .is_none()); + assert_eq!(fresh_session_id(&input), 0); + } + + #[test] + fn invalid_exported_digest_prevents_invalid_login_payload() { + let directory = tempfile::tempdir().unwrap(); + let mut input = crate::engine::tests::input(directory.path(), vec![]); + input.session.fingerprint_digests.as_mut().unwrap().dex = "invalid-hex".into(); + assert!(login_payload(&input, Some(101)).is_err()); + } + + #[test] + fn video_processing_retry_budget_matches_host() { + for (kind, expected) in [("VIDEO", 30), ("PHOTO", 20), ("FILE", 20)] { + let payload = json!({ + "chatId": 202, + "message": { + "cid": -1001, + "attaches": [{"_type": kind, "token": "synthetic-token"}], + }, + }); + assert_eq!(send_attempts(&payload), expected); + } + assert_eq!( + send_attempts(&json!({"message": {"text": "synthetic"}})), + 20 + ); + } +} diff --git a/scripts/build_ios_share.sh b/scripts/build_ios_share.sh new file mode 100644 index 00000000..6c6c7d6c --- /dev/null +++ b/scripts/build_ios_share.sh @@ -0,0 +1,38 @@ +#!/bin/bash +set -euo pipefail + +share_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +share_crate="$share_root/native/komet_share" +share_target_dir="${CARGO_TARGET_DIR:-$share_crate/target}" +share_output_dir="${BUILT_PRODUCTS_DIR:?}/KometShareTransport" +export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH" + +if ! command -v cargo >/dev/null 2>&1; then + echo "error: Rust is required to build Komet ShareExtension. Install Rust and the Apple iOS targets." >&2 + exit 1 +fi + +share_libraries=() +for share_arch in ${ARCHS:?}; do + case "${PLATFORM_NAME:?}:$share_arch" in + iphoneos:arm64) share_target=aarch64-apple-ios ;; + iphonesimulator:arm64) share_target=aarch64-apple-ios-sim ;; + iphonesimulator:x86_64) share_target=x86_64-apple-ios ;; + *) + echo "error: Unsupported Komet ShareExtension platform/architecture: $PLATFORM_NAME/$share_arch" >&2 + exit 1 + ;; + esac + + cargo build --locked --release --manifest-path "$share_crate/Cargo.toml" \ + --target "$share_target" --target-dir "$share_target_dir" + share_libraries+=("$share_target_dir/$share_target/release/libkomet_share.a") +done + +mkdir -p "$share_output_dir" +if [ "${#share_libraries[@]}" -eq 1 ]; then + cp "${share_libraries[0]}" "$share_output_dir/libkomet_share.a.tmp" +else + xcrun lipo -create "${share_libraries[@]}" -output "$share_output_dir/libkomet_share.a.tmp" +fi +mv "$share_output_dir/libkomet_share.a.tmp" "$share_output_dir/libkomet_share.a" diff --git a/scripts/pseudo_sign_ios.py b/scripts/pseudo_sign_ios.py new file mode 100644 index 00000000..84072619 --- /dev/null +++ b/scripts/pseudo_sign_ios.py @@ -0,0 +1,38 @@ +import pathlib +import plistlib +import subprocess +import sys +import tempfile + +app = pathlib.Path(sys.argv[1]).resolve() +with (app / "Info.plist").open("rb") as source: + app_info = plistlib.load(source) +group = app_info["KometShareAppGroup"] + + +def sign_bundle(bundle, entitlements): + with (bundle / "Info.plist").open("rb") as source: + info = plistlib.load(source) + entitlements["application-identifier"] = info["CFBundleIdentifier"] + with tempfile.NamedTemporaryFile(suffix=".plist") as target: + plistlib.dump(entitlements, target) + target.flush() + subprocess.run( + ["ldid", "-S" + target.name, str(bundle / info["CFBundleExecutable"])], + check=True, + ) + + +for dylib in app.rglob("*.dylib"): + subprocess.run(["ldid", "-S", str(dylib)], check=True) +for framework in app.rglob("*.framework"): + binary = framework / framework.stem + if binary.is_file(): + subprocess.run(["ldid", "-S", str(binary)], check=True) +for extension in (app / "PlugIns").glob("*.appex"): + sign_bundle(extension, {"com.apple.security.application-groups": [group]}) +sign_bundle(app, { + "get-task-allow": True, + "keychain-access-groups": [app_info["CFBundleIdentifier"]], + "com.apple.security.application-groups": [group], +}) diff --git a/scripts/sign_ios_appstore.py b/scripts/sign_ios_appstore.py new file mode 100644 index 00000000..a40e0f0c --- /dev/null +++ b/scripts/sign_ios_appstore.py @@ -0,0 +1,157 @@ +import argparse +from dataclasses import dataclass +from pathlib import Path +import plistlib +import shutil +import subprocess +import tempfile + + +class SigningPlanError(ValueError): + pass + + +@dataclass(frozen=True) +class ProfileIdentity: + bundle_id: str + team_id: str + entitlements: dict + + +@dataclass(frozen=True) +class SigningPlan: + app: ProfileIdentity + share: ProfileIdentity | None + group: str | None + + +def profile_identity(profile): + entitlements = profile.get("Entitlements") + if not isinstance(entitlements, dict): + raise SigningPlanError("Provisioning profile has no entitlements") + identifier = entitlements.get("application-identifier") + if not isinstance(identifier, str) or "." not in identifier or "*" in identifier: + raise SigningPlanError("App Store signing requires an explicit application identifier") + prefix, bundle_id = identifier.split(".", 1) + prefixes = profile.get("ApplicationIdentifierPrefix", []) + if not prefix or not bundle_id or prefix not in prefixes: + raise SigningPlanError("Application identifier does not match its profile prefix") + team = entitlements.get("com.apple.developer.team-identifier") + if not isinstance(team, str) or team not in profile.get("TeamIdentifier", []): + raise SigningPlanError("Provisioning profile has an inconsistent development team") + return ProfileIdentity(bundle_id, team, dict(entitlements)) + + +def profile_groups(identity): + values = identity.entitlements.get("com.apple.security.application-groups", []) + if not isinstance(values, list): + raise SigningPlanError("Provisioning profile has invalid App Groups") + return {value for value in values if isinstance(value, str) and value.startswith("group.") and "*" not in value} + + +def create_plan(app_profile, share_profile=None, preferred_group=None): + app = profile_identity(app_profile) + if share_profile is None: + return SigningPlan(app, None, None) + share = profile_identity(share_profile) + if app.team_id != share.team_id: + raise SigningPlanError("App and Share Extension profiles must belong to the same team") + if not share.bundle_id.startswith(app.bundle_id + "."): + raise SigningPlanError("Share Extension bundle identifier must be nested under the app identifier") + groups = profile_groups(app) & profile_groups(share) + if not groups: + raise SigningPlanError("App and Share Extension profiles must allow a common explicit App Group") + group = preferred_group if preferred_group in groups else sorted(groups)[0] + return SigningPlan(app, share, group) + + +def read_plist(path): + with Path(path).open("rb") as source: + return plistlib.load(source) + + +def write_plist(path, value): + with Path(path).open("wb") as output: + plistlib.dump(value, output, sort_keys=False) + + +def prepare_app(app_path, plan, app_profile_path, share_profile_path=None): + app_path = Path(app_path) + app_info_path = app_path / "Info.plist" + app_info = read_plist(app_info_path) + share_path = app_path / "PlugIns" / "ShareExtension.appex" + if plan.share is not None: + if not share_path.is_dir() or share_profile_path is None: + raise SigningPlanError("The app does not contain the configured Share Extension") + share_info_path = share_path / "Info.plist" + share_info = read_plist(share_info_path) + share_info["CFBundleIdentifier"] = plan.share.bundle_id + share_info["KometShareAppGroup"] = plan.group + write_plist(share_info_path, share_info) + shutil.copyfile(share_profile_path, share_path / "embedded.mobileprovision") + app_info["KometShareAppGroup"] = plan.group + app_info["KometShareExtensionEnabled"] = True + else: + if share_path.is_dir(): + shutil.rmtree(share_path) + app_info.pop("KometShareAppGroup", None) + app_info["KometShareExtensionEnabled"] = False + previous_id = app_info.get("CFBundleIdentifier") + app_info["CFBundleIdentifier"] = plan.app.bundle_id + for url_type in app_info.get("CFBundleURLTypes", []): + if url_type.get("CFBundleURLName") in {previous_id, "$(PRODUCT_BUNDLE_IDENTIFIER)"}: + url_type["CFBundleURLName"] = plan.app.bundle_id + write_plist(app_info_path, app_info) + shutil.copyfile(app_profile_path, app_path / "embedded.mobileprovision") + return share_path if plan.share else None + + +def load_profile(path): + result = subprocess.run(["security", "cms", "-D", "-i", str(path)], check=True, capture_output=True) + return plistlib.loads(result.stdout) + + +def sign_bundles(app_path, share_path, plan, identity, keychain, run=subprocess.run): + app_path = Path(app_path) + with tempfile.TemporaryDirectory(prefix="komet-appstore-signing-") as directory: + directory = Path(directory) + common = ["codesign", "--force", "--sign", identity, "--keychain", str(keychain)] + roots = [app_path / "Frameworks"] + if share_path is not None: + roots.append(Path(share_path) / "Frameworks") + nested = set() + for root in roots: + if root.is_dir(): + nested.update(root.rglob("*.framework")) + nested.update(root.rglob("*.dylib")) + for bundle in sorted(nested, key=lambda path: (-len(path.parts), str(path))): + run([*common, str(bundle)], check=True) + if plan.share is not None: + share_entitlements = directory / "share.entitlements" + write_plist(share_entitlements, plan.share.entitlements) + run([*common, "--entitlements", str(share_entitlements), str(share_path)], check=True) + app_entitlements = directory / "app.entitlements" + write_plist(app_entitlements, plan.app.entitlements) + run([*common, "--entitlements", str(app_entitlements), str(app_path)], check=True) + run(["codesign", "--verify", "--deep", "--strict", "--verbose=2", str(app_path)], check=True) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("app", type=Path) + parser.add_argument("--app-profile", type=Path, required=True) + parser.add_argument("--share-profile", type=Path) + parser.add_argument("--identity", required=True) + parser.add_argument("--keychain", type=Path, required=True) + args = parser.parse_args() + app_profile = load_profile(args.app_profile) + share_profile = load_profile(args.share_profile) if args.share_profile else None + plan = create_plan(app_profile, share_profile, read_plist(args.app / "Info.plist").get("KometShareAppGroup")) + share_path = prepare_app(args.app, plan, args.app_profile, args.share_profile) + if plan.share is None: + print("::notice::APPSTORE_SHARE_PROVISION_PROFILE_BASE64 is not set; building the app without Share Extension") + sign_bundles(args.app, share_path, plan, args.identity, args.keychain) + + +if __name__ == "__main__": + main() diff --git a/test/account_token_store_test.dart b/test/account_token_store_test.dart new file mode 100644 index 00000000..5cc54e59 --- /dev/null +++ b/test/account_token_store_test.dart @@ -0,0 +1,175 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/storage/account_token_store.dart'; + +class _TokenBackend { + final stored = { + 101: 'synthetic-original-101', + 202: 'synthetic-original-202', + }; + final events = []; + Future Function(int, String)? renewal; + Future Function(int, String)? beforeWrite; + Future Function(int)? beforeClear; + + late final store = AccountTokenStore( + readStored: (accountId) async { + events.add('read:$accountId'); + return stored[accountId]; + }, + writeStored: (accountId, token) async { + await beforeWrite?.call(accountId, token); + events.add('write:$accountId:$token'); + stored[accountId] = token; + }, + deleteStored: (accountId) async { + events.add('delete:$accountId'); + stored.remove(accountId); + }, + readRenewed: (accountId, token) async { + events.add('renew:$accountId:$token'); + return renewal?.call(accountId, token); + }, + clearShared: (accountId) async { + await beforeClear?.call(accountId); + events.add('clear:$accountId'); + }, + ); +} + +void main() { + test('logout cannot be undone by a delayed native token renewal', () async { + final backend = _TokenBackend(); + final requested = Completer(); + final renewed = Completer(); + backend.renewal = (_, _) { + requested.complete(); + return renewed.future; + }; + final read = backend.store.read(101); + await requested.future; + final logout = backend.store.delete(101); + renewed.complete('synthetic-renewed-101'); + expect(await read, 'synthetic-renewed-101'); + await logout; + expect(backend.events, [ + 'read:101', + 'renew:101:synthetic-original-101', + 'write:101:synthetic-renewed-101', + 'clear:101', + 'delete:101', + ]); + expect(await backend.store.read(101), isNull); + expect(backend.stored.containsKey(101), isFalse); + expect(backend.stored[202], 'synthetic-original-202'); + }); + + test('a fresh login saved during renewal keeps the newer token', () async { + final backend = _TokenBackend(); + final requested = Completer(); + final renewed = Completer(); + final observed = []; + backend.renewal = (_, token) { + observed.add(token); + if (observed.length == 1) { + requested.complete(); + return renewed.future; + } + return Future.value(null); + }; + final oldRead = backend.store.read(101); + await requested.future; + final freshLogin = backend.store.save(101, 'synthetic-fresh-login'); + renewed.complete('synthetic-old-renewal'); + await oldRead; + await freshLogin; + expect(await backend.store.read(101), 'synthetic-fresh-login'); + expect(observed, ['synthetic-original-101', 'synthetic-fresh-login']); + expect(backend.stored[101], 'synthetic-fresh-login'); + }); + + test( + 'another account can save and log out while renewal is pending', + () async { + final backend = _TokenBackend(); + final requested = Completer(); + final renewed = Completer(); + backend.renewal = (accountId, _) { + expect(accountId, 101); + requested.complete(); + return renewed.future; + }; + final pending = backend.store.read(101); + await requested.future; + await backend.store.save(202, 'synthetic-fresh-202'); + expect(backend.stored[202], 'synthetic-fresh-202'); + await backend.store.delete(202); + expect(backend.stored.containsKey(202), isFalse); + expect(backend.stored[101], 'synthetic-original-101'); + renewed.complete('synthetic-renewed-101'); + expect(await pending, 'synthetic-renewed-101'); + }, + ); + + test( + 'a failed renewal does not block an already queued fresh save', + () async { + final backend = _TokenBackend(); + final requested = Completer(); + final renewal = Completer(); + backend.renewal = (_, _) { + requested.complete(); + return renewal.future; + }; + final failure = expectLater(backend.store.read(101), throwsStateError); + await requested.future; + final save = backend.store.save(101, 'synthetic-recovery-token'); + renewal.completeError(StateError('synthetic native failure')); + await failure; + await save; + backend.renewal = null; + expect(await backend.store.read(101), 'synthetic-recovery-token'); + }, + ); + + test( + 'a failed renewal write still allows a queued logout to clear access', + () async { + final backend = _TokenBackend(); + final writeStarted = Completer(); + final writeFinished = Completer(); + backend.renewal = (_, _) async => 'synthetic-renewed-101'; + backend.beforeWrite = (_, _) { + writeStarted.complete(); + return writeFinished.future; + }; + final failure = expectLater(backend.store.read(101), throwsStateError); + await writeStarted.future; + final logout = backend.store.delete(101); + writeFinished.completeError(StateError('synthetic storage failure')); + await failure; + await logout; + expect(backend.stored.containsKey(101), isFalse); + expect(backend.events.sublist(backend.events.length - 2), [ + 'clear:101', + 'delete:101', + ]); + }, + ); + + test( + 'shared-clear failure is reported and the next logout can recover', + () async { + final backend = _TokenBackend(); + backend.beforeClear = (_) async => + throw StateError('synthetic clear failure'); + await expectLater(backend.store.delete(101), throwsStateError); + expect(backend.stored[101], 'synthetic-original-101'); + expect(backend.events, isNot(contains('delete:101'))); + backend.beforeClear = null; + await backend.store.delete(101); + expect(await backend.store.read(101), isNull); + }, + ); +} diff --git a/test/app_lock_layer_test.dart b/test/app_lock_layer_test.dart index d08c0dc5..29e0fcc2 100644 --- a/test/app_lock_layer_test.dart +++ b/test/app_lock_layer_test.dart @@ -65,4 +65,50 @@ void main() { expect(find.text('Введите код-пароль'), findsNothing); expect(find.text('synthetic chats'), findsOneWidget); }); + + testWidgets('auto-lock in the foreground fades in instead of snapping', ( + tester, + ) async { + await tester.runAsync(() => lock.setPin('1357')); + await _pumpApp(tester); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + + lock.lock(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 120)); + + expect(find.text('synthetic chats'), findsOneWidget); + final blocker = tester.widget( + find + .ancestor( + of: find.text('synthetic chats'), + matching: find.byType(IgnorePointer), + ) + .last, + ); + expect(blocker.ignoring, isTrue); + + await tester.pumpAndSettle(); + expect(find.text('synthetic chats'), findsNothing); + expect(find.text('Введите код-пароль'), findsOneWidget); + }); + + testWidgets('locking in the background covers the app at once', ( + tester, + ) async { + await tester.runAsync(() => lock.setPin('1357')); + await _pumpApp(tester); + final binding = tester.binding; + binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden); + + lock.lock(); + + binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pump(); + + expect(find.text('synthetic chats'), findsNothing); + expect(find.text('Введите код-пароль'), findsOneWidget); + }); } diff --git a/test/bottom_navigation_style_test.dart b/test/bottom_navigation_style_test.dart new file mode 100644 index 00000000..83f112f1 --- /dev/null +++ b/test/bottom_navigation_style_test.dart @@ -0,0 +1,250 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/config/app_bottom_navigation_style.dart'; +import 'package:komet/core/utils/haptics.dart'; +import 'package:komet/frontend/widgets/bottom_navigation_style_card.dart'; +import 'package:komet/frontend/widgets/compact_bottom_navigation_bar.dart'; +import 'package:komet/frontend/widgets/main_navigation_items.dart'; +import 'package:komet/l10n/app_localizations.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + SharedPreferences.setMockInitialValues({}); + AppBottomNavigationStyle.current.value = BottomNavigationStyle.floating; + Haptics.enabled = false; + }); + + tearDown(() { + AppBottomNavigationStyle.current.value = BottomNavigationStyle.floating; + Haptics.enabled = true; + }); + + test( + 'keeps the existing style by default and restores the saved choice', + () async { + expect( + await AppBottomNavigationStyle.load(), + BottomNavigationStyle.floating, + ); + await AppBottomNavigationStyle.save(BottomNavigationStyle.compact); + final prefs = await SharedPreferences.getInstance(); + expect(prefs.getString(AppBottomNavigationStyle.prefKey), 'compact'); + AppBottomNavigationStyle.current.value = BottomNavigationStyle.floating; + expect( + await AppBottomNavigationStyle.load(), + BottomNavigationStyle.compact, + ); + await prefs.setString(AppBottomNavigationStyle.prefKey, 'unknown-style'); + expect( + await AppBottomNavigationStyle.load(), + BottomNavigationStyle.floating, + ); + }, + ); + + testWidgets( + 'the appearance setting applies live and keeps the selected tab', + (tester) async { + var selected = 2; + await tester.pumpWidget( + MaterialApp( + locale: const Locale('ru'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: StatefulBuilder( + builder: (context, setState) => Scaffold( + body: const Align( + alignment: Alignment.topCenter, + child: BottomNavigationStyleCard(), + ), + bottomNavigationBar: + ValueListenableBuilder( + valueListenable: AppBottomNavigationStyle.current, + builder: (context, style, _) => + style == BottomNavigationStyle.compact + ? CompactBottomNavigationBar( + items: mainNavigationItems, + currentIndex: selected, + onTap: (index) => setState(() => selected = index), + ) + : const SizedBox(height: 68), + ), + ), + ), + ), + ); + expect(find.byType(CompactBottomNavigationBar), findsNothing); + await tester.tap(find.text('Компактная')); + await tester.pumpAndSettle(); + expect(find.byType(CompactBottomNavigationBar), findsOneWidget); + expect( + tester + .widget( + find.byType(CompactBottomNavigationBar), + ) + .currentIndex, + 2, + ); + final prefs = await SharedPreferences.getInstance(); + expect(prefs.getString(AppBottomNavigationStyle.prefKey), 'compact'); + + final semantics = tester.ensureSemantics(); + for (var index = 0; index < mainNavigationItems.length; index++) { + final label = mainNavigationItems[index].label; + await tester.tap(find.text(label)); + await tester.pumpAndSettle(); + expect(selected, index); + expect( + tester.getSemantics(find.bySemanticsLabel(label)), + matchesSemantics( + label: label, + isButton: true, + hasSelectedState: true, + isSelected: true, + hasTapAction: true, + ), + ); + } + semantics.dispose(); + + await tester.tap(find.text('Плавающая')); + await tester.pumpAndSettle(); + expect(find.byType(CompactBottomNavigationBar), findsNothing); + expect(selected, 3); + expect(prefs.getString(AppBottomNavigationStyle.prefKey), 'floating'); + }, + ); + + testWidgets( + 'compact tabs reserve the iPhone home indicator and all tap areas', + (tester) async { + await tester.pumpWidget( + MaterialApp( + home: MediaQuery( + data: const MediaQueryData( + padding: EdgeInsets.only(bottom: 34), + viewPadding: EdgeInsets.only(bottom: 34), + ), + child: Align( + alignment: Alignment.bottomCenter, + child: CompactBottomNavigationBar( + items: mainNavigationItems, + currentIndex: 0, + onTap: (_) {}, + ), + ), + ), + ), + ); + final bar = find.byType(CompactBottomNavigationBar); + expect(tester.getSize(bar).height, 84); + final bottom = tester.getBottomLeft(bar).dy; + for (final item in mainNavigationItems) { + final gesture = find.ancestor( + of: find.text(item.label), + matching: find.byType(GestureDetector), + ); + expect(tester.getSize(gesture).height, 50); + expect(tester.getBottomLeft(gesture).dy, bottom - 34); + } + }, + ); + + testWidgets( + 'settings long press retains account switching without selecting', + (tester) async { + int? pressedIndex; + Offset? pressedPosition; + var taps = 0; + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.bottomCenter, + child: CompactBottomNavigationBar( + items: mainNavigationItems, + currentIndex: 0, + onTap: (_) => taps++, + onItemLongPress: (index, position) { + pressedIndex = index; + pressedPosition = position; + }, + ), + ), + ), + ); + await tester.longPress(find.text('Настройки')); + await tester.pumpAndSettle(); + expect(pressedIndex, 3); + expect(pressedPosition, isNotNull); + expect(taps, 0); + }, + ); + + testWidgets('the compact bar hides with the keyboard and returns afterward', ( + tester, + ) async { + var keyboardHeight = 0.0; + late StateSetter update; + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (context, setState) { + update = setState; + return MediaQuery( + data: MediaQueryData( + viewInsets: EdgeInsets.only(bottom: keyboardHeight), + ), + child: Align( + alignment: Alignment.bottomCenter, + child: CompactBottomNavigationBar( + items: mainNavigationItems, + currentIndex: 2, + onTap: (_) {}, + ), + ), + ); + }, + ), + ), + ); + expect(find.text('Контакты'), findsOneWidget); + update(() => keyboardHeight = 300); + await tester.pump(); + expect(find.text('Контакты'), findsNothing); + expect(tester.getSize(find.byType(CompactBottomNavigationBar)).height, 0); + update(() => keyboardHeight = 0); + await tester.pump(); + expect(find.text('Контакты'), findsOneWidget); + }); + + testWidgets('compact tabs support large text in a narrow dark layout', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData.dark(), + home: MediaQuery( + data: const MediaQueryData(textScaler: TextScaler.linear(2)), + child: Center( + child: SizedBox( + width: 320, + child: CompactBottomNavigationBar( + items: mainNavigationItems, + currentIndex: 3, + onTap: (_) {}, + ), + ), + ), + ), + ), + ); + expect(tester.takeException(), isNull); + expect(tester.getSize(find.byType(CompactBottomNavigationBar)).height, 58); + for (final item in mainNavigationItems) { + expect(find.text(item.label), findsOneWidget); + } + }); +} diff --git a/test/call_mic_selection_test.dart b/test/call_mic_selection_test.dart index 6d886337..e4135dc0 100644 --- a/test/call_mic_selection_test.dart +++ b/test/call_mic_selection_test.dart @@ -2,7 +2,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:komet/core/calls/audio_devices.dart'; import 'package:komet/core/calls/pulse_audio.dart'; -import 'package:komet/core/config/call_no_mute.dart'; +import 'package:komet/core/config/launch_flags.dart'; const _deviceId = 'mic-test-0'; @@ -38,16 +38,15 @@ const _sourcesJson = ''' void main() { tearDown(() { debugDefaultTargetPlatformOverride = null; - CallNoMute.enabled = false; + LaunchFlags.reset(); }); test('--no-mute включается только своим флагом', () { - CallNoMute.enabled = false; - CallNoMute.parse(const ['--debug-test']); - expect(CallNoMute.enabled, isFalse); + LaunchFlags.parse(const ['--debug-test']); + expect(LaunchFlags.noMute, isFalse); - CallNoMute.parse(const ['--debug-test', '--no-mute']); - expect(CallNoMute.enabled, isTrue); + LaunchFlags.parse(const ['--debug-test', '--no-mute']); + expect(LaunchFlags.noMute, isTrue); }); test('desktop выбирает вход через sourceId', () { diff --git a/test/chat_swipe_gestures_test.dart b/test/chat_swipe_gestures_test.dart new file mode 100644 index 00000000..241a67ab --- /dev/null +++ b/test/chat_swipe_gestures_test.dart @@ -0,0 +1,299 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/utils/haptics.dart'; +import 'package:komet/frontend/widgets/swipe_route.dart'; +import 'package:komet/frontend/widgets/swipe_to_reply.dart'; +import 'package:komet/frontend/widgets/scroll_keyboard_dismiss.dart'; + +const _backgroundKey = ValueKey('background'); +const _pageKey = ValueKey('page'); +const _messageKey = ValueKey('message'); + +class _Harness { + final navigatorKey = GlobalKey(); + final focus = FocusNode(); + final scroll = ScrollController(); + int replies = 0; + + Future pump(WidgetTester tester, {bool canPop = true}) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.iOS), + navigatorKey: navigatorKey, + home: const Scaffold(body: SizedBox.expand(key: _backgroundKey)), + ), + ); + navigatorKey.currentState!.push( + SwipeRoute( + builder: (_) => PopScope( + canPop: canPop, + child: Scaffold( + key: _pageKey, + body: Column( + children: [ + Expanded( + child: ScrollKeyboardDismiss( + onDismiss: focus.unfocus, + child: CustomScrollView( + controller: scroll, + reverse: true, + keyboardDismissBehavior: + ScrollViewKeyboardDismissBehavior.manual, + slivers: [ + SliverList.builder( + itemCount: 30, + itemBuilder: (_, index) => SwipeToReply( + onReply: () => replies++, + child: SizedBox( + key: index == 2 ? _messageKey : null, + height: 100, + width: double.infinity, + child: Text('Synthetic message $index'), + ), + ), + ), + ], + ), + ), + ), + TextField(focusNode: focus), + ], + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + Future dispose(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + focus.dispose(); + scroll.dispose(); + } +} + +void main() { + setUp(() => Haptics.enabled = false); + tearDown(() => Haptics.enabled = true); + + testWidgets('a cancelled back gesture restores the page past halfway', ( + tester, + ) async { + final harness = _Harness(); + await harness.pump(tester); + final y = tester.getCenter(find.byKey(_messageKey)).dy; + final gesture = await tester.startGesture(Offset(100, y)); + await gesture.moveBy( + const Offset(450, 0), + timeStamp: const Duration(milliseconds: 700), + ); + await tester.pump(); + await gesture.cancel(); + await tester.pumpAndSettle(); + expect(find.byKey(_pageKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(_pageKey)).dx, 0); + expect(harness.navigatorKey.currentState!.userGestureInProgress, isFalse); + await harness.dispose(tester); + }); + + testWidgets('an interrupted route releases its active back gesture', ( + tester, + ) async { + final harness = _Harness(); + await harness.pump(tester); + final gesture = await tester.startGesture( + tester.getCenter(find.byKey(_messageKey)), + ); + await gesture.moveBy( + const Offset(60, 0), + timeStamp: const Duration(milliseconds: 200), + ); + await tester.pump(); + harness.navigatorKey.currentState!.pop(); + await tester.pumpAndSettle(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(find.byKey(_pageKey), findsNothing); + expect(harness.navigatorKey.currentState!.userGestureInProgress, isFalse); + expect(tester.takeException(), isNull); + await harness.dispose(tester); + }); + + testWidgets( + 'reply uses the initial movement and leaves back navigation idle', + (tester) async { + final harness = _Harness(); + await harness.pump(tester); + await tester.showKeyboard(find.byType(TextField)); + final initialLeft = tester.getTopLeft(find.byKey(_messageKey)).dx; + final gesture = await tester.startGesture( + tester.getCenter(find.byKey(_messageKey)), + ); + await gesture.moveBy( + const Offset(-60, 0), + timeStamp: const Duration(milliseconds: 300), + ); + await tester.pump(); + expect( + tester.getTopLeft(find.byKey(_messageKey)).dx, + lessThan(initialLeft - 56), + ); + expect(harness.navigatorKey.currentState!.userGestureInProgress, isFalse); + expect(harness.focus.hasFocus, isTrue); + expect(harness.replies, 0); + await gesture.up(); + await tester.pumpAndSettle(); + expect(harness.replies, 1); + expect(tester.getTopLeft(find.byKey(_messageKey)).dx, initialLeft); + await harness.dispose(tester); + }, + ); + + testWidgets('reply resistance is gradual and retracting cancels the reply', ( + tester, + ) async { + final harness = _Harness(); + await harness.pump(tester); + final gesture = await tester.startGesture( + tester.getCenter(find.byKey(_messageKey)), + ); + await gesture.moveBy(const Offset(-100, 0)); + await tester.pump(); + final firstOffset = tester.getTopLeft(find.byKey(_messageKey)).dx; + await gesture.moveBy(const Offset(-100, 0)); + await tester.pump(); + final nextOffset = tester.getTopLeft(find.byKey(_messageKey)).dx; + expect(nextOffset, lessThan(firstOffset)); + expect(firstOffset - nextOffset, lessThan(20)); + await gesture.moveBy(const Offset(180, 0)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(harness.replies, 0); + expect(tester.getTopLeft(find.byKey(_messageKey)).dx, 0); + await harness.dispose(tester); + }); + + testWidgets('pointer cancellation never commits a reply', (tester) async { + final harness = _Harness(); + await harness.pump(tester); + final gesture = await tester.startGesture( + tester.getCenter(find.byKey(_messageKey)), + ); + await gesture.moveBy(const Offset(-100, 0)); + await tester.pump(); + await gesture.cancel(); + await tester.pumpAndSettle(); + expect(harness.replies, 0); + expect(tester.getTopLeft(find.byKey(_messageKey)).dx, 0); + await harness.dispose(tester); + }); + + testWidgets( + 'vertical scrolling dismisses focus without replying or popping', + (tester) async { + final harness = _Harness(); + await harness.pump(tester); + await tester.showKeyboard(find.byType(TextField)); + final gesture = await tester.startGesture( + tester.getCenter(find.byKey(_messageKey)), + ); + for (var step = 1; step <= 8; step++) { + await gesture.moveBy( + const Offset(1, 14), + timeStamp: Duration(milliseconds: step * 28), + ); + await tester.pump(const Duration(milliseconds: 28)); + } + await gesture.up(timeStamp: const Duration(milliseconds: 230)); + await tester.pumpAndSettle(); + expect(harness.scroll.offset, greaterThan(0)); + expect(harness.focus.hasFocus, isFalse); + expect(harness.replies, 0); + expect(find.byKey(_pageKey), findsOneWidget); + expect(harness.navigatorKey.currentState!.userGestureInProgress, isFalse); + await harness.dispose(tester); + }, + ); + + testWidgets('slow vertical scrolling keeps the keyboard open', ( + tester, + ) async { + final harness = _Harness(); + await harness.pump(tester); + await tester.showKeyboard(find.byType(TextField)); + final gesture = await tester.startGesture( + tester.getCenter(find.byKey(_messageKey)), + ); + for (var step = 1; step <= 10; step++) { + await gesture.moveBy( + const Offset(0, 10), + timeStamp: Duration(milliseconds: step * 140), + ); + await tester.pump(const Duration(milliseconds: 140)); + expect(harness.focus.hasFocus, isTrue); + } + await gesture.up(timeStamp: const Duration(milliseconds: 1500)); + await tester.pumpAndSettle(); + expect(harness.scroll.offset, greaterThan(0)); + expect(tester.testTextInput.isVisible, isTrue); + expect(harness.replies, 0); + await harness.dispose(tester); + }); + + testWidgets('accelerating a slow scroll dismisses the keyboard', ( + tester, + ) async { + final harness = _Harness(); + await harness.pump(tester); + await tester.showKeyboard(find.byType(TextField)); + final gesture = await tester.startGesture( + tester.getCenter(find.byKey(_messageKey)), + ); + for (var step = 1; step <= 5; step++) { + await gesture.moveBy( + const Offset(0, 10), + timeStamp: Duration(milliseconds: step * 140), + ); + await tester.pump(const Duration(milliseconds: 140)); + } + expect(harness.focus.hasFocus, isTrue); + for (var step = 1; step <= 8; step++) { + await gesture.moveBy( + const Offset(0, 12), + timeStamp: Duration(milliseconds: 700 + step * 20), + ); + await tester.pump(const Duration(milliseconds: 20)); + } + expect(harness.focus.hasFocus, isFalse); + await gesture.up(timeStamp: const Duration(milliseconds: 880)); + await tester.pumpAndSettle(); + await harness.dispose(tester); + }); + + testWidgets('programmatic scrolling keeps the keyboard open', (tester) async { + final harness = _Harness(); + await harness.pump(tester); + await tester.showKeyboard(find.byType(TextField)); + harness.scroll.jumpTo(400); + await tester.pumpAndSettle(); + expect(harness.focus.hasFocus, isTrue); + expect(tester.testTextInput.isVisible, isTrue); + await harness.dispose(tester); + }); + + testWidgets('a blocked pop does not dismiss the composer or move the page', ( + tester, + ) async { + final harness = _Harness(); + await harness.pump(tester, canPop: false); + await tester.showKeyboard(find.byType(TextField)); + await tester.drag(find.byKey(_messageKey), const Offset(250, 0)); + await tester.pumpAndSettle(); + expect(harness.focus.hasFocus, isTrue); + expect(tester.getTopLeft(find.byKey(_pageKey)).dx, 0); + expect(harness.navigatorKey.currentState!.userGestureInProgress, isFalse); + await harness.dispose(tester); + }); +} diff --git a/test/color_wheel_picker_test.dart b/test/color_wheel_picker_test.dart new file mode 100644 index 00000000..c5fc7a88 --- /dev/null +++ b/test/color_wheel_picker_test.dart @@ -0,0 +1,117 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:komet/frontend/widgets/color_wheel_picker.dart'; + +const double _pickerWidth = 320; +const double _wheelSize = 260; +const double _rowInset = (_pickerWidth - _wheelSize - 44) / 2; + +class _Harness { + final ScrollController scroll = ScrollController(); + final List emitted = []; + + Widget build({double minBrightness = 0}) { + return MaterialApp( + home: Scaffold( + body: ListView( + controller: scroll, + children: [ + const SizedBox(height: 40), + Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: _pickerWidth, + child: ColorWheelPicker( + color: const Color(0xFF4F8EFF), + minBrightness: minBrightness, + onChanged: emitted.add, + ), + ), + ), + const SizedBox(height: 2000), + ], + ), + ), + ); + } +} + +Offset _barPoint(WidgetTester tester, double fraction) { + final origin = tester.getTopLeft(find.byType(ColorWheelPicker)); + return origin + + Offset(_rowInset + _wheelSize + 16 + 14, fraction * _wheelSize); +} + +Offset _wheelPoint(WidgetTester tester, Offset local) { + final origin = tester.getTopLeft(find.byType(ColorWheelPicker)); + return origin + Offset(_rowInset, 0) + local; +} + +void main() { + testWidgets('шкала яркости ведётся пальцем и не прокручивает экран', ( + tester, + ) async { + final harness = _Harness(); + addTearDown(harness.scroll.dispose); + await tester.pumpWidget(harness.build()); + + final gesture = await tester.startGesture(_barPoint(tester, 0.1)); + await tester.pump(); + for (var i = 0; i < 12; i++) { + await gesture.moveBy(const Offset(0, 15)); + await tester.pump(); + } + await gesture.up(); + await tester.pumpAndSettle(); + + expect(harness.scroll.offset, 0); + expect(harness.emitted.length, greaterThanOrEqualTo(13)); + final values = [ + for (final color in harness.emitted) HSVColor.fromColor(color).value, + ]; + for (var i = 1; i < values.length; i++) { + expect(values[i], lessThan(values[i - 1]), reason: '$values'); + } + }); + + testWidgets('нижний край шкалы упирается в minBrightness', (tester) async { + final harness = _Harness(); + addTearDown(harness.scroll.dispose); + await tester.pumpWidget(harness.build(minBrightness: 0.2)); + + final gesture = await tester.startGesture(_barPoint(tester, 0.5)); + await gesture.moveBy(const Offset(0, _wheelSize)); + await gesture.up(); + await tester.pumpAndSettle(); + + final value = HSVColor.fromColor(harness.emitted.last).value; + expect(value, closeTo(0.2, 0.01)); + expect(HSVColor.fromColor(harness.emitted.last).saturation, greaterThan(0)); + }); + + testWidgets('вертикальный жест по кругу меняет цвет, а не скроллит', ( + tester, + ) async { + final harness = _Harness(); + addTearDown(harness.scroll.dispose); + await tester.pumpWidget(harness.build()); + + final gesture = await tester.startGesture( + _wheelPoint(tester, const Offset(_wheelSize / 2 + 40, 30)), + ); + for (var i = 0; i < 8; i++) { + await gesture.moveBy(const Offset(0, 20)); + await tester.pump(); + } + await gesture.up(); + await tester.pumpAndSettle(); + + expect(harness.scroll.offset, 0); + expect(harness.emitted.length, greaterThanOrEqualTo(9)); + expect( + harness.emitted.map((c) => HSVColor.fromColor(c).hue).toSet().length, + greaterThan(5), + ); + }); +} diff --git a/test/file_bubble_test.dart b/test/file_bubble_test.dart new file mode 100644 index 00000000..593e84eb --- /dev/null +++ b/test/file_bubble_test.dart @@ -0,0 +1,281 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/l10n/app_localizations.dart'; +import 'package:komet/backend/modules/messages.dart'; +import 'package:komet/core/utils/download_history.dart'; +import 'package:komet/core/utils/download_progress.dart'; +import 'package:komet/core/utils/file_download.dart'; +import 'package:komet/core/utils/haptics.dart'; +import 'package:komet/core/utils/media_cache.dart'; +import 'package:komet/frontend/widgets/attachment/bubbles/bubble_context.dart'; +import 'package:komet/frontend/widgets/attachment/bubbles/file_bubble.dart'; +import 'package:komet/models/attachment.dart'; +import 'package:material_symbols_icons/symbols.dart'; +import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +class _SyntheticPathProvider extends PathProviderPlatform + with MockPlatformInterfaceMixin { + _SyntheticPathProvider(this.path); + + final String path; + + @override + Future getApplicationSupportPath() async => path; +} + +Future _pump( + WidgetTester tester, { + required String name, + required FileBubbleOpener openFile, + bool cached = false, + double? progress, + Widget Function(Widget child)? wrap, +}) async { + final cacheName = '901_$name'; + await tester.runAsync(() async { + if (cached) { + final local = await MediaCache.fileFor(cacheName); + await local.writeAsBytes(List.filled(2048, 0)); + } + await MediaCache.existing(cacheName); + }); + MediaDownloadProgress.set(cacheName, progress); + addTearDown(() => MediaDownloadProgress.set(cacheName, null)); + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('ru'), + home: Scaffold( + body: Builder( + builder: (context) { + final bubble = FileBubble( + fill: true, + file: FileAttachment(fileId: 901, name: name, size: 2048), + openFile: openFile, + ctx: BubbleContext( + context: context, + cs: Theme.of(context).colorScheme, + text: Colors.black, + shape: BubbleShape.singleMiddle, + contentType: MessageType.attachment, + hasPhotoWithCaption: false, + hasMultiplePhotosNoCaption: false, + message: CachedMessage( + id: 'synthetic-file-message', + accountId: 101, + chatId: 202, + senderId: 303, + time: 123456, + ), + isMe: false, + myId: 101, + chatType: 'DIALOG', + chatName: 'Synthetic chat', + ), + ); + return Center( + child: SizedBox(width: 320, child: wrap?.call(bubble) ?? bubble), + ); + }, + ), + ), + ), + ); + await tester.pump(); + return cacheName; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory directory; + late PathProviderPlatform originalPathProvider; + + setUpAll(() { + directory = Directory.systemTemp.createTempSync('synthetic_file_bubble'); + originalPathProvider = PathProviderPlatform.instance; + PathProviderPlatform.instance = _SyntheticPathProvider(directory.path); + Haptics.enabled = false; + }); + + tearDownAll(() { + PathProviderPlatform.instance = originalPathProvider; + Haptics.enabled = true; + directory.deleteSync(recursive: true); + }); + + testWidgets( + 'tapping a document title starts one download and shows progress', + (tester) async { + final completed = Completer(); + var opens = 0; + DownloadMetadata? metadata; + await _pump( + tester, + name: 'synthetic-download.pdf', + openFile: (cacheName, resolveUrl, {onProgress, onReady, download}) { + opens++; + metadata = download; + onProgress?.call(0.4); + return completed.future.whenComplete(() => onReady?.call()); + }, + ); + expect(find.text('Скачать · 2.0 КБ'), findsOneWidget); + + await tester.tap(find.text('synthetic-download.pdf')); + await tester.pump(); + expect(find.text('Загрузка 40% · 2.0 КБ'), findsOneWidget); + + await tester.tap(find.text('synthetic-download.pdf')); + await tester.tap(find.byIcon(Symbols.description)); + await tester.pump(); + expect(opens, 1); + expect(metadata?.name, 'synthetic-download.pdf'); + expect(metadata?.chatId, 202); + expect(metadata?.messageId, 'synthetic-file-message'); + completed.complete(const FileDownloadResult(ok: true)); + await tester.pumpAndSettle(); + }, + ); + + testWidgets('cached files open from card padding and reject repeated opens', ( + tester, + ) async { + final closed = Completer(); + var opens = 0; + await _pump( + tester, + name: 'synthetic-cached.zip', + cached: true, + openFile: (cacheName, resolveUrl, {onProgress, onReady, download}) { + opens++; + onReady?.call(); + return closed.future; + }, + ); + expect(find.text('Открыть · 2.0 КБ'), findsOneWidget); + final card = tester.getRect(find.byType(FileBubble)); + + await tester.tapAt(card.topLeft + const Offset(3, 3)); + await tester.pump(); + expect(find.text('Открытие… · 2.0 КБ'), findsOneWidget); + await tester.tap(find.text('synthetic-cached.zip')); + await tester.pump(); + expect(opens, 1); + + closed.complete(const FileDownloadResult(ok: true)); + await tester.pumpAndSettle(); + expect(find.text('Открыть · 2.0 КБ'), findsOneWidget); + }); + + testWidgets('active download taps neither restart it nor open the row menu', ( + tester, + ) async { + var opens = 0; + var menuTaps = 0; + await _pump( + tester, + name: 'synthetic-progress.pdf', + progress: 0.65, + wrap: (child) => GestureDetector(onTap: () => menuTaps++, child: child), + openFile: (cacheName, resolveUrl, {onProgress, onReady, download}) async { + opens++; + return const FileDownloadResult(ok: true); + }, + ); + + await tester.tap(find.text('synthetic-progress.pdf')); + await tester.pump(); + expect(find.text('Загрузка 65% · 2.0 КБ'), findsOneWidget); + expect(opens, 0); + expect(menuTaps, 0); + }); + + testWidgets('long press, reply drag and selection remain with the parent', ( + tester, + ) async { + var opens = 0; + var longPresses = 0; + var replyDrags = 0; + var selections = 0; + var selecting = false; + late StateSetter update; + await _pump( + tester, + name: 'synthetic-gestures.pdf', + wrap: (child) => StatefulBuilder( + builder: (context, setState) { + update = setState; + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => selections++, + onLongPress: () => longPresses++, + onHorizontalDragUpdate: (_) => replyDrags++, + child: IgnorePointer(ignoring: selecting, child: child), + ); + }, + ), + openFile: (cacheName, resolveUrl, {onProgress, onReady, download}) async { + opens++; + return const FileDownloadResult(ok: true); + }, + ); + + await tester.longPress(find.text('synthetic-gestures.pdf')); + await tester.drag( + find.text('synthetic-gestures.pdf'), + const Offset(-80, 0), + ); + expect(longPresses, 1); + expect(replyDrags, greaterThan(0)); + update(() => selecting = true); + await tester.pump(); + await tester.tapAt(tester.getCenter(find.text('synthetic-gestures.pdf'))); + expect(selections, 1); + expect(opens, 0); + }); + + testWidgets('screen readers receive the file action and download state', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + final cacheName = await _pump( + tester, + name: 'synthetic-accessibility.pdf', + openFile: (cacheName, resolveUrl, {onProgress, onReady, download}) async { + return const FileDownloadResult(ok: true); + }, + ); + final finder = find.bySemanticsLabel('synthetic-accessibility.pdf'); + expect( + tester.getSemantics(finder), + matchesSemantics( + label: 'synthetic-accessibility.pdf', + value: 'Скачать · 2.0 КБ', + hint: 'Скачать и открыть файл', + isButton: true, + hasEnabledState: true, + isEnabled: true, + hasTapAction: true, + ), + ); + + MediaDownloadProgress.set(cacheName, 0.5); + await tester.pump(); + expect( + tester.getSemantics(finder), + matchesSemantics( + label: 'synthetic-accessibility.pdf', + value: 'Загрузка 50% · 2.0 КБ', + isButton: true, + hasEnabledState: true, + ), + ); + semantics.dispose(); + }); +} diff --git a/test/fixtures/share_fingerprint_vectors.json b/test/fixtures/share_fingerprint_vectors.json new file mode 100644 index 00000000..d7b86b03 --- /dev/null +++ b/test/fixtures/share_fingerprint_vectors.json @@ -0,0 +1,74 @@ +[ + { + "arch": "arm64-v8a", + "pre_login": false, + "seed": 101, + "device_id": "synthetic-device", + "digests": { + "signature": "1684414033eb263e2c615f8b7df5ed8793850a07656304997fbf07e9e21e1e93", + "dex": "9affa687874d88ea80b298949f826bcf8c1bba36f24d48c44b8f54cdbf01c96f", + "so": "38e2e5de3d4a9010ea1053eb28573593683c5b2bb16b09914a8822476c8aab8c" + }, + "fingerprint": "75d0d0ec9cd94eaed0ae481442fd4ef90c56e5ccace7b46bfdaf72b2623b2228137b10306c333ab2149b4f76d2404f92940ce45930e08953cbbf30fb42a9add6f39fc63c31b6b0d1c321bfdffc9d42c56a185f013a4bfd85b89bb08508ad36d2" + }, + { + "arch": "armeabi-v7a", + "pre_login": false, + "seed": 101, + "device_id": "synthetic-device", + "digests": { + "signature": "1684414033eb263e2c615f8b7df5ed8793850a07656304997fbf07e9e21e1e93", + "dex": "9affa687874d88ea80b298949f826bcf8c1bba36f24d48c44b8f54cdbf01c96f", + "so": "f60cb2576885e0af5350c98fe88355a2f26008a372c998c193b6222f717e274f" + }, + "fingerprint": "75d0d0ec9cd94eaed0ae481442fd4ef90c56e5ccace7b46bfdaf72b2623b2228137b10306c333ab2149b4f76d2404f92940ce45930e08953cbbf30fb42a9add6f39d8a9dba26c45c0343024ed1961141c70c9b4305d3577756e165eff2e67451" + }, + { + "arch": "x86", + "pre_login": false, + "seed": 101, + "device_id": "synthetic-device", + "digests": { + "signature": "1684414033eb263e2c615f8b7df5ed8793850a07656304997fbf07e9e21e1e93", + "dex": "9affa687874d88ea80b298949f826bcf8c1bba36f24d48c44b8f54cdbf01c96f", + "so": "80bd04964e7d0492740113047ff20ebdf88ba6e6eb48d8765cbd5fe678283065" + }, + "fingerprint": "75d0d0ec9cd94eaed0ae481442fd4ef90c56e5ccace7b46bfdaf72b2623b2228137b10306c333ab2149b4f76d2404f92940ce45930e08953cbbf30fb42a9add6cf225027b31b6bc35cfba1bc4afc742eb9391bf2e6e84810fbe7b13d6bb5a6e8" + }, + { + "arch": "x86_64", + "pre_login": false, + "seed": 101, + "device_id": "synthetic-device", + "digests": { + "signature": "1684414033eb263e2c615f8b7df5ed8793850a07656304997fbf07e9e21e1e93", + "dex": "9affa687874d88ea80b298949f826bcf8c1bba36f24d48c44b8f54cdbf01c96f", + "so": "96173e7c2d9449c1ab4474265b410f37ce45f560b0974460a75c7c6000ca22fd" + }, + "fingerprint": "75d0d0ec9cd94eaed0ae481442fd4ef90c56e5ccace7b46bfdaf72b2623b2228137b10306c333ab2149b4f76d2404f92940ce45930e08953cbbf30fb42a9add69b180e6dba4e9b7a4a908cfd9d81391ed61e99aa3cc107683aab796c45704385" + }, + { + "arch": "unknown-synthetic-arch", + "pre_login": false, + "seed": 101, + "device_id": "synthetic-device", + "digests": { + "signature": "1684414033eb263e2c615f8b7df5ed8793850a07656304997fbf07e9e21e1e93", + "dex": "9affa687874d88ea80b298949f826bcf8c1bba36f24d48c44b8f54cdbf01c96f", + "so": "38e2e5de3d4a9010ea1053eb28573593683c5b2bb16b09914a8822476c8aab8c" + }, + "fingerprint": "75d0d0ec9cd94eaed0ae481442fd4ef90c56e5ccace7b46bfdaf72b2623b2228137b10306c333ab2149b4f76d2404f92940ce45930e08953cbbf30fb42a9add6f39fc63c31b6b0d1c321bfdffc9d42c56a185f013a4bfd85b89bb08508ad36d2" + }, + { + "arch": "x86_64", + "pre_login": true, + "seed": 101, + "device_id": "synthetic-device", + "digests": { + "signature": "1684414033eb263e2c615f8b7df5ed8793850a07656304997fbf07e9e21e1e93", + "dex": "38cff46f392dc1734c308be011c2f0d8da152a390b41063dbb2c913e3032f4b3", + "so": "634ecc42b246784d975f180b4fecf903df235cdf0476da47163a85630eb1a6a8" + }, + "fingerprint": "75d0d0ec9cd94eaed0ae481442fd4ef90c56e5ccace7b46bfdaf72b2623b22286d8d099e4dae6571ace2c0411bfe7a3cc8ba29db61c01b9db848a36b8e9741182f21b1976e45e7f1c11a744fa40a896272f6a4f3169e1cf91eaa4e7bbef1b0f8" + } +] diff --git a/test/launch_flags_test.dart b/test/launch_flags_test.dart new file mode 100644 index 00000000..01573c72 --- /dev/null +++ b/test/launch_flags_test.dart @@ -0,0 +1,140 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:kolibri/kolibri.dart' show WireLogEvent; +import 'package:komet/core/config/launch_flags.dart'; +import 'package:komet/core/protocol/opcode_map.dart'; +import 'package:komet/core/transport/wire_debug_log.dart'; +import 'package:komet/core/utils/logger.dart'; + +const _loginJson = '{"token":"synthetic-token","interactive":true}'; + +WireLogEvent _event({ + required int opcode, + String direction = 'out', + String cmd = 'request', + String json = '{"chatId":1}', +}) => WireLogEvent( + direction: direction, + cmd: cmd, + opcode: opcode, + seq: 7, + json: json, +); + +void main() { + tearDown(LaunchFlags.reset); + + test('--debug включает лог, но не раскрывает LOGIN', () { + LaunchFlags.parse(const ['--debug-test', '--no-mute']); + expect(LaunchFlags.debug, isFalse); + + LaunchFlags.parse(const ['--debug']); + expect(LaunchFlags.debug, isTrue); + expect(LaunchFlags.revealLoginPayload, isFalse); + expect(LaunchFlags.activeDebugFlag, '--debug'); + }); + + test('--dw19p-im-crazy включает лог вместе с LOGIN', () { + LaunchFlags.parse(const ['--dw19p-im-crazy']); + expect(LaunchFlags.debug, isTrue); + expect(LaunchFlags.revealLoginPayload, isTrue); + expect(LaunchFlags.activeDebugFlag, '--dw19p-im-crazy'); + }); + + test('все флаги разбираются одним проходом', () { + LaunchFlags.parse(const ['--berserk', '--no-mute', '--contacts', '25']); + expect(LaunchFlags.berserk, isTrue); + expect(LaunchFlags.noMute, isTrue); + expect(LaunchFlags.debugTest, isTrue); + expect(LaunchFlags.contactCount, 25); + expect(LaunchFlags.unknown, isEmpty); + expect(LaunchFlags.summary, [ + '--debug-test', + '--contacts=25', + '--berserk', + '--no-mute', + ]); + }); + + test('--contacts=N тоже включает тестовый режим', () { + LaunchFlags.parse(const ['--contacts=7']); + expect(LaunchFlags.debugTest, isTrue); + expect(LaunchFlags.contactCount, 7); + }); + + test('неизвестные аргументы собираются для предупреждения', () { + LaunchFlags.parse(const ['--debgu', '--contacts']); + expect(LaunchFlags.debug, isFalse); + expect(LaunchFlags.debugTest, isFalse); + expect(LaunchFlags.unknown, ['--debgu', '--contacts']); + }); + + test('payload LOGIN скрыт без --dw19p-im-crazy в обе стороны', () { + for (final direction in const ['out', 'in']) { + final line = WireDebugLog.describe( + session: 'api1/auth', + event: _event( + opcode: Opcode.login, + direction: direction, + json: _loginJson, + ), + revealLoginPayload: false, + ); + expect(line, contains('LOGIN(19)')); + expect(line, isNot(contains('synthetic-token'))); + expect(line, contains('--dw19p-im-crazy')); + } + }); + + test('payload LOGIN виден с --dw19p-im-crazy', () { + final line = WireDebugLog.describe( + session: 'api1/auth', + event: _event(opcode: Opcode.login, json: _loginJson), + revealLoginPayload: true, + ); + expect(line, contains('synthetic-token')); + }); + + test('остальные опкоды пишутся с payload целиком', () { + final line = WireDebugLog.describe( + session: 'api2/web', + event: _event( + opcode: Opcode.authRequest, + direction: 'in', + cmd: 'ok', + json: '{"token":"synthetic-auth"}', + ), + revealLoginPayload: false, + ); + expect(line, startsWith('WIRE [api2/web] << ok AUTH_REQUEST(17) seq=7 ')); + expect(line, endsWith('{"token":"synthetic-auth"}')); + }); + + test('длинная строка режется на куски без разрыва суррогатных пар', () { + final max = KometLogPrinter.maxLineLength; + final message = '${'a' * (max - 1)}😀${'b' * max}\nхвост'; + final lines = KometLogPrinter.splitForConsole(message); + expect(lines.every((l) => l.length <= max), isTrue); + expect(lines.join(), message.replaceAll('\n', '')); + expect(lines.last, 'хвост'); + for (final line in lines) { + final last = line.codeUnitAt(line.length - 1); + expect(last >= 0xD800 && last <= 0xDBFF, isFalse); + } + }); + + test('пароли в трафике всегда замазаны', () { + final line = WireDebugLog.describe( + session: 'api1/pre', + event: _event( + opcode: Opcode.authLoginCheckPassword, + json: r'{"password":"synthetic \"pass\"","trackId":"t-1",' + r'"newPassword":"synthetic-new"}', + ), + revealLoginPayload: true, + ); + expect(line, isNot(contains('synthetic'))); + expect(line, contains('"password":"***"')); + expect(line, contains('"newPassword":"***"')); + expect(line, contains('"trackId":"t-1"')); + }); +} diff --git a/test/native/ios_share_accounts_test.swift b/test/native/ios_share_accounts_test.swift new file mode 100644 index 00000000..2b029c31 --- /dev/null +++ b/test/native/ios_share_accounts_test.swift @@ -0,0 +1,77 @@ +import Foundation + +private final class SyntheticCredentialStorage: KometShareCredentialStorage { + var values: [String: Data] = [:] + + func read(accountID: String) throws -> Data { + guard let value = values[accountID] else { throw KometShareError.invalidRequest } + return value + } + + func write(_ data: Data, accountID: String) throws { values[accountID] = data } + + func remove(accountID: String?) throws { + if let accountID = accountID { values.removeValue(forKey: accountID) } else { values.removeAll() } + } +} + +@main +struct KometShareAccountsTests { + static func main() throws { + let manager = FileManager.default + let container = manager.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? manager.removeItem(at: container) } + let storage = SyntheticCredentialStorage() + let accounts = try KometShareAccounts(containerURL: container, credentialStore: storage) + let reopened = try KometShareAccounts(containerURL: container, credentialStore: storage) + try expect(accounts.accounts().isEmpty, "First launch has no account snapshot") + var input: [String: Any] = [ + "accountId": "12", "accountName": "Synthetic account", "token": "synthetic-source-token", + "session": ["proxy": "synthetic-secret-proxy"], "login": ["exp": ["synthetic": ["$bin": "AA=="]]], + "chats": [["id": "34", "title": "Synthetic chat", "type": "DIALOG", "disabledReason": "Encrypted"]] + ] + try accounts.sync(input) + try expect(reopened.accounts().first?.chats.first?.disabledReason == "Encrypted", "Disabled recipients must persist across processes") + try expectThrows { _ = try reopened.authorizedCredentials(accountID: "12", chatID: "34") } + try expectThrows { _ = try reopened.authorizedCredentials(accountID: "12", chatID: "999") } + input["chats"] = [["id": "34", "title": "Synthetic chat", "type": "DIALOG"]] + try accounts.sync(input) + try expect(reopened.authorizedCredentials(accountID: "12", chatID: "34")["account_id"] as? String == "12", "Allowed recipient and credentials must be read in one transaction") + let snapshot = try String(contentsOf: container.appendingPathComponent("KometShare/accounts.json"), encoding: .utf8) + try expect(!snapshot.contains("synthetic-source-token") && !snapshot.contains("synthetic-secret-proxy"), "Credentials must never enter the shared snapshot") + try accounts.updateToken(accountID: "12", previousToken: "synthetic-source-token", refreshedToken: "synthetic-renewed-token") + try expect(reopened.refreshedToken(accountID: "12", knownToken: "synthetic-source-token") == "synthetic-renewed-token", "Host must retrieve renewal for its matching baseline") + try expect(reopened.refreshedToken(accountID: "12", knownToken: "unrelated-token") == nil, "Renewal must not overwrite another login") + try reopened.sync(input) + try expect(accounts.credentials(accountID: "12")["token"] as? String == "synthetic-renewed-token", "Stale baseline export must not replace a renewed token") + input["token"] = "synthetic-fresh-login" + try reopened.sync(input) + try accounts.updateToken(accountID: "12", previousToken: "synthetic-renewed-token", refreshedToken: "synthetic-stale-renewal") + try expect(accounts.credentials(accountID: "12")["token"] as? String == "synthetic-fresh-login", "Delayed refresh must preserve a new login token") + input["accountId"] = "56" + input["accountName"] = "Second synthetic account" + try accounts.sync(input) + try expect(reopened.accounts().count == 2, "Multiple account snapshots must coexist") + try reopened.clear(accountID: "12") + do { + try accounts.updateToken(accountID: "12", previousToken: "synthetic-fresh-login", refreshedToken: "late-token") + throw Failure(message: "Removed accounts must reject token renewal") + } catch is KometShareError {} + try expect(storage.values["12"] == nil, "Token renewal must never resurrect a logged out account") + try expect(accounts.accounts().map { $0.id } == ["56"], "Account-specific logout must preserve other accounts") + try accounts.clear(accountID: nil) + try expect(reopened.accounts().isEmpty && storage.values.isEmpty, "Logout all must clear credentials and snapshots") + print("KometShareAccounts: all tests passed") + } + + static func expect(_ condition: @autoclosure () throws -> Bool, _ message: String) throws { + guard try condition() else { throw Failure(message: message) } + } + + static func expectThrows(_ action: () throws -> Void) throws { + do { try action() } catch { return } + throw Failure(message: "Expected a disabled or missing recipient to reject authorization") + } + + struct Failure: Error { let message: String } +} diff --git a/test/native/ios_share_images_test.swift b/test/native/ios_share_images_test.swift new file mode 100644 index 00000000..615b978b --- /dev/null +++ b/test/native/ios_share_images_test.swift @@ -0,0 +1,67 @@ +import Foundation +import ImageIO +import CoreGraphics +import CoreServices + +@main +struct KometShareImagesTests { + static func main() throws { + let manager = FileManager.default + let root = manager.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? manager.removeItem(at: root) } + let store = try KometShareStore(containerURL: root) + let draft = try store.beginRequest() + let fixtureURL = root.appendingPathComponent("large.png") + guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB), + let context = CGContext(data: nil, width: 5200, height: 1000, bitsPerComponent: 8, + bytesPerRow: 0, space: colorSpace, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { + throw Failure(message: "Synthetic image context unavailable") + } + context.setFillColor(CGColor(red: 0.3, green: 0.5, blue: 0.7, alpha: 0.5)) + context.fill(CGRect(x: 0, y: 0, width: 5200, height: 1000)) + guard let image = context.makeImage() else { throw Failure(message: "Synthetic image unavailable") } + try write(image, type: kUTTypePNG, to: fixtureURL) + let imported = try store.copyFile(at: fixtureURL, suggestedName: "Synthetic photo", typeIdentifier: "public.image", into: draft) + let generic = KometSharedFile(relativePath: imported.relativePath, name: "Synthetic photo", mime: "application/octet-stream", size: imported.size) + let normalized = try KometShareSender.prepareImages([generic], in: draft)[0] + try expect(normalized.mime == "image/jpeg" && normalized.name == "Synthetic photo.jpg", "Actual image bytes must determine generic provider content") + let jpegURL = draft.directoryURL.appendingPathComponent(normalized.relativePath) + guard let source = CGImageSourceCreateWithURL(jpegURL as CFURL, nil), + let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], + let width = properties[kCGImagePropertyPixelWidth] as? Int, + let height = properties[kCGImagePropertyPixelHeight] as? Int else { + throw Failure(message: "Normalized image missing") + } + try expect(max(width, height) <= 2560, "Photo decode must be bounded to extension memory budget") + try expect(CGImageSourceGetType(source).map { $0 as String } == "public.jpeg", "JPEG MIME must match actual encoded bytes") + try expect(!manager.fileExists(atPath: draft.directoryURL.appendingPathComponent(imported.relativePath).path), "Normalization must release the original staging copy") + let text = try store.saveData(Data("Synthetic text file".utf8), suggestedName: "document.txt", typeIdentifier: "public.plain-text", into: draft) + let unchanged = try KometShareSender.prepareImages([text], in: draft)[0] + try expect(unchanged.relativePath == text.relativePath && unchanged.mime == text.mime, "Documents must preserve their bytes and metadata") + let heicURL = root.appendingPathComponent("synthetic.heic") + if (CGImageDestinationCopyTypeIdentifiers() as! [String]).contains("public.heic") { + try write(image, type: "public.heic" as CFString, to: heicURL) + let heic = try store.copyFile(at: heicURL, suggestedName: "Synthetic.heic", typeIdentifier: "public.heic", into: draft) + let converted = try KometShareSender.prepareImages([heic], in: draft)[0] + try expect(converted.mime == "image/jpeg" && converted.name == "Synthetic.jpg", "HEIC must use actual JPEG bytes for photo upload") + } + let response = try KometShareSender.send(credentials: [:], request: [:]) { _, _, _ in } + try expect(response.status == "unknown", "A missing transport result must not be presented as sent") + print("KometShareImages: all tests passed") + } + + static func write(_ image: CGImage, type: CFString, to url: URL) throws { + guard let output = CGImageDestinationCreateWithURL(url as CFURL, type, 1, nil) else { + throw Failure(message: "Synthetic image destination unavailable") + } + CGImageDestinationAddImage(output, image, nil) + guard CGImageDestinationFinalize(output) else { throw Failure(message: "Synthetic image encode failed") } + } + + static func expect(_ condition: @autoclosure () throws -> Bool, _ message: String) throws { + guard try condition() else { throw Failure(message: message) } + } + + struct Failure: Error { let message: String } +} diff --git a/test/native/ios_share_store_test.swift b/test/native/ios_share_store_test.swift new file mode 100644 index 00000000..63875217 --- /dev/null +++ b/test/native/ios_share_store_test.swift @@ -0,0 +1,139 @@ +import Foundation + +@main +struct KometShareStoreTests { + static func main() throws { + let manager = FileManager.default + let container = manager.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? manager.removeItem(at: container) } + let store = try KometShareStore(containerURL: container) + + let abandoned = try store.beginRequest() + _ = try store.saveData(Data("uncommitted".utf8), suggestedName: "draft.txt", typeIdentifier: "public.plain-text", into: abandoned) + try expect(store.nextPayload() == nil, "Uncommitted requests must not be visible") + store.discard(abandoned) + + let first = try store.beginRequest() + let attachment = try store.saveData(Data(), suggestedName: "empty.txt", typeIdentifier: "public.plain-text", into: first) + let firstID = try store.commit(first, files: [attachment], text: " Synthetic caption ", subject: nil) + let second = try store.beginRequest() + let secondID = try store.commit(second, files: [], text: "https://example.test/shared", subject: nil) + let payload = try require(store.nextPayload(), "First payload is missing") + try expect(payload["id"] as? String == firstID, "Requests must preserve order") + try expect(payload["text"] as? String == "Synthetic caption", "Text must be normalized") + let files = try require(payload["files"] as? [[String: Any]], "File metadata is missing") + let path = try require(files.first?["path"] as? String, "Attachment path is missing") + try expect(manager.fileExists(atPath: path), "Empty documents must be accepted") + + let restarted = try KometShareStore(containerURL: container) + try expect(restarted.nextPayload()?["id"] as? String == firstID, "Claim must survive process restart") + try restarted.acknowledge(id: firstID) + try expect(manager.fileExists(atPath: path), "Acknowledgment must not remove attachment bytes") + try expect(restarted.nextPayload()?["id"] as? String == secondID, "Acknowledgment must advance the queue") + try restarted.removeCompleted(id: firstID) + try expect(!manager.fileExists(atPath: path), "Explicit release must remove exact completed request") + try restarted.acknowledge(id: firstID) + try restarted.removeCompleted(id: firstID) + try expect(restarted.nextPayload()?["id"] as? String == secondID, "Idempotent release must preserve the next request") + + try expectThrows { try restarted.removeCompleted(id: secondID) } + try expectThrows { try restarted.acknowledge(id: "../invalid") } + try restarted.acknowledge(id: secondID) + try restarted.removeCompleted(id: secondID) + + let broken = try restarted.beginRequest() + let brokenFile = try restarted.saveData(Data("fixture".utf8), suggestedName: "sample.txt", typeIdentifier: "public.plain-text", into: broken) + let brokenID = try restarted.commit(broken, files: [brokenFile], text: nil, subject: nil) + let missing = container.appendingPathComponent("KometShare/requests/\(brokenID)/\(brokenFile.relativePath)") + try manager.removeItem(at: missing) + let later = try restarted.beginRequest() + let laterID = try restarted.commit(later, files: [], text: "Later synthetic share", subject: nil) + try expectThrows { _ = try restarted.nextPayload() } + try expect(restarted.nextPayload()?["id"] as? String == laterID, "Corrupt requests must not permanently block the queue") + + let oversized = try restarted.beginRequest() + for index in 0.. Bool, _ message: String) throws { + guard try condition() else { throw Failure(message: message) } + } + + static func require(_ value: T?, _ message: String) throws -> T { + guard let value = value else { throw Failure(message: message) } + return value + } + + static func expectThrows(_ operation: () throws -> Void) throws { + do { + try operation() + } catch { + return + } + throw Failure(message: "Expected operation to reject invalid input") + } + + struct Failure: Error { + let message: String + } +} diff --git a/test/native/komet_share_transport_stub.c b/test/native/komet_share_transport_stub.c new file mode 100644 index 00000000..51a92243 --- /dev/null +++ b/test/native/komet_share_transport_stub.c @@ -0,0 +1,8 @@ +#include "../../ios/ShareExtension/KometShareTransport.h" +#include + +char *komet_share_send(const char *json, KometShareProgress progress, void *context) { + return NULL; +} + +void komet_share_free(char *value) {} diff --git a/test/native/test_ios_appstore_signing.py b/test/native/test_ios_appstore_signing.py new file mode 100644 index 00000000..1d59a787 --- /dev/null +++ b/test/native/test_ios_appstore_signing.py @@ -0,0 +1,172 @@ +import importlib.util +from pathlib import Path +import plistlib +import sys +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +SPEC = importlib.util.spec_from_file_location("komet_appstore_signing", ROOT / "scripts/sign_ios_appstore.py") +SIGNING = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = SIGNING +SPEC.loader.exec_module(SIGNING) + + +def profile(bundle_id="example.synthetic.app", groups=None, team="SYNTH12345"): + entitlements = { + "application-identifier": f"{team}.{bundle_id}", + "com.apple.developer.team-identifier": team, + "keychain-access-groups": [f"{team}.{bundle_id}"], + "get-task-allow": False, + } + if groups is not None: + entitlements["com.apple.security.application-groups"] = groups + return { + "ApplicationIdentifierPrefix": [team], + "TeamIdentifier": [team], + "Entitlements": entitlements, + } + + +class AppStoreSigningPlanTest(unittest.TestCase): + def setUp(self): + self.app_profile = profile(groups=["group.synthetic.second", "group.synthetic.shared"]) + self.share_profile = profile("example.synthetic.app.ShareExtension", ["group.synthetic.shared", "group.synthetic.second"]) + + def test_uses_profiles_own_identifiers_and_entitlements(self): + plan = SIGNING.create_plan(self.app_profile, self.share_profile, "group.synthetic.shared") + self.assertEqual(plan.app.bundle_id, "example.synthetic.app") + self.assertEqual(plan.share.bundle_id, "example.synthetic.app.ShareExtension") + self.assertEqual(plan.group, "group.synthetic.shared") + self.assertEqual(plan.app.entitlements, self.app_profile["Entitlements"]) + self.assertEqual(plan.share.entitlements, self.share_profile["Entitlements"]) + self.assertNotEqual(plan.app.entitlements["application-identifier"], plan.share.entitlements["application-identifier"]) + + def test_selects_a_common_authorized_group_when_default_is_unavailable(self): + self.share_profile["Entitlements"]["com.apple.security.application-groups"] = ["group.synthetic.shared"] + plan = SIGNING.create_plan(self.app_profile, self.share_profile, "group.synthetic.unavailable") + self.assertEqual(plan.group, "group.synthetic.shared") + + def test_app_only_profile_needs_no_shared_capabilities(self): + app_profile = profile() + plan = SIGNING.create_plan(app_profile) + self.assertIsNone(plan.share) + self.assertIsNone(plan.group) + self.assertEqual(plan.app.entitlements, app_profile["Entitlements"]) + + def test_rejects_unrelated_or_wildcard_extension_identifier(self): + for bundle in ["example.synthetic.appOther.Extension", "example.synthetic.app", "example.synthetic.app.*"]: + with self.subTest(bundle=bundle), self.assertRaises(SIGNING.SigningPlanError): + SIGNING.create_plan(self.app_profile, profile(bundle, ["group.synthetic.shared"])) + + def test_rejects_profiles_from_different_teams(self): + with self.assertRaises(SIGNING.SigningPlanError): + SIGNING.create_plan(self.app_profile, profile("example.synthetic.app.ShareExtension", ["group.synthetic.shared"], "OTHER12345")) + + def test_rejects_missing_or_wildcard_shared_group(self): + for groups in [[], ["group.synthetic.other"], ["group.*"]]: + with self.subTest(groups=groups), self.assertRaises(SIGNING.SigningPlanError): + SIGNING.create_plan(self.app_profile, profile("example.synthetic.app.ShareExtension", groups)) + + def test_rejects_inconsistent_profile_prefix(self): + self.app_profile["ApplicationIdentifierPrefix"] = ["OTHER12345"] + with self.assertRaises(SIGNING.SigningPlanError): + SIGNING.create_plan(self.app_profile) + + +class AppStoreBundlePreparationTest(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="synthetic signing ") + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.app = self.root / "Runner.app" + self.share = self.app / "PlugIns/ShareExtension.appex" + self.other = self.app / "PlugIns/Unrelated.appex" + self.share.mkdir(parents=True) + self.other.mkdir() + SIGNING.write_plist(self.app / "Info.plist", { + "CFBundleIdentifier": "example.previous.app", + "CFBundleVersion": "22", + "KometShareAppGroup": "group.previous.app", + "CFBundleURLTypes": [ + {"CFBundleURLName": "example.previous.app", "CFBundleURLSchemes": ["synthetic"]}, + {"CFBundleURLName": "unrelated", "CFBundleURLSchemes": ["other"]}, + ], + }) + SIGNING.write_plist(self.share / "Info.plist", { + "CFBundleIdentifier": "example.previous.app.ShareExtension", + "KometShareAppGroup": "group.previous.app", + }) + self.app_profile_path = self.root / "app.mobileprovision" + self.app_profile_path.write_bytes(b"synthetic app profile") + self.share_profile_path = self.root / "share.mobileprovision" + self.share_profile_path.write_bytes(b"synthetic extension profile") + + def test_app_only_removes_generated_extension_and_disables_shared_storage(self): + plan = SIGNING.create_plan(profile()) + result = SIGNING.prepare_app(self.app, plan, self.app_profile_path) + self.assertIsNone(result) + self.assertFalse(self.share.exists()) + self.assertTrue(self.other.exists()) + info = SIGNING.read_plist(self.app / "Info.plist") + self.assertNotIn("KometShareAppGroup", info) + self.assertFalse(info["KometShareExtensionEnabled"]) + self.assertEqual(info["CFBundleIdentifier"], plan.app.bundle_id) + self.assertEqual(info["CFBundleURLTypes"][0]["CFBundleURLName"], plan.app.bundle_id) + self.assertEqual(info["CFBundleURLTypes"][1]["CFBundleURLName"], "unrelated") + self.assertEqual(info["CFBundleVersion"], "22") + self.assertEqual((self.app / "embedded.mobileprovision").read_bytes(), b"synthetic app profile") + + def test_enabled_extension_uses_separate_profile_and_matching_group(self): + plan = SIGNING.create_plan(profile(groups=["group.synthetic.shared"]), profile("example.synthetic.app.ShareExtension", ["group.synthetic.shared"])) + result = SIGNING.prepare_app(self.app, plan, self.app_profile_path, self.share_profile_path) + self.assertEqual(result, self.share) + self.assertTrue(self.other.exists()) + app_info = SIGNING.read_plist(self.app / "Info.plist") + share_info = SIGNING.read_plist(self.share / "Info.plist") + self.assertTrue(app_info["KometShareExtensionEnabled"]) + self.assertEqual(app_info["KometShareAppGroup"], plan.group) + self.assertEqual(share_info["KometShareAppGroup"], plan.group) + self.assertEqual(share_info["CFBundleIdentifier"], plan.share.bundle_id) + self.assertEqual((self.share / "embedded.mobileprovision").read_bytes(), b"synthetic extension profile") + + def test_signs_nested_binaries_then_extension_then_app_with_distinct_entitlements(self): + framework = self.app / "Frameworks/Synthetic.framework" + framework.mkdir(parents=True) + nested = self.share / "Frameworks/Synthetic.dylib" + nested.parent.mkdir() + nested.write_bytes(b"synthetic binary") + plan = SIGNING.create_plan(profile(groups=["group.synthetic.shared"]), profile("example.synthetic.app.ShareExtension", ["group.synthetic.shared"])) + calls = [] + entitlements = {} + + def capture(command, **options): + calls.append(command) + self.assertTrue(options["check"]) + if "--entitlements" in command: + path = command[command.index("--entitlements") + 1] + entitlements[command[-1]] = SIGNING.read_plist(path) + + SIGNING.sign_bundles(self.app, self.share, plan, "Synthetic Identity With Spaces", self.root / "synthetic.keychain", run=capture) + self.assertEqual(calls[-3][-1], str(self.share)) + self.assertEqual(calls[-2][-1], str(self.app)) + self.assertEqual(calls[-1], ["codesign", "--verify", "--deep", "--strict", "--verbose=2", str(self.app)]) + self.assertEqual(entitlements[str(self.share)], plan.share.entitlements) + self.assertEqual(entitlements[str(self.app)], plan.app.entitlements) + self.assertEqual({command[-1] for command in calls[:-3]}, {str(framework), str(nested)}) + for command in calls[:-1]: + self.assertEqual(command[command.index("--sign") + 1], "Synthetic Identity With Spaces") + + def test_missing_extension_fails_before_modifying_host(self): + plan = SIGNING.create_plan(profile(groups=["group.synthetic.shared"]), profile("example.synthetic.app.ShareExtension", ["group.synthetic.shared"])) + (self.share / "Info.plist").unlink() + self.share.rmdir() + before = (self.app / "Info.plist").read_bytes() + with self.assertRaises(SIGNING.SigningPlanError): + SIGNING.prepare_app(self.app, plan, self.app_profile_path, self.share_profile_path) + self.assertEqual((self.app / "Info.plist").read_bytes(), before) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/native/test_ios_share_build.py b/test/native/test_ios_share_build.py new file mode 100644 index 00000000..a1eb6333 --- /dev/null +++ b/test/native/test_ios_share_build.py @@ -0,0 +1,134 @@ +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +BUILD_SCRIPT = ROOT / "scripts/build_ios_share.sh" + + +class ShareTransportBuildTest(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory(prefix="komet share build ") + self.addCleanup(self.directory.cleanup) + self.path = Path(self.directory.name) + self.bin = self.path / "cargo/bin" + self.bin.mkdir(parents=True) + tool = '''#!/usr/bin/env python3 +import json +import os +from pathlib import Path +import sys + +args = sys.argv[1:] +with open(os.environ["SHARE_TEST_LOG"], "a") as output: + output.write(json.dumps([Path(sys.argv[0]).name, *args]) + "\\n") +if os.environ.get("SHARE_TEST_FAIL") == "1": + sys.exit(1) +if Path(sys.argv[0]).name == "cargo": + target = args[args.index("--target") + 1] + directory = Path(args[args.index("--target-dir") + 1]) / target / "release" + directory.mkdir(parents=True) + (directory / "libkomet_share.a").write_text(target) +else: + output = Path(args[args.index("-output") + 1]) + libraries = args[2:args.index("-output")] + output.write_text("\\n".join(Path(library).read_text() for library in libraries)) +''' + for name in ["cargo", "xcrun"]: + executable = self.bin / name + executable.write_text(tool) + executable.chmod(0o755) + self.env = { + **os.environ, + "CARGO_HOME": str(self.path / "cargo"), + "CARGO_TARGET_DIR": str(self.path / "rust target"), + "BUILT_PRODUCTS_DIR": str(self.path / "products"), + "SHARE_TEST_LOG": str(self.path / "calls.jsonl"), + } + self.output = self.path / "products/KometShareTransport/libkomet_share.a" + + def run_build(self, platform, architectures, **environment): + return subprocess.run( + ["/bin/bash", str(BUILD_SCRIPT)], + env={**self.env, "PLATFORM_NAME": platform, "ARCHS": architectures, **environment}, + capture_output=True, + text=True, + ) + + def calls(self): + return [json.loads(line) for line in (self.path / "calls.jsonl").read_text().splitlines()] + + def test_device_uses_locked_release_library_and_paths_with_spaces(self): + result = self.run_build("iphoneos", "arm64") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.output.read_text(), "aarch64-apple-ios") + call, = self.calls() + self.assertEqual(call[:4], ["cargo", "build", "--locked", "--release"]) + self.assertEqual(call[call.index("--manifest-path") + 1], str(ROOT / "native/komet_share/Cargo.toml")) + + def test_simulator_combines_arm_and_intel_libraries(self): + result = self.run_build("iphonesimulator", "arm64 x86_64") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.output.read_text().splitlines(), ["aarch64-apple-ios-sim", "x86_64-apple-ios"]) + self.assertEqual(self.calls()[-1][:3], ["xcrun", "lipo", "-create"]) + + def test_unknown_architecture_fails_before_publishing_library(self): + result = self.run_build("iphoneos", "x86_64") + self.assertNotEqual(result.returncode, 0) + self.assertIn("Unsupported", result.stderr) + self.assertFalse(self.output.exists()) + + def test_failed_cargo_build_does_not_replace_previous_library(self): + self.output.parent.mkdir(parents=True) + self.output.write_text("previous synthetic library") + result = self.run_build("iphoneos", "arm64", SHARE_TEST_FAIL="1") + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.output.read_text(), "previous synthetic library") + + +class ShareProjectWiringTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + result = subprocess.run( + ["/usr/bin/plutil", "-convert", "json", "-o", "-", str(ROOT / "ios/Runner.xcodeproj/project.pbxproj")], + check=True, + capture_output=True, + text=True, + ) + cls.objects = json.loads(result.stdout)["objects"] + cls.targets = { + item["name"]: item + for item in cls.objects.values() + if item["isa"] == "PBXNativeTarget" + } + + def sources(self, target): + phases = [self.objects[key] for key in self.targets[target]["buildPhases"]] + source_phase = next(phase for phase in phases if phase["isa"] == "PBXSourcesBuildPhase") + return {self.objects[self.objects[key]["fileRef"]]["path"] for key in source_phase["files"]} + + def test_shared_accounts_compile_in_both_targets_and_sender_only_in_extension(self): + for target in ["Runner", "ShareExtension"]: + self.assertIn("KometShareAccounts.swift", self.sources(target)) + self.assertIn("KometShareSender.swift", self.sources("ShareExtension")) + self.assertNotIn("KometShareSender.swift", self.sources("Runner")) + + def test_library_build_precedes_swift_and_declares_linker_output(self): + phases = [self.objects[key] for key in self.targets["ShareExtension"]["buildPhases"]] + self.assertEqual(phases[0]["name"], "Build Komet Share Transport") + self.assertEqual(phases[0]["alwaysOutOfDate"], "1") + self.assertEqual(phases[0]["outputPaths"], ["$(BUILT_PRODUCTS_DIR)/KometShareTransport/libkomet_share.a"]) + configs = self.objects[self.targets["ShareExtension"]["buildConfigurationList"]]["buildConfigurations"] + for key in configs: + settings = self.objects[key]["buildSettings"] + self.assertEqual(settings["SWIFT_OBJC_BRIDGING_HEADER"], "ShareExtension/ShareExtension-Bridging-Header.h") + self.assertIn("-force_load", settings["OTHER_LDFLAGS"]) + self.assertIn('"$(BUILT_PRODUCTS_DIR)/KometShareTransport/libkomet_share.a"', settings["OTHER_LDFLAGS"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/per_chat_json_store_test.dart b/test/per_chat_json_store_test.dart new file mode 100644 index 00000000..ed77635a --- /dev/null +++ b/test/per_chat_json_store_test.dart @@ -0,0 +1,157 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/storage/per_chat_json_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _prefsKey = 'synthetic_per_chat_settings'; +const _channel = MethodChannel('plugins.flutter.io/shared_preferences'); + +class _ChatFlags extends PerChatJsonStore { + _ChatFlags() + : super( + prefsKey: _prefsKey, + fromJson: (value) => value is bool ? value : null, + toJson: (value) => value, + ); + + bool? valueOf(int accountId, int chatId) => read(accountId, chatId); + Future setFlag(int accountId, int chatId, bool? value) => + write(accountId, chatId, value); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + + setUp(SharedPreferences.resetStatic); + tearDown(() { + messenger.setMockMethodCallHandler(_channel, null); + SharedPreferences.resetStatic(); + }); + + test( + 'concurrent initial loads and writes preserve existing chat entries', + () async { + final started = Completer(); + final initial = Completer>(); + final persisted = >[]; + var loadCount = 0; + messenger.setMockMethodCallHandler(_channel, (call) async { + switch (call.method) { + case 'getAll': + loadCount++; + started.complete(); + return initial.future; + case 'setString': + final arguments = call.arguments as Map; + expect(arguments['key'], 'flutter.$_prefsKey'); + persisted.add( + jsonDecode(arguments['value'] as String) as Map, + ); + return true; + default: + throw StateError('Unexpected preference operation: ${call.method}'); + } + }); + final store = _ChatFlags(); + addTearDown(store.revision.dispose); + final firstLoad = store.load(); + await started.future; + final secondLoad = store.load(); + final changed = store.setFlag(101, 11, false); + final added = store.setFlag(202, 22, true); + expect(store.revision.value, 0); + expect(persisted, isEmpty); + initial.complete({ + 'flutter.$_prefsKey': jsonEncode({'101/11': true, '101/12': true}), + }); + await Future.wait([firstLoad, secondLoad, changed, added]); + expect(loadCount, 1); + expect(store.valueOf(101, 11), isFalse); + expect(store.valueOf(101, 12), isTrue); + expect(store.valueOf(202, 22), isTrue); + expect(store.revision.value, 2); + expect(persisted.last, {'101/11': false, '101/12': true, '202/22': true}); + final restored = _ChatFlags(); + addTearDown(restored.revision.dispose); + await restored.load(); + expect(restored.valueOf(101, 11), isFalse); + expect(restored.valueOf(101, 12), isTrue); + expect(restored.valueOf(202, 22), isTrue); + }, + ); + + test( + 'deleting during first load waits for the saved entry before removal', + () async { + final started = Completer(); + final initial = Completer>(); + Map? persisted; + messenger.setMockMethodCallHandler(_channel, (call) async { + if (call.method == 'getAll') { + started.complete(); + return initial.future; + } + if (call.method == 'setString') { + persisted = + jsonDecode((call.arguments as Map)['value'] as String) + as Map; + return true; + } + throw StateError('Unexpected preference operation: ${call.method}'); + }); + final store = _ChatFlags(); + addTearDown(store.revision.dispose); + final loading = store.load(); + await started.future; + final deletion = store.setFlag(101, 11, null); + initial.complete({ + 'flutter.$_prefsKey': jsonEncode({'101/11': true, '202/11': false}), + }); + await Future.wait([loading, deletion]); + expect(store.valueOf(101, 11), isNull); + expect(store.valueOf(202, 11), isFalse); + expect(persisted, {'202/11': false}); + expect(store.revision.value, 1); + }, + ); + + test( + 'failed initial loading can retry without losing stored chat settings', + () async { + var loadCount = 0; + Map? persisted; + messenger.setMockMethodCallHandler(_channel, (call) async { + if (call.method == 'getAll') { + loadCount++; + if (loadCount == 1) { + throw PlatformException(code: 'SYNTHETIC_UNAVAILABLE'); + } + return { + 'flutter.$_prefsKey': jsonEncode({'101/11': true}), + }; + } + if (call.method == 'setString') { + persisted = + jsonDecode((call.arguments as Map)['value'] as String) + as Map; + return true; + } + throw StateError('Unexpected preference operation: ${call.method}'); + }); + final store = _ChatFlags(); + addTearDown(store.revision.dispose); + await expectLater(store.load(), throwsA(isA())); + expect(store.revision.value, 0); + await store.setFlag(202, 22, false); + expect(loadCount, 2); + expect(store.valueOf(101, 11), isTrue); + expect(store.valueOf(202, 22), isFalse); + expect(persisted, {'101/11': true, '202/22': false}); + }, + ); +} diff --git a/test/photo_viewer_test.dart b/test/photo_viewer_test.dart index 53cb282b..c0213f26 100644 --- a/test/photo_viewer_test.dart +++ b/test/photo_viewer_test.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:komet/backend/modules/messages.dart'; +import 'package:komet/frontend/widgets/attachment/photo_hero.dart'; import 'package:komet/frontend/widgets/photo_viewer.dart'; import 'package:komet/l10n/app_localizations.dart'; import 'package:komet/models/attachment.dart'; @@ -41,7 +42,212 @@ Future _pumpViewer( await tester.pump(); } +Future _pushViewer( + WidgetTester tester, { + PhotoHeroController? hero, +}) async { + Widget viewer(BuildContext context) => PhotoViewerScreen( + photos: const [ + PhotoAttachment(baseUrl: 'https://example.test/first.jpg'), + PhotoAttachment(baseUrl: 'https://example.test/second.jpg'), + ], + hero: hero, + ); + await tester.pumpWidget( + MaterialApp( + locale: const Locale('ru'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) => Scaffold( + backgroundColor: Colors.green, + body: TextButton( + onPressed: () => Navigator.of(context).push( + hero == null + ? PhotoViewerRoute(builder: viewer) + : PhotoHeroRoute(hero: hero, builder: viewer), + ), + child: const Text('open'), + ), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); +} + +Offset _dismissOffset(WidgetTester tester) { + final transform = tester.widget( + find.byKey(const ValueKey('media-dismiss-transform')), + ); + return Offset(transform.transform[12], transform.transform[13]); +} + void main() { + testWidgets('drag dismissal flies back from the dragged photo position', ( + tester, + ) async { + final image = (await tester.runAsync( + () => createTestImage(width: 20, height: 10), + ))!; + addTearDown(image.dispose); + final hero = PhotoHeroController( + origin: () => const Rect.fromLTWH(20, 60, 80, 80), + image: RawImageProvider(image), + ); + await _pushViewer(tester, hero: hero); + final gesture = await tester.startGesture(const Offset(400, 260)); + await gesture.moveBy( + const Offset(0, 140), + timeStamp: const Duration(milliseconds: 400), + ); + await tester.pump(); + final draggedPhoto = inscribeRect(const Size(20, 10), hero.areaRect!); + await gesture.up(timeStamp: const Duration(milliseconds: 500)); + await tester.pump(); + + final flight = find.byWidgetPredicate( + (widget) => widget is Image && widget.image is RawImageProvider, + ); + expect(flight, findsOneWidget); + expect(tester.getRect(flight).top, closeTo(draggedPhoto.top, 1)); + await tester.pump(const Duration(milliseconds: 320)); + expect(find.byType(PhotoViewerScreen), findsNothing); + }); + + testWidgets( + 'vertical drag follows the finger, fades the background and closes', + (tester) async { + await _pushViewer(tester); + final gesture = await tester.startGesture(const Offset(400, 260)); + await gesture.moveBy( + const Offset(12, 140), + timeStamp: const Duration(milliseconds: 400), + ); + await tester.pump(); + + expect(_dismissOffset(tester).dy, 140); + final backdrop = tester.widget( + find.byKey(const ValueKey('media-dismiss-backdrop')), + ); + expect(backdrop.color.a, lessThan(1)); + + await gesture.up(timeStamp: const Duration(milliseconds: 500)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(find.byType(PhotoViewerScreen), findsNothing); + }, + ); + + testWidgets('short slow drag and cancelled drag restore the photo', ( + tester, + ) async { + await _pushViewer(tester); + var gesture = await tester.startGesture(const Offset(400, 260)); + await gesture.moveBy( + const Offset(0, 50), + timeStamp: const Duration(milliseconds: 400), + ); + await gesture.up(timeStamp: const Duration(milliseconds: 700)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(_dismissOffset(tester), Offset.zero); + expect(find.byType(PhotoViewerScreen), findsOneWidget); + + gesture = await tester.startGesture(const Offset(400, 260)); + await gesture.moveBy( + const Offset(0, -150), + timeStamp: const Duration(milliseconds: 400), + ); + await tester.pump(); + expect(_dismissOffset(tester).dy, -150); + await gesture.cancel(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(_dismissOffset(tester), Offset.zero); + expect(find.byType(PhotoViewerScreen), findsOneWidget); + }); + + testWidgets('a short fast vertical fling dismisses the photo', ( + tester, + ) async { + await _pushViewer(tester); + await tester.flingFrom(const Offset(400, 260), const Offset(0, -70), 1500); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(find.byType(PhotoViewerScreen), findsNothing); + }); + + testWidgets('horizontal swipe changes photos without dismissing', ( + tester, + ) async { + await _pushViewer(tester); + await tester.timedDragFrom( + const Offset(650, 260), + const Offset(-500, 0), + const Duration(milliseconds: 600), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.byType(PhotoViewerScreen), findsOneWidget); + expect(_dismissOffset(tester), Offset.zero); + expect(find.byIcon(Symbols.chevron_left), findsOneWidget); + expect(find.byIcon(Symbols.chevron_right), findsNothing); + }); + + testWidgets('zoomed photos pan vertically without dismissing', ( + tester, + ) async { + await _pushViewer(tester); + final viewer = tester.widget( + find.byType(InteractiveViewer).first, + ); + viewer.transformationController!.value = Matrix4.diagonal3Values(2, 2, 1); + await tester.pump(); + await tester.dragFrom(const Offset(400, 260), const Offset(0, 160)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(find.byType(PhotoViewerScreen), findsOneWidget); + expect(_dismissOffset(tester), Offset.zero); + expect( + viewer.transformationController!.value.getMaxScaleOnAxis(), + greaterThan(1), + ); + }); + + testWidgets('a second finger cancels dismissal and preserves pinch zoom', ( + tester, + ) async { + await _pushViewer(tester); + final first = await tester.startGesture(const Offset(340, 260), pointer: 1); + await first.moveBy(const Offset(0, 40)); + await tester.pump(); + expect(_dismissOffset(tester).dy, 40); + final second = await tester.startGesture( + const Offset(460, 300), + pointer: 2, + ); + await first.moveTo(const Offset(280, 300)); + await second.moveTo(const Offset(520, 300)); + await tester.pump(); + await first.up(); + await second.up(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + + expect(find.byType(PhotoViewerScreen), findsOneWidget); + expect(_dismissOffset(tester), Offset.zero); + final viewer = tester.widget( + find.byType(InteractiveViewer).first, + ); + expect( + viewer.transformationController!.value.getMaxScaleOnAxis(), + greaterThan(1), + ); + }); + testWidgets('shows who sent the photo and when', (tester) async { await _pumpViewer(tester, message: _message()); diff --git a/test/seed_scheme_test.dart b/test/seed_scheme_test.dart index a966d6bb..6eeced1d 100644 --- a/test/seed_scheme_test.dart +++ b/test/seed_scheme_test.dart @@ -8,6 +8,13 @@ import 'package:material_color_utilities/material_color_utilities.dart'; double _chroma(Color color) => Hct.fromInt(color.toARGB32()).chroma; +double _tone(Color color) => Hct.fromInt(color.toARGB32()).tone; + +double _contrast(Color a, Color b) => Contrast.ratioOfTones(_tone(a), _tone(b)); + +Color _accent(double brightness) => + HSVColor.fromAHSV(1, 220, 0.7, brightness).toColor(); + bool _isGray(Color color) { final argb = color.toARGB32(); final r = (argb >> 16) & 0xFF; @@ -30,11 +37,7 @@ void main() { for (final brightness in Brightness.values) { final scheme = schemeFromSeed(seed, brightness); expect(_isGray(scheme.primary), isTrue, reason: '$brightness'); - expect( - _isGray(scheme.secondaryContainer), - isTrue, - reason: '$brightness', - ); + expect(_isGray(scheme.secondaryContainer), isTrue, reason: '$brightness'); } }); @@ -57,4 +60,56 @@ void main() { expect(_isGray(derived.primary), isTrue); }); + + test('акцент полной яркости не отличается от обычной схемы', () { + final seed = _accent(1); + for (final brightness in Brightness.values) { + expect( + accentSchemeFromSeed(seed, brightness), + schemeFromSeed(seed, brightness), + reason: '$brightness', + ); + } + }); + + test('ползунок яркости затемняет акцент плавно до самого низа', () { + final steps = [1.0, 0.8, 0.6, 0.4, kAccentMinBrightness]; + for (final brightness in Brightness.values) { + final tones = [ + for (final value in steps) + _tone( + accentSchemeFromSeed(_accent(value), brightness).primaryContainer, + ), + ]; + for (var i = 1; i < tones.length; i++) { + expect(tones[i], lessThan(tones[i - 1]), reason: '$brightness $tones'); + } + } + }); + + test('самый тёмный акцент остаётся цветным и читаемым', () { + final seed = _accent(kAccentMinBrightness); + for (final brightness in Brightness.values) { + final scheme = accentSchemeFromSeed(seed, brightness); + final bubbleText = brightness == Brightness.dark + ? Colors.white + : Colors.black; + + expect(_chroma(scheme.primaryContainer), greaterThan(20)); + expect(scheme.surfaceTint, scheme.primary); + expect(_contrast(bubbleText, scheme.primaryContainer), greaterThan(4.5)); + expect( + _contrast(scheme.onPrimaryContainer, scheme.primaryContainer), + greaterThanOrEqualTo(4.5), + ); + expect( + _contrast(scheme.onSecondaryContainer, scheme.secondaryContainer), + greaterThanOrEqualTo(4.5), + ); + expect( + _contrast(scheme.onPrimary, scheme.primary), + greaterThanOrEqualTo(4.5), + ); + } + }); } diff --git a/test/share_account_snapshot_test.dart b/test/share_account_snapshot_test.dart new file mode 100644 index 00000000..96b51816 --- /dev/null +++ b/test/share_account_snapshot_test.dart @@ -0,0 +1,142 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/share/native_share_account_channel.dart'; +import 'package:komet/core/share/share_account_snapshot.dart'; + +ShareAccountSnapshot _snapshot({String token = 'synthetic-session-token'}) => + ShareAccountSnapshot( + accountId: 42, + accountName: 'Synthetic Account', + token: token, + session: const {'host': 'server.example.invalid', 'port': 443}, + login: { + 'token': 'ignored-login-token', + 'chatCacheFingerprint': Uint8List.fromList([1, 2, 3]), + 'interactive': false, + 'exp': { + 'chatsCountGroups': Uint8List.fromList([11, 50]), + }, + }, + chats: const [ + ShareRecipientSnapshot( + id: 9007199254741001, + title: 'Synthetic Group', + type: 'CHAT', + ), + ShareRecipientSnapshot( + id: 20, + title: 'Synthetic Encrypted Chat', + type: 'DIALOG', + disabledReason: 'Open Komet to send encrypted messages', + ), + ], + ); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const method = MethodChannel('test.komet/share-account'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + + tearDown(() => messenger.setMockMethodCallHandler(method, null)); + + test('snapshot keeps binary login fields and exact large recipient IDs', () { + final map = _snapshot().toMap(); + final serialized = jsonDecode(jsonEncode(map)) as Map; + expect(serialized['accountId'], '42'); + expect(serialized['token'], 'synthetic-session-token'); + final login = serialized['login'] as Map; + expect(login.containsKey('token'), isFalse); + expect(login.containsKey('chatCacheFingerprint'), isFalse); + expect(login['interactive'], isFalse); + expect(login['exp'], { + 'chatsCountGroups': {r'$bin': 'CzI='}, + }); + final chats = serialized['chats'] as List; + expect(chats.first['id'], '9007199254741001'); + expect(chats.last['disabledReason'], contains('encrypted')); + }); + + test('logout invalidates queued and stale account exports', () async { + final calls = []; + final started = Completer(); + final finish = Completer(); + messenger.setMockMethodCallHandler(method, (call) async { + calls.add(call); + if (call.method == 'syncShareAccount') { + started.complete(); + await finish.future; + } + return null; + }); + final channel = NativeShareAccountChannel(channel: method, enabled: true); + final generation = channel.generation(42); + final first = channel.publish(_snapshot(), generation); + await started.future; + final queued = channel.publish(_snapshot(), generation); + final removal = channel.remove(42); + finish.complete(); + await Future.wait([first, queued, removal]); + await channel.publish(_snapshot(), generation); + expect(calls.map((call) => call.method), [ + 'syncShareAccount', + 'clearShareAccount', + ]); + expect(calls.last.arguments, {'accountId': '42'}); + }); + + test('a failed sync does not prevent clearing the account', () async { + final calls = []; + messenger.setMockMethodCallHandler(method, (call) async { + calls.add(call.method); + if (call.method == 'syncShareAccount') { + throw PlatformException(code: 'UNAVAILABLE'); + } + return null; + }); + final channel = NativeShareAccountChannel(channel: method, enabled: true); + await expectLater( + channel.publish(_snapshot(), channel.generation(42)), + throwsA(isA()), + ); + await channel.remove(42); + expect(calls, ['syncShareAccount', 'clearShareAccount']); + }); + + test( + 'token renewal supplies the current token for native matching', + () async { + MethodCall? captured; + messenger.setMockMethodCallHandler(method, (call) async { + captured = call; + return 'synthetic-renewed-token'; + }); + final channel = NativeShareAccountChannel(channel: method, enabled: true); + expect( + await channel.renewedToken(42, 'synthetic-original-token'), + 'synthetic-renewed-token', + ); + expect(captured!.method, 'readShareToken'); + expect(captured!.arguments, { + 'accountId': '42', + 'knownToken': 'synthetic-original-token', + }); + }, + ); + + test('disabled platforms do not access native sharing credentials', () async { + final calls = []; + messenger.setMockMethodCallHandler(method, (call) async { + calls.add(call); + return null; + }); + final channel = NativeShareAccountChannel(channel: method, enabled: false); + await channel.publish(_snapshot(), 0); + await channel.remove(42); + expect(await channel.renewedToken(42, 'synthetic-token'), isNull); + expect(calls, isEmpty); + }); +} diff --git a/test/share_fingerprint_test.dart b/test/share_fingerprint_test.dart new file mode 100644 index 00000000..7daa05e1 --- /dev/null +++ b/test/share_fingerprint_test.dart @@ -0,0 +1,59 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/protocol/chat_cache_fingerprint.dart'; +import 'package:komet/core/share/share_account_snapshot.dart'; + +void main() { + final vectors = + jsonDecode( + File( + 'test/fixtures/share_fingerprint_vectors.json', + ).readAsStringSync(), + ) + as List; + + for (final raw in vectors) { + final vector = raw as Map; + test( + 'native share fingerprint matches ${vector['arch']} preLogin=${vector['pre_login']}', + () { + final arch = vector['arch'] as String; + final preLogin = vector['pre_login'] as bool; + final digests = ChatCacheFingerprint.exportDigests( + arch: arch, + preLogin: preLogin, + ); + expect(digests, vector['digests']); + final computed = ChatCacheFingerprint.compute( + vector['seed'] as int, + vector['device_id'] as String, + arch: arch, + preLogin: preLogin, + ); + expect( + computed.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join(), + vector['fingerprint'], + ); + final snapshot = ShareAccountSnapshot( + accountId: 101, + accountName: 'Synthetic Account', + token: 'synthetic-token', + session: {'fingerprint_digests': digests, 'arch': arch}, + login: {'chatCacheFingerprint': computed}, + chats: const [], + ); + final exported = jsonDecode(jsonEncode(snapshot.toMap())) as Map; + expect( + (exported['session'] as Map)['fingerprint_digests'], + vector['digests'], + ); + expect( + (exported['login'] as Map).containsKey('chatCacheFingerprint'), + isFalse, + ); + }, + ); + } +} diff --git a/test/share_inbox_test.dart b/test/share_inbox_test.dart new file mode 100644 index 00000000..ba17d0ee --- /dev/null +++ b/test/share_inbox_test.dart @@ -0,0 +1,295 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/share/share_inbox.dart'; +import 'package:komet/core/share/shared_file_usage.dart'; + +Map _share(String id) => {'id': id, 'text': 'Synthetic $id'}; + +void main() { + test('coalesces initial, resumed and native event checks', () async { + final response = Completer(); + var consumes = 0; + final received = []; + final inbox = ShareInbox( + consume: () { + consumes++; + return response.future; + }, + acknowledge: (_) async {}, + onShare: (payload) => received.add(payload.text), + ); + + final first = inbox.check(); + final second = inbox.check(); + final third = inbox.check(); + expect(consumes, 1); + response.complete(_share('first')); + await Future.wait([first, second, third]); + + expect(consumes, 1); + expect(received, ['Synthetic first']); + }); + + test('keeps the active share until explicitly completed', () async { + var consumes = 0; + final acknowledged = []; + final received = []; + final inbox = ShareInbox( + consume: () async { + consumes++; + return _share('pending'); + }, + acknowledge: (id) async => acknowledged.add(id), + onShare: (payload) => received.add(payload.text), + ); + + await inbox.check(); + for (var i = 0; i < 150; i++) { + await inbox.check(); + } + + expect(consumes, 1); + expect(acknowledged, isEmpty); + expect(received, ['Synthetic pending']); + }); + + test('acknowledges one share before consuming the next', () async { + final pending = ['first', 'second']; + final operations = []; + final received = []; + final inbox = ShareInbox( + consume: () async { + operations.add('consume'); + return pending.isEmpty ? null : _share(pending.first); + }, + acknowledge: (id) async { + operations.add('acknowledge $id'); + expect(pending.removeAt(0), id); + }, + onShare: (payload) => received.add(payload.text), + ); + + await inbox.check(); + await Future.wait([inbox.complete(), inbox.check(), inbox.check()]); + expect(received, ['Synthetic first', 'Synthetic second']); + expect(operations, ['consume', 'acknowledge first', 'consume']); + + await inbox.complete(); + expect(operations, [ + 'consume', + 'acknowledge first', + 'consume', + 'acknowledge second', + 'consume', + ]); + }); + + test('retries failed acknowledgement without presenting again', () async { + var failed = false; + final pending = ['first', 'second']; + final received = []; + final inbox = ShareInbox( + consume: () async => pending.isEmpty ? null : _share(pending.first), + acknowledge: (id) async { + if (!failed) { + failed = true; + throw StateError('Synthetic acknowledgement failure'); + } + expect(pending.removeAt(0), id); + }, + onShare: (payload) => received.add(payload.text), + ); + + await inbox.check(); + await expectLater(inbox.complete(), throwsStateError); + await inbox.check(); + + expect(received, ['Synthetic first', 'Synthetic second']); + expect(pending, ['second']); + }); + + test('skips an empty envelope without blocking subsequent shares', () async { + final pending = [ + {'id': 'missing-files', 'files': []}, + _share('valid'), + ]; + final acknowledged = []; + final received = []; + final inbox = ShareInbox( + consume: () async => pending.isEmpty ? null : pending.first, + acknowledge: (id) async { + acknowledged.add(id); + pending.removeAt(0); + }, + onShare: (payload) => received.add(payload.text), + ); + + await inbox.check(); + + expect(acknowledged, ['missing-files']); + expect(received, ['Synthetic valid']); + }); + + test( + 'rechecks when a native event arrives during an empty consume', + () async { + final initial = Completer(); + var consumes = 0; + final received = []; + final inbox = ShareInbox( + consume: () { + consumes++; + return consumes == 1 ? initial.future : Future.value(_share('new')); + }, + acknowledge: (_) async {}, + onShare: (payload) => received.add(payload.text), + ); + + final first = inbox.check(); + final second = inbox.check(); + initial.complete(null); + await Future.wait([first, second]); + + expect(consumes, 2); + expect(received, ['Synthetic new']); + }, + ); + + test( + 'a dismissed share cannot replay after restart during an upload', + () async { + final usage = SharedFileUsage(); + final uploaded = Completer(); + final upload = usage.use([ + '/synthetic/shared-file', + ], () => uploaded.future); + final acknowledged = Completer(); + var nativeState = 'claimed'; + var filesExist = true; + final received = []; + Future consume() async => + nativeState == 'claimed' ? _share('accepted') : null; + final inbox = ShareInbox( + consume: consume, + acknowledge: (_) async { + nativeState = 'completed'; + acknowledged.complete(); + }, + release: (_) async => filesExist = false, + onShare: (payload) => received.add(payload.text), + ); + await inbox.check(); + + final completion = inbox.complete( + waitForRelease: () => usage.waitUntilUnused(['/synthetic/shared-file']), + ); + await acknowledged.future; + expect(nativeState, 'completed'); + expect(filesExist, isTrue); + + final restarted = ShareInbox( + consume: consume, + acknowledge: (_) async {}, + onShare: (payload) => received.add(payload.text), + ); + await restarted.check(); + expect(received, ['Synthetic accepted']); + + uploaded.complete(); + await upload; + await completion; + expect(filesExist, isFalse); + }, + ); + + test( + 'resume events during delayed release never reoffer the share', + () async { + final readyToRelease = Completer(); + final acknowledged = Completer(); + final operations = []; + final received = []; + var nativeState = 'claimed'; + final inbox = ShareInbox( + consume: () async { + operations.add('consume'); + return nativeState == 'claimed' ? _share('first') : null; + }, + acknowledge: (id) async { + operations.add('acknowledge $id'); + nativeState = 'completed'; + acknowledged.complete(); + }, + release: (id) async => operations.add('release $id'), + onShare: (payload) => received.add(payload.text), + ); + await inbox.check(); + final completion = inbox.complete( + waitForRelease: () => readyToRelease.future, + ); + await acknowledged.future; + final checks = [inbox.check(), inbox.check(), inbox.check()]; + expect(operations, ['consume', 'acknowledge first']); + readyToRelease.complete(); + await Future.wait([completion, ...checks]); + expect(received, ['Synthetic first']); + expect(operations, [ + 'consume', + 'acknowledge first', + 'release first', + 'consume', + ]); + }, + ); + + test( + 'failed cleanup retries without acknowledging or presenting twice', + () async { + var acknowledgements = 0; + var releases = 0; + var nativeState = 'claimed'; + final received = []; + final inbox = ShareInbox( + consume: () async => nativeState == 'claimed' ? _share('first') : null, + acknowledge: (_) async { + acknowledgements++; + nativeState = 'completed'; + }, + release: (_) async { + releases++; + if (releases == 1) throw StateError('Synthetic cleanup failure'); + }, + onShare: (payload) => received.add(payload.text), + ); + await inbox.check(); + await expectLater(inbox.complete(), throwsStateError); + await inbox.check(); + + expect(acknowledgements, 1); + expect(releases, 2); + expect(received, ['Synthetic first']); + }, + ); + + test( + 'a new explicit request with identical content remains deliverable', + () async { + final pending = ['first', 'second']; + var delivered = 0; + final inbox = ShareInbox( + consume: () async => pending.isEmpty + ? null + : {'id': pending.first, 'text': 'The same synthetic content'}, + acknowledge: (id) async => expect(pending.removeAt(0), id), + release: (_) async {}, + onShare: (_) => delivered++, + ); + await inbox.check(); + await inbox.complete(); + expect(delivered, 2); + await inbox.complete(); + expect(delivered, 2); + }, + ); +} diff --git a/test/share_recipient_eligibility_test.dart b/test/share_recipient_eligibility_test.dart new file mode 100644 index 00000000..8d4b20c4 --- /dev/null +++ b/test/share_recipient_eligibility_test.dart @@ -0,0 +1,51 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/crypto/e2ee_service.dart'; +import 'package:komet/core/share/share_account_snapshot.dart'; +import 'package:komet/core/share/share_recipient_eligibility.dart'; + +String? _reason({ + E2eePhase e2ee = E2eePhase.none, + bool legacy = false, + bool channel = false, + bool canPost = false, +}) => shareRecipientDisabledReason( + legacyEncryptionEnabled: legacy, + e2eePhase: e2ee, + isChannel: channel, + canPostToChannel: canPost, +); + +void main() { + for (final phase in E2eePhase.values.where( + (phase) => phase != E2eePhase.none, + )) { + test( + 'native share prevents plaintext sending while E2EE is ${phase.name}', + () { + final reason = _reason(e2ee: phase); + expect(reason, isNotNull); + final recipient = ShareRecipientSnapshot( + id: 202, + title: 'Synthetic encrypted chat', + type: 'DIALOG', + disabledReason: reason, + ); + final exported = jsonDecode(jsonEncode(recipient.toMap())) as Map; + expect(exported['disabledReason'], reason); + }, + ); + } + + test('legacy encrypted chats remain blocked without an E2EE session', () { + expect(_reason(legacy: true), _reason(e2ee: E2eePhase.established)); + expect(_reason(legacy: true, channel: true, canPost: true), isNotNull); + }); + + test('ordinary dialogs and writable channels remain available', () { + expect(_reason(), isNull); + expect(_reason(channel: true, canPost: true), isNull); + expect(_reason(channel: true), isNotNull); + }); +} diff --git a/test/shared_file_usage_test.dart b/test/shared_file_usage_test.dart new file mode 100644 index 00000000..24130c30 --- /dev/null +++ b/test/shared_file_usage_test.dart @@ -0,0 +1,75 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/share/shared_file_usage.dart'; + +void main() { + test('waits for every concurrent upload using a shared file', () async { + final usage = SharedFileUsage(); + final first = Completer(); + final second = Completer(); + final firstUpload = usage.use(['/synthetic/photo'], () => first.future); + final secondUpload = usage.use(['/synthetic/photo'], () => second.future); + var released = false; + final cleanup = usage + .waitUntilUnused(['/synthetic/photo']) + .then((_) => released = true); + + first.complete(); + await firstUpload; + expect(released, isFalse); + second.complete(); + await secondUpload; + await cleanup; + expect(released, isTrue); + }); + + test('protects uploads started after the composer has closed', () async { + final usage = SharedFileUsage(); + final readyToUpload = Completer(); + final uploaded = Completer(); + late Future upload; + final preparing = usage.use(['/synthetic/video'], () async { + await readyToUpload.future; + upload = usage.use(['/synthetic/video'], () => uploaded.future); + }); + var released = false; + final cleanup = usage + .waitUntilUnused(['/synthetic/video']) + .then((_) => released = true); + + readyToUpload.complete(); + await preparing; + expect(released, isFalse); + uploaded.complete(); + await upload; + await cleanup; + expect(released, isTrue); + }); + + test('releases failed readers and deduplicates repeated paths', () async { + final usage = SharedFileUsage(); + final failed = Completer(); + final upload = usage.use([ + '/synthetic/document', + '/synthetic/document', + ], () => failed.future); + final result = expectLater(upload, throwsStateError); + final cleanup = usage.waitUntilUnused(['/synthetic/document']); + + failed.completeError(StateError('Synthetic upload failure')); + await result; + await cleanup; + await usage.waitUntilUnused(['/synthetic/document']); + }); + + test('does not block cleanup on files from another share', () async { + final usage = SharedFileUsage(); + final uploaded = Completer(); + final upload = usage.use(['/synthetic/other'], () => uploaded.future); + + await usage.waitUntilUnused(['/synthetic/current']); + uploaded.complete(); + await upload; + }); +} diff --git a/test/shared_photo_preview_test.dart b/test/shared_photo_preview_test.dart new file mode 100644 index 00000000..a912dda5 --- /dev/null +++ b/test/shared_photo_preview_test.dart @@ -0,0 +1,257 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/l10n/app_localizations.dart'; +import 'package:image/image.dart' as img; +import 'package:komet/backend/modules/messages.dart'; +import 'package:komet/backend/modules/share_sender.dart'; +import 'package:komet/core/media/share_thumbnail.dart'; +import 'package:komet/frontend/screens/chats/share_composer_bar.dart'; +import 'package:komet/frontend/widgets/attachment/bubbles/bubble_context.dart'; +import 'package:komet/frontend/widgets/attachment/bubbles/photo_bubble.dart'; +import 'package:komet/frontend/widgets/rich_message_controller.dart'; +import 'package:komet/models/attachment.dart'; +import 'package:komet/models/shared_payload.dart'; +import 'package:material_symbols_icons/symbols.dart'; + +Future _resolveImages(WidgetTester tester) async { + for (var pass = 0; pass < 2; pass++) { + final images = tester.widgetList(find.byType(Image)).toList(); + final context = tester.element(find.byType(Scaffold)); + await tester.runAsync(() async { + await Future.wait([ + for (final image in images) + precacheImage(image.image, context, onError: (_, _) {}), + ]); + }); + await tester.pump(); + } +} + +Future _pumpWithImages(WidgetTester tester, Widget widget) async { + await tester.runAsync(() => tester.pumpWidget(widget)); + await _resolveImages(tester); +} + +bool _hasRenderedImage(WidgetTester tester) => tester + .widgetList(find.byType(RawImage)) + .any((image) => image.image != null); + +Future _pumpComposer(WidgetTester tester, PreparedShare share) async { + final controller = RichMessageController(); + addTearDown(controller.dispose); + await _pumpWithImages( + tester, + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('ru'), + home: Scaffold( + body: Align( + alignment: Alignment.bottomCenter, + child: Builder( + builder: (context) => ShareComposerBar.forShare( + l10n: AppLocalizations.of(context)!, + share: share, + controller: controller, + recipientNames: const ['Synthetic recipient'], + onSend: (_) async {}, + ), + ), + ), + ), + ), + ); +} + +void main() { + late Directory directory; + late File photo; + + setUp(() { + directory = Directory.systemTemp.createTempSync('synthetic_shared_photo'); + final raster = img.Image(width: 320, height: 160); + img.fill(raster, color: img.ColorRgb8(32, 144, 224)); + photo = File('${directory.path}/synthetic-photo.png') + ..writeAsBytesSync(img.encodePng(raster)); + }); + + tearDown(() { + PaintingBinding.instance.imageCache.clear(); + PaintingBinding.instance.imageCache.clearLiveImages(); + directory.deleteSync(recursive: true); + }); + + SharedFile source({String mime = 'image/png'}) => SharedFile( + path: photo.path, + name: 'synthetic-photo.png', + mime: mime, + size: photo.lengthSync(), + ); + + test( + 'generic MIME retains image/video kinds without overriding explicit document MIME', + () { + expect( + source(mime: 'application/octet-stream').kind, + SharedFileKind.photo, + ); + for (final extension in ['JPG', 'HEIC', 'heif']) { + expect( + SharedFile( + path: '/synthetic/$extension', + name: 'photo.$extension', + mime: '', + size: 1, + ).kind, + SharedFileKind.photo, + ); + } + expect( + const SharedFile( + path: '/synthetic/movie', + name: 'clip.MOV', + mime: 'application/octet-stream', + size: 1, + ).kind, + SharedFileKind.video, + ); + expect(source(mime: 'application/pdf').kind, SharedFileKind.file); + expect(source(mime: 'image/svg+xml').kind, SharedFileKind.file); + expect( + source(mime: 'IMAGE/PNG; charset=binary').kind, + SharedFileKind.photo, + ); + expect( + const SharedFile( + path: '/synthetic/jpeg', + name: 'jpeg', + mime: '', + size: 1, + ).kind, + SharedFileKind.file, + ); + }, + ); + + testWidgets( + 'an incoming local photo prepares and renders a retained thumbnail', + (tester) async { + final payload = SharedPayload.fromMap({ + 'files': [ + { + 'path': photo.path, + 'name': 'synthetic-photo.png', + 'mime': 'application/octet-stream', + 'size': photo.lengthSync(), + }, + ], + })!; + final prepared = await tester.runAsync( + () => PreparedShare.prepare(payload), + ); + final file = prepared!.files.single; + expect(file.kind, SharedFileKind.photo); + expect(file.width, 320); + expect(file.height, 160); + expect(photo.existsSync(), isTrue); + final data = base64Decode(file.thumbDataUri!.split(',').last); + final thumb = img.decodeImage(data)!; + expect((thumb.width, thumb.height), (128, 64)); + + await _pumpComposer(tester, prepared); + expect(_hasRenderedImage(tester), isTrue); + expect(find.byIcon(Symbols.description), findsNothing); + + await tester.pumpWidget(const SizedBox.shrink()); + PaintingBinding.instance.imageCache.clear(); + PaintingBinding.instance.imageCache.clearLiveImages(); + photo.deleteSync(); + await _pumpComposer(tester, prepared); + expect(_hasRenderedImage(tester), isTrue); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('composer uses the local image when no thumbnail is supplied', ( + tester, + ) async { + await _pumpComposer( + tester, + PreparedShare(files: [PreparedShareFile(source: source())]), + ); + expect(_hasRenderedImage(tester), isTrue); + expect(photo.existsSync(), isTrue); + expect(find.byIcon(Symbols.description), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'outgoing photo keeps its embedded preview if the local file is gone', + (tester) async { + final preview = await tester.runAsync( + () => sharedThumbnailDataUri(source()), + ); + final attachment = PhotoAttachment( + localPath: photo.path, + previewData: preview, + width: 320, + height: 160, + ); + photo.deleteSync(); + await _pumpWithImages( + tester, + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('ru'), + home: Scaffold( + body: Builder( + builder: (context) => Center( + child: PhotoBubble( + media: [attachment], + ctx: BubbleContext( + context: context, + cs: Theme.of(context).colorScheme, + text: Colors.black, + shape: BubbleShape.singleMiddle, + contentType: MessageType.attachment, + hasPhotoWithCaption: false, + hasMultiplePhotosNoCaption: false, + message: CachedMessage( + id: 'synthetic-photo-message', + accountId: 101, + chatId: 202, + senderId: 101, + time: 123456, + attachments: [attachment], + ), + isMe: true, + myId: 101, + chatType: 'DIALOG', + ), + ), + ), + ), + ), + ), + ); + expect(_hasRenderedImage(tester), isTrue); + expect(find.byIcon(Symbols.image), findsNothing); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('a malformed image leaves thumbnail preparation recoverable', ( + tester, + ) async { + photo.writeAsBytesSync([1, 2, 3, 4]); + final thumbnail = await tester.runAsync( + () => sharedThumbnailDataUri(source()), + ); + expect(thumbnail, isNull); + expect(photo.existsSync(), isTrue); + }); +} diff --git a/test/slow_login_hint_test.dart b/test/slow_login_hint_test.dart new file mode 100644 index 00000000..5d204f35 --- /dev/null +++ b/test/slow_login_hint_test.dart @@ -0,0 +1,36 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/frontend/screens/auth/slow_login_hint.dart'; +import 'package:komet/l10n/app_localizations.dart'; + +Widget _host(bool active) => MaterialApp( + locale: const Locale('ru'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SlowLoginHint(active: active, idle: const Text('synthetic idle')), + ), +); + +void main() { + testWidgets('подсказка появляется только через 2 секунды ожидания', ( + tester, + ) async { + await tester.pumpWidget(_host(false)); + expect(find.text('synthetic idle'), findsOneWidget); + + await tester.pumpWidget(_host(true)); + await tester.pump(const Duration(milliseconds: 1500)); + expect(find.textContaining('дольше обычного'), findsNothing); + + await tester.pump(const Duration(milliseconds: 600)); + await tester.pumpAndSettle(); + expect(find.textContaining('дольше обычного'), findsOneWidget); + expect(find.text('synthetic idle'), findsNothing); + + await tester.pumpWidget(_host(false)); + await tester.pumpAndSettle(); + expect(find.text('synthetic idle'), findsOneWidget); + expect(find.textContaining('дольше обычного'), findsNothing); + }); +} diff --git a/test/webapp_bridge_test.dart b/test/webapp_bridge_test.dart index 8a32ee35..140cbae3 100644 --- a/test/webapp_bridge_test.dart +++ b/test/webapp_bridge_test.dart @@ -43,10 +43,13 @@ class _FakeBiometry implements WebAppBiometry { } } +const _syntheticDeviceId = 'synthetic-device-id'; + void main() { TestWidgetsFlutterBinding.ensureInitialized(); late List<(String, Map, bool)> sent; late int closeCalls; + late int restartCalls; WebAppBridge buildBridge({ bool privateChannel = false, @@ -60,7 +63,9 @@ void main() { contextResolver: () => null, viewportResolver: () => const Size(420, 800), onClose: () => closeCalls++, + onRestart: () => restartCalls++, biometry: biometry, + deviceIdResolver: () => _syntheticDeviceId, emitter: (method, payload, private) => sent.add(( method, jsonDecode(payload) as Map, @@ -72,6 +77,7 @@ void main() { setUp(() { sent = []; closeCalls = 0; + restartCalls = 0; }); test('reports the launch context it was created with', () async { @@ -323,7 +329,7 @@ void main() { 'accessRequested': false, 'accessGranted': false, 'tokenSaved': false, - 'deviceId': null, + 'deviceId': _syntheticDeviceId, }); expect(biometry.consentReasons, isEmpty); expect(biometry.authReasons, isEmpty); @@ -358,6 +364,7 @@ void main() { expect(sent.first.$2['available'], isFalse); expect(sent.first.$2['type'], ['unknown']); + expect(sent.first.$2['deviceId'], _syntheticDeviceId); expect(sent.skip(1).map((event) => event.$2), [ errorOf('biometry_request_access', 'not_supported', 'synthetic-off'), errorOf('biometry_request_auth', 'not_supported', 'synthetic-off'), @@ -395,7 +402,7 @@ void main() { )); }); - test('remembers a refusal and keeps the device id private', () async { + test('remembers a refusal and still identifies the device', () async { biometry.consent = false; final bridge = buildBridge(biometry: biometry); @@ -412,7 +419,7 @@ void main() { expect(sent.first.$2['accessRequested'], isTrue); expect(sent.first.$2['accessGranted'], isFalse); - expect(sent.first.$2['deviceId'], isNull); + expect(sent.first.$2['deviceId'], _syntheticDeviceId); expect( sent.last.$2, errorOf('biometry_request_auth', 'permission_denied', 'synthetic-auth'), @@ -461,7 +468,7 @@ void main() { expect( sent.first.$2, - errorOf('biometry_request_auth', 'auth_failed', 'synthetic-denied'), + errorOf('biometry_request_auth', 'access_denied', 'synthetic-denied'), ); expect(sent.last.$2, { 'requestId': 'synthetic-passed', @@ -484,7 +491,7 @@ void main() { expect( sent.single.$2, - errorOf('biometry_request_auth', 'not_found', 'synthetic-auth'), + errorOf('biometry_request_auth', 'token_not_found', 'synthetic-auth'), ); expect(secureValues, isEmpty); expect(biometry.authReasons, isEmpty); @@ -511,7 +518,11 @@ void main() { expect( sent.first.$2, - errorOf('biometry_update_token', 'auth_failed', 'synthetic-denied'), + errorOf( + 'biometry_update_token', + 'permission_denied', + 'synthetic-denied', + ), ); expect(sent.last.$2, { 'requestId': 'synthetic-passed', @@ -585,7 +596,7 @@ void main() { '{"requestId":"synthetic-kept"}', false, ); - expect(closeCalls, 0); + expect(restartCalls, 0); biometry.consent = true; await bridge.handleEvent( @@ -598,7 +609,8 @@ void main() { {'requestId': 'synthetic-kept', 'status': 'opened'}, {'requestId': 'synthetic-changed', 'status': 'opened'}, ]); - expect(closeCalls, 1); + expect(restartCalls, 1); + expect(closeCalls, 0); expect(await AppDatabase.getWebAppBiometryAccess(accountId, botId), ( true, true, From a16ccdf38316de67049628871d0d6abca28503f2 Mon Sep 17 00:00:00 2001 From: Jganenokk Date: Sun, 11 Oct 2026 21:15:20 +0700 Subject: [PATCH 04/63] =?UTF-8?q?fix/refactor/feature:=20=D1=84=D0=B8?= =?UTF-8?q?=D0=BA=D1=81=D1=8B=20=D1=81=20@teamkometchat,=20=D0=BD=D0=B0?= =?UTF-8?q?=D1=81=D1=82=D1=80=D0=BE=D0=B9=D0=BA=D0=B8=20=D1=87=D0=B0=D1=82?= =?UTF-8?q?=D0=B0,=20=D0=B2=D0=B8=D0=B7=D1=83=D0=B0=D0=BB=D1=8C=D0=BD?= =?UTF-8?q?=D1=8B=D0=B5=20=D0=B8=20=D0=B2=D0=BD=D1=83=D1=82=D1=80=D0=B5?= =?UTF-8?q?=D0=BD=D0=BD=D0=B8=D0=B5=20=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/backend/modules/calls.dart | 120 +++++----- lib/backend/modules/chats.dart | 43 +++- lib/backend/modules/file_uploader.dart | 52 ++++- lib/backend/modules/messages.dart | 9 +- lib/backend/modules/share_sender.dart | 4 + lib/backend/modules/upload_service.dart | 103 +++++++-- lib/core/cache/message_session_cache.dart | 12 + lib/core/cache/official_options.dart | 46 ++++ lib/core/calls/call_session.dart | 14 +- lib/core/config/komet_settings.dart | 35 +++ lib/core/media/auto_download_gate.dart | 18 ++ lib/core/media/gallery_source.dart | 181 +++++++++++++-- lib/core/media/voice_audio_controller.dart | 37 +++ lib/core/protocol/opcode_map.dart | 2 + lib/core/security/app_lock.dart | 12 +- lib/core/storage/ghost_read_store.dart | 65 ++++++ lib/core/storage/per_chat_json_store.dart | 56 ++++- .../calls/call_participants_sheet.dart | 15 +- lib/frontend/screens/calls/call_screen.dart | 41 +++- lib/frontend/screens/calls/calls_tab.dart | 19 +- .../chat/chat_media_send_controller.dart | 6 + .../screens/chats/chat/view/chat_header.dart | 17 +- .../chats/chat/view/composer_area.dart | 3 + .../chats/chat/view/composer_input.dart | 49 +++- .../chats/chat_admin/chat_admin_widgets.dart | 8 +- .../screens/chats/chat_info_screen.dart | 13 +- .../screens/chats/chat_list_screen.dart | 36 ++- lib/frontend/screens/chats/chat_screen.dart | 29 ++- lib/frontend/screens/chats/e2ee_screen.dart | 45 ++++ lib/frontend/screens/chats/search_screen.dart | 11 +- .../screens/contacts/contacts_tab.dart | 9 +- .../screens/profile/chat_settings_screen.dart | 108 +++++++++ .../profile/komet_settings_screen.dart | 13 +- .../screens/profile/settings_tab.dart | 14 ++ .../screens/stories/story_viewer_screen.dart | 9 +- .../widgets/attachment/attachment_sheet.dart | 216 ++++++++++++++---- .../attachment/bubbles/bubble_context.dart | 3 + .../attachment/bubbles/file_bubble.dart | 1 + .../attachment/bubbles/forwarded_bubble.dart | 9 +- .../attachment/bubbles/photo_bubble.dart | 167 ++++++++++---- .../attachment/bubbles/video_bubble.dart | 89 ++++++-- .../attachment/bubbles/video_note_bubble.dart | 7 +- .../attachment/bubbles/voice_bubble.dart | 3 + .../attachment/contact_picker_page.dart | 8 +- lib/frontend/widgets/chat_wallpaper_view.dart | 20 +- lib/frontend/widgets/message_bubble.dart | 82 +++++-- lib/frontend/widgets/official_name.dart | 70 ++++++ lib/frontend/widgets/sender_badge.dart | 47 ++++ .../widgets/upload_progress_ring.dart | 45 ++-- lib/frontend/widgets/verified_mark.dart | 21 ++ lib/l10n/app_en.arb | 18 ++ lib/l10n/app_localizations.dart | 108 +++++++++ lib/l10n/app_localizations_en.dart | 55 +++++ lib/l10n/app_localizations_ru.dart | 55 +++++ lib/l10n/app_ru.arb | 18 ++ lib/main.dart | 6 +- lib/models/contact_info.dart | 1 + test/gallery_filter_test.dart | 8 +- 58 files changed, 1946 insertions(+), 365 deletions(-) create mode 100644 lib/core/cache/official_options.dart create mode 100644 lib/core/media/auto_download_gate.dart create mode 100644 lib/core/storage/ghost_read_store.dart create mode 100644 lib/frontend/screens/profile/chat_settings_screen.dart create mode 100644 lib/frontend/widgets/official_name.dart create mode 100644 lib/frontend/widgets/sender_badge.dart create mode 100644 lib/frontend/widgets/verified_mark.dart diff --git a/lib/backend/modules/calls.dart b/lib/backend/modules/calls.dart index 0653217b..1d6a0887 100644 --- a/lib/backend/modules/calls.dart +++ b/lib/backend/modules/calls.dart @@ -78,8 +78,9 @@ class CallLogEntry { final int count; final bool isGroup; final bool isBot; + final List ids; - const CallLogEntry({ + CallLogEntry({ required this.id, required this.accountId, required this.peerId, @@ -90,11 +91,12 @@ class CallLogEntry { this.count = 1, this.isGroup = false, this.isBot = false, - }); + List? ids, + }) : ids = ids ?? [id]; bool get canCallBack => !isGroup && !isBot; - CallLogEntry withCount(int count) => CallLogEntry( + CallLogEntry mergedWith(CallLogEntry other) => CallLogEntry( id: id, accountId: accountId, peerId: peerId, @@ -102,9 +104,10 @@ class CallLogEntry { avatarUrl: avatarUrl, status: status, time: time, - count: count, + count: count + 1, isGroup: isGroup, isBot: isBot, + ids: [...ids, ...other.ids], ); } @@ -313,11 +316,15 @@ class CallsModule { int accountId, int currentUserId, ) async { - final payload = await _api.sendRequestMap(Opcode.videoChatHistory, {}); + final payload = await _api.sendRequestMap(Opcode.callHistorySync, { + 'callHistorySync': 0, + }); if (payload == null) return []; - return parseHistoryPayload( - payload, + final items = payload['callHistoryItems']; + if (items is! List) return []; + return _entriesFromItems( + items.whereType().toList(), accountId, currentUserId, resolver: resolveContacts, @@ -356,66 +363,41 @@ class CallsModule { } // #***! разбор истории, запись это сообщение с вложением CALL - static Future> parseHistoryPayload( - Map payload, + Future> _entriesFromItems( + List items, int accountId, int currentUserId, { Future>> Function(List ids)? resolver, }) async { - final history = payload['history']; - if (history is! List || history.isEmpty) return []; final recentContacts = await ContactsModule.getContacts(accountId); final contactsMap = {for (final c in recentContacts) c.id: c}; - final parsed = <({int peerId, CallStatus status, int time, String id})>[]; - for (final item in history.whereType()) { - final msg = item['message']; - if (msg is! Map) continue; - final attaches = msg['attaches']; - if (attaches is! List || attaches.isEmpty) continue; - final callAttach = attaches.firstWhere( - (a) => a is Map && a['_type'] == 'CALL', - orElse: () => null, - ); - if (callAttach == null) continue; // #***! у исходящего собеседник в contactIds, у входящего отправитель - final senderId = (msg['sender'] as int?) ?? 0; - final isOutgoing = senderId == currentUserId; - - int peerId = 0; - if (isOutgoing) { - final contactIds = callAttach['contactIds']; - if (contactIds is List && contactIds.isNotEmpty) { - peerId = (contactIds.first as int?) ?? 0; - } - } else { - peerId = senderId; - } - - parsed.add(( - peerId: peerId, - status: _parseCallStatus(callAttach, isOutgoing), - time: (msg['time'] as int?) ?? 0, - id: - msg['id']?.toString() ?? - DateTime.now().millisecondsSinceEpoch.toString(), - )); + int peerOf(Map item) { + final isOutgoing = item['callerId'] == currentUserId; + return isOutgoing + ? ((item['chatId'] as int?) ?? 0) ^ currentUserId + : (item['callerId'] as int?) ?? 0; } // #***! на сервер идём только за теми кого нет локально + bool isGroupItem(Map item) => + ((item['chatId'] as int?) ?? 0) < 0 || item['callName'] != null; + bool localResolved(int id) { final c = contactsMap[id]; return c != null && c.firstName.isNotEmpty; } - final unresolvedIds = parsed - .map((e) => e.peerId) + final unresolvedIds = items + .where((item) => !isGroupItem(item)) + .map(peerOf) .where((id) => id != 0 && !localResolved(id)) .toSet() .toList(); @@ -425,44 +407,48 @@ class CallsModule { fetched = await resolver(unresolvedIds); } - final List extractedCalls = []; - for (final e in parsed) { - final contact = contactsMap[e.peerId]; - final info = fetched[e.peerId]; + final entries = []; + for (final item in items) { + final historyId = item['historyId']; + if (historyId == null) continue; + final isOutgoing = item['callerId'] == currentUserId; + final isGroup = isGroupItem(item); + final peerId = isGroup ? 0 : peerOf(item); + final contact = contactsMap[peerId]; + final info = fetched[peerId]; + String name; String? avatarUrl; - bool isGroup = false; - if (contact != null && contact.firstName.isNotEmpty) { + if (isGroup) { + name = (item['callName'] as String?) ?? 'Групповой звонок'; + } else if (contact != null && contact.firstName.isNotEmpty) { name = '${contact.firstName} ${contact.lastName ?? ''}'.trim(); avatarUrl = contact.baseUrl; } else { - final resolved = _nameFromInfo(info); - if (resolved != null) { - name = resolved; - avatarUrl = (info?['baseUrl'] as String?) ?? contact?.baseUrl; - } else { // #***! имя не нашлось, значит групповой - name = 'Групповой звонок'; - isGroup = true; - } + name = _nameFromInfo(info) ?? '$peerId'; + avatarUrl = (info?['baseUrl'] as String?) ?? contact?.baseUrl; } - extractedCalls.add( + final duration = ((item['durationMs'] as int?) ?? 0) ~/ 1000; + entries.add( CallLogEntry( - id: e.id, + id: historyId.toString(), accountId: accountId, - peerId: e.peerId, + peerId: peerId, name: name, avatarUrl: avatarUrl, - status: e.status, - time: e.time, + status: _parseCallStatus({ + 'hangupType': item['hangupType'], + 'duration': duration, + }, isOutgoing), + time: (item['time'] as int?) ?? 0, isGroup: isGroup, - isBot: !isGroup && _isHistoryPeerBot(e.peerId, contact, info), + isBot: !isGroup && _isHistoryPeerBot(peerId, contact, info), ), ); } - - return extractedCalls; + return entries; } static bool _isHistoryPeerBot( diff --git a/lib/backend/modules/chats.dart b/lib/backend/modules/chats.dart index bf30504c..8d75a8c4 100644 --- a/lib/backend/modules/chats.dart +++ b/lib/backend/modules/chats.dart @@ -15,6 +15,7 @@ import '../../core/media/deleted_media_keeper.dart'; import '../../core/storage/app_database.dart'; import '../../core/storage/chat_activity_store.dart'; import '../../core/storage/chat_members_store.dart'; +import '../../core/storage/ghost_read_store.dart'; import '../../core/storage/token_storage.dart'; import '../../core/utils/logger.dart'; import '../../core/utils/text_format.dart'; @@ -570,8 +571,12 @@ class ChatsModule { final row = Map.from(rows.first); if ((row['unread_count'] as int? ?? 0) == 0) return; + final ghost = KometSettings.ghostMode.value; + if (ghost) { + await _rememberGhostRead(accountId, chatId, rows.first, mark); + } final msgIdNum = int.tryParse(messageId); - if (msgIdNum != null && !KometSettings.antiRead.value) { + if (msgIdNum != null && !KometSettings.antiRead.value && !ghost) { try { await api.sendRequest(Opcode.chatMark, { 'type': 'READ_MESSAGE', @@ -602,8 +607,9 @@ class ChatsModule { int mark, { required int remaining, }) async { + final ghost = KometSettings.ghostMode.value; final msgIdNum = int.tryParse(messageId); - if (msgIdNum != null && !KometSettings.antiRead.value) { + if (msgIdNum != null && !KometSettings.antiRead.value && !ghost) { try { await api.sendRequest(Opcode.chatMark, { 'type': 'READ_MESSAGE', @@ -616,6 +622,9 @@ class ChatsModule { final rows = await AppDatabase.loadChat(accountId, chatId); if (rows.isEmpty) return; + if (ghost) { + await _rememberGhostRead(accountId, chatId, rows.first, mark); + } final cached = CachedChat.fromDbRow(rows.first); final next = remaining < 0 ? 0 : remaining; final currentMark = cached.participants[accountId] ?? 0; @@ -901,6 +910,36 @@ class ChatsModule { ChatInfoFetch.invalidate(chatId); unawaited(ChatInfoFetch.get(chatId)); } + Future _rememberGhostRead( + int accountId, + int chatId, + Map row, + int mark, + ) { + final cached = CachedChat.fromDbRow(row); + return GhostReadStore.instance.remember( + accountId, + chatId, + mark: mark, + unread: cached.unreadCount, + ownMark: cached.participants[accountId] ?? 0, + ); + } + Future restoreGhostReads() async { + final entries = GhostReadStore.instance.snapshot(); + for (final entry in entries) { + final read = entry.read; + await _updateChat(entry.accountId, entry.chatId, (chat) { + final participants = Map.from(chat.participants) + ..[entry.accountId] = read.ownMark; + return chat.copyWith( + unreadCount: read.unread, + participants: participants, + ); + }); + } + await GhostReadStore.instance.clearAll(); + } // #***! шаблон прочитать поменять сохранить оповестить Future _updateChat( diff --git a/lib/backend/modules/file_uploader.dart b/lib/backend/modules/file_uploader.dart index 44e90418..bb4edd76 100644 --- a/lib/backend/modules/file_uploader.dart +++ b/lib/backend/modules/file_uploader.dart @@ -193,6 +193,7 @@ class FileUploader { Uri uri, File file, { void Function(int sent, int total)? onProgress, + Future? cancel, Duration overallTimeout = const Duration(minutes: 5), Duration progressThrottle = const Duration(milliseconds: 16), }) async { @@ -208,6 +209,7 @@ class FileUploader { connection: 'close', ), onProgress: onProgress, + cancel: cancel, ); if (result.error != null) { logger.w('uploadMediaFile: ${result.error}'); @@ -262,6 +264,7 @@ class FileUploader { File file, { String filename = 'photo.jpg', void Function(int sent, int total)? onProgress, + Future? cancel, Duration progressThrottle = const Duration(milliseconds: 16), }) async { final session = api.session; @@ -274,6 +277,7 @@ class FileUploader { filename: filename, ), onProgress: onProgress, + cancel: cancel, ); if (result.error != null || result.status != 200) { logger.w('uploadPhoto: status=${result.status} error=${result.error}'); @@ -291,6 +295,7 @@ class FileUploader { Uri uri, File file, { void Function(int sent, int total)? onProgress, + Future? cancel, int chunkSize = 2 * 1024 * 1024, int concurrency = 4, Duration overallTimeout = const Duration(minutes: 30), @@ -306,10 +311,13 @@ class FileUploader { concurrency: concurrency, ), onProgress: onProgress, + cancel: cancel, ); if (result.error != null || result.status != 200) { + final respBody = utf8.decode(result.body, allowMalformed: true); logger.w( - 'uploadVideoFile: status=${result.status} error=${result.error}', + 'uploadVideoFile: status=${result.status} error=${result.error} ' + 'body=${respBody.length > 500 ? respBody.substring(0, 500) : respBody}', ); } return result.error == null && result.status == 200; @@ -400,21 +408,41 @@ class FileUploader { Future<({int status, Uint8List body, String? error})> _consume( Stream stream, { void Function(int sent, int total)? onProgress, + Future? cancel, }) async { var status = 0; var body = Uint8List(0); String? error; - await for (final event in stream) { - switch (event) { - case kb.UploadEvent_Progress(:final sent, :final total): - onProgress?.call(sent.toInt(), total.toInt()); - case kb.UploadEvent_Done(status: final s, body: final b): - status = s; - body = b; - case kb.UploadEvent_Error(:final message): - error = message; - } - } + final done = Completer(); + final sub = stream.listen( + (event) { + switch (event) { + case kb.UploadEvent_Progress(:final sent, :final total): + onProgress?.call(sent.toInt(), total.toInt()); + case kb.UploadEvent_Done(status: final s, body: final b): + status = s; + body = b; + case kb.UploadEvent_Error(:final message): + error = message; + } + }, + onError: (Object err) { + error = err.toString(); + if (!done.isCompleted) done.complete(); + }, + onDone: () { + if (!done.isCompleted) done.complete(); + }, + cancelOnError: true, + ); + cancel?.then((_) { + if (done.isCompleted) return; + error = 'cancelled'; + sub.cancel(); + done.complete(); + }); + await done.future; + await sub.cancel(); return (status: status, body: body, error: error); } diff --git a/lib/backend/modules/messages.dart b/lib/backend/modules/messages.dart index 199252f3..9551ea30 100644 --- a/lib/backend/modules/messages.dart +++ b/lib/backend/modules/messages.dart @@ -19,6 +19,8 @@ import 'message_copy.dart'; // #***! быстрый кэш id -> имя аватарка телефон, из него подписи в пузырях class ContactCache { + static final ValueNotifier officialRevision = ValueNotifier(0); + static final Map _nameCache = {}; static final Map _avatarCache = {}; static final Map> _optionsCache = {}; @@ -64,8 +66,13 @@ class ContactCache { } } - static void putOptions(int id, Set opts) { + static void putOptions(int id, Set opts, {bool notify = true}) { + final before = _optionsCache[id]; _optionsCache[id] = opts; + final changed = + before == null || + before.contains('OFFICIAL') != opts.contains('OFFICIAL'); + if (notify && changed) officialRevision.value++; _scheduleSave(); } diff --git a/lib/backend/modules/share_sender.dart b/lib/backend/modules/share_sender.dart index f40ffdef..168d9941 100644 --- a/lib/backend/modules/share_sender.dart +++ b/lib/backend/modules/share_sender.dart @@ -142,6 +142,10 @@ class ShareSender { static void _onUploadEvent(UploadJobEvent event) { final entry = _tracked.remove(event.tempId); if (entry == null) return; + if (event is UploadJobCancelled) { + unawaited(chats.reconcileLastMessage(entry.accountId, entry.chatId)); + return; + } final status = event is UploadJobDone ? 'sent' : 'error'; final messageId = event is UploadJobDone ? (event.message?.id ?? event.tempId) diff --git a/lib/backend/modules/upload_service.dart b/lib/backend/modules/upload_service.dart index eaf1656a..22de027c 100644 --- a/lib/backend/modules/upload_service.dart +++ b/lib/backend/modules/upload_service.dart @@ -63,6 +63,14 @@ class UploadJobFailed extends UploadJobEvent { } // #***! ошибка загрузки с кодом причины +class UploadJobCancelled extends UploadJobEvent { + const UploadJobCancelled({ + required super.chatId, + required super.tempId, + required super.kind, + required super.scheduled, + }); +} class UploadFailure implements Exception { const UploadFailure(this.message); @@ -72,6 +80,13 @@ class UploadFailure implements Exception { String toString() => 'UploadFailure($message)'; } +class UploadCancelled implements Exception { + const UploadCancelled(); + + @override + String toString() => 'UploadCancelled'; +} + class UploadBytes { const UploadBytes(this.sent, this.total); @@ -119,11 +134,17 @@ class UploadJob { final int _slots; final List _sent; final List _total; + final Completer _cancelSignal = Completer(); bool get scheduled => scheduledTime != null; int get slots => _slots; + bool get isCancelled => _cancelSignal.isCompleted; + Future get cancelled => _cancelSignal.future; // #***! прогресс по слоту, дальше считаем общий + void cancel() { + if (!isCancelled) _cancelSignal.complete(); + } void report(int slot, int sent, int total) { if (slot < 0 || slot >= _slots) return; _sent[slot] = sent; @@ -200,6 +221,8 @@ class UploadService { UploadJob? job(String tempId) => _jobs[tempId]; + void cancel(String tempId) => _jobs[tempId]?.cancel(); + ValueListenable>? progressFor(String tempId) => _jobs[tempId]?.progress; @@ -249,6 +272,7 @@ class UploadService { if (tokens.any((token) => token == null)) { throw const UploadFailure('upload_failed'); } + if (job.isCancelled) throw const UploadCancelled(); final sent = await messagesModule.sendPhotoMessage( chatId, tokens.cast(), @@ -290,9 +314,11 @@ class UploadService { Uri.parse(info.url), file, onProgress: (sent, total) => job.report(0, sent, total), + cancel: job.cancelled, ); if (!ok) throw const UploadFailure('upload_failed'); job.markUploaded(); + if (job.isCancelled) throw const UploadCancelled(); final sent = await messagesModule.sendVideoMessage( chatId, info.token, @@ -393,6 +419,7 @@ class UploadService { Uri.parse(info.url), file, onProgress: (sent, total) => job.report(0, sent, total), + cancel: job.cancelled, ); if (!ok) throw const UploadFailure('upload_failed'); job.markUploaded(); @@ -525,6 +552,9 @@ class UploadService { } }, ); + job.cancelled.then((_) { + if (!result.isCompleted) result.completeError(const UploadCancelled()); + }); try { return await result.future; } finally { @@ -548,9 +578,16 @@ class UploadService { CachedMessage? real; String? failure; try { - real = await upload(job); // #***! для отложенного null это нормально, оно уйдёт позже - if (real == null && !job.scheduled) failure = 'send_failed'; + final work = upload(job); + unawaited(work.then((_) {}, onError: (_) {})); + real = await Future.any([ + work, + job.cancelled.then((_) => null), + ]); + if (real == null && !job.scheduled && !job.isCancelled) { + failure = 'send_failed'; + } } catch (e) { failure = e is UploadFailure ? e.message : e.toString(); } @@ -558,6 +595,19 @@ class UploadService { UploadNotificationService.end(job.id); _jobs.remove(job.id); + if (job.isCancelled && real == null) { + _dropCancelled(job); + _events.add( + UploadJobCancelled( + chatId: job.chatId, + tempId: job.id, + kind: job.kind, + scheduled: job.scheduled, + ), + ); + return; + } + if (failure != null) { logger.w('UploadService: ${job.id} — $failure'); if (!job.scheduled) { @@ -620,6 +670,11 @@ class UploadService { } // #***! строку в списке чатов двигаем отсюда, а не с экрана чата: его + void _dropCancelled(UploadJob job) { + if (job.scheduled || job.placeholder == null) return; + MessageSessionCache.removeMessage(job.accountId, job.chatId, job.id); + unawaited(chats.reconcileLastMessage(job.accountId, job.chatId)); + } // могли закрыть сразу после выбора файла, а загрузка живёт дальше void _syncChatPreview( CachedMessage? message, @@ -691,26 +746,36 @@ class UploadService { logger.w('optimize photo: $e'); file = photo.file; } - for (var attempt = 0; attempt < _photoAttempts; attempt++) { - if (attempt > 0) { - await Future.delayed(Duration(seconds: attempt)); - job.resetSlot(index); + try { + if (job.isCancelled) return null; + for (var attempt = 0; attempt < _photoAttempts; attempt++) { + if (attempt > 0) { + await Future.delayed(Duration(seconds: attempt)); + if (job.isCancelled) return null; + job.resetSlot(index); + } + try { + final url = await messagesModule.requestPhotoUploadUrl(); + if (url == null || url.isEmpty) continue; + final token = await fileUploader.uploadPhoto( + Uri.parse(url), + file, + filename: _photoFilename(file), + onProgress: (sent, total) => job.report(index, sent, total), + cancel: job.cancelled, + ); + if (token != null) return token; + } catch (e) { + logger.w('uploadOnePhoto attempt ${attempt + 1}: $e'); + } + if (job.isCancelled) return null; } - try { - final url = await messagesModule.requestPhotoUploadUrl(); - if (url == null || url.isEmpty) continue; - final token = await fileUploader.uploadPhoto( - Uri.parse(url), - file, - filename: _photoFilename(file), - onProgress: (sent, total) => job.report(index, sent, total), - ); - if (token != null) return token; - } catch (e) { - logger.w('uploadOnePhoto attempt ${attempt + 1}: $e'); + return null; + } finally { + if (file.path != photo.file.path) { + unawaited(file.delete().catchError((_) => file)); } } - return null; } // #***! имя файла из пути иначе photo.jpg diff --git a/lib/core/cache/message_session_cache.dart b/lib/core/cache/message_session_cache.dart index f548bbbc..be2836c5 100644 --- a/lib/core/cache/message_session_cache.dart +++ b/lib/core/cache/message_session_cache.dart @@ -63,6 +63,18 @@ class MessageSessionCache { save(accountId, chatId, list, reachedStart: cached.reachedStart); } + static void removeMessage(int accountId, int chatId, String messageId) { + final cached = get(accountId, chatId); + if (cached == null) return; + final list = cached.messages.where((m) => m.id != messageId).toList(); + if (list.length == cached.messages.length) return; + if (list.isEmpty) { + remove(accountId, chatId); + return; + } + save(accountId, chatId, list, reachedStart: cached.reachedStart); + } + static void append(int accountId, int chatId, List added) { final cached = _store[_key(accountId, chatId)]; if (cached == null) return; diff --git a/lib/core/cache/official_options.dart b/lib/core/cache/official_options.dart new file mode 100644 index 00000000..dd119e91 --- /dev/null +++ b/lib/core/cache/official_options.dart @@ -0,0 +1,46 @@ +import 'dart:async'; + +import '../../backend/modules/messages.dart' show ContactCache; +import 'info_cache.dart'; + +class OfficialOptions { + OfficialOptions._(); + + static final Set _pending = {}; + static final Set _requested = {}; + static bool _scheduled = false; + + static void request(int id) { + if (id == 0 || ContactCache.getOptions(id) != null) return; + if (!_requested.add(id)) return; + _pending.add(id); + if (!_scheduled) { + _scheduled = true; + scheduleMicrotask(_flush); + } + } + + static void requestAll(Iterable ids) { + for (final id in ids) { + request(id); + } + } + + static Future _flush() async { + _scheduled = false; + final ids = _pending.toList(); + _pending.clear(); + if (ids.isEmpty) return; + final infos = await ContactInfoFetch.getMany(ids); + _requested.removeWhere((id) => ids.contains(id) && !infos.containsKey(id)); + if (infos.isEmpty) return; + for (final entry in infos.entries) { + ContactCache.putOptions( + entry.key, + entry.value.options.toSet(), + notify: false, + ); + } + ContactCache.officialRevision.value++; + } +} diff --git a/lib/core/calls/call_session.dart b/lib/core/calls/call_session.dart index 7b2ecb84..757fd30a 100644 --- a/lib/core/calls/call_session.dart +++ b/lib/core/calls/call_session.dart @@ -2219,12 +2219,22 @@ class CallSession { } // #***! включение камеры - Future _startCamera() async { + Future switchCamera() async { + if (!_localVideo || _pc == null) return; + final cameras = await CameraDevices.cameras(); + if (cameras.length < 2) return; + final currentId = _cameraStream?.getVideoTracks().firstOrNull?.getSettings()['deviceId']; + final current = cameras.where((c) => c.id == currentId).firstOrNull; + final next = cameras.where((c) => c.id != currentId && c.facing != current?.facing).firstOrNull ?? + cameras.firstWhere((c) => c.id != currentId, orElse: () => cameras.first); + await _startCamera(deviceId: next.id); + } + Future _startCamera({String? deviceId}) async { final pc = _pc; if (pc == null) return; final stream = await navigator.mediaDevices.getUserMedia({ - 'video': CameraDevices.constraints(AppCamera.deviceId), + 'video': CameraDevices.constraints(deviceId ?? AppCamera.deviceId), 'audio': false, }); diff --git a/lib/core/config/komet_settings.dart b/lib/core/config/komet_settings.dart index 5f96f7c8..eba386f5 100644 --- a/lib/core/config/komet_settings.dart +++ b/lib/core/config/komet_settings.dart @@ -16,6 +16,10 @@ class KometSettings { static const _kHideAllChatsFolder = 'komet_hide_all_chats_folder'; static const _kShowHiddenChats = 'komet_show_hidden_chats'; static const _kArchiveOnPull = 'komet_archive_on_pull'; + static const _kAutoDownloadPhoto = 'komet_auto_download_photo'; + static const _kAutoDownloadVideo = 'komet_auto_download_video'; + static const _kAutoDownloadVoice = 'komet_auto_download_voice'; + static const _kAutoDownloadVideoNote = 'komet_auto_download_video_note'; static const _kRecordDebugLogs = 'komet_record_debug_logs'; // #***! каждая настройка это ValueNotifier, юишка подписана напрямую @@ -30,6 +34,10 @@ class KometSettings { static final ValueNotifier hideAllChatsFolder = ValueNotifier(false); static final ValueNotifier showHiddenChats = ValueNotifier(false); static final ValueNotifier archiveOnPull = ValueNotifier(false); + static final ValueNotifier autoDownloadPhoto = ValueNotifier(true); + static final ValueNotifier autoDownloadVideo = ValueNotifier(true); + static final ValueNotifier autoDownloadVoice = ValueNotifier(true); + static final ValueNotifier autoDownloadVideoNote = ValueNotifier(true); static final ValueNotifier recordDebugLogs = ValueNotifier(true); // #***! читаем всё разом на старте @@ -51,6 +59,11 @@ class KometSettings { hideAllChatsFolder.value = prefs.getBool(_kHideAllChatsFolder) ?? false; showHiddenChats.value = prefs.getBool(_kShowHiddenChats) ?? false; archiveOnPull.value = prefs.getBool(_kArchiveOnPull) ?? false; + autoDownloadPhoto.value = prefs.getBool(_kAutoDownloadPhoto) ?? true; + autoDownloadVideo.value = prefs.getBool(_kAutoDownloadVideo) ?? true; + autoDownloadVoice.value = prefs.getBool(_kAutoDownloadVoice) ?? true; + autoDownloadVideoNote.value = + prefs.getBool(_kAutoDownloadVideoNote) ?? true; recordDebugLogs.value = prefs.getBool(_kRecordDebugLogs) ?? true; } @@ -110,6 +123,28 @@ class KometSettings { await prefs.setBool(_kHideAllChatsFolder, value); } + static Future setAutoDownloadPhoto(bool value) => + _setFlag(autoDownloadPhoto, _kAutoDownloadPhoto, value); + + static Future setAutoDownloadVideo(bool value) => + _setFlag(autoDownloadVideo, _kAutoDownloadVideo, value); + + static Future setAutoDownloadVoice(bool value) => + _setFlag(autoDownloadVoice, _kAutoDownloadVoice, value); + + static Future setAutoDownloadVideoNote(bool value) => + _setFlag(autoDownloadVideoNote, _kAutoDownloadVideoNote, value); + + static Future _setFlag( + ValueNotifier notifier, + String key, + bool value, + ) async { + notifier.value = value; + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(key, value); + } + static Future setArchiveOnPull(bool value) async { archiveOnPull.value = value; final prefs = await SharedPreferences.getInstance(); diff --git a/lib/core/media/auto_download_gate.dart b/lib/core/media/auto_download_gate.dart new file mode 100644 index 00000000..02f03541 --- /dev/null +++ b/lib/core/media/auto_download_gate.dart @@ -0,0 +1,18 @@ +import 'package:flutter/foundation.dart'; + +class AutoDownloadGate { + AutoDownloadGate._(); + + static final Map> _loaded = {}; + + static ValueListenable listen(String key) => + _loaded.putIfAbsent(key, () => ValueNotifier(false)); + + static bool allows(bool autoEnabled, String key) => + autoEnabled || (_loaded[key]?.value ?? false); + + static void loadManually(String key) { + final notifier = _loaded.putIfAbsent(key, () => ValueNotifier(false)); + notifier.value = true; + } +} diff --git a/lib/core/media/gallery_source.dart b/lib/core/media/gallery_source.dart index fadceede..f0acba2a 100644 --- a/lib/core/media/gallery_source.dart +++ b/lib/core/media/gallery_source.dart @@ -11,6 +11,19 @@ import 'desktop_video_probe.dart'; enum GalleryPermission { granted, limited, denied } // #***! элемент галереи, за ним системный ассет или просто файл +enum GallerySortField { date, name } + +class GallerySort { + final GallerySortField field; + final bool ascending; + + const GallerySort({required this.field, required this.ascending}); + + static const newestFirst = GallerySort( + field: GallerySortField.date, + ascending: false, + ); +} abstract class GalleryItem { String get id; bool get isVideo; @@ -23,6 +36,7 @@ abstract class GalleryItem { required int maxDimension, required int quality, }); + String get name; static GalleryItem fromFile(File file) => _FileGalleryItem(file); } @@ -46,6 +60,19 @@ class PickedPhoto { } // #***! размеры картинки без полного декодирования +class GalleryAlbum { + final String id; + final String name; + final int count; + final bool isAll; + + const GalleryAlbum({ + required this.id, + required this.name, + required this.count, + required this.isAll, + }); +} Future<(int, int)?> imageFileDimensions(File file) async { ui.ImmutableBuffer? buffer; ui.ImageDescriptor? descriptor; @@ -69,7 +96,7 @@ abstract class GallerySource { static const Duration maxInt32Duration = Duration(milliseconds: 0x7fffffff); // #***! фильтр без ограничений, иначе часть видео пропадает - static FilterOptionGroup mediaFilter() => FilterOptionGroup( + static FilterOptionGroup mediaFilter(GallerySort sort) => FilterOptionGroup( imageOption: const FilterOption( sizeConstraint: SizeConstraint(ignoreSize: true), ), @@ -81,10 +108,18 @@ abstract class GallerySource { ), ), createTimeCond: DateTimeCond.def().copyWith(ignore: true), - orders: const [OrderOption(type: OrderOptionType.createDate, asc: false)], + orders: [ + OrderOption( + type: OrderOptionType.createDate, + asc: sort.field == GallerySortField.date && sort.ascending, + ), + ], ); Future ensurePermission(); + Future> albums(); + void selectAlbum(GalleryAlbum album); + void setSort(GallerySort sort); Future load({int offset, int limit}); Future openSettings(); Future manageAccess(); @@ -107,8 +142,95 @@ class _PhotoManagerSource implements GallerySource { return GalleryPermission.denied; } + List _paths = const []; + String? _albumId; AssetPathEntity? _album; int _total = 0; + GallerySort _sort = GallerySort.newestFirst; + List? _nameOrder; + String? _nameOrderKey; + DateTime _nameOrderAt = DateTime.fromMillisecondsSinceEpoch(0); + static List? _albumsCache; + static DateTime _albumsCachedAt = DateTime.fromMillisecondsSinceEpoch(0); + + Future _fetchPaths() async { + _paths = await PhotoManager.getAssetPathList( + type: RequestType.common, + onlyAll: false, + filterOption: GallerySource.mediaFilter(_sort), + ); + } + + AssetPathEntity? _pathFor(String? id) { + for (final path in _paths) { + if (path.id == id) return path; + } + for (final path in _paths) { + if (path.isAll) return path; + } + return _paths.isEmpty ? null : _paths.first; + } + + @override + Future> albums() async { + final cached = _albumsCache; + if (cached != null && + DateTime.now().difference(_albumsCachedAt) < const Duration(minutes: 1)) { + return cached; + } + await _fetchPaths(); + final result = []; + for (final path in _paths) { + final count = await path.assetCountAsync; + if (count == 0) continue; + result.add( + GalleryAlbum( + id: path.id, + name: path.name, + count: count, + isAll: path.isAll, + ), + ); + } + result.sort((a, b) => (b.isAll ? 1 : 0).compareTo(a.isAll ? 1 : 0)); + _albumsCache = result; + _albumsCachedAt = DateTime.now(); + return result; + } + + @override + void selectAlbum(GalleryAlbum album) { + _albumId = album.id; + _album = null; + _total = 0; + _nameOrder = null; + } + + @override + void setSort(GallerySort sort) { + _sort = sort; + _album = null; + _total = 0; + _nameOrder = null; + } + + Future> _assetsByName(AssetPathEntity album) async { + final key = '${album.id}:${_sort.ascending}'; + final cached = _nameOrder; + if (cached != null && + _nameOrderKey == key && + DateTime.now().difference(_nameOrderAt) < const Duration(minutes: 1)) { + return cached; + } + final assets = await album.getAssetListRange(start: 0, end: _total); + int compare(AssetEntity a, AssetEntity b) => + (a.title ?? '').toLowerCase().compareTo((b.title ?? '').toLowerCase()); + assets.sort(_sort.ascending ? compare : (a, b) => compare(b, a)); + _nameOrder = assets; + _nameOrderKey = key; + _nameOrderAt = DateTime.now(); + return assets; + } @override Future load({ @@ -116,23 +238,24 @@ class _PhotoManagerSource implements GallerySource { int limit = GallerySource.pageSize, }) async { if (offset == 0 || _album == null) { - final paths = await PhotoManager.getAssetPathList( - type: RequestType.common, - onlyAll: true, - filterOption: GallerySource.mediaFilter(), - ); - if (paths.isEmpty) { - _album = null; + await _fetchPaths(); + final album = _pathFor(_albumId); + _album = album; + if (album == null) { _total = 0; return GalleryPage.empty; } - _album = paths.first; - _total = await paths.first.assetCountAsync; + _total = await album.assetCountAsync; } final album = _album; if (album == null || offset >= _total) return GalleryPage.empty; final end = offset + limit < _total ? offset + limit : _total; - final assets = await album.getAssetListRange(start: offset, end: end); + final List assets; + if (_sort.field == GallerySortField.name) { + assets = (await _assetsByName(album)).sublist(offset, end); + } else { + assets = await album.getAssetListRange(start: offset, end: end); + } return GalleryPage( items: assets.map((a) => _AssetGalleryItem(a)).toList(), hasMore: end < _total, @@ -155,6 +278,9 @@ class _AssetGalleryItem implements GalleryItem { @override String get id => asset.id; + @override + String get name => asset.title ?? ''; + @override bool get isVideo => asset.type == AssetType.video; @@ -218,6 +344,8 @@ String _fileExtension(String path) { return path.substring(dot).toLowerCase(); } +String _baseName(String path) => path.split(RegExp(r'[\\/]')).last; + bool isVideoPath(String path) => kGalleryVideoExtensions.contains(_fileExtension(path)); @@ -230,6 +358,22 @@ class _DesktopGallerySource implements GallerySource { Future ensurePermission() async => GalleryPermission.granted; + @override + Future> albums() async => const [ + GalleryAlbum(id: 'desktop', name: '', count: 0, isAll: true), + ]; + + @override + void selectAlbum(GalleryAlbum album) {} + + GallerySort _sort = GallerySort.newestFirst; + + @override + void setSort(GallerySort sort) { + _sort = sort; + _all = const []; + } + List<_FileGalleryItem> _all = const []; @override @@ -268,7 +412,15 @@ class _DesktopGallerySource implements GallerySource { } } catch (_) {} } - entries.sort((a, b) => b.modified.compareTo(a.modified)); + entries.sort((a, b) { + final order = switch (_sort.field) { + GallerySortField.date => a.modified.compareTo(b.modified), + GallerySortField.name => _baseName( + a.file.path, + ).toLowerCase().compareTo(_baseName(b.file.path).toLowerCase()), + }; + return _sort.ascending ? order : -order; + }); return entries.map((e) => _FileGalleryItem(e.file)).toList(); } @@ -314,6 +466,9 @@ class _FileGalleryItem implements GalleryItem { @override String get id => file.path; + @override + String get name => _baseName(file.path); + @override bool get isVideo => isVideoPath(file.path); diff --git a/lib/core/media/voice_audio_controller.dart b/lib/core/media/voice_audio_controller.dart index 5150bfca..5960a30b 100644 --- a/lib/core/media/voice_audio_controller.dart +++ b/lib/core/media/voice_audio_controller.dart @@ -1,3 +1,4 @@ +import 'dart:collection'; import 'dart:async'; import 'dart:io'; @@ -15,6 +16,34 @@ import 'opus_ogg_index.dart'; enum VoiceAudioFailure { none, download, playback } // #***! воспроизведение одного голосового +class _PrefetchSlots { + _PrefetchSlots(this._limit); + + final int _limit; + int _running = 0; + final Queue> _waiting = Queue>(); + + Future acquire() { + if (_running < _limit) { + _running++; + return Future.value(); + } + final waiter = Completer(); + _waiting.add(waiter); + return waiter.future; + } + + void release() { + if (_waiting.isEmpty) { + _running--; + return; + } + _waiting.removeFirst().complete(); + } +} + +final _PrefetchSlots _prefetchSlots = _PrefetchSlots(2); + class VoiceAudioController { VoiceAudioController({ required this.cacheName, @@ -175,6 +204,14 @@ class VoiceAudioController { _disposePlayer(); if (resume) await _startAt(position.value); } + Future prefetch() async { + await _prefetchSlots.acquire(); + try { + await _ensureLoaded(); + } finally { + _prefetchSlots.release(); + } + } // #***! качаем один раз, повторные нажатия ждут ту же загрузку Future _ensureLoaded() async { diff --git a/lib/core/protocol/opcode_map.dart b/lib/core/protocol/opcode_map.dart index 841defea..bc7804e3 100644 --- a/lib/core/protocol/opcode_map.dart +++ b/lib/core/protocol/opcode_map.dart @@ -111,6 +111,7 @@ abstract class Opcode { static const int videoChatStartActive = 78; // Инициация активного звонка static const int videoChatHistory = 79; // История звонков static const int videoChatDeleteHistory = 164; // Удаление записей истории звонков + static const int callHistorySync = 163; // Синхронизация истории звонков static const int videoChatCreateJoinLink = 84; // Ссылка для входа в видеочат static const int videoChatJoinByLink = 166; // Вход в звонок по ссылке static const int videoChatMembers = 195; // Участники видеочата @@ -330,6 +331,7 @@ abstract class Opcode { videoChatStartActive: 'VIDEO_CHAT_START_ACTIVE', videoChatHistory: 'VIDEO_CHAT_HISTORY', videoChatDeleteHistory: 'VIDEO_CHAT_DELETE_HISTORY', + callHistorySync: 'CALL_HISTORY_SYNC', videoChatCreateJoinLink: 'VIDEO_CHAT_CREATE_JOIN_LINK', videoChatJoinByLink: 'VIDEO_CHAT_JOIN_BY_LINK', videoChatMembers: 'VIDEO_CHAT_MEMBERS', diff --git a/lib/core/security/app_lock.dart b/lib/core/security/app_lock.dart index a4e8e7b8..37c277b9 100644 --- a/lib/core/security/app_lock.dart +++ b/lib/core/security/app_lock.dart @@ -231,11 +231,13 @@ class AppLock { Future authenticateBiometric(String reason) async { if (!await biometricAvailable()) return false; try { - return await _auth.authenticate( - localizedReason: reason, - biometricOnly: true, - sensitiveTransaction: false, - ); + return await _auth + .authenticate( + localizedReason: reason, + biometricOnly: true, + sensitiveTransaction: false, + ) + .timeout(const Duration(seconds: 20), onTimeout: () => false); } catch (e) { logger.w('AppLock: биометрия не прошла: $e'); return false; diff --git a/lib/core/storage/ghost_read_store.dart b/lib/core/storage/ghost_read_store.dart new file mode 100644 index 00000000..69bdd1c7 --- /dev/null +++ b/lib/core/storage/ghost_read_store.dart @@ -0,0 +1,65 @@ +import 'per_chat_json_store.dart'; + +class GhostRead { + final int mark; + final int unread; + final int ownMark; + + const GhostRead({required this.mark, required this.unread, required this.ownMark}); +} + +class GhostReadStore extends PerChatJsonStore { + GhostReadStore._() + : super( + prefsKey: 'ghost_reads', + fromJson: _fromJson, + toJson: (value) => { + 'mark': value.mark, + 'unread': value.unread, + 'ownMark': value.ownMark, + }, + ); + + static final GhostReadStore instance = GhostReadStore._(); + + static GhostRead? _fromJson(Object? raw) { + if (raw is! Map) return null; + final mark = raw['mark']; + final unread = raw['unread']; + final ownMark = raw['ownMark']; + if (mark is! int || unread is! int || ownMark is! int) return null; + return GhostRead(mark: mark, unread: unread, ownMark: ownMark); + } + + Future remember( + int accountId, + int chatId, { + required int mark, + required int unread, + required int ownMark, + }) { + final prev = read(accountId, chatId); + return write( + accountId, + chatId, + GhostRead( + mark: mark, + unread: prev?.unread ?? unread, + ownMark: prev?.ownMark ?? ownMark, + ), + ); + } + + List<({int accountId, int chatId, GhostRead read})> snapshot() { + final out = <({int accountId, int chatId, GhostRead read})>[]; + for (final entry in allEntries) { + final parts = entry.key.split('/'); + if (parts.length != 2) continue; + final accountId = int.tryParse(parts[0]); + final chatId = int.tryParse(parts[1]); + if (accountId == null || chatId == null) continue; + out.add((accountId: accountId, chatId: chatId, read: entry.value)); + } + return out; + } +} diff --git a/lib/core/storage/per_chat_json_store.dart b/lib/core/storage/per_chat_json_store.dart index e8ed81b8..aa941abf 100644 --- a/lib/core/storage/per_chat_json_store.dart +++ b/lib/core/storage/per_chat_json_store.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart'; @@ -5,13 +6,23 @@ import 'package:shared_preferences/shared_preferences.dart'; // #***! база для всех настроек на чат, всё одним джейсоном в prefs abstract class PerChatJsonStore { + static final Set> _all = {}; + + static Future flushAll() async { + for (final store in _all) { + await store.flush(); + } + } + PerChatJsonStore({ required String prefsKey, required T? Function(Object? raw) fromJson, required Object? Function(T value) toJson, }) : _prefsKey = prefsKey, _fromJson = fromJson, - _toJson = toJson; + _toJson = toJson { + _all.add(this as PerChatJsonStore); + } final String _prefsKey; final T? Function(Object? raw) _fromJson; @@ -22,6 +33,8 @@ abstract class PerChatJsonStore { final ValueNotifier revision = ValueNotifier(0); bool _loaded = false; Future? _loading; + Timer? _persistTimer; + static const Duration _persistDelay = Duration(milliseconds: 400); String _buildKey(int accountId, int chatId) => '$accountId/$chatId'; @@ -62,6 +75,41 @@ abstract class PerChatJsonStore { if (accountId == 0) return null; return _values[_buildKey(accountId, chatId)]; } + Future clearAll() async { + _persistTimer?.cancel(); + _persistTimer = null; + if (_values.isEmpty) { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_prefsKey); + return; + } + _values.clear(); + revision.value++; + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_prefsKey); + } + + Future flush() async { + if (_persistTimer == null) return; + _persistTimer!.cancel(); + _persistTimer = null; + await _persist(); + } + + void _schedulePersist() { + _persistTimer?.cancel(); + _persistTimer = Timer(_persistDelay, () { + _persistTimer = null; + unawaited(_persist()); + }); + } + + Future _persist() async { + final prefs = await SharedPreferences.getInstance(); + final serializable = {}; + _values.forEach((k, v) => serializable[k] = _toJson(v)); + await prefs.setString(_prefsKey, jsonEncode(serializable)); + } // #***! accountId 0 значит не залогинены, писать некуда @protected @@ -78,10 +126,6 @@ abstract class PerChatJsonStore { _values[key] = value; } revision.value++; - final prefs = await SharedPreferences.getInstance(); - // #***! перезаписываем весь джейсон, записей мало - final serializable = {}; - _values.forEach((k, v) => serializable[k] = _toJson(v)); - await prefs.setString(_prefsKey, jsonEncode(serializable)); + _schedulePersist(); } } diff --git a/lib/frontend/screens/calls/call_participants_sheet.dart b/lib/frontend/screens/calls/call_participants_sheet.dart index 35af86e7..8030e4ab 100644 --- a/lib/frontend/screens/calls/call_participants_sheet.dart +++ b/lib/frontend/screens/calls/call_participants_sheet.dart @@ -12,12 +12,18 @@ import '../../widgets/prompt_dialog.dart'; import '../../widgets/sheet_helpers.dart'; import '../../../core/config/app_fonts.dart'; import '../../../l10n/app_localizations.dart'; +import '../../widgets/official_name.dart'; class CallParticipantView { final String name; final String? avatarUrl; + final int? contactId; - const CallParticipantView({required this.name, this.avatarUrl}); + const CallParticipantView({ + required this.name, + this.avatarUrl, + this.contactId, + }); } typedef CallParticipantResolver = @@ -543,11 +549,10 @@ class _ParticipantsSheetState extends State<_ParticipantsSheet> { return ListTile( leading: KometAvatar(name: view.name, imageUrl: view.avatarUrl, size: 40), - title: Text( - view.name, + title: OfficialName( + contactId: view.contactId ?? 0, + text: view.name, style: TextStyle(color: cs.onSurface, fontSize: 16), - maxLines: 1, - overflow: TextOverflow.ellipsis, ), subtitle: subtitle.isEmpty ? null diff --git a/lib/frontend/screens/calls/call_screen.dart b/lib/frontend/screens/calls/call_screen.dart index 74f68ac0..100e3e2d 100644 --- a/lib/frontend/screens/calls/call_screen.dart +++ b/lib/frontend/screens/calls/call_screen.dart @@ -19,6 +19,7 @@ import '../../../core/config/launch_flags.dart'; import '../../../core/utils/format.dart'; import '../../../core/utils/screen_wake.dart'; import '../../../l10n/app_localizations.dart'; +import '../../widgets/official_name.dart'; import '../../widgets/call_video_view.dart'; import '../../widgets/custom_notification.dart'; import '../../widgets/glossy_pill.dart'; @@ -396,6 +397,23 @@ class _CallScreenState extends State with TickerProviderStateMixin { } } + Future _switchCamera() async { + final session = _session; + if (session == null || _videoBusy) return; + final l10n = AppLocalizations.of(context)!; + setState(() => _videoBusy = true); + try { + await session.switchCamera(); + } catch (e) { + if (mounted) { + showCustomNotification(context, l10n.callCameraUnavailable(e)); + } + } finally { + _syncLocalPreview(); + if (mounted) setState(() => _videoBusy = false); + } + } + Future _toggleScreen() async { final session = _session; if (session == null || _videoBusy) return; @@ -466,6 +484,7 @@ class _CallScreenState extends State with TickerProviderStateMixin { ? info!.name! : l10n.callParticipantFallback, avatarUrl: info?.avatar, + contactId: ext, ); }, ); @@ -614,11 +633,11 @@ class _CallScreenState extends State with TickerProviderStateMixin { padding: const EdgeInsets.symmetric(horizontal: 24), child: Column( children: [ - Text( - _displayName, + OfficialName( + contactId: _session?.peerUserId ?? 0, + text: _displayName, textAlign: TextAlign.center, maxLines: 1, - overflow: TextOverflow.ellipsis, style: TextStyle( color: cs.onSurface, fontSize: 24, @@ -1176,11 +1195,12 @@ class _CallScreenState extends State with TickerProviderStateMixin { Widget _buildName(ColorScheme cs) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 32), - child: Text( - _displayName, + child: OfficialName( + contactId: _session?.peerUserId ?? 0, + text: _displayName, textAlign: TextAlign.center, + iconSize: 18, maxLines: 2, - overflow: TextOverflow.ellipsis, style: TextStyle( color: cs.onSurface, fontSize: 30, @@ -1298,6 +1318,15 @@ class _CallScreenState extends State with TickerProviderStateMixin { busy: _videoBusy, onTap: _toggleVideo, ), + if (video) + CallButton( + icon: Symbols.cameraswitch, + label: l10n.callSwitchCamera, + background: cs.surfaceContainerHighest, + foreground: cs.onSurface, + busy: _videoBusy, + onTap: _switchCamera, + ), CallButton( icon: Symbols.screen_share, label: l10n.callScreenLabel, diff --git a/lib/frontend/screens/calls/calls_tab.dart b/lib/frontend/screens/calls/calls_tab.dart index 4885648b..faa1c384 100644 --- a/lib/frontend/screens/calls/calls_tab.dart +++ b/lib/frontend/screens/calls/calls_tab.dart @@ -11,6 +11,7 @@ import '../../../backend/modules/calls.dart'; import '../../widgets/komet_avatar.dart'; import '../../widgets/connection_status.dart'; import '../../widgets/reload_on_reconnect.dart'; +import '../../../core/utils/logger.dart'; import '../../widgets/custom_notification.dart'; import '../../widgets/chat_menu_overlay.dart'; import '../../widgets/small_spinner.dart'; @@ -90,7 +91,7 @@ class _CallsTabState extends State grouped.last.status == call.status && _isSameDay(grouped.last.time, call.time)) { final last = grouped.removeLast(); - grouped.add(last.withCount(last.count + 1)); + grouped.add(last.mergedWith(call)); } else { grouped.add(call); } @@ -275,10 +276,20 @@ class _CallsTabState extends State void _deleteCall(CallLogEntry call) { if (_removing.contains(call.id)) return; setState(() => _removing.add(call.id)); - final historyId = int.tryParse(call.id); - if (historyId != null) { - unawaited(CallsModule(api).deleteHistory([historyId])); + final historyIds = call.ids.map(int.tryParse).whereType().toList(); + unawaited(_removeOnServer(historyIds)); + } + + Future _removeOnServer(List historyIds) async { + var ok = false; + try { + ok = await CallsModule(api).deleteHistory(historyIds); + } catch (e) { + logger.w('deleteHistory: $e'); } + if (ok || !mounted) return; + showCustomNotification(context, AppLocalizations.of(context)!.callsTabDeleteFailed); + unawaited(_loadHistory()); } void _onRemovalComplete(String id) { diff --git a/lib/frontend/screens/chats/chat/chat_media_send_controller.dart b/lib/frontend/screens/chats/chat/chat_media_send_controller.dart index 6da81a90..e6d5a1b7 100644 --- a/lib/frontend/screens/chats/chat/chat_media_send_controller.dart +++ b/lib/frontend/screens/chats/chat/chat_media_send_controller.dart @@ -897,6 +897,12 @@ class ChatMediaSendController { chatController.setMessageAt(idx, real); bumpMessages(); } + } else if (event is UploadJobCancelled) { + if (event.scheduled) return; + final idx = chatController.indexOfId(event.tempId); + if (idx == -1) return; + chatController.removeMessageAt(idx); + bumpMessages(); } else if (event is UploadJobFailed) { if (event.scheduled) { Haptics.error(); diff --git a/lib/frontend/screens/chats/chat/view/chat_header.dart b/lib/frontend/screens/chats/chat/view/chat_header.dart index 9bcecc58..f5661035 100644 --- a/lib/frontend/screens/chats/chat/view/chat_header.dart +++ b/lib/frontend/screens/chats/chat/view/chat_header.dart @@ -18,6 +18,7 @@ import 'package:komet/main.dart' show storiesModule; import 'package:komet/models/story.dart'; import '../../../../../core/config/app_fonts.dart'; import '../../../../widgets/local_avatar_builder.dart'; +import '../../../../widgets/verified_mark.dart'; class ChatHeaderRow extends StatelessWidget { final bool glossy; @@ -202,13 +203,7 @@ class ChatHeaderRow extends StatelessWidget { ), if (isOfficial) ...[ const SizedBox(width: 4), - Icon( - Symbols.verified, - color: cs.primary, - size: 16, - weight: 600, - fill: 1, - ), + VerifiedMark(color: cs.primary, size: 16), ], ], ), @@ -381,13 +376,7 @@ class ChatHeaderRow extends StatelessWidget { ), if (isOfficial) ...[ const SizedBox(width: 4), - Icon( - Symbols.verified, - color: cs.primary, - size: 16, - weight: 600, - fill: 1, - ), + VerifiedMark(color: cs.primary, size: 16), ], ], ), diff --git a/lib/frontend/screens/chats/chat/view/composer_area.dart b/lib/frontend/screens/chats/chat/view/composer_area.dart index 466558c5..a499bf4d 100644 --- a/lib/frontend/screens/chats/chat/view/composer_area.dart +++ b/lib/frontend/screens/chats/chat/view/composer_area.dart @@ -65,6 +65,7 @@ class ComposerArea extends StatelessWidget { final VoiceRecordController voiceRec; final VideoNoteController note; final VoidCallback onToggleStickerPanel; + final VoidCallback? onOpenMiniApp; final VoidCallback onScheduleMessage; final VoidCallback onOpenAttach; final VoidCallback onOpenAttachScheduled; @@ -142,6 +143,7 @@ class ComposerArea extends StatelessWidget { required this.voiceRec, required this.note, required this.onToggleStickerPanel, + this.onOpenMiniApp, required this.onScheduleMessage, required this.onOpenAttach, required this.onOpenAttachScheduled, @@ -283,6 +285,7 @@ class ComposerArea extends StatelessWidget { voiceRec: voiceRec, note: note, onToggleStickerPanel: onToggleStickerPanel, + onOpenMiniApp: onOpenMiniApp, onSendText: onSendMessage, onScheduleMessage: onScheduleMessage, onOpenAttach: onOpenAttach, diff --git a/lib/frontend/screens/chats/chat/view/composer_input.dart b/lib/frontend/screens/chats/chat/view/composer_input.dart index 89a95176..d48b6951 100644 --- a/lib/frontend/screens/chats/chat/view/composer_input.dart +++ b/lib/frontend/screens/chats/chat/view/composer_input.dart @@ -18,6 +18,7 @@ import 'package:komet/frontend/screens/chats/chat/voice_record_controller.dart'; import 'package:komet/frontend/widgets/composer_morph_icon.dart'; import 'package:komet/frontend/widgets/glossy_pill.dart'; import 'package:komet/frontend/widgets/liquid_glass.dart'; +import 'package:komet/frontend/widgets/sender_badge.dart'; import 'package:komet/frontend/widgets/lottie_slash_icon.dart'; import 'package:komet/frontend/widgets/paste_media_scope.dart'; import 'package:komet/frontend/widgets/reply_preview.dart'; @@ -43,6 +44,7 @@ class ComposerInputBar extends StatelessWidget { required this.voiceRec, required this.note, required this.onToggleStickerPanel, + this.onOpenMiniApp, required this.onSendText, required this.onScheduleMessage, required this.onOpenAttach, @@ -87,6 +89,7 @@ class ComposerInputBar extends StatelessWidget { final VoiceRecordController voiceRec; final VideoNoteController note; final VoidCallback onToggleStickerPanel; + final VoidCallback? onOpenMiniApp; final VoidCallback onSendText; final VoidCallback onScheduleMessage; final VoidCallback onOpenAttach; @@ -167,6 +170,21 @@ class ComposerInputBar extends StatelessWidget { child: Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ + if (onOpenMiniApp != null) ...[ + _actionSurface( + color: cs.primary, + onTap: onOpenMiniApp, + borderSide: BorderSide.none, + child: SizedBox( + width: _controlSize, + height: _controlSize, + child: Center( + child: Icon(Symbols.apps, color: cs.onPrimary, size: 24), + ), + ), + ), + SizedBox(width: _actionGap), + ], Expanded( child: AnimatedContainer( duration: const Duration(milliseconds: 200), @@ -600,6 +618,7 @@ class ComposerInputBar extends StatelessWidget { required Widget child, VoidCallback? onTap, VoidCallback? onLongPress, + BorderSide? borderSide, }) { return TweenAnimationBuilder( tween: ColorTween(end: color), @@ -609,6 +628,7 @@ class ComposerInputBar extends StatelessWidget { color: tinted ?? color, onTap: onTap, onLongPress: onLongPress, + borderSide: borderSide, child: child, ), ); @@ -619,6 +639,7 @@ class ComposerInputBar extends StatelessWidget { required Widget child, VoidCallback? onTap, VoidCallback? onLongPress, + BorderSide? borderSide, }) { if (_flat) { return Material( @@ -634,6 +655,7 @@ class ComposerInputBar extends StatelessWidget { liquid: _liquid, backdropKey: backdropKey, borderRadius: BorderRadius.circular(_controlSize / 2), + borderSide: borderSide, onTap: onTap, onLongPress: onLongPress, keepInkLayer: true, @@ -781,15 +803,24 @@ class ComposerInputBar extends StatelessWidget { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - l10n.composerInputReplyTo(name), - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - color: cs.primary, - fontSize: 13, - fontWeight: FontWeight.w600, - ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Text( + l10n.composerInputReplyTo(name), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: cs.primary, + fontSize: 13, + fontWeight: FontWeight.w600, + ), + ), + ), + if (reply.senderId != myId) + SenderBadge(senderId: reply.senderId, size: 13), + ], ), if (preview.isNotEmpty) _previewLine(cs, visual, preview), ], diff --git a/lib/frontend/screens/chats/chat_admin/chat_admin_widgets.dart b/lib/frontend/screens/chats/chat_admin/chat_admin_widgets.dart index 034234f1..19f35a33 100644 --- a/lib/frontend/screens/chats/chat_admin/chat_admin_widgets.dart +++ b/lib/frontend/screens/chats/chat_admin/chat_admin_widgets.dart @@ -8,6 +8,7 @@ import '../../../../core/utils/format.dart'; import '../../../../l10n/app_localizations.dart'; import '../../../widgets/komet_avatar.dart'; import '../../../widgets/small_spinner.dart'; +import '../../../widgets/official_name.dart'; class AdminScaffold extends StatelessWidget { final String title; @@ -118,10 +119,9 @@ class AdminMemberTile extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - title, - maxLines: 1, - overflow: TextOverflow.ellipsis, + OfficialName( + contactId: id, + text: title, style: TextStyle( color: cs.onSurface, fontSize: 15, diff --git a/lib/frontend/screens/chats/chat_info_screen.dart b/lib/frontend/screens/chats/chat_info_screen.dart index cdcbbffb..cf7ee2e7 100644 --- a/lib/frontend/screens/chats/chat_info_screen.dart +++ b/lib/frontend/screens/chats/chat_info_screen.dart @@ -64,6 +64,8 @@ import 'chat_admin/admin_section.dart'; import 'chat_admin/member_actions.dart'; import 'chat_admin/chat_admin_state.dart'; import 'chat_admin/ownership_transfer.dart'; +import '../../widgets/official_name.dart'; +import '../../widgets/verified_mark.dart'; enum ChatInfoTab { media } @@ -340,6 +342,7 @@ class _ChatInfoScreenState extends State if (contact != null) { _contactData = contact; _isBot = _contactData!.options.contains('BOT'); + ContactCache.putOptions(otherId, contact.options.toSet()); } if (presence != null) { _seenTime = presence['seen'] as int?; @@ -1287,6 +1290,11 @@ class _ChatInfoScreenState extends State ), ), ), + if (_otherId != null && ContactCache.isOfficial(_otherId!)) + Padding( + padding: const EdgeInsets.only(left: 4), + child: VerifiedMark(size: 18, color: cs.primary), + ), SizedBox( width: hasToggle ? 30 : 0, height: 28, @@ -2456,8 +2464,9 @@ class _ChatInfoScreenState extends State child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - name, + OfficialName( + contactId: member.id, + text: name, style: TextStyle( color: cs.onSurface, fontSize: 15, diff --git a/lib/frontend/screens/chats/chat_list_screen.dart b/lib/frontend/screens/chats/chat_list_screen.dart index dacc2a05..bb7739d6 100644 --- a/lib/frontend/screens/chats/chat_list_screen.dart +++ b/lib/frontend/screens/chats/chat_list_screen.dart @@ -74,6 +74,7 @@ import '../../../core/config/app_spectrum_background.dart'; import '../../../core/config/app_nav_pill_style.dart'; import '../../../core/config/app_bottom_navigation_style.dart'; import '../../../core/cache/info_cache.dart'; +import '../../../core/cache/official_options.dart'; import '../../../core/config/app_visual_style.dart'; import '../../../core/config/app_stories.dart'; import '../../../core/config/app_colors.dart'; @@ -119,6 +120,7 @@ import '../../widgets/media_playback_pill.dart'; import '../../../core/config/app_fonts.dart'; import '../lock/lock_glyph.dart'; import '../../../core/security/app_lock.dart'; +import '../../widgets/verified_mark.dart'; const String _savedWelcomeKey = 'welcome.saved.dialog.message'; @@ -1015,6 +1017,7 @@ class _ChatListScreenState extends State } }); chats.chatOrderRevision.addListener(_onChatsChanged); + ContactCache.officialRevision.addListener(_onOfficialRevision); ArchivedChatsStore.instance.revision.addListener(_onArchivedChanged); ChatEncryptionStore.instance.revision.addListener(_onEncryptionChanged); E2eeService.instance.revision.addListener(_onEncryptionChanged); @@ -1201,6 +1204,22 @@ class _ChatListScreenState extends State void _onChatsChanged() { _requestReload(); } + void _prefetchPeerOptions(List items, int myId) { + final peers = []; + for (final chat in items) { + if (chat.type != 'DIALOG') continue; + final peer = chat.participants.keys.firstWhere( + (id) => id != myId, + orElse: () => 0, + ); + if (peer != 0) peers.add(peer); + } + OfficialOptions.requestAll(peers); + } + + void _onOfficialRevision() { + if (mounted) setState(() {}); + } Future _reloadChatsAndFolders() async { final p = await AppDatabase.loadActiveProfile(); @@ -1291,6 +1310,7 @@ class _ChatListScreenState extends State _chats = filteredChats; _chatsWithArchived = visibleChats; _archivedIds = archivedIds; + _prefetchPeerOptions(visibleChats, p.id); _archivedCount = archivedCount; _contactIds = contactIds; _enteringChatIds = entering; @@ -1779,6 +1799,7 @@ class _ChatListScreenState extends State appRouteObserver.unsubscribe(this); _settleTimer?.cancel(); chats.chatOrderRevision.removeListener(_onChatsChanged); + ContactCache.officialRevision.removeListener(_onOfficialRevision); ArchivedChatsStore.instance.revision.removeListener(_onArchivedChanged); ChatEncryptionStore.instance.revision.removeListener(_onEncryptionChanged); E2eeService.instance.revision.removeListener(_onEncryptionChanged); @@ -3677,8 +3698,9 @@ class _ChatListScreenState extends State int.tryParse(id) ?? 0, ) || E2eeService.instance.isOn(_profile?.id ?? 0, int.tryParse(id) ?? 0); - final isVerified = + final e2eeVerified = e2eeInfo?.phase == E2eePhase.established && e2eeInfo!.verified; + final showVerified = isVerified || e2eeVerified; final Widget? statusIcon = (ownStatus != null && draft == null) ? _ownStatusIcon(cs, ownStatus, ownRead) : null; @@ -3864,7 +3886,7 @@ class _ChatListScreenState extends State bottom: -2, child: EncryptionLockBadge( size: 18, - verified: isVerified, + verified: showVerified, ), ), if (isSelected) @@ -3943,15 +3965,9 @@ class _ChatListScreenState extends State overflow: TextOverflow.ellipsis, ), ), - if (isVerified) ...[ + if (showVerified) ...[ const SizedBox(width: 4), - Icon( - Symbols.verified, - color: cs.primary, - size: 16, - weight: 600, - fill: 1, - ), + VerifiedMark(color: cs.primary, size: 16), ], ], ), diff --git a/lib/frontend/screens/chats/chat_screen.dart b/lib/frontend/screens/chats/chat_screen.dart index 6f2be225..526f299a 100644 --- a/lib/frontend/screens/chats/chat_screen.dart +++ b/lib/frontend/screens/chats/chat_screen.dart @@ -294,6 +294,11 @@ class _ChatScreenState extends State ValueListenable>? _photoProgressFor(CachedMessage m) => UploadService.instance.progressFor(m.id); + VoidCallback? _cancelUploadFor(CachedMessage m) => + UploadService.instance.progressFor(m.id) == null + ? null + : () => UploadService.instance.cancel(m.id); + ValueNotifier?> _reactionNotifierFor(CachedMessage m) { final existing = _reactionNotifiers[m.id]; if (existing != null) return existing; @@ -558,6 +563,7 @@ class _ChatScreenState extends State set _myId(int v) => _chatController.myId = v; CachedChat? chat; bool _peerIsBot = false; + bool _peerOfficial = false; bool _peerKindKnown = false; bool _greetingMounted = false; bool _botStartRequested = false; @@ -888,10 +894,18 @@ class _ChatScreenState extends State avatar.isNotEmpty && ContactCache.getAvatar(peerId) != avatar; if (avatarIsNew) ContactCache.putAvatar(peerId, avatar); - if (_peerKindKnown && _peerIsBot == info.isBot && !avatarIsNew) return; + ContactCache.putOptions(peerId, info.options.toSet()); + final official = info.isOfficial; + if (_peerKindKnown && + _peerIsBot == info.isBot && + _peerOfficial == official && + !avatarIsNew) { + return; + } setState(() { _peerKindKnown = true; _peerIsBot = info.isBot; + _peerOfficial = official; }); } @@ -2842,6 +2856,7 @@ class _ChatScreenState extends State voiceRec: _voiceRec, note: _note, onToggleStickerPanel: _toggleStickerPanel, + onOpenMiniApp: _hasMiniApp ? () => unawaited(_openMiniApp()) : null, onScheduleMessage: _scheduleMessage, onOpenAttach: _openAttachmentSheet, onOpenAttachScheduled: _openAttachmentSheetScheduled, @@ -3334,13 +3349,6 @@ class _ChatScreenState extends State context: context, anchorRect: anchorRect, items: [ - if (_hasMiniApp) - ChatMenuItem( - icon: Symbols.apps, - label: l10n.miniAppOpen, - dividerAfter: true, - onTap: () => unawaited(_openMiniApp()), - ), ChatMenuItem( icon: (chat?.isMuted ?? false) ? Symbols.volume_off @@ -4715,7 +4723,9 @@ class _ChatScreenState extends State name: _headerName(), imageUrl: _headerAvatarUrl(), chatType: widget.chatType, - isOfficial: chat?.isOfficial ?? false, + isOfficial: widget.chatType == 'DIALOG' + ? _peerOfficial + : (chat?.isOfficial ?? false), encrypted: _encryptionEnabled, verified: _e2eeVerified, myId: _myId, @@ -4985,6 +4995,7 @@ class _ChatScreenState extends State ), reactionAnimation: _reactionAnimation, uploadProgress: _photoProgressFor(message), + onCancelUpload: _cancelUploadFor(message), onReplyTap: (id) => unawaited( _scrollNav.goTo( id, diff --git a/lib/frontend/screens/chats/e2ee_screen.dart b/lib/frontend/screens/chats/e2ee_screen.dart index 603bc78c..eb819a5e 100644 --- a/lib/frontend/screens/chats/e2ee_screen.dart +++ b/lib/frontend/screens/chats/e2ee_screen.dart @@ -9,6 +9,7 @@ import 'package:share_plus/share_plus.dart'; import '../../../core/config/app_fonts.dart'; import '../../../core/crypto/e2ee_service.dart'; +import '../../../core/storage/chat_encryption_store.dart'; import '../../../l10n/app_localizations.dart'; import '../../widgets/custom_notification.dart'; import '../../widgets/glossy_pill.dart'; @@ -359,11 +360,51 @@ class _E2eeScreenState extends State { } } + Future _disableLegacy() async { + final store = ChatEncryptionStore.instance; + await store.deleteKey(widget.accountId, widget.chatId); + await store.setEnabled(widget.accountId, widget.chatId, false); + if (!mounted) return; + setState(() {}); + showCustomNotification( + context, + AppLocalizations.of(context)!.chatEncryptionDisabled, + ); + } + + Widget _legacyBlock(ColorScheme cs, AppLocalizations l10n) { + return GlossyPill( + color: cs.surfaceContainerHigh, + borderRadius: BorderRadius.circular(20), + padding: const EdgeInsets.all(20), + depth: 6, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + l10n.e2eeLegacyDescription, + style: TextStyle(color: cs.onSurface, fontSize: 15, height: 1.3), + ), + const SizedBox(height: 12), + FilledButton.tonal( + onPressed: _disableLegacy, + child: Text(l10n.e2eeLegacyDisable), + ), + ], + ), + ); + } + + @override @override Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; final l10n = AppLocalizations.of(context)!; final info = _info; + final legacyEnabled = ChatEncryptionStore.instance.isEnabled( + widget.accountId, + widget.chatId, + ); final showFingerprint = _phase == E2eePhase.established || _phase == E2eePhase.keyChanged; return Scaffold( @@ -416,6 +457,10 @@ class _E2eeScreenState extends State { ), ), const SizedBox(height: 16), + if (legacyEnabled) ...[ + _legacyBlock(cs, l10n), + const SizedBox(height: 16), + ], ..._actions(l10n), if (showFingerprint) ...[ const SizedBox(height: 16), diff --git a/lib/frontend/screens/chats/search_screen.dart b/lib/frontend/screens/chats/search_screen.dart index 9aa58186..63171e6b 100644 --- a/lib/frontend/screens/chats/search_screen.dart +++ b/lib/frontend/screens/chats/search_screen.dart @@ -16,6 +16,7 @@ import '../../widgets/small_spinner.dart'; import '../../widgets/swipe_route.dart'; import '../contacts/open_contact_profile.dart'; import 'chat_screen.dart'; +import '../../widgets/official_name.dart'; class SearchScreen extends StatefulWidget { const SearchScreen({super.key}); @@ -305,6 +306,7 @@ class _SearchScreenState extends State { _ResultTile( name: _contactName(row), imageUrl: row['base_url'] as String?, + contactId: row['id'] as int?, subtitle: _contactLabels(row).subtitle, onTap: () => _openContact(row), ), @@ -397,12 +399,14 @@ class _ResultTile extends StatelessWidget { final String? imageUrl; final String? subtitle; final VoidCallback onTap; + final int? contactId; const _ResultTile({ required this.name, required this.onTap, this.imageUrl, this.subtitle, + this.contactId, }); @override @@ -422,12 +426,11 @@ class _ResultTile extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ - Text( - name.isEmpty + OfficialName( + contactId: contactId ?? 0, + text: name.isEmpty ? AppLocalizations.of(context)!.searchScreenUntitled : name, - maxLines: 1, - overflow: TextOverflow.ellipsis, style: TextStyle( color: cs.onSurface, fontSize: 16, diff --git a/lib/frontend/screens/contacts/contacts_tab.dart b/lib/frontend/screens/contacts/contacts_tab.dart index 3c2be909..698fa9f7 100644 --- a/lib/frontend/screens/contacts/contacts_tab.dart +++ b/lib/frontend/screens/contacts/contacts_tab.dart @@ -24,6 +24,7 @@ import 'nfc_exchange_sheet.dart'; import 'open_contact_profile.dart'; import '../../../core/config/app_frost.dart'; import '../../../core/config/app_fonts.dart'; +import '../../widgets/verified_mark.dart'; class ContactsTab extends StatefulWidget { const ContactsTab({super.key, this.bottomPadding = 120}); @@ -284,13 +285,7 @@ class _ContactsTabState extends State with SpectrumSurface { ), if (contact.isVerified) ...[ const SizedBox(width: 4), - Icon( - Symbols.verified, - color: cs.primary, - size: 16, - weight: 600, - fill: 1, - ), + VerifiedMark(color: cs.primary, size: 16), ], ], ), diff --git a/lib/frontend/screens/profile/chat_settings_screen.dart b/lib/frontend/screens/profile/chat_settings_screen.dart new file mode 100644 index 00000000..d7cb085b --- /dev/null +++ b/lib/frontend/screens/profile/chat_settings_screen.dart @@ -0,0 +1,108 @@ +import 'package:flutter/material.dart'; +import 'package:material_symbols_icons/symbols.dart'; + +import '../../../core/config/app_fonts.dart'; +import '../../../core/config/komet_settings.dart'; +import '../../../l10n/app_localizations.dart'; +import '../../widgets/section_header.dart'; +import '../../widgets/settings_card.dart'; + +class ChatSettingsScreen extends StatelessWidget { + const ChatSettingsScreen({super.key}); + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + + return Scaffold( + backgroundColor: cs.surface, + appBar: AppBar( + backgroundColor: cs.surface, + surfaceTintColor: Colors.transparent, + title: Text( + l10n.chatSettingsTitle, + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.w700, + fontFamily: displayFontOf(context), + ), + ), + ), + body: SafeArea( + top: false, + child: ListView( + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.fromLTRB(16, 12, 16, 120), + children: [ + SettingsCard( + children: [ + ValueListenableBuilder( + valueListenable: KometSettings.archiveOnPull, + builder: (context, value, _) => SettingsToggleTile( + icon: Symbols.archive, + label: l10n.chatSettingsArchiveOnPull, + subtitle: l10n.kometSettingsArchiveOnPullSubtitle, + value: value, + onChanged: KometSettings.setArchiveOnPull, + ), + ), + ], + ), + const SizedBox(height: 20), + SectionHeader( + l10n.chatSettingsAutoDownloadTitle, + padding: const EdgeInsets.fromLTRB(8, 0, 8, 8), + fontSize: 14, + ), + SettingsCard( + children: [ + _autoDownload( + KometSettings.autoDownloadPhoto, + KometSettings.setAutoDownloadPhoto, + Symbols.image, + l10n.chatSettingsAutoDownloadPhoto, + ), + _autoDownload( + KometSettings.autoDownloadVideo, + KometSettings.setAutoDownloadVideo, + Symbols.videocam, + l10n.chatSettingsAutoDownloadVideo, + ), + _autoDownload( + KometSettings.autoDownloadVoice, + KometSettings.setAutoDownloadVoice, + Symbols.mic, + l10n.chatSettingsAutoDownloadVoice, + ), + _autoDownload( + KometSettings.autoDownloadVideoNote, + KometSettings.setAutoDownloadVideoNote, + Symbols.radio_button_checked, + l10n.chatSettingsAutoDownloadVideoNote, + ), + ], + ), + ], + ), + ), + ); + } + + Widget _autoDownload( + ValueNotifier notifier, + Future Function(bool value) onChanged, + IconData icon, + String label, + ) { + return ValueListenableBuilder( + valueListenable: notifier, + builder: (context, value, _) => SettingsToggleTile( + icon: icon, + label: label, + value: value, + onChanged: onChanged, + ), + ); + } +} diff --git a/lib/frontend/screens/profile/komet_settings_screen.dart b/lib/frontend/screens/profile/komet_settings_screen.dart index a98f7ff4..7ca2ca39 100644 --- a/lib/frontend/screens/profile/komet_settings_screen.dart +++ b/lib/frontend/screens/profile/komet_settings_screen.dart @@ -4,6 +4,7 @@ import 'package:material_symbols_icons/symbols.dart'; import '../../widgets/connection_status.dart'; import '../../../core/config/build_profile.dart'; +import '../../../backend/modules/chats.dart' show chats; import '../../../core/config/komet_settings.dart'; import '../../../l10n/app_localizations.dart'; import '../../../main.dart'; @@ -129,16 +130,7 @@ class KometSettingsScreen extends StatelessWidget { onChanged: KometSettings.setShowHiddenChats, ), ), - ValueListenableBuilder( - valueListenable: KometSettings.archiveOnPull, - builder: (context, value, _) => SettingsToggleTile( - icon: Symbols.archive, - label: 'Pull-down archive', - subtitle: l10n.kometSettingsArchiveOnPullSubtitle, - value: value, - onChanged: KometSettings.setArchiveOnPull, - ), - ), + ], ), const SizedBox(height: 20), @@ -209,6 +201,7 @@ class KometSettingsScreen extends StatelessWidget { Future _setGhostMode(bool value) async { await KometSettings.setGhostMode(value); + if (!value) await chats.restoreGhostReads(); api.sendPing(interactive: !value); } } diff --git a/lib/frontend/screens/profile/settings_tab.dart b/lib/frontend/screens/profile/settings_tab.dart index e2012d4e..a6bb7e4b 100644 --- a/lib/frontend/screens/profile/settings_tab.dart +++ b/lib/frontend/screens/profile/settings_tab.dart @@ -63,6 +63,7 @@ import 'spoof_screen.dart'; import '../../widgets/media_playback_pill.dart'; import '../../../core/config/app_fonts.dart'; import '../../../core/config/app_shape.dart'; +import 'chat_settings_screen.dart'; class SettingsTab extends StatefulWidget { const SettingsTab({super.key, this.bottomPadding = 120}); @@ -710,6 +711,19 @@ class _SettingsTabState extends State child: _buildSection( context, items: [ + _SettingsItem( + icon: Symbols.chat, + label: l10n.chatSettingsTitle, + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => + const ChatSettingsScreen(), + ), + ); + }, + ), _SettingsItem( icon: Symbols.notifications_active, label: l10n.notificationsTitle, diff --git a/lib/frontend/screens/stories/story_viewer_screen.dart b/lib/frontend/screens/stories/story_viewer_screen.dart index 91fbb578..ae1a34c4 100644 --- a/lib/frontend/screens/stories/story_viewer_screen.dart +++ b/lib/frontend/screens/stories/story_viewer_screen.dart @@ -23,6 +23,7 @@ import 'story_owner_info.dart'; import '../../../core/config/app_frost.dart'; import '../../../core/config/app_fonts.dart'; import '../../../l10n/app_localizations.dart'; +import '../../widgets/official_name.dart'; const Duration _photoDuration = Duration(seconds: 5); @@ -646,10 +647,10 @@ class _StoryViewerScreenState extends State crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ - Text( - info?.name.isNotEmpty == true ? info!.name : '…', - maxLines: 1, - overflow: TextOverflow.ellipsis, + OfficialName( + contactId: preview.owner.ownerId, + text: info?.name.isNotEmpty == true ? info!.name : '…', + iconSize: 15, style: TextStyle( color: Colors.white, fontSize: 15, diff --git a/lib/frontend/widgets/attachment/attachment_sheet.dart b/lib/frontend/widgets/attachment/attachment_sheet.dart index de48c326..0490d623 100644 --- a/lib/frontend/widgets/attachment/attachment_sheet.dart +++ b/lib/frontend/widgets/attachment/attachment_sheet.dart @@ -126,8 +126,12 @@ class _AttachmentSheetState extends State { static List? _cachedItems; static GalleryPermission _cachedPermission = GalleryPermission.granted; static bool _cachedHasMore = false; + static GalleryAlbum? _cachedAlbum; + static GallerySort _cachedSort = GallerySort.newestFirst; final GallerySource _source = GallerySource.create(); + GalleryAlbum? _album; + GallerySort _sort = _cachedSort; final ValueNotifier> _selected = ValueNotifier({}); final Map> _thumbKeys = {}; final Map _edits = {}; @@ -154,6 +158,10 @@ class _AttachmentSheetState extends State { @override void initState() { super.initState(); + _album = _cachedAlbum; + final chosen = _album; + if (chosen != null) _source.selectAlbum(chosen); + _source.setSort(_sort); final cached = _cachedItems; if (cached != null) { _items = cached; @@ -254,6 +262,160 @@ class _AttachmentSheetState extends State { _publishItems([..._items, ...page.items], page.hasMore); } + void _chooseAlbum(GalleryAlbum album) { + if (_album?.id == album.id) return; + _album = album; + _cachedAlbum = album; + _cachedItems = null; + _source.selectAlbum(album); + _loadGallery(); + } + + void _chooseSort(GallerySort sort) { + if (_sort.field == sort.field && _sort.ascending == sort.ascending) return; + _sort = sort; + _cachedSort = sort; + _cachedItems = null; + _source.setSort(sort); + _loadGallery(); + } + + Future _openSortPicker() async { + final l10n = AppLocalizations.of(context)!; + final options = <(GallerySort, String)>[ + ( + const GallerySort(field: GallerySortField.date, ascending: false), + l10n.attachSheetSortNewestFirst, + ), + ( + const GallerySort(field: GallerySortField.date, ascending: true), + l10n.attachSheetSortOldestFirst, + ), + ( + const GallerySort(field: GallerySortField.name, ascending: true), + l10n.attachSheetSortNameAsc, + ), + ( + const GallerySort(field: GallerySortField.name, ascending: false), + l10n.attachSheetSortNameDesc, + ), + ]; + final picked = await showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (sheetContext) => SafeArea( + child: ListView( + shrinkWrap: true, + padding: const EdgeInsets.only(bottom: 12), + children: [ + for (final (sort, label) in options) + ListTile( + leading: Icon( + sort.ascending ? Symbols.arrow_upward : Symbols.arrow_downward, + ), + title: Text(label), + selected: + sort.field == _sort.field && sort.ascending == _sort.ascending, + onTap: () => Navigator.of(sheetContext).pop(sort), + ), + ], + ), + ), + ); + if (picked != null) _chooseSort(picked); + } + + Future _openAlbumPicker() async { + final l10n = AppLocalizations.of(context)!; + final albums = await _source.albums(); + if (!mounted) return; + final picked = await showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (sheetContext) => SafeArea( + child: ListView( + shrinkWrap: true, + padding: const EdgeInsets.only(bottom: 12), + children: [ + for (final album in albums) + ListTile( + leading: Icon( + album.isAll ? Symbols.photo_library : Symbols.folder, + ), + title: Text(_albumTitle(album, l10n)), + trailing: Text('${album.count}'), + selected: album.id == _album?.id, + onTap: () => Navigator.of(sheetContext).pop(album), + ), + ], + ), + ), + ); + if (picked != null) _chooseAlbum(picked); + } + + String _albumTitle(GalleryAlbum album, AppLocalizations l10n) => + album.name.isEmpty ? l10n.attachSheetAllMedia : album.name; + + Widget _buildGalleryHeader(ColorScheme cs) { + final l10n = AppLocalizations.of(context)!; + final current = _album; + final label = current == null + ? l10n.attachSheetAlbumsTitle + : _albumTitle(current, l10n); + return Padding( + padding: const EdgeInsets.fromLTRB(8, 0, 8, 6), + child: Row( + children: [ + Expanded( + child: Material( + color: cs.surfaceContainerHigh, + shape: const StadiumBorder(), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: _openAlbumPicker, + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 9, 10, 9), + child: Row( + children: [ + Expanded( + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: cs.onSurface, + fontWeight: FontWeight.w600, + ), + ), + ), + Icon(Symbols.expand_more, size: 20, color: cs.onSurface), + ], + ), + ), + ), + ), + ), + IconButton( + tooltip: l10n.attachSheetSort, + onPressed: _openSortPicker, + icon: Icon( + _sort.ascending ? Symbols.arrow_upward : Symbols.arrow_downward, + color: cs.onSurface, + ), + ), + if (widget.onSendSeparately != null) + ValueListenableBuilder>( + valueListenable: _selected, + builder: (context, selected, _) => selected.isEmpty + ? const SizedBox.shrink() + : _GalleryMenuButton(cs: cs, onTap: _openGalleryMenu), + ), + ], + ), + ); + } + void _publishItems(List items, bool hasMore) { final seen = {}; final unique = [ @@ -842,11 +1004,14 @@ class _AttachmentSheetState extends State { return Center(child: SmallSpinner(size: 36, color: cs.primary)); } if (items.isEmpty) { - return _buildMessage( + return _scrollableCenter( scrollController, - cs, - AppLocalizations.of(context)!.attachSheetNoImagesFound, bottomReserve, + Text( + AppLocalizations.of(context)!.attachSheetNoImagesFound, + style: TextStyle(color: cs.onSurfaceVariant, fontSize: 15), + ), + header: _buildGalleryHeader(cs), ); } @@ -866,6 +1031,7 @@ class _AttachmentSheetState extends State { slivers: [ if (_permission == GalleryPermission.limited) SliverToBoxAdapter(child: _buildLimitedBanner(cs)), + SliverToBoxAdapter(child: _buildGalleryHeader(cs)), SliverPadding( padding: const EdgeInsets.fromLTRB(hpad, hpad, hpad, 0), sliver: SliverToBoxAdapter( @@ -1112,27 +1278,17 @@ class _AttachmentSheetState extends State { ); } - Widget _buildMessage( - ScrollController scrollController, - ColorScheme cs, - String text, - double bottomReserve, - ) { - return _scrollableCenter( - scrollController, - bottomReserve, - Text(text, style: TextStyle(color: cs.onSurfaceVariant, fontSize: 15)), - ); - } Widget _scrollableCenter( ScrollController scrollController, double bottomReserve, - Widget child, - ) { + Widget child, { + Widget? header, + }) { return CustomScrollView( controller: scrollController, slivers: [ + if (header != null) SliverToBoxAdapter(child: header), SliverFillRemaining( hasScrollBody: false, child: Padding( @@ -1144,25 +1300,7 @@ class _AttachmentSheetState extends State { ); } - Widget _buildGrabberBar(ColorScheme cs) { - if (widget.onSendSeparately == null) return const SheetGrabber(); - return SheetGrabberBar( - action: AnimatedBuilder( - animation: Listenable.merge([_selected, _pageController]), - builder: (context, child) { - final galleryT = (1 - _currentPageT()).clamp(0.0, 1.0); - if (_selected.value.isEmpty || galleryT == 0) { - return const SizedBox.shrink(); - } - return Opacity( - opacity: galleryT, - child: IgnorePointer(ignoring: galleryT < 0.5, child: child), - ); - }, - child: _GalleryMenuButton(cs: cs, onTap: _openGalleryMenu), - ), - ); - } + Widget _buildGrabberBar(ColorScheme cs) => const SheetGrabber(); void _openGalleryMenu(BuildContext anchorContext) { if (widget.onSendSeparately == null) return; @@ -1663,9 +1801,9 @@ class _GalleryTileState extends State<_GalleryTile> { fit: StackFit.expand, children: [ AnimatedScale( - scale: _selected ? 0.86 : 1.0, - duration: const Duration(milliseconds: 150), - curve: Curves.easeOut, + scale: _selected ? 0.88 : 1.0, + duration: const Duration(milliseconds: 240), + curve: Curves.easeInOutCubic, child: _Thumbnail( key: widget.thumbKey, item: item, diff --git a/lib/frontend/widgets/attachment/bubbles/bubble_context.dart b/lib/frontend/widgets/attachment/bubbles/bubble_context.dart index 90f38e65..a0201575 100644 --- a/lib/frontend/widgets/attachment/bubbles/bubble_context.dart +++ b/lib/frontend/widgets/attachment/bubbles/bubble_context.dart @@ -91,6 +91,7 @@ class BubbleContext { final String? overrideStatus; final ValueListenable? otherReadTime; final ValueListenable>? uploadProgress; + final VoidCallback? onCancelUpload; final void Function(StickerAttachment sticker)? onStickerTap; final ForwardedSourceTap? onForwardedSourceTap; final BubblePresentation? presentation; @@ -116,6 +117,7 @@ class BubbleContext { this.overrideStatus, this.otherReadTime, this.uploadProgress, + this.onCancelUpload, this.onStickerTap, this.onForwardedSourceTap, this.reactionInfo, @@ -153,6 +155,7 @@ class BubbleContext { overrideStatus: overrideStatus, otherReadTime: otherReadTime, uploadProgress: uploadProgress, + onCancelUpload: onCancelUpload, onStickerTap: onStickerTap, onForwardedSourceTap: onForwardedSourceTap, reactionInfo: reactionInfo, diff --git a/lib/frontend/widgets/attachment/bubbles/file_bubble.dart b/lib/frontend/widgets/attachment/bubbles/file_bubble.dart index c4a08330..364c1678 100644 --- a/lib/frontend/widgets/attachment/bubbles/file_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/file_bubble.dart @@ -144,6 +144,7 @@ class _FileBubbleState extends State { strokeWidth: 2.4, iconSize: 14, padding: const EdgeInsets.all(4), + onCancel: ctx.onCancelUpload, ), ), const SizedBox(width: 10), diff --git a/lib/frontend/widgets/attachment/bubbles/forwarded_bubble.dart b/lib/frontend/widgets/attachment/bubbles/forwarded_bubble.dart index 0b5f3bef..1133151c 100644 --- a/lib/frontend/widgets/attachment/bubbles/forwarded_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/forwarded_bubble.dart @@ -7,6 +7,7 @@ import '../../../../backend/modules/messages.dart'; import '../../../../l10n/app_localizations.dart'; import '../../../../models/attachment.dart'; import 'bubble_context.dart'; +import '../../official_name.dart'; String _forwardedSourceName( ForwardedMessageAttachment forwarded, @@ -90,10 +91,10 @@ class ForwardedHeader extends StatelessWidget { else _avatar(displaySender), Flexible( - child: Text( - displaySender, - maxLines: 1, - overflow: TextOverflow.ellipsis, + child: OfficialName( + contactId: forwarded.originalSenderId, + text: displaySender, + iconSize: 12, style: TextStyle( color: headerColor, fontSize: 12, diff --git a/lib/frontend/widgets/attachment/bubbles/photo_bubble.dart b/lib/frontend/widgets/attachment/bubbles/photo_bubble.dart index bdb8752e..3cfe6934 100644 --- a/lib/frontend/widgets/attachment/bubbles/photo_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/photo_bubble.dart @@ -16,6 +16,8 @@ import '../../text_with_meta.dart'; import 'album_layout.dart'; import 'bubble_context.dart'; import 'video_bubble.dart'; +import '../../../../core/config/komet_settings.dart'; +import '../../../../core/media/auto_download_gate.dart'; class PhotoBubble extends StatelessWidget { static const Radius _bigRadius = Radius.circular( @@ -246,20 +248,26 @@ class PhotoBubble extends StatelessWidget { ), ..._videoBadges(photo, compact: false), if (ctx.uploadProgress != null) - _buildUploadOverlay(ctx.uploadProgress!, 0), + _buildUploadOverlay(ctx, ctx.uploadProgress!, 0), if (ctx.uploadProgress == null) Positioned.fill( child: Builder( builder: (tileContext) => GestureDetector( behavior: HitTestBehavior.opaque, - onTap: () => _openMedia( - ctx.context, - 0, - tileContext: tileContext, - radius: radius, - memWidth: memWidth, - memHeight: memHeight, - ), + onTap: () { + if (_awaitsManualLoad(photo)) { + AutoDownloadGate.loadManually(_previewUrlOf(photo)); + return; + } + _openMedia( + ctx.context, + 0, + tileContext: tileContext, + radius: radius, + memWidth: memWidth, + memHeight: memHeight, + ); + }, ), ), ), @@ -295,22 +303,71 @@ class PhotoBubble extends StatelessWidget { } final imageUrl = _previewUrlOf(photo); if (imageUrl.isNotEmpty && !imageUrl.startsWith('data:')) { - return CachedNetworkImage( - imageUrl: imageUrl, - width: width, - height: height, - fit: BoxFit.cover, - memCacheWidth: memWidth, - memCacheHeight: memHeight, - fadeInDuration: Duration.zero, - placeholderFadeInDuration: Duration.zero, - placeholder: (_, _) => _buildPreviewImage(ctx, photo, width, height), - errorWidget: (_, _, _) => _buildPreviewImage(ctx, photo, width, height), + return ListenableBuilder( + listenable: Listenable.merge([ + AutoDownloadGate.listen(imageUrl), + KometSettings.autoDownloadPhoto, + ]), + builder: (context, _) { + if (!AutoDownloadGate.allows( + KometSettings.autoDownloadPhoto.value, + imageUrl, + )) { + return _manualLoadTile(ctx, photo, imageUrl, width, height); + } + return CachedNetworkImage( + imageUrl: imageUrl, + width: width, + height: height, + fit: BoxFit.cover, + memCacheWidth: memWidth, + memCacheHeight: memHeight, + fadeInDuration: Duration.zero, + placeholderFadeInDuration: Duration.zero, + placeholder: (_, _) => + _buildPreviewImage(ctx, photo, width, height), + errorWidget: (_, _, _) => + _buildPreviewImage(ctx, photo, width, height), + ); + }, ); } return _buildPreviewImage(ctx, photo, width, height); } + Widget _manualLoadTile( + BubbleContext ctx, + MessageAttachment photo, + String key, + double width, + double height, + ) { + return SizedBox( + width: width, + height: height, + child: Stack( + fit: StackFit.expand, + children: [ + _buildPreviewImage(ctx, photo, width, height), + Center( + child: GestureDetector( + onTap: () => AutoDownloadGate.loadManually(key), + child: Container( + width: 48, + height: 48, + decoration: const BoxDecoration( + color: Colors.black54, + shape: BoxShape.circle, + ), + child: const Icon(Symbols.download, color: Colors.white), + ), + ), + ), + ], + ), + ); + } + Widget _buildPreviewImage( BubbleContext ctx, MessageAttachment photo, @@ -372,25 +429,38 @@ class PhotoBubble extends StatelessWidget { } Widget _buildUploadOverlay( + BubbleContext ctx, ValueListenable> progress, int index, ) { + final onCancel = ctx.onCancelUpload; return Positioned.fill( child: ValueListenableBuilder>( valueListenable: progress, builder: (context, values, _) { final value = index < values.length ? values[index] : 1.0; final indeterminate = value <= 0 || value >= 1.0; - return Container( - color: Colors.black.withValues(alpha: 0.4), - alignment: Alignment.center, - child: SizedBox( - width: 34, - height: 34, - child: CircularProgressIndicator( - strokeWidth: 2.5, - value: indeterminate ? null : value, - color: Colors.white, + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onCancel, + child: Container( + color: Colors.black.withValues(alpha: 0.4), + alignment: Alignment.center, + child: Stack( + alignment: Alignment.center, + children: [ + SizedBox( + width: 52, + height: 52, + child: CircularProgressIndicator( + strokeWidth: 3, + value: indeterminate ? null : value, + color: Colors.white, + ), + ), + if (onCancel != null) + const Icon(Symbols.close, size: 18, color: Colors.white), + ], ), ), ); @@ -524,9 +594,9 @@ class PhotoBubble extends StatelessWidget { ), ), if (ctx.uploadProgress != null) - _buildUploadOverlay(ctx.uploadProgress!, index), + _buildUploadOverlay(ctx, ctx.uploadProgress!, index), if (ctx.uploadProgress == null) - _buildTileTapTarget(ctx, index, memWidth, memHeight), + _buildTileTapTarget(ctx, index, memWidth, memHeight, photo), ], ); }, @@ -538,24 +608,41 @@ class PhotoBubble extends StatelessWidget { int index, int memWidth, int memHeight, + MessageAttachment photo, ) { return Positioned.fill( child: Builder( builder: (tileContext) => GestureDetector( behavior: HitTestBehavior.opaque, - onTap: () => _openMedia( - ctx.context, - index, - tileContext: tileContext, - radius: BorderRadius.zero, - memWidth: memWidth, - memHeight: memHeight, - ), + onTap: () { + if (_awaitsManualLoad(photo)) { + AutoDownloadGate.loadManually(_previewUrlOf(photo)); + return; + } + _openMedia( + ctx.context, + index, + tileContext: tileContext, + radius: BorderRadius.zero, + memWidth: memWidth, + memHeight: memHeight, + ); + }, ), ), ); } + bool _awaitsManualLoad(MessageAttachment photo) { + if (_localPathOf(photo) != null) return false; + final url = _previewUrlOf(photo); + if (url.isEmpty || url.startsWith('data:')) return false; + return !AutoDownloadGate.allows( + KometSettings.autoDownloadPhoto.value, + url, + ); + } + Widget _buildPhotoPlaceholder(ColorScheme cs, double w, double h) { return Container( width: w, diff --git a/lib/frontend/widgets/attachment/bubbles/video_bubble.dart b/lib/frontend/widgets/attachment/bubbles/video_bubble.dart index d0b2fcec..6614f7fc 100644 --- a/lib/frontend/widgets/attachment/bubbles/video_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/video_bubble.dart @@ -10,6 +10,8 @@ import '../../../../l10n/app_localizations.dart'; import '../../../../models/attachment.dart'; import '../../custom_notification.dart'; import '../../upload_progress_ring.dart'; +import '../../../../core/config/komet_settings.dart'; +import '../../../../core/media/auto_download_gate.dart'; import '../../photo_viewer.dart'; import '../../text_with_meta.dart'; import 'bubble_context.dart'; @@ -47,6 +49,7 @@ class VideoBubble extends StatelessWidget { textColor: ctx.text, meta: ctx.meta(), uploadProgress: ctx.uploadProgress, + onCancelUpload: ctx.onCancelUpload, ); } final hasMessageCaption = ctx.contentText?.isNotEmpty ?? false; @@ -76,26 +79,73 @@ class VideoBubble extends StatelessWidget { ); final localThumb = dataUriImage(video, video.previewData); + final awaitsPreviewLoad = + previewUrl.isNotEmpty && + !previewUrl.startsWith('data:') && + !AutoDownloadGate.allows( + KometSettings.autoDownloadVideo.value, + previewUrl, + ); final uploading = ctx.uploadProgress; Widget previewImage() { if (previewUrl.isNotEmpty && !previewUrl.startsWith('data:')) { - return CachedNetworkImage( - imageUrl: previewUrl, - width: width, - height: height, - fit: BoxFit.cover, - memCacheWidth: (width * dpr).round(), - fadeInDuration: Duration.zero, - placeholderFadeInDuration: Duration.zero, - errorWidget: (_, _, _) => localThumb == null - ? placeholder() - : Image( - image: localThumb, - width: width, - height: height, - fit: BoxFit.cover, + return ListenableBuilder( + listenable: Listenable.merge([ + AutoDownloadGate.listen(previewUrl), + KometSettings.autoDownloadVideo, + ]), + builder: (context, _) { + if (!AutoDownloadGate.allows( + KometSettings.autoDownloadVideo.value, + previewUrl, + )) { + return SizedBox( + width: width, + height: height, + child: Stack( + fit: StackFit.expand, + children: [ + placeholder(), + Center( + child: GestureDetector( + onTap: () => AutoDownloadGate.loadManually(previewUrl), + child: Container( + width: 48, + height: 48, + decoration: const BoxDecoration( + color: Colors.black54, + shape: BoxShape.circle, + ), + child: const Icon( + Symbols.download, + color: Colors.white, + ), + ), + ), + ), + ], ), + ); + } + return CachedNetworkImage( + imageUrl: previewUrl, + width: width, + height: height, + fit: BoxFit.cover, + memCacheWidth: (width * dpr).round(), + fadeInDuration: Duration.zero, + placeholderFadeInDuration: Duration.zero, + errorWidget: (_, _, _) => localThumb == null + ? placeholder() + : Image( + image: localThumb, + width: width, + height: height, + fit: BoxFit.cover, + ), + ); + }, ); } if (localThumb != null) { @@ -125,6 +175,7 @@ class VideoBubble extends StatelessWidget { progress: uploading, color: Colors.white, trackColor: Colors.white24, + onCancel: ctx.onCancelUpload, ), ), ), @@ -167,7 +218,13 @@ class VideoBubble extends StatelessWidget { Positioned.fill( child: GestureDetector( behavior: HitTestBehavior.opaque, - onTap: () => _playVideo(ctx.context, video), + onTap: () { + if (awaitsPreviewLoad) { + AutoDownloadGate.loadManually(previewUrl); + return; + } + _playVideo(ctx.context, video); + }, ), ), ], diff --git a/lib/frontend/widgets/attachment/bubbles/video_note_bubble.dart b/lib/frontend/widgets/attachment/bubbles/video_note_bubble.dart index 3c67a6d1..11fd9aef 100644 --- a/lib/frontend/widgets/attachment/bubbles/video_note_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/video_note_bubble.dart @@ -13,6 +13,7 @@ import 'package:komet/main.dart'; import '../../../../core/media/media_playback.dart'; import '../../../../core/media/video_note_frame.dart'; +import '../../../../core/config/komet_settings.dart'; import '../../../../core/media/video_note_preloader.dart'; import '../../../../core/utils/format.dart'; import '../../../../core/utils/haptics.dart'; @@ -37,6 +38,7 @@ class VideoNoteBubble extends StatefulWidget { final Color textColor; final Widget meta; final ValueListenable>? uploadProgress; + final VoidCallback? onCancelUpload; const VideoNoteBubble({ super.key, @@ -52,6 +54,7 @@ class VideoNoteBubble extends StatefulWidget { required this.textColor, required this.meta, this.uploadProgress, + this.onCancelUpload, }); @override @@ -133,7 +136,8 @@ class _VideoNoteBubbleState extends State unawaited(_openLocalPreview(File(local))); return; } - if (VideoNotePreloader.autoLoads(widget.attachment.duration)) { + if (KometSettings.autoDownloadVideoNote.value && + VideoNotePreloader.autoLoads(widget.attachment.duration)) { unawaited(_warmCache()); } } @@ -807,6 +811,7 @@ class _VideoNoteBubbleState extends State progress: uploading, color: Colors.white, trackColor: Colors.white24, + onCancel: widget.onCancelUpload, ), ] else ...[ if (ready && !muted) _buildRing(size), diff --git a/lib/frontend/widgets/attachment/bubbles/voice_bubble.dart b/lib/frontend/widgets/attachment/bubbles/voice_bubble.dart index 759faa06..4cad2555 100644 --- a/lib/frontend/widgets/attachment/bubbles/voice_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/voice_bubble.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:material_symbols_icons/symbols.dart'; @@ -90,6 +92,7 @@ class _VoiceMessageBubbleState extends State { _audio.failure.addListener(_onFailure); TranscriptionCache.listen(_sourceMessageId, _onTranscriptionPush); _adoptCachedTranscription(); + if (KometSettings.autoDownloadVoice.value) unawaited(_audio.prefetch()); } @override diff --git a/lib/frontend/widgets/attachment/contact_picker_page.dart b/lib/frontend/widgets/attachment/contact_picker_page.dart index a3e86a11..6e318584 100644 --- a/lib/frontend/widgets/attachment/contact_picker_page.dart +++ b/lib/frontend/widgets/attachment/contact_picker_page.dart @@ -9,6 +9,7 @@ import 'package:komet/frontend/widgets/komet_avatar.dart'; import 'package:komet/frontend/widgets/small_spinner.dart'; import 'package:komet/frontend/widgets/springy_tap.dart'; import 'package:komet/l10n/app_localizations.dart'; +import '../official_name.dart'; class ContactPickerPage extends StatefulWidget { final double bottomReserve; @@ -192,10 +193,9 @@ class _ContactPickerPageState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - name, - maxLines: 1, - overflow: TextOverflow.ellipsis, + OfficialName( + contactId: contact.id, + text: name, style: TextStyle( color: cs.onSurface, fontSize: 15, diff --git a/lib/frontend/widgets/chat_wallpaper_view.dart b/lib/frontend/widgets/chat_wallpaper_view.dart index 45951ffd..19cb2510 100644 --- a/lib/frontend/widgets/chat_wallpaper_view.dart +++ b/lib/frontend/widgets/chat_wallpaper_view.dart @@ -62,7 +62,8 @@ class WallpaperImageLayer extends StatefulWidget { State createState() => _WallpaperImageLayerState(); } -class _WallpaperImageLayerState extends State { +class _WallpaperImageLayerState extends State + with WidgetsBindingObserver { static const double _maxShift = 20; static const double _motionScale = 1.16; static const double _blurSigma = 22; @@ -74,9 +75,19 @@ class _WallpaperImageLayerState extends State { @override void initState() { super.initState(); + WidgetsBinding.instance.addObserver(this); if (widget.motion) _startMotion(); } + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + if (widget.motion) _startMotion(); + } else { + _stopMotion(); + } + } + @override void didUpdateWidget(WallpaperImageLayer old) { super.didUpdateWidget(old); @@ -87,7 +98,7 @@ class _WallpaperImageLayerState extends State { void _startMotion() { _offset.value = Offset.zero; _sub ??= accelerometerEventStream( - samplingPeriod: SensorInterval.gameInterval, + samplingPeriod: SensorInterval.uiInterval, ).listen(_onAccelerometer, onError: (_) {}, cancelOnError: false); } @@ -100,14 +111,17 @@ class _WallpaperImageLayerState extends State { final targetX = (-event.x / 9.8).clamp(-1.0, 1.0) * _maxShift; final targetY = (event.y / 9.8).clamp(-1.0, 1.0) * _maxShift; final prev = _offset.value; - _offset.value = Offset( + final next = Offset( prev.dx + (targetX - prev.dx) * 0.12, prev.dy + (targetY - prev.dy) * 0.12, ); + if ((next - prev).distance < 0.25) return; + _offset.value = next; } @override void dispose() { + WidgetsBinding.instance.removeObserver(this); _sub?.cancel(); _offset.dispose(); super.dispose(); diff --git a/lib/frontend/widgets/message_bubble.dart b/lib/frontend/widgets/message_bubble.dart index eee4a1f3..edb08b25 100644 --- a/lib/frontend/widgets/message_bubble.dart +++ b/lib/frontend/widgets/message_bubble.dart @@ -25,6 +25,7 @@ import 'custom_notification.dart'; import 'hint_bubble.dart'; import 'formatted_message_text.dart'; import 'reply_preview.dart'; +import 'sender_badge.dart'; import 'text_entity_actions.dart'; import 'sending_clock_icon.dart'; import 'photo_viewer.dart'; @@ -47,6 +48,7 @@ import 'attachment/bubbles/file_bubble.dart'; import 'attachment/bubbles/forwarded_bubble.dart'; import 'lottie_image.dart'; import 'text_with_meta.dart'; +import 'official_name.dart'; final Expando _contentTypeCache = Expando(); final Expando> _contentAttachmentsCache = @@ -652,6 +654,7 @@ class MessageBubble extends StatelessWidget { final ValueListenable? reactionAnimation; final ReactionAnimojiResolver? reactionAnimojiResolver; final ValueListenable>? uploadProgress; + final VoidCallback? onCancelUpload; final void Function(String messageId)? onReplyTap; final void Function(int senderId)? onAvatarTap; final ForwardedSourceTap? onForwardedSourceTap; @@ -685,6 +688,7 @@ class MessageBubble extends StatelessWidget { this.reactionAnimation, this.reactionAnimojiResolver, this.uploadProgress, + this.onCancelUpload, this.onReplyTap, this.onAvatarTap, this.onForwardedSourceTap, @@ -982,15 +986,23 @@ class MessageBubble extends StatelessWidget { padding: needsInset ? const EdgeInsets.fromLTRB(12, 6, 12, 2) : const EdgeInsets.only(bottom: 2), - child: Text( - name, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - color: _senderColor(message.senderId), - fontSize: 13, - fontWeight: FontWeight.w600, - ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Text( + name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: _senderColor(message.senderId), + fontSize: 13, + fontWeight: FontWeight.w600, + ), + ), + ), + SenderBadge(senderId: message.senderId, size: 13), + ], ), ); @@ -1162,6 +1174,7 @@ class MessageBubble extends StatelessWidget { overrideStatus: overrideStatus, otherReadTime: otherReadTime, uploadProgress: uploadProgress, + onCancelUpload: onCancelUpload, onStickerTap: onStickerTap, onForwardedSourceTap: onForwardedSourceTap, reactionInfo: _resolveReactionInfo(), @@ -1399,14 +1412,14 @@ class MessageBubble extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - for (final row in keyboard.rows) + for (final (r, row) in keyboard.rows.indexed) if (row.isNotEmpty) Padding( - padding: const EdgeInsets.only(bottom: 4), + padding: const EdgeInsets.only(bottom: 2), child: Row( children: [ for (var i = 0; i < row.length; i++) ...[ - if (i > 0) const SizedBox(width: 4), + if (i > 0) const SizedBox(width: 2), Expanded( child: Builder( builder: (buttonContext) => @@ -1415,6 +1428,11 @@ class MessageBubble extends StatelessWidget { cs, keyboard, row[i], + radius: _inlineKeyboardRadius( + keyboard.rows, + r, + i, + ), ), ), ), @@ -1427,12 +1445,38 @@ class MessageBubble extends StatelessWidget { ); } + static BorderRadius _inlineKeyboardRadius( + List> rows, + int row, + int col, + ) { + const outer = Radius.circular(14); + const inner = Radius.circular(4); + bool has(int r, int c) => + r >= 0 && + r < rows.length && + c >= 0 && + c < rows[r].length; + Radius corner(bool vertical, bool horizontal) { + final vNeighbor = has(row + (vertical ? -1 : 1), col); + final hNeighbor = has(row, col + (horizontal ? -1 : 1)); + return vNeighbor || hNeighbor ? inner : outer; + } + return BorderRadius.only( + topLeft: corner(true, true), + topRight: corner(true, false), + bottomLeft: corner(false, true), + bottomRight: corner(false, false), + ); + } + Widget _buildInlineKeyboardButton( BuildContext context, ColorScheme cs, InlineKeyboardAttachment keyboard, - InlineKeyboardButton button, - ) { + InlineKeyboardButton button, { + required BorderRadius radius, + }) { final trailingIcon = switch (button.type) { 'LINK' => Symbols.open_in_new, 'OPEN_APP' => Symbols.chevron_right, @@ -1441,7 +1485,7 @@ class MessageBubble extends StatelessWidget { final isClipboard = button.type == 'CLIPBOARD'; return Material( color: cs.primary.withValues(alpha: 0.12), - borderRadius: BorderRadius.circular(12), + borderRadius: radius, clipBehavior: Clip.antiAlias, child: InkWell( onTap: () => _onInlineButtonTap(context, keyboard, button), @@ -2116,10 +2160,10 @@ class MessageBubble extends StatelessWidget { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - name, - maxLines: 1, - overflow: TextOverflow.ellipsis, + OfficialName( + contactId: reply.senderId == myId ? 0 : reply.senderId, + text: name, + iconSize: 12, style: TextStyle( color: accent, fontSize: 12.5, diff --git a/lib/frontend/widgets/official_name.dart b/lib/frontend/widgets/official_name.dart new file mode 100644 index 00000000..bccc4789 --- /dev/null +++ b/lib/frontend/widgets/official_name.dart @@ -0,0 +1,70 @@ +import 'package:flutter/material.dart'; + +import '../../backend/modules/messages.dart' show ContactCache; +import '../../core/cache/official_options.dart'; +import 'verified_mark.dart'; + +class OfficialName extends StatefulWidget { + final int contactId; + final String text; + final TextStyle? style; + final int maxLines; + final double iconSize; + final TextAlign? textAlign; + + const OfficialName({ + super.key, + required this.contactId, + required this.text, + this.style, + this.maxLines = 1, + this.iconSize = 15, + this.textAlign, + }); + + @override + State createState() => _OfficialNameState(); +} + +class _OfficialNameState extends State { + @override + void initState() { + super.initState(); + OfficialOptions.request(widget.contactId); + } + + @override + void didUpdateWidget(OfficialName old) { + super.didUpdateWidget(old); + if (old.contactId != widget.contactId) { + OfficialOptions.request(widget.contactId); + } + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder( + valueListenable: ContactCache.officialRevision, + builder: (context, _, _) { + final text = Text( + widget.text, + maxLines: widget.maxLines, + overflow: TextOverflow.ellipsis, + textAlign: widget.textAlign, + style: widget.style, + ); + if (!ContactCache.isOfficial(widget.contactId)) return text; + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible(child: text), + Padding( + padding: const EdgeInsets.only(left: 3), + child: VerifiedMark(size: widget.iconSize), + ), + ], + ); + }, + ); + } +} diff --git a/lib/frontend/widgets/sender_badge.dart b/lib/frontend/widgets/sender_badge.dart new file mode 100644 index 00000000..67e1c22e --- /dev/null +++ b/lib/frontend/widgets/sender_badge.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart'; + +import '../../backend/modules/messages.dart' show ContactCache; +import '../../core/cache/official_options.dart'; +import 'verified_mark.dart'; + +class SenderBadge extends StatefulWidget { + final int senderId; + final double size; + + const SenderBadge({super.key, required this.senderId, this.size = 14}); + + @override + State createState() => _SenderBadgeState(); +} + +class _SenderBadgeState extends State { + @override + void initState() { + super.initState(); + OfficialOptions.request(widget.senderId); + } + + @override + void didUpdateWidget(SenderBadge old) { + super.didUpdateWidget(old); + if (old.senderId != widget.senderId) { + OfficialOptions.request(widget.senderId); + } + } + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder( + valueListenable: ContactCache.officialRevision, + builder: (context, _, _) { + if (!ContactCache.isOfficial(widget.senderId)) { + return const SizedBox.shrink(); + } + return Padding( + padding: const EdgeInsets.only(left: 3), + child: VerifiedMark(size: widget.size), + ); + }, + ); + } +} diff --git a/lib/frontend/widgets/upload_progress_ring.dart b/lib/frontend/widgets/upload_progress_ring.dart index 1b6785ba..5f8085d4 100644 --- a/lib/frontend/widgets/upload_progress_ring.dart +++ b/lib/frontend/widgets/upload_progress_ring.dart @@ -10,6 +10,7 @@ class UploadProgressRing extends StatelessWidget { final double strokeWidth; final double iconSize; final EdgeInsets padding; + final VoidCallback? onCancel; const UploadProgressRing({ super.key, @@ -20,6 +21,7 @@ class UploadProgressRing extends StatelessWidget { this.strokeWidth = 3, this.iconSize = 22, this.padding = EdgeInsets.zero, + this.onCancel, }); @override @@ -31,30 +33,35 @@ class UploadProgressRing extends StatelessWidget { ? 0.0 : values.reduce((a, b) => a + b) / values.length; final done = value >= 1.0; + final cancel = onCancel; return SizedBox.square( dimension: size, - child: Stack( - alignment: Alignment.center, - children: [ - Padding( - padding: padding, - child: SizedBox.expand( - child: TweenAnimationBuilder( - tween: Tween(end: value.clamp(0.0, 1.0)), - duration: const Duration(milliseconds: 220), - curve: Curves.easeOut, - builder: (context, shown, _) => CircularProgressIndicator( - value: done ? null : shown, - strokeWidth: strokeWidth, - backgroundColor: - trackColor ?? color.withValues(alpha: 0.25), - color: color, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: cancel, + child: Stack( + alignment: Alignment.center, + children: [ + Padding( + padding: padding, + child: SizedBox.expand( + child: TweenAnimationBuilder( + tween: Tween(end: value.clamp(0.0, 1.0)), + duration: const Duration(milliseconds: 220), + curve: Curves.easeOut, + builder: (context, shown, _) => CircularProgressIndicator( + value: done ? null : shown, + strokeWidth: strokeWidth, + backgroundColor: + trackColor ?? color.withValues(alpha: 0.25), + color: color, + ), ), ), ), - ), - Icon(Symbols.close, size: iconSize, color: color), - ], + Icon(Symbols.close, size: iconSize, color: color), + ], + ), ), ); }, diff --git a/lib/frontend/widgets/verified_mark.dart b/lib/frontend/widgets/verified_mark.dart new file mode 100644 index 00000000..f0141a36 --- /dev/null +++ b/lib/frontend/widgets/verified_mark.dart @@ -0,0 +1,21 @@ +import 'package:flutter/material.dart'; +import 'package:material_symbols_icons/symbols.dart'; + +class VerifiedMark extends StatelessWidget { + final double size; + final Color? color; + + const VerifiedMark({super.key, this.size = 15, this.color}); + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + return Icon( + Symbols.verified, + size: size, + color: color ?? cs.primary, + weight: 600, + fill: 1, + ); + } +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 812015b4..0ee2cee0 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -402,6 +402,15 @@ "callDecline": "Decline", "callAccept": "Accept", "callSpeaker": "Speaker", + "callSwitchCamera": "Switch camera", + "callsTabDeleteFailed": "Could not delete the call", + "chatSettingsTitle": "Chat settings", + "chatSettingsArchiveOnPull": "Pull-down archive", + "chatSettingsAutoDownloadTitle": "Media auto-download", + "chatSettingsAutoDownloadPhoto": "Photos", + "chatSettingsAutoDownloadVideo": "Videos", + "chatSettingsAutoDownloadVoice": "Voice messages", + "chatSettingsAutoDownloadVideoNote": "Video notes", "callVideoLabel": "Video", "callScreenLabel": "Screen", "callUnmute": "Unmute", @@ -984,6 +993,13 @@ "digitalIdDocChildInn": "Child's INN", "digitalIdDocChildOms": "Child's health insurance policy (OMS)", "attachSheetGallery": "Gallery", + "attachSheetAlbumsTitle": "Albums", + "attachSheetAllMedia": "All photos and videos", + "attachSheetSort": "Sort", + "attachSheetSortNewestFirst": "By date: newest first", + "attachSheetSortOldestFirst": "By date: oldest first", + "attachSheetSortNameAsc": "By name: A to Z", + "attachSheetSortNameDesc": "By name: Z to A", "attachSheetPoll": "Poll", "attachSheetCameraError": "Couldn't open the camera", "attachSheetSendFileTitle": "Send a file", @@ -1882,6 +1898,8 @@ "chatEncryptionProfileNotLoaded": "Profile hasn't loaded yet", "chatEncryptionEnterKeyHint": "Enter an encryption key", "chatEncryptionEnabled": "Encryption enabled", + "e2eeLegacyDescription": "Key-based encryption from the old version is on in this chat. It works separately from the new one. Turn it off so messages are sent without the key.", + "e2eeLegacyDisable": "Turn off old encryption", "chatEncryptionDisabled": "Encryption disabled", "chatEncryptionTitle": "Message encryption", "chatEncryptionToggle": "Encrypt messages", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 46f62364..9a3b6921 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2174,6 +2174,60 @@ abstract class AppLocalizations { /// **'Speaker'** String get callSpeaker; + /// No description provided for @callSwitchCamera. + /// + /// In en, this message translates to: + /// **'Switch camera'** + String get callSwitchCamera; + + /// No description provided for @callsTabDeleteFailed. + /// + /// In en, this message translates to: + /// **'Could not delete the call'** + String get callsTabDeleteFailed; + + /// No description provided for @chatSettingsTitle. + /// + /// In en, this message translates to: + /// **'Chat settings'** + String get chatSettingsTitle; + + /// No description provided for @chatSettingsArchiveOnPull. + /// + /// In en, this message translates to: + /// **'Pull-down archive'** + String get chatSettingsArchiveOnPull; + + /// No description provided for @chatSettingsAutoDownloadTitle. + /// + /// In en, this message translates to: + /// **'Media auto-download'** + String get chatSettingsAutoDownloadTitle; + + /// No description provided for @chatSettingsAutoDownloadPhoto. + /// + /// In en, this message translates to: + /// **'Photos'** + String get chatSettingsAutoDownloadPhoto; + + /// No description provided for @chatSettingsAutoDownloadVideo. + /// + /// In en, this message translates to: + /// **'Videos'** + String get chatSettingsAutoDownloadVideo; + + /// No description provided for @chatSettingsAutoDownloadVoice. + /// + /// In en, this message translates to: + /// **'Voice messages'** + String get chatSettingsAutoDownloadVoice; + + /// No description provided for @chatSettingsAutoDownloadVideoNote. + /// + /// In en, this message translates to: + /// **'Video notes'** + String get chatSettingsAutoDownloadVideoNote; + /// No description provided for @callVideoLabel. /// /// In en, this message translates to: @@ -4508,6 +4562,48 @@ abstract class AppLocalizations { /// **'Gallery'** String get attachSheetGallery; + /// No description provided for @attachSheetAlbumsTitle. + /// + /// In en, this message translates to: + /// **'Albums'** + String get attachSheetAlbumsTitle; + + /// No description provided for @attachSheetAllMedia. + /// + /// In en, this message translates to: + /// **'All photos and videos'** + String get attachSheetAllMedia; + + /// No description provided for @attachSheetSort. + /// + /// In en, this message translates to: + /// **'Sort'** + String get attachSheetSort; + + /// No description provided for @attachSheetSortNewestFirst. + /// + /// In en, this message translates to: + /// **'By date: newest first'** + String get attachSheetSortNewestFirst; + + /// No description provided for @attachSheetSortOldestFirst. + /// + /// In en, this message translates to: + /// **'By date: oldest first'** + String get attachSheetSortOldestFirst; + + /// No description provided for @attachSheetSortNameAsc. + /// + /// In en, this message translates to: + /// **'By name: A to Z'** + String get attachSheetSortNameAsc; + + /// No description provided for @attachSheetSortNameDesc. + /// + /// In en, this message translates to: + /// **'By name: Z to A'** + String get attachSheetSortNameDesc; + /// No description provided for @attachSheetPoll. /// /// In en, this message translates to: @@ -8504,6 +8600,18 @@ abstract class AppLocalizations { /// **'Encryption enabled'** String get chatEncryptionEnabled; + /// No description provided for @e2eeLegacyDescription. + /// + /// In en, this message translates to: + /// **'Key-based encryption from the old version is on in this chat. It works separately from the new one. Turn it off so messages are sent without the key.'** + String get e2eeLegacyDescription; + + /// No description provided for @e2eeLegacyDisable. + /// + /// In en, this message translates to: + /// **'Turn off old encryption'** + String get e2eeLegacyDisable; + /// No description provided for @chatEncryptionDisabled. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index eb6fd869..c0be2a38 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1105,6 +1105,33 @@ class AppLocalizationsEn extends AppLocalizations { @override String get callSpeaker => 'Speaker'; + @override + String get callSwitchCamera => 'Switch camera'; + + @override + String get callsTabDeleteFailed => 'Could not delete the call'; + + @override + String get chatSettingsTitle => 'Chat settings'; + + @override + String get chatSettingsArchiveOnPull => 'Pull-down archive'; + + @override + String get chatSettingsAutoDownloadTitle => 'Media auto-download'; + + @override + String get chatSettingsAutoDownloadPhoto => 'Photos'; + + @override + String get chatSettingsAutoDownloadVideo => 'Videos'; + + @override + String get chatSettingsAutoDownloadVoice => 'Voice messages'; + + @override + String get chatSettingsAutoDownloadVideoNote => 'Video notes'; + @override String get callVideoLabel => 'Video'; @@ -2357,6 +2384,27 @@ class AppLocalizationsEn extends AppLocalizations { @override String get attachSheetGallery => 'Gallery'; + @override + String get attachSheetAlbumsTitle => 'Albums'; + + @override + String get attachSheetAllMedia => 'All photos and videos'; + + @override + String get attachSheetSort => 'Sort'; + + @override + String get attachSheetSortNewestFirst => 'By date: newest first'; + + @override + String get attachSheetSortOldestFirst => 'By date: oldest first'; + + @override + String get attachSheetSortNameAsc => 'By name: A to Z'; + + @override + String get attachSheetSortNameDesc => 'By name: Z to A'; + @override String get attachSheetPoll => 'Poll'; @@ -4681,6 +4729,13 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chatEncryptionEnabled => 'Encryption enabled'; + @override + String get e2eeLegacyDescription => + 'Key-based encryption from the old version is on in this chat. It works separately from the new one. Turn it off so messages are sent without the key.'; + + @override + String get e2eeLegacyDisable => 'Turn off old encryption'; + @override String get chatEncryptionDisabled => 'Encryption disabled'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index b360572a..39921df4 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1106,6 +1106,33 @@ class AppLocalizationsRu extends AppLocalizations { @override String get callSpeaker => 'Динамик'; + @override + String get callSwitchCamera => 'Переключить камеру'; + + @override + String get callsTabDeleteFailed => 'Не удалось удалить вызов'; + + @override + String get chatSettingsTitle => 'Настройки чатов'; + + @override + String get chatSettingsArchiveOnPull => 'Архив при свайпе вниз'; + + @override + String get chatSettingsAutoDownloadTitle => 'Автозагрузка медиа'; + + @override + String get chatSettingsAutoDownloadPhoto => 'Фото'; + + @override + String get chatSettingsAutoDownloadVideo => 'Видео'; + + @override + String get chatSettingsAutoDownloadVoice => 'Голосовые'; + + @override + String get chatSettingsAutoDownloadVideoNote => 'Кружки'; + @override String get callVideoLabel => 'Видео'; @@ -2368,6 +2395,27 @@ class AppLocalizationsRu extends AppLocalizations { @override String get attachSheetGallery => 'Галерея'; + @override + String get attachSheetAlbumsTitle => 'Альбомы'; + + @override + String get attachSheetAllMedia => 'Все фото и видео'; + + @override + String get attachSheetSort => 'Сортировка'; + + @override + String get attachSheetSortNewestFirst => 'По дате: сначала новые'; + + @override + String get attachSheetSortOldestFirst => 'По дате: сначала старые'; + + @override + String get attachSheetSortNameAsc => 'По имени: от А до Я'; + + @override + String get attachSheetSortNameDesc => 'По имени: от Я до А'; + @override String get attachSheetPoll => 'Опрос'; @@ -4720,6 +4768,13 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chatEncryptionEnabled => 'Шифрование включено'; + @override + String get e2eeLegacyDescription => + 'В этом чате включено старое шифрование по ключу. Оно работает отдельно от нового и не выключается здесь само. Выключите его, чтобы сообщения шли без ключа.'; + + @override + String get e2eeLegacyDisable => 'Выключить старое шифрование'; + @override String get chatEncryptionDisabled => 'Шифрование отключено'; diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 4d05ec48..7355a663 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -360,6 +360,15 @@ "callDecline": "Отклонить", "callAccept": "Принять", "callSpeaker": "Динамик", + "callSwitchCamera": "Переключить камеру", + "callsTabDeleteFailed": "Не удалось удалить вызов", + "chatSettingsTitle": "Настройки чатов", + "chatSettingsArchiveOnPull": "Архив при свайпе вниз", + "chatSettingsAutoDownloadTitle": "Автозагрузка медиа", + "chatSettingsAutoDownloadPhoto": "Фото", + "chatSettingsAutoDownloadVideo": "Видео", + "chatSettingsAutoDownloadVoice": "Голосовые", + "chatSettingsAutoDownloadVideoNote": "Кружки", "callVideoLabel": "Видео", "callScreenLabel": "Экран", "callUnmute": "Вкл. звук", @@ -749,6 +758,13 @@ "digitalIdDocChildInn": "ИНН ребёнка", "digitalIdDocChildOms": "Полис ОМС ребёнка", "attachSheetGallery": "Галерея", + "attachSheetAlbumsTitle": "Альбомы", + "attachSheetAllMedia": "Все фото и видео", + "attachSheetSort": "Сортировка", + "attachSheetSortNewestFirst": "По дате: сначала новые", + "attachSheetSortOldestFirst": "По дате: сначала старые", + "attachSheetSortNameAsc": "По имени: от А до Я", + "attachSheetSortNameDesc": "По имени: от Я до А", "attachSheetPoll": "Опрос", "attachSheetCameraError": "Не удалось открыть камеру", "attachSheetSendFileTitle": "Отправить файл", @@ -1524,6 +1540,8 @@ "chatEncryptionProfileNotLoaded": "Профиль ещё не загружен", "chatEncryptionEnterKeyHint": "Введите ключ шифрования", "chatEncryptionEnabled": "Шифрование включено", + "e2eeLegacyDescription": "В этом чате включено старое шифрование по ключу. Оно работает отдельно от нового и не выключается здесь само. Выключите его, чтобы сообщения шли без ключа.", + "e2eeLegacyDisable": "Выключить старое шифрование", "chatEncryptionDisabled": "Шифрование отключено", "chatEncryptionTitle": "Шифрование сообщений", "chatEncryptionToggle": "Шифровать сообщения", diff --git a/lib/main.dart b/lib/main.dart index 99b78a7f..8dbea778 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -96,6 +96,7 @@ import 'core/share/share_intent_bridge.dart'; import 'core/share/native_share_account_sync.dart'; import 'core/push/push_service.dart'; import 'core/storage/app_database.dart'; +import 'core/storage/per_chat_json_store.dart'; import 'core/transport/tls_config.dart'; import 'core/transport/traffic_monitor.dart'; import 'core/transport/vpn_bypass.dart'; @@ -348,7 +349,7 @@ void main(List args) async { spectrumBackgroundFuture, ]); debugPrint('KOMET-STARTUP: DeviceContactsService.loadFromStartup...'); - await DeviceContactsService.loadFromStartup(); + unawaited(DeviceContactsService.loadFromStartup()); await trafficCaptureFuture; await debugLogFuture; debugPrint('KOMET-STARTUP: runApp'); @@ -691,6 +692,9 @@ class KometAppState extends State @override void didChangeAppLifecycleState(AppLifecycleState state) { AppLock.instance.onLifecycle(state); + if (state == AppLifecycleState.paused || state == AppLifecycleState.hidden) { + unawaited(PerChatJsonStore.flushAll()); + } final background = state == AppLifecycleState.paused || state == AppLifecycleState.hidden || diff --git a/lib/models/contact_info.dart b/lib/models/contact_info.dart index fb32ab51..5609a3a2 100644 --- a/lib/models/contact_info.dart +++ b/lib/models/contact_info.dart @@ -104,6 +104,7 @@ class ContactInfo { bool get isBot => options.contains('BOT'); // #***! accountStatus не ноль значит удалён + bool get isOfficial => options.contains('OFFICIAL'); bool get isDeleted { final status = raw['accountStatus']; return status is int && status != 0; diff --git a/test/gallery_filter_test.dart b/test/gallery_filter_test.dart index 4cca1569..ffa6222a 100644 --- a/test/gallery_filter_test.dart +++ b/test/gallery_filter_test.dart @@ -7,7 +7,7 @@ const int _maxInt32 = 0x7fffffff; void main() { test('длительности в фильтре галереи влезают в int32 миллисекунд', () { - final filter = GallerySource.mediaFilter(); + final filter = GallerySource.mediaFilter(GallerySort.newestFirst); for (final type in [AssetType.image, AssetType.video, AssetType.audio]) { final duration = filter.getOption(type).durationConstraint.toMap(); @@ -26,7 +26,7 @@ void main() { }); test('размеры в фильтре галереи влезают в int32', () { - final filter = GallerySource.mediaFilter(); + final filter = GallerySource.mediaFilter(GallerySort.newestFirst); for (final type in [AssetType.image, AssetType.video, AssetType.audio]) { final size = filter.getOption(type).sizeConstraint.toMap(); @@ -44,7 +44,7 @@ void main() { }); test('фильтр пропускает видео любой разумной длины', () { - final video = GallerySource.mediaFilter().getOption(AssetType.video); + final video = GallerySource.mediaFilter(GallerySort.newestFirst).getOption(AssetType.video); expect(video.sizeConstraint.ignoreSize, isTrue); expect(video.durationConstraint.allowNullable, isTrue); @@ -55,7 +55,7 @@ void main() { }); test('фильтр не режет фото по размеру и дате создания', () { - final filter = GallerySource.mediaFilter(); + final filter = GallerySource.mediaFilter(GallerySort.newestFirst); expect(filter.getOption(AssetType.image).sizeConstraint.ignoreSize, isTrue); expect(filter.createTimeCond.ignore, isTrue); From 3b93c9fc618f7890f0739d751261d97d43bf141f Mon Sep 17 00:00:00 2001 From: Jganenokk Date: Sun, 11 Oct 2026 23:58:46 +0700 Subject: [PATCH 05/63] =?UTF-8?q?PR=20#173,=20=D0=BD=D0=B5=20=D0=B2=D0=B7?= =?UTF-8?q?=D1=8F=D0=BB=20=D0=BD=D0=B5=D0=BA=D0=BE=D1=82=D0=BE=D1=80=D0=BE?= =?UTF-8?q?=D0=B5.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: alcovaibe <132335071+alcovaibe@users.noreply.github.com> --- .github/workflows/tests.yml | 27 +- ios/Runner/KometShareBridge.swift | 16 +- ios/Shared/KometShareAccounts.swift | 32 +- lib/backend/modules/account.dart | 57 ++- lib/backend/modules/file_uploader.dart | 81 ++-- lib/backend/modules/forward_sender.dart | 11 +- lib/backend/modules/messages.dart | 163 +++++++- lib/backend/modules/outbox.dart | 7 +- lib/backend/modules/share_sender.dart | 35 +- lib/backend/modules/upload_service.dart | 84 +++- lib/core/crypto/chat_crypto_service.dart | 62 ++- lib/core/crypto/decrypted_photo_store.dart | 134 +++++++ lib/core/crypto/e2ee_service.dart | 15 +- lib/core/crypto/encrypted_photo.dart | 150 +++++--- lib/core/crypto/encrypted_photo_cache.dart | 128 +++++-- lib/core/crypto/message_decryption_cache.dart | 295 ++++++++------ lib/core/crypto/noise_png.dart | 35 +- lib/core/crypto/outgoing_message_policy.dart | 41 ++ lib/core/media/gallery_source.dart | 111 ++++-- lib/core/plugins/plugin_host.dart | 1 + lib/core/plugins/plugin_media_downloader.dart | 56 +-- lib/core/plugins/plugin_network_policy.dart | 119 ++++++ lib/core/plugins/plugin_runtime.dart | 63 ++- lib/core/plugins/plugin_storage.dart | 101 ++++- lib/core/plugins/plugin_store.dart | 2 +- .../share/native_share_account_channel.dart | 21 + lib/core/share/native_share_account_sync.dart | 15 +- .../share/share_recipient_eligibility.dart | 7 +- lib/core/storage/chat_encryption_store.dart | 19 + .../storage/temporary_password_recovery.dart | 87 +++++ lib/core/storage/token_storage.dart | 5 + lib/core/storage/webapp_storage.dart | 11 + lib/core/transport/wire_debug_log.dart | 10 +- lib/core/utils/cache_notifier.dart | 7 + lib/core/utils/debug_session_log.dart | 13 +- lib/core/utils/log_redact.dart | 16 +- lib/core/utils/media_cache.dart | 174 ++++++--- lib/frontend/commands/commands.dart | 4 + .../auth/code_confirmation_screen.dart | 18 + .../chat/chat_media_send_controller.dart | 137 +++++-- .../chats/chat/chat_text_send_controller.dart | 55 ++- .../screens/chats/chat_list_screen.dart | 12 +- lib/frontend/screens/chats/chat_screen.dart | 30 +- .../chats/scheduled_messages_screen.dart | 30 +- .../screens/profile/security_screen.dart | 8 + .../screens/webapp/web_app_bridge.dart | 272 +++++++++---- .../screens/webapp/web_app_origin_policy.dart | 22 ++ .../screens/webapp/web_app_screen.dart | 82 +++- lib/frontend/widgets/decrypted_photo.dart | 13 +- lib/frontend/widgets/decrypted_text.dart | 25 +- lib/frontend/widgets/sliding_pill_nav.dart | 175 +++++---- .../temporary_password_recovery_dialog.dart | 49 +++ lib/l10n/app_en.arb | 9 +- lib/l10n/app_localizations.dart | 36 ++ lib/l10n/app_localizations_en.dart | 22 ++ lib/l10n/app_localizations_ru.dart | 23 ++ lib/l10n/app_ru.arb | 9 +- lib/main.dart | 4 + native/komet_share/src/authorization.rs | 71 ++++ native/komet_share/src/engine.rs | 41 +- native/komet_share/src/engine/tests.rs | 98 +++++ native/komet_share/src/lib.rs | 4 + native/komet_share/src/transport.rs | 16 + pubspec.lock | 36 +- pubspec.yaml | 2 +- test/avatar_picker_test.dart | 3 +- test/chat_text_send_controller_test.dart | 2 +- test/decrypted_photo_store_test.dart | 176 +++++++++ test/dev22_followup_regressions_test.dart | 207 ++++++++++ test/forward_encryption_test.dart | 65 +++- test/launch_flags_test.dart | 10 +- test/media_cache_security_test.dart | 85 +++++ test/native/ios_share_accounts_test.swift | 5 + test/security_audit_regressions_test.dart | 360 ++++++++++++++++++ test/share_recipient_eligibility_test.dart | 41 +- 75 files changed, 3671 insertions(+), 797 deletions(-) create mode 100644 lib/core/crypto/decrypted_photo_store.dart create mode 100644 lib/core/crypto/outgoing_message_policy.dart create mode 100644 lib/core/plugins/plugin_network_policy.dart create mode 100644 lib/core/storage/temporary_password_recovery.dart create mode 100644 lib/core/utils/cache_notifier.dart create mode 100644 lib/frontend/screens/webapp/web_app_origin_policy.dart create mode 100644 lib/frontend/widgets/temporary_password_recovery_dialog.dart create mode 100644 native/komet_share/src/authorization.rs create mode 100644 test/decrypted_photo_store_test.dart create mode 100644 test/dev22_followup_regressions_test.dart create mode 100644 test/media_cache_security_test.dart create mode 100644 test/security_audit_regressions_test.dart diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index c51ea549..d27486d1 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -2,6 +2,7 @@ name: Tests on: push: + pull_request: workflow_dispatch: permissions: @@ -30,10 +31,34 @@ jobs: cache: true - name: Build crypto core - run: make -C native/crypto-core shared + run: make -C native/crypto-core test asan shared - name: Install dependencies run: flutter pub get + - name: Analyze Dart + run: flutter analyze lib test tool + - name: Flutter test run: flutter test + + share-native: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@stable + - name: Test share authorization and transport + run: cargo test --locked --manifest-path native/komet_share/Cargo.toml + + share-swift: + runs-on: macos-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v5 + - name: Test share accounts + run: | + swiftc ios/Shared/KometShareStore.swift ios/Shared/KometShareAccounts.swift test/native/ios_share_accounts_test.swift -o /tmp/komet-share-accounts-test + /tmp/komet-share-accounts-test + - name: Test native build scripts + run: python3 -m unittest discover -s test/native -p 'test*.py' diff --git a/ios/Runner/KometShareBridge.swift b/ios/Runner/KometShareBridge.swift index 5ff9796e..2107f50a 100644 --- a/ios/Runner/KometShareBridge.swift +++ b/ios/Runner/KometShareBridge.swift @@ -12,7 +12,7 @@ final class KometShareBridge { } func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { - if !extensionEnabled && ["syncShareAccount", "clearShareAccount", "clearAllShareAccounts", "readShareToken"].contains(call.method) { + if !extensionEnabled && ["syncShareAccount", "invalidateShareAccount", "invalidateShareAccounts", "clearShareAccount", "clearAllShareAccounts", "readShareToken"].contains(call.method) { result(nil) return } @@ -46,6 +46,20 @@ final class KometShareBridge { try KometShareAccounts().sync(arguments) return nil } + case "invalidateShareAccounts": + perform(result) { _ in + try KometShareAccounts().invalidate(accountID: nil) + return nil + } + case "invalidateShareAccount": + guard let id = (call.arguments as? [String: Any])?["accountId"] as? String else { + result(FlutterError(code: "INVALID_SHARE_ACCOUNT", message: "Missing account ID", details: nil)) + return + } + perform(result) { _ in + try KometShareAccounts().invalidate(accountID: id) + return nil + } case "clearShareAccount": guard let id = (call.arguments as? [String: Any])?["accountId"] as? String else { result(FlutterError(code: "INVALID_SHARE_ACCOUNT", message: "Missing account ID", details: nil)) diff --git a/ios/Shared/KometShareAccounts.swift b/ios/Shared/KometShareAccounts.swift index 127ab73e..f212b394 100644 --- a/ios/Shared/KometShareAccounts.swift +++ b/ios/Shared/KometShareAccounts.swift @@ -13,6 +13,8 @@ struct KometShareAccount: Codable { let id: String let name: String let chats: [KometShareChat] + var policyEpoch: String? = nil + var updatedAtMillis: Int64? = nil } protocol KometShareCredentialStorage { @@ -120,9 +122,16 @@ final class KometShareAccounts { "account_id": id, "token": activeToken, "sourceToken": token, "session": session, "login": login ] try writeCredentials(credentials, accountID: id) - var saved = try readAccounts().filter { $0.id != id } + let accounts = try readAccounts() + let previous = accounts.first { $0.id == id } + let permissions = Dictionary(chats.map { ($0.id, $0.disabledReason ?? "allowed") }, uniquingKeysWith: { _, new in new }) + let oldPermissions = Dictionary((previous?.chats ?? []).map { ($0.id, $0.disabledReason ?? "allowed") }, uniquingKeysWith: { _, new in new }) + let sameCredentials = existing?["sourceToken"] as? String == token + && (existing?["session"] as? NSDictionary)?.isEqual(to: session) == true + let epoch = permissions == oldPermissions && sameCredentials ? previous?.policyEpoch ?? UUID().uuidString : UUID().uuidString + var saved = accounts.filter { $0.id != id } let name = arguments["accountName"] as? String ?? "Komet" - saved.insert(KometShareAccount(id: id, name: name, chats: chats), at: 0) + saved.insert(KometShareAccount(id: id, name: name, chats: chats, policyEpoch: epoch, updatedAtMillis: Int64(Date().timeIntervalSince1970 * 1000)), at: 0) try writeAccounts(saved) } } @@ -134,12 +143,27 @@ final class KometShareAccounts { func authorizedCredentials(accountID: String, chatID: String) throws -> [String: Any] { try withLock { guard let account = try readAccounts().first(where: { $0.id == accountID }), - let chat = account.chats.first(where: { $0.id == chatID }), chat.disabledReason == nil else { + let chat = account.chats.first(where: { $0.id == chatID }), chat.disabledReason == nil, + let epoch = account.policyEpoch, let updated = account.updatedAtMillis, + Int64(Date().timeIntervalSince1970 * 1000) >= updated, + Int64(Date().timeIntervalSince1970 * 1000) - updated <= 300_000 else { throw NSError(domain: "KometShare", code: 1, userInfo: [ NSLocalizedDescriptionKey: "Этот чат недоступен для отправки. Обновите список чатов в Komet." ]) } - return try readCredentials(accountID: accountID) + var credentials = try readCredentials(accountID: accountID) + credentials["authorization"] = ["snapshot_path": snapshotURL.path, "lock_path": lockURL.path, "epoch": epoch] + return credentials + } + } + + func invalidate(accountID: String?) throws { + try withLock { + var saved = try readAccounts() + for index in saved.indices where accountID == nil || saved[index].id == accountID { + saved[index].policyEpoch = nil + } + try writeAccounts(saved) } } diff --git a/lib/backend/modules/account.dart b/lib/backend/modules/account.dart index 3ddea7a5..8995c56a 100644 --- a/lib/backend/modules/account.dart +++ b/lib/backend/modules/account.dart @@ -12,11 +12,20 @@ import '../../core/protocol/opcode_map.dart'; import '../../core/protocol/packet.dart'; import '../../core/media/media_playback.dart'; import '../../core/crypto/e2ee_service.dart'; +import '../../core/crypto/encrypted_photo_cache.dart'; +import '../../core/crypto/decrypted_photo_store.dart'; +import '../../core/crypto/chat_crypto_service.dart'; +import '../../core/crypto/message_decryption_cache.dart'; +import '../../core/storage/chat_encryption_store.dart'; +import '../../core/storage/webapp_storage.dart'; import '../../core/storage/app_database.dart'; import '../../core/utils/parse.dart'; import '../../core/storage/profile_deletion_store.dart'; import '../../core/storage/spoofing_service.dart'; import '../../core/storage/token_storage.dart'; +import '../../core/storage/temporary_password_recovery.dart'; +import '../../core/plugins/plugin_storage.dart'; +import '../../core/share/native_share_account_channel.dart'; import '../../core/utils/device_locale.dart'; import '../../core/utils/logger.dart'; import '../../models/login_info.dart'; @@ -399,6 +408,9 @@ class AccountModule { await TokenStorage.clearActiveAccount(); + ChatCryptoService.instance.clearKeys(); + MessageDecryptionCache.instance.clear(); + EncryptedPhotoCache.instance.clear(); ContactCache.clear(); TranscriptionCache.clear(); ComplaintsModule.clear(); @@ -419,6 +431,9 @@ class AccountModule { await _api.disconnect(); } catch (_) {} + ChatCryptoService.instance.clearKeys(); + MessageDecryptionCache.instance.clear(); + EncryptedPhotoCache.instance.clear(); ContactCache.clear(); TranscriptionCache.clear(); ComplaintsModule.clear(); @@ -470,6 +485,9 @@ class AccountModule { // обёрнуто в try с откатом. final bool weSetPassword = existingPassword == null; final String password = existingPassword ?? _generateStrongPassword(); + final recovery = weSetPassword + ? await TemporaryPasswordRecovery.save(accountId, password) + : null; var passwordCleared = !weSetPassword; try { @@ -624,7 +642,9 @@ class AccountModule { passwordCleared = await _removeTempPassword(password); } if (!passwordCleared) { - logger.e('SMS-вход: ВРЕМЕННЫЙ ПАРОЛЬ НЕ СНЯТ. Пароль: $password'); + logger.e( + 'SMS-вход: временный пароль не снят; сохранено защищённое восстановление', + ); } } catch (e, st) { logger.d( @@ -632,18 +652,21 @@ class AccountModule { '(веб-сессия=${_api.state.name})\n$st', ); // #***! любой сбой после установки пароля — откатываем, пока веб-сессия - // ещё жива; если не вышло, пароль хотя бы попадёт в лог if (weSetPassword && !passwordCleared) { if (_api.state == SessionState.online) { passwordCleared = await _removeTempPassword(password); } if (!passwordCleared) { logger.e( - 'SMS-вход: сбой, ВРЕМЕННЫЙ ПАРОЛЬ НЕ СНЯТ. Пароль: $password', + 'SMS-вход: временный пароль не снят; сохранено защищённое восстановление', ); } } rethrow; + } finally { + if (passwordCleared && recovery != null) { + await recovery.clearAfterRollback(); + } } } @@ -681,7 +704,9 @@ class AccountModule { final prepared = _smsSocket; _smsSocket = null; if (prepared == null) return; - logger.d('[${prepared.api.debugTag}] SMS-вход: заготовленный сокет B закрыт'); + logger.d( + '[${prepared.api.debugTag}] SMS-вход: заготовленный сокет B закрыт', + ); unawaited(_closeSmsSocket(prepared.api)); } @@ -702,7 +727,7 @@ class AccountModule { await remove2fa(trackId); return true; } catch (e) { - logger.w('SMS-вход: снять временный пароль не удалось: $e'); + logger.w('SMS-вход: снять временный пароль не удалось: ${e.runtimeType}'); return false; } } @@ -719,8 +744,7 @@ class AccountModule { } static String _generateStrongPassword() { - const chars = - 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'; + const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'; final rng = Random.secure(); return List.generate(16, (_) => chars[rng.nextInt(chars.length)]).join(); } @@ -734,10 +758,7 @@ class AccountModule { final text = msg['text']; final looksLikeLogin = text is String && - RegExp( - r'код|code|войти|профил', - caseSensitive: false, - ).hasMatch(text); + RegExp(r'код|code|войти|профил', caseSensitive: false).hasMatch(text); if (!looksLikeLogin) return null; final attaches = msg['attaches']; @@ -784,6 +805,9 @@ class AccountModule { await AppDatabase.setActiveAccount(accountId); await TokenStorage.setActiveAccount(accountId); + ChatCryptoService.instance.clearKeys(); + MessageDecryptionCache.instance.clear(); + EncryptedPhotoCache.instance.clear(); ContactCache.clear(); TranscriptionCache.clear(); ComplaintsModule.clear(); @@ -813,6 +837,14 @@ class AccountModule { // #***! удаляем локально, база токен спуф и заявка Future removeAccount(int accountId) async { + await NativeShareAccountChannel.instance.remove(accountId); + await PluginStorage.eraseAccount(accountId); + ChatCryptoService.instance.clearKeys(); + MessageDecryptionCache.instance.clear(); + EncryptedPhotoCache.instance.clear(); + await DecryptedPhotoStore.clear(); + await ChatEncryptionStore.instance.eraseAccount(accountId); + await WebAppStorage.eraseAccount(accountId); await E2eeService.instance.eraseAccount(accountId); await AppDatabase.deleteAccount(accountId); await TokenStorage.deleteAccount(accountId); @@ -872,6 +904,9 @@ class AccountModule { if (accountId != null) { await removeAccount(accountId); } + ChatCryptoService.instance.clearKeys(); + MessageDecryptionCache.instance.clear(); + EncryptedPhotoCache.instance.clear(); ContactCache.clear(); TranscriptionCache.clear(); ComplaintsModule.clear(); diff --git a/lib/backend/modules/file_uploader.dart b/lib/backend/modules/file_uploader.dart index bb4edd76..83d7a12b 100644 --- a/lib/backend/modules/file_uploader.dart +++ b/lib/backend/modules/file_uploader.dart @@ -65,6 +65,8 @@ class FileUploader { required String filename, required int totalSize, String? text, + bool encryptedPayload = false, + void Function()? beforeSend, int? scheduledTime, Duration autoForceAfter = const Duration(seconds: 1), Duration overallTimeout = const Duration(minutes: 5), @@ -81,7 +83,9 @@ class FileUploader { Future run() async { try { - final info = await messages.requestUploadUrl(); + final initialSession = api.session; + beforeSend?.call(); + final info = await messages.requestUploadUrl(beforeSend: beforeSend); if (cancelled) return; if (info == null) { ctrl.add(const UploadError('no_upload_url')); @@ -89,6 +93,10 @@ class FileUploader { } final session = api.session; + beforeSend?.call(); + if (!identical(session, initialSession)) { + throw StateError('Account changed during upload'); + } if (session == null) { ctrl.add(const UploadError('no_session')); return; @@ -100,7 +108,7 @@ class FileUploader { await api.sendRequest(Opcode.msgTyping, { 'chatId': chatId, 'type': 'FILE', - }); + }, beforeSend: beforeSend); } catch (_) {} }()); @@ -108,39 +116,35 @@ class FileUploader { String? error; final done = Completer(); // #***! подписка на события ядра - sub = - session - .uploadFilePath( - url: info.url, - path: file.path, - filename: filename, - connection: 'close', - ) - .listen( - (e) { - switch (e) { - case kb.UploadEvent_Progress(:final sent, :final total): - ctrl.add( - UploadProgress( - sent: sent.toInt(), - total: total.toInt(), - ), - ); - case kb.UploadEvent_Done(status: final s): - status = s; - case kb.UploadEvent_Error(:final message): - error = message; - } - }, - onError: (Object err) { - error = err.toString(); - if (!done.isCompleted) done.complete(); - }, - onDone: () { - if (!done.isCompleted) done.complete(); - }, - cancelOnError: true, - ); + sub = session + .uploadFilePath( + url: info.url, + path: file.path, + filename: filename, + connection: 'close', + ) + .listen( + (e) { + switch (e) { + case kb.UploadEvent_Progress(:final sent, :final total): + ctrl.add( + UploadProgress(sent: sent.toInt(), total: total.toInt()), + ); + case kb.UploadEvent_Done(status: final s): + status = s; + case kb.UploadEvent_Error(:final message): + error = message; + } + }, + onError: (Object err) { + error = err.toString(); + if (!done.isCompleted) done.complete(); + }, + onDone: () { + if (!done.isCompleted) done.complete(); + }, + cancelOnError: true, + ); await done.future; if (cancelled) return; if (error != null) { @@ -159,7 +163,14 @@ class FileUploader { info.fileId, token: info.token, text: text, + encryptedPayload: encryptedPayload, scheduledTime: scheduledTime, + beforeSend: () { + if (!identical(api.session, initialSession)) { + throw StateError('Account changed during upload'); + } + beforeSend?.call(); + }, ); if (cancelled) return; if (messageId == null) { diff --git a/lib/backend/modules/forward_sender.dart b/lib/backend/modules/forward_sender.dart index bd294a7e..3974916e 100644 --- a/lib/backend/modules/forward_sender.dart +++ b/lib/backend/modules/forward_sender.dart @@ -3,7 +3,7 @@ import 'dart:math'; import '../../core/cache/message_session_cache.dart'; import '../../core/crypto/e2ee_service.dart'; -import '../../core/storage/chat_encryption_store.dart'; +import '../../core/crypto/outgoing_message_policy.dart'; import '../../core/utils/logger.dart'; import '../../main.dart'; import 'chats.dart'; @@ -94,24 +94,19 @@ class ForwardSender { static Stream> get delivered => _deliveredController.stream; - static bool isBlocked(int accountId, int chatId) => - ChatEncryptionStore.instance.isEnabled(accountId, chatId) || - E2eeService.instance.isActive(accountId, chatId); - static Future _prepareDispatch( int accountId, int chatId, MessagesModule sender, int expectedSessionEpoch, ) async { - await ChatEncryptionStore.instance.load(); - await E2eeService.instance.ensureLoaded(accountId); + await OutgoingMessagePolicy.load(accountId); void check() { if (!E2eeService.instance.isLoaded(accountId) || sender.sessionEpoch != expectedSessionEpoch) { throw StateError('Сессия изменилась до пересылки'); } - if (isBlocked(accountId, chatId)) { + if (OutgoingMessagePolicy.requiresEncryption(accountId, chatId)) { throw StateError('Пересылка в зашифрованный чат недоступна'); } } diff --git a/lib/backend/modules/messages.dart b/lib/backend/modules/messages.dart index 9551ea30..edba1382 100644 --- a/lib/backend/modules/messages.dart +++ b/lib/backend/modules/messages.dart @@ -1,13 +1,16 @@ import 'dart:async'; import 'dart:convert'; + import 'package:flutter/foundation.dart'; import 'package:shared_preferences/shared_preferences.dart'; + import '../api.dart'; import '../../core/config/komet_settings.dart'; import '../../core/contacts/device_contacts_service.dart'; import '../../core/protocol/opcode_map.dart'; import '../../core/protocol/packet.dart'; import '../../core/crypto/e2ee_service.dart'; +import '../../core/crypto/outgoing_message_policy.dart'; import '../../core/storage/app_database.dart'; import '../../core/storage/message_ranges.dart'; import '../../core/storage/token_storage.dart'; @@ -1010,11 +1013,68 @@ class MessagesModule { } // #***! отправка текста, cid спасает от дублей + Future _sendUserMessage( + Map payload, { + int opcode = Opcode.msgSend, + int? accountId, + bool encryptedPayload = false, + bool encryptionControl = false, + void Function()? beforeSend, + }) async { + final session = _api.session; + final epoch = _api.sessionEpoch; + final accountEpoch = TokenStorage.accountEpoch; + beforeSend?.call(); + final chatId = payload['chatId']; + if (chatId is! int) { + throw ArgumentError.value(chatId, 'chatId', 'Message without chat'); + } + if (encryptionControl && + !OutgoingMessagePolicy.isEncryptionControl(_outgoingText(payload))) { + throw ArgumentError('Only E2EE handshake messages skip encryption'); + } + final owner = accountId ?? await TokenStorage.getActiveAccountId(); + if (owner == null) { + throw StateError('No active account for message dispatch'); + } + await OutgoingMessagePolicy.load(owner); + if (await TokenStorage.getActiveAccountId() != owner) { + throw StateError('Account changed before message dispatch'); + } + return _api.sendRequest( + opcode, + payload, + beforeSend: () { + beforeSend?.call(); + if (!identical(_api.session, session) || + _api.sessionEpoch != epoch || + TokenStorage.accountEpoch != accountEpoch) { + throw StateError('Account changed before message dispatch'); + } + if (!encryptionControl) { + OutgoingMessagePolicy.requireSupported( + owner, + chatId, + encryptedPayload: encryptedPayload, + ); + } + }, + ); + } + + static String _outgoingText(Map payload) { + final message = payload['message']; + final text = message is Map ? message['text'] : payload['text']; + return text is String ? text : ''; + } + Future sendMessage( int accountId, int chatId, String text, { bool notify = true, + bool encryptedPayload = false, + bool encryptionControl = false, int? scheduledTime, int? replyToMessageId, int? replySourceChatId, @@ -1046,6 +1106,9 @@ class MessagesModule { payload, 'Ошибка отправки', beforeSend: beforeSend, + accountId: accountId, + encryptedPayload: encryptedPayload, + encryptionControl: encryptionControl, ); } @@ -1092,10 +1155,15 @@ class MessagesModule { Map payload, String defaultError, { void Function()? beforeSend, + int? accountId, + bool encryptedPayload = false, + bool encryptionControl = false, }) async { - final response = await _api.sendRequest( - Opcode.msgSend, + final response = await _sendUserMessage( payload, + accountId: accountId, + encryptedPayload: encryptedPayload, + encryptionControl: encryptionControl, beforeSend: beforeSend, ); if (!response.isOk) { @@ -1136,10 +1204,16 @@ class MessagesModule { required Duration retryDelay, required T Function(Packet response) onResult, required T onExhausted, + void Function()? beforeSend, + bool encryptedPayload = false, }) async { for (var attempt = 0; attempt < maxAttempts; attempt++) { try { - final response = await _api.sendRequest(Opcode.msgSend, payload); + final response = await _sendUserMessage( + payload, + encryptedPayload: encryptedPayload, + beforeSend: beforeSend, + ); return onResult(response); } on PacketError catch (e) { if (!(e.errorKey?.contains('not.ready') ?? false)) { @@ -1192,7 +1266,7 @@ class MessagesModule { bool notify = true, void Function()? beforeSend, }) async { - final response = await _api.sendRequest(Opcode.msgSend, { + final response = await _sendUserMessage({ 'chatId': chatId, 'message': { 'cid': -_nextCid(), @@ -1381,6 +1455,8 @@ class MessagesModule { int chatId, String messageId, { required String text, + bool encryptedPayload = false, + bool encryptionControl = false, List> elements = const [], bool sendAttachments = false, }) async { @@ -1395,13 +1471,21 @@ class MessagesModule { }; if (sendAttachments) payload['attachments'] = const []; - return _api.sendRequestOk(Opcode.msgEdit, payload); + final response = await _sendUserMessage( + payload, + opcode: Opcode.msgEdit, + encryptedPayload: encryptedPayload, + encryptionControl: encryptionControl, + ); + return response.isOk; } Future editScheduledMessage( int chatId, String messageId, { required String text, + bool encryptedPayload = false, + bool encryptionControl = false, required int timeToFire, }) async { final id = int.tryParse(messageId); @@ -1415,7 +1499,13 @@ class MessagesModule { 'delayedAttributes': {'timeToFire': timeToFire, 'notifySender': true}, }; - return _api.sendRequestOk(Opcode.msgEdit, payload); + final response = await _sendUserMessage( + payload, + opcode: Opcode.msgEdit, + encryptedPayload: encryptedPayload, + encryptionControl: encryptionControl, + ); + return response.isOk; } // #***! удаление, deleteForAll значит у всех @@ -1642,9 +1732,16 @@ class MessagesModule { } // #***! дальше пары запросить адрес и отправить, на каждый тип медиа - Future requestUploadUrl({int count = 1}) async { + Future requestUploadUrl({ + int count = 1, + void Function()? beforeSend, + }) async { final payload = {'count': count}; - final response = await _api.sendRequest(Opcode.fileUpload, payload); + final response = await _api.sendRequest( + Opcode.fileUpload, + payload, + beforeSend: beforeSend, + ); if (!response.isOk) return null; final data = response.payload; @@ -1675,6 +1772,8 @@ class MessagesModule { int? scheduledTime, int maxAttempts = 20, Duration retryDelay = const Duration(seconds: 1), + void Function()? beforeSend, + bool encryptedPayload = false, }) async { final message = { 'isLive': false, @@ -1703,14 +1802,19 @@ class MessagesModule { retryDelay: retryDelay, onResult: (response) => _sentMessageMap(response)?['id']?.toString(), onExhausted: null, + beforeSend: beforeSend, + encryptedPayload: encryptedPayload, ); } - Future requestPhotoUploadUrl({int? type}) async { + Future requestPhotoUploadUrl({ + int? type, + void Function()? beforeSend, + }) async { final response = await _api.sendRequest(Opcode.photoUpload, { 'type': ?type, 'count': 1, - }); + }, beforeSend: beforeSend); if (!response.isOk) return null; final data = response.payload; if (data is! Map) return null; @@ -1725,6 +1829,7 @@ class MessagesModule { int? scheduledTime, int maxAttempts = 20, Duration retryDelay = const Duration(seconds: 1), + void Function()? beforeSend, }) async { final message = { 'cid': -_nextCid(), @@ -1748,15 +1853,19 @@ class MessagesModule { retryDelay: retryDelay, onResult: _sentMessageMap, onExhausted: null, + beforeSend: beforeSend, ); } - Future requestVideoUploadUrl({int type = 0}) async { + Future requestVideoUploadUrl({ + int type = 0, + void Function()? beforeSend, + }) async { final response = await _api.sendRequest(Opcode.videoUpload, { 'uploaderType': 0, 'type': type, 'count': 1, - }); + }, beforeSend: beforeSend); if (!response.isOk) return null; final data = response.payload; @@ -1783,6 +1892,7 @@ class MessagesModule { int? scheduledTime, int maxAttempts = 30, Duration retryDelay = const Duration(seconds: 1), + void Function()? beforeSend, }) async { final message = { 'isLive': false, @@ -1808,15 +1918,18 @@ class MessagesModule { retryDelay: retryDelay, onResult: _sentMessageMap, onExhausted: null, + beforeSend: beforeSend, ); } - Future requestAudioUploadUrl() async { + Future requestAudioUploadUrl({ + void Function()? beforeSend, + }) async { final response = await _api.sendRequest(Opcode.videoUpload, { 'uploaderType': 1, 'type': 2, 'count': 1, - }); + }, beforeSend: beforeSend); if (!response.isOk) return null; final data = response.payload; @@ -1844,6 +1957,7 @@ class MessagesModule { int? scheduledTime, int maxAttempts = 30, Duration retryDelay = const Duration(seconds: 1), + void Function()? beforeSend, }) async { final message = { 'isLive': false, @@ -1873,15 +1987,18 @@ class MessagesModule { retryDelay: retryDelay, onResult: _sentMessageMap, onExhausted: null, + beforeSend: beforeSend, ); } - Future requestVideoNoteUploadUrl() async { + Future requestVideoNoteUploadUrl({ + void Function()? beforeSend, + }) async { final response = await _api.sendRequest(Opcode.videoUpload, { 'uploaderType': 1, 'type': 1, 'count': 1, - }); + }, beforeSend: beforeSend); if (!response.isOk) return null; final data = response.payload; @@ -1909,6 +2026,7 @@ class MessagesModule { bool notify = true, int maxAttempts = 30, Duration retryDelay = const Duration(seconds: 1), + void Function()? beforeSend, }) async { final message = { 'isLive': false, @@ -1934,6 +2052,7 @@ class MessagesModule { retryDelay: retryDelay, onResult: _sentMessageMap, onExhausted: null, + beforeSend: beforeSend, ); } @@ -1943,6 +2062,7 @@ class MessagesModule { double longitude, { double zoom = 15, bool notify = true, + void Function()? beforeSend, }) async { final payload = { 'chatId': chatId, @@ -1960,7 +2080,7 @@ class MessagesModule { 'notify': notify, }; - final response = await _api.sendRequest(Opcode.msgSend, payload); + final response = await _sendUserMessage(payload, beforeSend: beforeSend); return _sentMessageMap(response); } @@ -1968,6 +2088,7 @@ class MessagesModule { int chatId, int contactId, { bool notify = true, + void Function()? beforeSend, }) async { final payload = { 'chatId': chatId, @@ -1980,7 +2101,7 @@ class MessagesModule { 'notify': notify, }; - final response = await _api.sendRequest(Opcode.msgSend, payload); + final response = await _sendUserMessage(payload, beforeSend: beforeSend); return _sentMessageMap(response); } @@ -1994,6 +2115,7 @@ class MessagesModule { bool multiple = false, bool anonymous = true, bool notify = true, + void Function()? beforeSend, }) async { final settings = (anonymous ? _pollAnonymousFlag : 0) | @@ -2016,7 +2138,7 @@ class MessagesModule { 'notify': notify, }; - final response = await _api.sendRequest(Opcode.msgSend, payload); + final response = await _sendUserMessage(payload, beforeSend: beforeSend); return _sentMessageMap(response); } @@ -2036,6 +2158,7 @@ class MessagesModule { int chatId, int stickerId, { bool notify = true, + void Function()? beforeSend, }) async { final payload = { 'chatId': chatId, @@ -2048,7 +2171,7 @@ class MessagesModule { 'notify': notify, }; - final response = await _api.sendRequest(Opcode.msgSend, payload); + final response = await _sendUserMessage(payload, beforeSend: beforeSend); return _sentMessageMap(response); } diff --git a/lib/backend/modules/outbox.dart b/lib/backend/modules/outbox.dart index 4289406b..7ab7f2dd 100644 --- a/lib/backend/modules/outbox.dart +++ b/lib/backend/modules/outbox.dart @@ -1,6 +1,7 @@ import 'dart:async'; import '../../core/protocol/packet.dart'; +import '../../core/crypto/chat_crypto_service.dart'; import '../../core/storage/app_database.dart'; import '../../core/storage/token_storage.dart'; import '../../core/utils/logger.dart'; @@ -86,6 +87,10 @@ class OutboxService { accountId, pending.chatId, text, + encryptedPayload: + ChatCryptoService.instance.looksEncrypted(text) || + pending.sealedText != null || + pending.e2ee != CachedMessage.e2eeNone, replyToMessageId: replyToMessageId, replySourceChatId: replySourceChatId, elements: elements, @@ -123,7 +128,7 @@ class OutboxService { status: 'sent', elements: elements.isEmpty ? null : elements, ); - // #***! временную ошибку оставляем в очереди, окончательную помечаем и не трогаем + // #***! временную ошибку оставляем в очереди, окончательную помечаем и не трогаем } catch (e) { if (!await _ownsSession(api, epoch, accountId)) return; if (!isPermanentSendFailure(e)) { diff --git a/lib/backend/modules/share_sender.dart b/lib/backend/modules/share_sender.dart index 168d9941..6f3b4091 100644 --- a/lib/backend/modules/share_sender.dart +++ b/lib/backend/modules/share_sender.dart @@ -2,10 +2,12 @@ import 'dart:async'; import 'dart:io'; import '../../core/media/gallery_source.dart'; +import '../../core/crypto/outgoing_message_policy.dart'; import '../../core/media/share_thumbnail.dart'; import '../../core/media/video_transcoder.dart'; import '../../core/share/shared_file_usage.dart'; import '../../core/storage/app_database.dart'; +import '../../core/storage/token_storage.dart'; import '../../core/utils/logger.dart'; import '../../models/attachment.dart'; import '../../models/chat_preview_media.dart'; @@ -173,12 +175,29 @@ class ShareSender { required List chatIds, required PreparedShare share, required String caption, - }) { + }) async { + final session = api.session; + final epoch = api.sessionEpoch; + final accountEpoch = TokenStorage.accountEpoch; + await OutgoingMessagePolicy.load(accountId); + if (session == null || + !identical(api.session, session) || + api.sessionEpoch != epoch || + TokenStorage.accountEpoch != accountEpoch || + await TokenStorage.getActiveAccountId() != accountId) { + throw StateError('Account changed during sharing'); + } + for (final chatId in chatIds) { + OutgoingMessagePolicy.requireSupported(accountId, chatId); + } return SharedFileUsage.instance.use( share.files.map((file) => file.source.path), () async { var messages = 0; for (final chatId in chatIds) { + if (!identical(api.session, session) || api.sessionEpoch != epoch || TokenStorage.accountEpoch != accountEpoch) { + throw StateError('Account changed during sharing'); + } messages += await _sendToChat( accountId: accountId, chatId: chatId, @@ -204,6 +223,7 @@ class ShareSender { required PreparedShare share, required String caption, }) async { + OutgoingMessagePolicy.requireSupported(accountId, chatId); if (share.isTextOnly) { final text = caption.trim().isNotEmpty ? caption @@ -262,6 +282,7 @@ class ShareSender { required int chatId, required String text, }) async { + final session = api.session; final now = DateTime.now().millisecondsSinceEpoch; final tempId = UploadService.instance.newTempId(); final placeholder = CachedMessage( @@ -288,7 +309,17 @@ class ShareSender { String realId = tempId; var status = 'sent'; try { - final sent = await messagesModule.sendMessage(accountId, chatId, text); + final sent = await messagesModule.sendMessage( + accountId, + chatId, + text, + beforeSend: () { + if (session == null || !identical(api.session, session)) { + throw StateError('Account changed during sharing'); + } + OutgoingMessagePolicy.requireSupported(accountId, chatId); + }, + ); if (sent.isNotEmpty) realId = sent; } catch (e) { logger.w('Поделиться: текст в $chatId не ушёл: $e'); diff --git a/lib/backend/modules/upload_service.dart b/lib/backend/modules/upload_service.dart index 22de027c..b50f4797 100644 --- a/lib/backend/modules/upload_service.dart +++ b/lib/backend/modules/upload_service.dart @@ -4,11 +4,13 @@ import 'dart:io'; import 'package:flutter/foundation.dart'; import '../../core/cache/message_session_cache.dart'; +import '../../core/crypto/outgoing_message_policy.dart'; +import '../../core/storage/token_storage.dart'; import '../../core/media/gallery_source.dart'; import '../../core/media/image_optimizer.dart'; import '../../core/storage/app_database.dart'; import '../../core/utils/logger.dart'; -import '../../main.dart' show fileUploader, messagesModule; +import '../../main.dart' show api, fileUploader, messagesModule; import '../../models/attachment.dart'; import 'chats.dart' show chats; import 'file_uploader.dart'; @@ -106,7 +108,11 @@ class UploadJob { this.totalBytes = 0, this.placeholder, this.scheduledTime, - }) : _slots = slots < 1 ? 1 : slots, + this.encryptedPayload = false, + }) : _session = api.session, + _sessionEpoch = api.sessionEpoch, + _accountEpoch = TokenStorage.accountEpoch, + _slots = slots < 1 ? 1 : slots, _sent = List.filled(slots < 1 ? 1 : slots, 0), _total = List.filled(slots < 1 ? 1 : slots, 0), progress = ValueNotifier>( @@ -124,6 +130,24 @@ class UploadJob { final int totalBytes; final CachedMessage? placeholder; final int? scheduledTime; + final bool encryptedPayload; + final Object? _session; + final int _sessionEpoch; + final int _accountEpoch; + + void ensureSendAllowed() { + if (_session == null || + !identical(api.session, _session) || + api.sessionEpoch != _sessionEpoch || + TokenStorage.accountEpoch != _accountEpoch) { + throw const UploadFailure('account_changed'); + } + OutgoingMessagePolicy.requireSupported( + accountId, + chatId, + encryptedPayload: encryptedPayload, + ); + } final ValueNotifier> progress; final ValueNotifier bytes; @@ -278,6 +302,7 @@ class UploadService { tokens.cast(), caption: caption.isEmpty ? null : caption, scheduledTime: scheduledTime, + beforeSend: job.ensureSendAllowed, ); if (sent == null) return null; return CachedMessage.fromPushPayload(accountId, chatId, sent); @@ -306,10 +331,13 @@ class UploadService { scheduledTime: scheduledTime, ), (job) async { - final info = await messagesModule.requestVideoUploadUrl(); + final info = await messagesModule.requestVideoUploadUrl( + beforeSend: job.ensureSendAllowed, + ); if (info == null || info.url.isEmpty) { throw const UploadFailure('no_upload_url'); } + job.ensureSendAllowed(); final ok = await fileUploader.uploadVideoFile( Uri.parse(info.url), file, @@ -324,6 +352,7 @@ class UploadService { info.token, caption: caption.isEmpty ? null : caption, scheduledTime: scheduledTime, + beforeSend: job.ensureSendAllowed, ); if (sent == null) return null; return CachedMessage.fromPushPayload(accountId, chatId, sent); @@ -348,15 +377,18 @@ class UploadService { file: file, kind: UploadKind.voice, placeholder: placeholder, - requestUpload: () async { - final info = await messagesModule.requestAudioUploadUrl(); + requestUpload: (beforeSend) async { + final info = await messagesModule.requestAudioUploadUrl( + beforeSend: beforeSend, + ); return info == null ? null : (url: info.url, token: info.token); }, - send: (token) => messagesModule.sendAudioMessage( + send: (token, beforeSend) => messagesModule.sendAudioMessage( chatId, token, duration: durationMs, wave: wave, + beforeSend: beforeSend, ), ); } @@ -377,14 +409,17 @@ class UploadService { file: file, kind: UploadKind.videoNote, placeholder: placeholder, - requestUpload: () async { - final info = await messagesModule.requestVideoNoteUploadUrl(); + requestUpload: (beforeSend) async { + final info = await messagesModule.requestVideoNoteUploadUrl( + beforeSend: beforeSend, + ); return info == null ? null : (url: info.url, token: info.token); }, - send: (token) => messagesModule.sendVideoNoteMessage( + send: (token, beforeSend) => messagesModule.sendVideoNoteMessage( chatId, token, duration: durationMs, + beforeSend: beforeSend, ), ); } @@ -396,8 +431,15 @@ class UploadService { required String tempId, required File file, required UploadKind kind, - required Future<({String url, String token})?> Function() requestUpload, - required Future?> Function(String token) send, + required Future<({String url, String token})?> Function( + void Function() beforeSend, + ) + requestUpload, + required Future?> Function( + String token, + VoidCallback beforeSend, + ) + send, CachedMessage? placeholder, }) { return _run( @@ -411,10 +453,11 @@ class UploadService { ), (job) async { try { - final info = await requestUpload(); + final info = await requestUpload(job.ensureSendAllowed); if (info == null || info.url.isEmpty) { throw const UploadFailure('no_upload_url'); } + job.ensureSendAllowed(); final ok = await fileUploader.uploadMediaFile( Uri.parse(info.url), file, @@ -423,7 +466,7 @@ class UploadService { ); if (!ok) throw const UploadFailure('upload_failed'); job.markUploaded(); - final sent = await send(info.token); + final sent = await send(info.token, job.ensureSendAllowed); if (sent == null) return null; return CachedMessage.fromPushPayload(accountId, chatId, sent); } finally { @@ -446,6 +489,7 @@ class UploadService { CachedMessage? placeholder, String? text, int? scheduledTime, + bool encryptedPayload = false, }) { return _run( UploadJob._( @@ -458,6 +502,7 @@ class UploadService { totalBytes: size, placeholder: placeholder, scheduledTime: scheduledTime, + encryptedPayload: encryptedPayload, ), (job) async { final done = await _uploadFile( @@ -528,7 +573,9 @@ class UploadService { filename: filename, totalSize: size, text: text, + encryptedPayload: job.encryptedPayload, scheduledTime: scheduledTime, + beforeSend: job.ensureSendAllowed, ) .listen( (event) { @@ -578,6 +625,12 @@ class UploadService { CachedMessage? real; String? failure; try { + await OutgoingMessagePolicy.load(job.accountId); + final activeAccount = await TokenStorage.getActiveAccountId(); + if (activeAccount != job.accountId) { + throw const UploadFailure('account_changed'); + } + job.ensureSendAllowed(); // #***! для отложенного null это нормально, оно уйдёт позже final work = upload(job); unawaited(work.then((_) {}, onError: (_) {})); @@ -755,8 +808,11 @@ class UploadService { job.resetSlot(index); } try { - final url = await messagesModule.requestPhotoUploadUrl(); + final url = await messagesModule.requestPhotoUploadUrl( + beforeSend: job.ensureSendAllowed, + ); if (url == null || url.isEmpty) continue; + job.ensureSendAllowed(); final token = await fileUploader.uploadPhoto( Uri.parse(url), file, diff --git a/lib/core/crypto/chat_crypto_service.dart b/lib/core/crypto/chat_crypto_service.dart index 2db2a7ca..0e4d60f5 100644 --- a/lib/core/crypto/chat_crypto_service.dart +++ b/lib/core/crypto/chat_crypto_service.dart @@ -81,7 +81,11 @@ class ChatCryptoService { chatId, ); if (password == null || password.isEmpty) return null; - return await Isolate.run(() => KometCrypto.deriveKey(password)); + final libraryPath = KometCrypto.libraryPath; + return await Isolate.run(() { + KometCrypto.libraryPath = libraryPath; + return KometCrypto.deriveKey(password); + }); } catch (e) { logger.w('derive key for chat $chatId: $e'); return null; @@ -133,7 +137,7 @@ class ChatCryptoService { if (key == null) return CryptoBytesResult.failed(_noKeyFailure()); try { final blob = KometCrypto.encryptImageBlob(png, key); - final wrapped = wrapNoisePng(blob); + final wrapped = await Isolate.run(() => wrapNoisePng(blob)); if (wrapped == null) { return const CryptoBytesResult.failed(CryptoFailure.malformed); } @@ -144,23 +148,36 @@ class ChatCryptoService { } } + Future _imageWork = Future.value(); + + Future _runImageWork(Future Function() work) { + final result = _imageWork.then((_) => work()); + _imageWork = result.then( + (_) {}, + onError: (Object _, StackTrace _) {}, + ); + return result; + } + Future decryptImageBytes( int accountId, int chatId, Uint8List noisePng, ) async { - final key = await _keyFor(accountId, chatId); - if (key == null) return CryptoBytesResult.failed(_noKeyFailure()); - final raw = unwrapNoisePng(noisePng); - if (raw == null) { - return const CryptoBytesResult.failed(CryptoFailure.notEncrypted); - } - try { - return CryptoBytesResult.ok(KometCrypto.decryptImageBlob(raw, key)); - } catch (e) { - logger.w('image decrypt for chat $chatId: $e'); - return CryptoBytesResult.failed(cryptoFailureOf(e)); - } + return _runImageWork(() async { + final key = await _keyFor(accountId, chatId); + if (key == null) return CryptoBytesResult.failed(_noKeyFailure()); + final workerKey = Uint8List.fromList(key); + final libraryPath = KometCrypto.libraryPath; + try { + return await _decryptImageInIsolate(noisePng, workerKey, libraryPath); + } catch (e) { + logger.w('image decrypt for chat $chatId: $e'); + return CryptoBytesResult.failed(cryptoFailureOf(e)); + } finally { + KometCrypto.wipe(workerKey); + } + }); } // #***! похоже ли это вообще на наш шифр, чтоб отличить чужой ключ от обычного текста @@ -199,3 +216,20 @@ class ChatCryptoService { } } } + +Future _decryptImageInIsolate( + Uint8List noisePng, + Uint8List key, + String? libraryPath, +) => Isolate.run(() { + KometCrypto.libraryPath = libraryPath; + try { + final raw = unwrapNoisePng(noisePng); + if (raw == null || !KometCrypto.looksEncryptedImageBlob(raw)) { + return const CryptoBytesResult.failed(CryptoFailure.notEncrypted); + } + return CryptoBytesResult.ok(KometCrypto.decryptImageBlob(raw, key)); + } finally { + KometCrypto.wipe(key); + } +}); diff --git a/lib/core/crypto/decrypted_photo_store.dart b/lib/core/crypto/decrypted_photo_store.dart new file mode 100644 index 00000000..ec68ee6c --- /dev/null +++ b/lib/core/crypto/decrypted_photo_store.dart @@ -0,0 +1,134 @@ +import 'dart:io'; +import 'dart:convert'; + +import 'package:crypto/crypto.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; + +import '../storage/app_instance.dart'; +import '../utils/media_cache.dart'; +import '../utils/logger.dart'; + +class DecryptedPhotoStore { + DecryptedPhotoStore._(); + static Future? _initialization; + static int _generation = 0; + static int get generation => _generation; + static const int maxBytes = 64 * 1024 * 1024; + static const int maxTotalBytes = 128 * 1024 * 1024; + static Future _publications = Future.value(); + + static Future _publish(Future Function() action) { + final next = _publications.then((_) => action()); + _publications = next.then( + (_) {}, + onError: (Object _, StackTrace _) {}, + ); + return next; + } + + static Future _root() => _initialization ??= () async { + final root = Directory( + p.join( + (await getTemporaryDirectory()).path, + 'komet_decrypted${AppInstance.suffix}', + ), + ); + if (await root.exists()) await root.delete(recursive: true); + await root.create(recursive: true); + for (final file in await MediaCache.files()) { + final name = p.basename(file.path); + if (name.startsWith('decrypted_')) await MediaCache.discard(name); + } + return root; + }(); + + static String _filename(String name) => + sha256.convert(utf8.encode(name)).toString(); + + static Future existing(String name) async { + final generation = _generation; + final root = await _root(); + final file = File(p.join(root.path, '$generation', _filename(name))); + if (generation != _generation || + !await file.exists() || + await file.length() == 0) { + return null; + } + return generation == _generation ? file : null; + } + + static Future write( + String name, + Future Function(File) fill, + ) async { + final generation = _generation; + final root = await _root(); + if (generation != _generation) { + throw StateError('Encryption context changed'); + } + final staging = await root.createTemp('writing_${generation}_'); + final part = File(p.join(staging.path, 'content.part')); + try { + if (generation != _generation) { + throw StateError('Encryption context changed'); + } + await fill(part); + if (generation != _generation) { + throw StateError('Encryption context changed'); + } + if (!await part.exists() || + await part.length() == 0 || + await part.length() > maxBytes) { + throw const FormatException('Empty decrypted file'); + } + return await _publish(() async { + final dir = Directory(p.join(root.path, '$generation')); + await dir.create(recursive: true); + var total = await part.length(); + final filename = _filename(name); + await for (final entity in dir.list()) { + if (entity is File && p.basename(entity.path) != filename) { + total += await entity.length(); + } + } + if (total > maxTotalBytes) { + throw const FormatException('Decrypted cache quota exceeded'); + } + if (generation != _generation) { + throw StateError('Encryption context changed'); + } + final target = await part.rename(p.join(dir.path, filename)); + if (generation != _generation) { + await target.delete(); + throw StateError('Encryption context changed'); + } + return target; + }); + } finally { + if (await staging.exists()) await staging.delete(recursive: true); + } + } + + static Future clear() async { + final generation = ++_generation; + final root = await _root(); + await for (final entry in root.list()) { + if (entry is Directory) { + final name = p.basename(entry.path); + final oldGeneration = + int.tryParse(name) ?? + int.tryParse( + RegExp(r'^writing_(\d+)_').firstMatch(name)?.group(1) ?? '', + ); + if (oldGeneration != null && oldGeneration < generation) { + try { + await entry.delete(recursive: true); + } on FileSystemException catch (error) { + logger.w('decrypted cache cleanup: $error'); + } + } + } + } + } +} diff --git a/lib/core/crypto/e2ee_service.dart b/lib/core/crypto/e2ee_service.dart index 2d9e939e..fa99ccef 100644 --- a/lib/core/crypto/e2ee_service.dart +++ b/lib/core/crypto/e2ee_service.dart @@ -367,6 +367,7 @@ class E2eeService { accountId, chatId, '$kE2eeOfferPrefix\n${offer.text}', + encryptionControl: true, ); if (messageId.isEmpty) return false; final previous = info(accountId, chatId); @@ -414,6 +415,7 @@ class E2eeService { accountId, chatId, '$kE2eeAnswerPrefix\n${answer.text}', + encryptionControl: true, ); if (messageId.isEmpty) return false; final peek = KometCrypto.handshakePeek(offerText); @@ -685,7 +687,12 @@ class E2eeService { if (offerMessageId != null && messages != null) { unawaited( messages - .editMessage(chatId, offerMessageId, text: kE2eeOfferDonePrefix) + .editMessage( + chatId, + offerMessageId, + text: kE2eeOfferDonePrefix, + encryptionControl: true, + ) .catchError((_) => false), ); } @@ -983,7 +990,11 @@ class E2eeService { final items = []; var offset = 4; final count = _readBe32(container, 0); - for (var index = 0; index < count && offset + 4 <= container.length; index++) { + for ( + var index = 0; + index < count && offset + 4 <= container.length; + index++ + ) { final length = _readBe32(container, offset); offset += 4; if (offset + length > container.length) return null; diff --git a/lib/core/crypto/encrypted_photo.dart b/lib/core/crypto/encrypted_photo.dart index ee12ec55..02cb97eb 100644 --- a/lib/core/crypto/encrypted_photo.dart +++ b/lib/core/crypto/encrypted_photo.dart @@ -8,7 +8,8 @@ import 'package:crypto/crypto.dart'; import 'package:path_provider/path_provider.dart'; import '../utils/logger.dart'; -import '../utils/media_cache.dart'; +import '../storage/chat_encryption_store.dart'; +import 'decrypted_photo_store.dart'; import 'chat_crypto_service.dart'; // #***! парольное фото уходит на сервер как png, сквозное как шифртекст без обёртки @@ -89,20 +90,27 @@ Future openEncryptedPhoto({ required File encrypted, required String cacheName, }) async { - final target = await MediaCache.fileFor( - decryptedCacheName(accountId, chatId, cacheName), - ); - if (await target.exists() && await target.length() > 0) { - return EncryptedPhotoResult.ok(target); + final generation = DecryptedPhotoStore.generation; + if (await ChatEncryptionStore.instance.readKey(accountId, chatId) == null || + generation != DecryptedPhotoStore.generation) { + return const EncryptedPhotoResult.failed(CryptoFailure.noKey); } + final name = decryptedCacheName(accountId, chatId, cacheName); + final target = await DecryptedPhotoStore.existing(name); + if (target != null) return EncryptedPhotoResult.ok(target); final result = await ChatCryptoService.instance.decryptImageBytes( accountId, chatId, await encrypted.readAsBytes(), ); if (!result.isOk) return EncryptedPhotoResult.failed(result.failure!); - await target.writeAsBytes(result.bytes!, flush: true); - return EncryptedPhotoResult.ok(target); + if (generation != DecryptedPhotoStore.generation) { + return const EncryptedPhotoResult.failed(CryptoFailure.noKey); + } + final file = await DecryptedPhotoStore.write(name, (part) async { + await part.writeAsBytes(result.bytes!, flush: true); + }); + return EncryptedPhotoResult.ok(file); } // #***! сквозное фото: свой ключ на файл, билет едет внутри рэтчет-сообщения @@ -121,9 +129,10 @@ Future prepareE2eePhoto({ if (png == null) return null; final key = KometCrypto.randomBytes(KometCryptoSizes.fileKey); final nonce = KometCrypto.randomBytes(KometCryptoSizes.fileNonce); - final out = BytesBuilder(copy: false); + FileSealer? sealer; try { - final sealer = KometCrypto.fileSealer(key, nonce); + final out = BytesBuilder(copy: false); + sealer = KometCrypto.fileSealer(key, nonce); var offset = 0; while (true) { final last = png.length - offset <= KometCryptoSizes.fileChunk; @@ -132,75 +141,104 @@ Future prepareE2eePhoto({ offset = end; if (last) break; } - sealer.dispose(); - } catch (e) { - logger.w('e2ee photo seal: $e'); + final dir = await _scratchDir(); + final file = File('${dir.path}/enc_$stamp$kE2eePhotoExtension'); + await file.writeAsBytes(out.toBytes(), flush: true); + final name = Uint8List.fromList(utf8.encode('photo_$stamp.png')); + final ticket = Uint8List(_ticketHeader + name.length); + ticket.setAll(0, key); + ticket.setAll(KometCryptoSizes.fileKey, nonce); + var size = png.length; + for (var i = _ticketHeader - 1; i >= _ticketHeader - 8; i--) { + ticket[i] = size & 0xff; + size >>= 8; + } + ticket.setAll(_ticketHeader, name); + return E2eePhotoPrepared(file, ticket); + } catch (error) { + logger.w('e2ee photo seal: $error'); return null; + } finally { + sealer?.dispose(); + KometCrypto.wipe(key); } - final dir = await _scratchDir(); - final file = File('${dir.path}/enc_$stamp$kE2eePhotoExtension'); - await file.writeAsBytes(out.toBytes(), flush: true); - final name = Uint8List.fromList(utf8.encode('photo_$stamp.png')); - final ticket = Uint8List(_ticketHeader + name.length); - ticket.setAll(0, key); - ticket.setAll(KometCryptoSizes.fileKey, nonce); - var size = png.length; - for (var i = _ticketHeader - 1; i >= _ticketHeader - 8; i--) { - ticket[i] = size & 0xff; - size >>= 8; - } - ticket.setAll(_ticketHeader, name); - KometCrypto.wipe(key); - return E2eePhotoPrepared(file, ticket); } Future openE2eePhoto({ required File encrypted, required Uint8List ticket, }) async { + final generation = DecryptedPhotoStore.generation; if (ticket.length < _ticketHeader) { return const EncryptedPhotoResult.failed(CryptoFailure.malformed); } - final target = await MediaCache.fileFor(e2eeDecryptedCacheName(ticket)); - if (await target.exists() && await target.length() > 0) { + final name = e2eeDecryptedCacheName(ticket); + final target = await DecryptedPhotoStore.existing(name); + if (target != null) { return EncryptedPhotoResult.ok(target); } final key = ticket.sublist(0, KometCryptoSizes.fileKey); final nonce = ticket.sublist(KometCryptoSizes.fileKey, _ticketHeader - 8); const step = KometCryptoSizes.fileChunk + KometCryptoSizes.tag; - final total = await encrypted.length(); // #***! блоками, размер выбирает сервер и в память вложение не влезет - final source = await encrypted.open(); - final sink = target.openWrite(); + var expectedSize = 0; + for (var i = _ticketHeader - 8; i < _ticketHeader; i++) { + expectedSize = (expectedSize << 8) | ticket[i]; + } + if (expectedSize <= 0 || expectedSize > DecryptedPhotoStore.maxBytes) { + KometCrypto.wipe(key); + return const EncryptedPhotoResult.failed(CryptoFailure.malformed); + } + if (generation != DecryptedPhotoStore.generation) { + KometCrypto.wipe(key); + return const EncryptedPhotoResult.failed(CryptoFailure.noKey); + } try { - final opener = KometCrypto.fileOpener(key, nonce); - try { - var offset = 0; - while (true) { - final last = total - offset <= step; - final take = last ? total - offset : step; - final block = await source.read(take); - if (block.length != take) throw const FormatException('truncated'); - sink.add(opener.chunk(block, last: last)); - offset += take; - if (last) break; - } - } finally { - opener.dispose(); + final total = await encrypted.length(); + if (generation != DecryptedPhotoStore.generation) { + return const EncryptedPhotoResult.failed(CryptoFailure.noKey); } - await sink.close(); + final file = await DecryptedPhotoStore.write(name, (part) async { + final source = await encrypted.open(); + IOSink? sink; + FileOpener? opener; + var written = 0; + try { + sink = part.openWrite(); + opener = KometCrypto.fileOpener(key, nonce); + var offset = 0; + while (true) { + final last = total - offset <= step; + final take = last ? total - offset : step; + final block = await source.read(take); + if (block.length != take) throw const FormatException('truncated'); + final plain = opener.chunk(block, last: last); + written += plain.length; + if (written > expectedSize) { + throw const FormatException('invalid file size'); + } + sink.add(plain); + offset += take; + if (last) break; + } + if (written != expectedSize) { + throw const FormatException('invalid file size'); + } + await sink.flush(); + } finally { + opener?.dispose(); + try { + await sink?.close(); + } finally { + await source.close(); + } + } + }); + return EncryptedPhotoResult.ok(file); } catch (e) { logger.w('e2ee photo open: $e'); - try { - await sink.close(); - } catch (_) {} - try { - if (await target.exists()) await target.delete(); - } catch (_) {} return EncryptedPhotoResult.failed(cryptoFailureOf(e)); } finally { KometCrypto.wipe(key); - await source.close(); } - return EncryptedPhotoResult.ok(target); } diff --git a/lib/core/crypto/encrypted_photo_cache.dart b/lib/core/crypto/encrypted_photo_cache.dart index 838e3bff..ded014e7 100644 --- a/lib/core/crypto/encrypted_photo_cache.dart +++ b/lib/core/crypto/encrypted_photo_cache.dart @@ -3,14 +3,17 @@ import 'dart:collection'; import 'dart:io'; import 'package:flutter/foundation.dart'; +import 'package:crypto/crypto.dart'; import '../storage/chat_encryption_store.dart'; import 'e2ee_service.dart'; import '../utils/download_progress.dart'; import '../utils/logger.dart'; +import '../utils/cache_notifier.dart'; import '../utils/media_cache.dart'; import 'chat_crypto_service.dart'; import 'encrypted_photo.dart'; +import 'decrypted_photo_store.dart'; typedef EncryptedPhotoUrlLoader = Future Function(); @@ -60,6 +63,7 @@ class _AutoRequest { class EncryptedPhotoCache { EncryptedPhotoCache._() { ChatEncryptionStore.instance.revision.addListener(clear); + E2eeService.instance.revision.addListener(clear); } static final EncryptedPhotoCache instance = EncryptedPhotoCache._(); @@ -72,25 +76,46 @@ class EncryptedPhotoCache { static const int _maxConcurrentAuto = 3; // #***! на картинку свой notifier, перерисуется только её пузырь - final LinkedHashMap> _entries = + final LinkedHashMap> _entries = LinkedHashMap(); final Map> _inFlight = {}; // #***! очередь расшифровок для видимых пузырей final Queue<_AutoRequest> _queue = Queue(); final Set _queued = {}; int _running = 0; + int _generation = 0; - ValueListenable listenableFor(String cacheName) => - _entryFor(cacheName); + String _key( + int accountId, + int chatId, + String cacheName, [ + Uint8List? sealedTicket, + ]) => + '$accountId/$chatId/$cacheName/${sealedTicket == null ? '' : sha256.convert(sealedTicket)}'; - ValueNotifier _entryFor(String cacheName) => - _entries[cacheName] ??= ValueNotifier(null); + ValueListenable listenableFor( + String cacheName, { + required int accountId, + required int chatId, + Uint8List? sealedTicket, + }) => _entryFor(_key(accountId, chatId, cacheName, sealedTicket)); + + CacheNotifier _entryFor(String cacheName) => + _entries[cacheName] ??= CacheNotifier(null); void _evictStale(String keep) { - while (_entries.length > _maxEntries) { - final oldest = _entries.keys.first; - if (oldest == keep) break; - _entries.remove(oldest); + if (_entries.length <= _maxEntries) return; + for (final key in _entries.keys.toList()) { + if (_entries.length <= _maxEntries) break; + final entry = _entries[key]!; + if (key == keep || + entry.isObserved || + _inFlight.containsKey(key) || + _queued.contains(key)) { + continue; + } + _entries.remove(key); + entry.dispose(); } } @@ -107,10 +132,11 @@ class EncryptedPhotoCache { !ChatCryptoService.instance.isEnabled(accountId, chatId)) { return; } - if (_entryFor(cacheName).value != null) return; - if (_inFlight.containsKey(cacheName)) return; - if (!_queued.add(cacheName)) return; - _evictStale(cacheName); + final key = _key(accountId, chatId, cacheName, sealedTicket); + if (_entryFor(key).value != null) return; + if (_inFlight.containsKey(key)) return; + if (!_queued.add(key)) return; + _evictStale(key); _queue.add( _AutoRequest( accountId: accountId, @@ -133,15 +159,24 @@ class EncryptedPhotoCache { int? size, Uint8List? sealedTicket, }) { - final known = _entryFor(cacheName).value; + final known = _entryFor( + _key(accountId, chatId, cacheName, sealedTicket), + ).value; if (known != null && known.status != EncryptedPhotoStatus.locked) { return Future.value(known); } - _dequeue(cacheName); + _dequeue(_key(accountId, chatId, cacheName, sealedTicket)); return _start(accountId, chatId, cacheName, urlLoader, size, sealedTicket); } void clear() { + _generation++; + _inFlight.clear(); + unawaited( + DecryptedPhotoStore.clear().catchError((Object error) { + logger.w('decrypted cache clear: $error'); + }), + ); _queue.clear(); _queued.clear(); for (final entry in _entries.values) { @@ -151,14 +186,25 @@ class EncryptedPhotoCache { void _dequeue(String cacheName) { if (!_queued.remove(cacheName)) return; - _queue.removeWhere((request) => request.cacheName == cacheName); + _queue.removeWhere( + (request) => + _key( + request.accountId, + request.chatId, + request.cacheName, + request.sealedTicket, + ) == + cacheName, + ); } // #***! насос очереди void _pump() { while (_running < _maxConcurrentAuto && _queue.isNotEmpty) { final next = _queue.removeLast(); - _queued.remove(next.cacheName); + _queued.remove( + _key(next.accountId, next.chatId, next.cacheName, next.sealedTicket), + ); _running++; final done = _start( next.accountId, @@ -185,7 +231,9 @@ class EncryptedPhotoCache { int? autoSize, Uint8List? sealedTicket, ) { - final running = _inFlight[cacheName]; + final key = _key(accountId, chatId, cacheName, sealedTicket); + final generation = _generation; + final running = _inFlight[key]; if (running != null) return running; final future = _resolve( accountId, @@ -194,9 +242,14 @@ class EncryptedPhotoCache { urlLoader, autoSize, sealedTicket, + generation, + ); + _inFlight[key] = future; + unawaited( + future.whenComplete(() { + if (identical(_inFlight[key], future)) _inFlight.remove(key); + }), ); - _inFlight[cacheName] = future; - unawaited(future.whenComplete(() => _inFlight.remove(cacheName))); return future; } @@ -207,6 +260,7 @@ class EncryptedPhotoCache { EncryptedPhotoUrlLoader urlLoader, int? autoSize, Uint8List? sealedTicket, + int generation, ) async { EncryptedPhotoView view; try { @@ -217,12 +271,14 @@ class EncryptedPhotoCache { urlLoader, autoSize, sealedTicket, + generation, ); } catch (e) { logger.w('encrypted preview $cacheName: $e'); view = const EncryptedPhotoView.locked(); } - _entryFor(cacheName).value = view; + if (generation != _generation) return const EncryptedPhotoView.locked(); + _entryFor(_key(accountId, chatId, cacheName, sealedTicket)).value = view; return view; } @@ -234,6 +290,7 @@ class EncryptedPhotoCache { EncryptedPhotoUrlLoader urlLoader, int? autoSize, Uint8List? sealedTicket, + int generation, ) async { // #***! имя расшифрованного берётся из билета, поэтому билет первым Uint8List? ticket; @@ -243,11 +300,18 @@ class EncryptedPhotoCache { chatId, sealedTicket, ); + if (generation != _generation) return const EncryptedPhotoView.locked(); if (ticket == null) return const EncryptedPhotoView.locked(); - final ready = await MediaCache.existing(e2eeDecryptedCacheName(ticket)); + final ready = await DecryptedPhotoStore.existing( + e2eeDecryptedCacheName(ticket), + ); if (ready != null) return EncryptedPhotoView.decrypted(ready); } else { - final ready = await MediaCache.existing( + if (await ChatEncryptionStore.instance.readKey(accountId, chatId) == null || + generation != _generation) { + return const EncryptedPhotoView.locked(); + } + final ready = await DecryptedPhotoStore.existing( decryptedCacheName(accountId, chatId, cacheName), ); if (ready != null) return EncryptedPhotoView.decrypted(ready); @@ -264,25 +328,18 @@ class EncryptedPhotoCache { : (autoSize < _maxAutoBytes ? autoSize : _maxAutoBytes); encrypted = await _download(cacheName, urlLoader, cap); } - if (encrypted == null) return const EncryptedPhotoView.locked(); + if (generation != _generation || encrypted == null) { + return const EncryptedPhotoView.locked(); + } if (ticket != null) { - final opened = await openE2eePhoto( - encrypted: encrypted, - ticket: ticket, - ); + final opened = await openE2eePhoto(encrypted: encrypted, ticket: ticket); if (opened.isOk) return EncryptedPhotoView.decrypted(opened.file!); return opened.failure == CryptoFailure.unavailable ? const EncryptedPhotoView.locked() : const EncryptedPhotoView.wrongKey(); } - if (!ChatCryptoService.instance.looksEncryptedImage( - await encrypted.readAsBytes(), - )) { - return const EncryptedPhotoView.plain(); - } - final result = await openEncryptedPhoto( accountId: accountId, chatId: chatId, @@ -290,6 +347,9 @@ class EncryptedPhotoCache { cacheName: cacheName, ); if (result.isOk) return EncryptedPhotoView.decrypted(result.file!); + if (result.failure == CryptoFailure.notEncrypted) { + return const EncryptedPhotoView.plain(); + } return result.failure == CryptoFailure.unavailable ? const EncryptedPhotoView.locked() : const EncryptedPhotoView.wrongKey(); diff --git a/lib/core/crypto/message_decryption_cache.dart b/lib/core/crypto/message_decryption_cache.dart index 8bbfd2ba..aea9e3fe 100644 --- a/lib/core/crypto/message_decryption_cache.dart +++ b/lib/core/crypto/message_decryption_cache.dart @@ -7,75 +7,114 @@ import 'package:komet_crypto/komet_crypto.dart'; import '../../backend/modules/messages.dart'; import '../storage/app_database.dart'; import '../storage/chat_encryption_store.dart'; +import '../utils/cache_notifier.dart'; import 'chat_crypto_service.dart'; import 'e2ee_service.dart'; -// #***! расшифровалось, ключ не тот, либо копии текста на этом устройстве нет enum MessageDecryptionState { decrypted, wrongKey, unavailable } -// #***! результат по одному сообщению @immutable class MessageDecryption { final String? plaintext; final MessageDecryptionState state; - const MessageDecryption.decrypted(String this.plaintext) : state = MessageDecryptionState.decrypted; - const MessageDecryption.wrongKey() : plaintext = null, state = MessageDecryptionState.wrongKey; - const MessageDecryption.unavailable() : plaintext = null, state = MessageDecryptionState.unavailable; - bool get isDecrypted => state == MessageDecryptionState.decrypted; } -// #***! кэш расшифровок, при смене ключа сбрасывается целиком +typedef MessageDecryptor = + Future Function( + int accountId, + int chatId, + String messageId, + String cipherText, + ); +typedef _MessageKey = (int, int, String); + class MessageDecryptionCache { - MessageDecryptionCache._() { + MessageDecryptionCache._() : _decryptor = null { ChatEncryptionStore.instance.revision.addListener(clear); E2eeService.instance.revision.addListener(clear); } - + @visibleForTesting + MessageDecryptionCache.forTesting(MessageDecryptor decryptor) + : _decryptor = decryptor; static final MessageDecryptionCache instance = MessageDecryptionCache._(); - - // #***! тысяча последних, дальше вытесняем static const int _maxEntries = 1000; - - final LinkedHashMap> _entries = + final MessageDecryptor? _decryptor; + final LinkedHashMap<_MessageKey, CacheNotifier> _entries = LinkedHashMap(); - final Map> _inFlight = {}; - - // #***! пузырь подписывается сюда и перерисуется когда текст расшифруется - ValueListenable listenableFor(String messageId) => - _entryFor(messageId); + final Map<_MessageKey, String> _cipherTexts = {}; + final Map<_MessageKey, Future> _inFlight = {}; + final Map<_MessageKey, int> _versions = {}; + int _generation = 0; - ValueNotifier _entryFor(String messageId) => - _entries[messageId] ??= ValueNotifier(null); + ValueListenable listenableFor( + String messageId, { + required int accountId, + required int chatId, + }) => _entryFor((accountId, chatId, messageId)); + CacheNotifier _entryFor(_MessageKey key) => + _entries[key] ??= CacheNotifier(null); - void _evictStale(String keep) { - while (_entries.length > _maxEntries) { - final oldest = _entries.keys.first; - if (oldest == keep) break; - _entries.remove(oldest); + void _evictStale(_MessageKey keep) { + if (_entries.length <= _maxEntries) return; + for (final key in _entries.keys.toList()) { + if (_entries.length <= _maxEntries) break; + if (key == keep || + _entries[key]!.isObserved || + _inFlight.containsKey(key)) { + continue; + } + _entries.remove(key)!.dispose(); + _cipherTexts.remove(key); + _versions.remove(key); } } - // #***! известный текст кладём сразу, например своё только что отправленное - void seed(String messageId, String plaintext) { - _entryFor(messageId).value = MessageDecryption.decrypted(plaintext); + void seed( + String messageId, + String plaintext, { + required int accountId, + required int chatId, + String? cipherText, + }) { + final key = (accountId, chatId, messageId); + _versions[key] = (_versions[key] ?? 0) + 1; + if (cipherText == null) { + _cipherTexts.remove(key); + } else { + _cipherTexts[key] = cipherText; + } + _entryFor(key).value = MessageDecryption.decrypted(plaintext); + _evictStale(key); } - // #***! поменяли временный id на настоящий, переносим расшифровку - void adopt(String fromMessageId, String toMessageId) { - final value = _entries[fromMessageId]?.value; - if (value != null) _entryFor(toMessageId).value = value; + void adopt( + String fromMessageId, + String toMessageId, { + required int accountId, + required int chatId, + }) { + final from = (accountId, chatId, fromMessageId); + final value = _entries[from]?.value; + if (value?.isDecrypted == true) { + seed( + toMessageId, + value!.plaintext!, + accountId: accountId, + chatId: chatId, + cipherText: _cipherTexts[from], + ); + } } - // #***! _inFlight чтоб не расшифровывать одно сообщение дважды void request({ required int accountId, required int chatId, @@ -92,16 +131,16 @@ class MessageDecryptionCache { required String messageId, required String cipherText, }) async { - try { - await _begin(accountId, chatId, messageId, cipherText); - } catch (_) { - return const MessageDecryption.unavailable(); - } - return _entries[messageId]?.value; + await _begin(accountId, chatId, messageId, cipherText); + return _entries[(accountId, chatId, messageId)]?.value; } String? readableText(CachedMessage message) { - final decryption = _entries[message.id]?.value; + final key = (message.accountId, message.chatId, message.id); + if (_cipherTexts.containsKey(key) && _cipherTexts[key] != message.text) { + return null; + } + final decryption = _entries[key]?.value; if (decryption == null) return message.selectableText; return decryption.isDecrypted ? decryption.plaintext : null; } @@ -112,109 +151,121 @@ class MessageDecryptionCache { String messageId, String cipherText, ) { - if (cipherText.isEmpty) return null; - final e2ee = E2eeService.instance.isOn(accountId, chatId); - if (!e2ee && !ChatCryptoService.instance.isEnabled(accountId, chatId)) { + if (cipherText.isEmpty) { + final key = (accountId, chatId, messageId); + _versions[key] = (_versions[key] ?? 0) + 1; + _inFlight.remove(key); + _cipherTexts[key] = cipherText; + _entries[key]?.value = null; + return null; + } + if (_decryptor == null && + !E2eeService.instance.isOn(accountId, chatId) && + !ChatCryptoService.instance.isEnabled(accountId, chatId)) { return null; } - if (_entryFor(messageId).value != null) return null; - final running = _inFlight[messageId]; + final key = (accountId, chatId, messageId); + final entry = _entryFor(key); + if (_cipherTexts.containsKey(key) && _cipherTexts[key] != cipherText) { + _versions[key] = (_versions[key] ?? 0) + 1; + _inFlight.remove(key); + entry.value = null; + } + _cipherTexts[key] = cipherText; + if (entry.value != null) return null; + final running = _inFlight[key]; if (running != null) return running; - _evictStale(messageId); + final generation = _generation; + final version = _versions[key] ?? 0; late final Future job; job = - (e2ee - ? _resolveSealed(accountId, chatId, messageId, cipherText) - : _resolve(accountId, chatId, messageId, cipherText)) - .whenComplete(() { - if (identical(_inFlight[messageId], job)) { - _inFlight.remove(messageId); - } - }); - _inFlight[messageId] = job; + () async { + MessageDecryption? result; + try { + result = await (_decryptor ?? _decryptMessage)( + accountId, + chatId, + messageId, + cipherText, + ); + } catch (_) { + result = const MessageDecryption.unavailable(); + } + if (generation == _generation && + version == (_versions[key] ?? 0) && + identical(_entries[key], entry) && + _cipherTexts[key] == cipherText) { + entry.value = result; + } + }().whenComplete(() { + if (identical(_inFlight[key], job)) _inFlight.remove(key); + }); + _inFlight[key] = job; + _evictStale(key); return job; } - // #***! сквозное: открытый текст лежит в базе под локальным ключом - Future _resolveSealed( + Future _decryptMessage( int accountId, int chatId, String messageId, String cipherText, ) async { - final row = await AppDatabase.loadMessage(accountId, chatId, messageId); - if (row == null) return; - final flag = row['e2ee'] as int? ?? 0; - final sealed = row['text_sealed']; - if (flag == CachedMessage.e2eeText && sealed is Uint8List) { - final text = await E2eeService.instance.openText( - accountId, - chatId, - sealed, - ); - _entryFor(messageId).value = text == null - ? const MessageDecryption.unavailable() - : MessageDecryption.decrypted(text); - return; - } - if (flag == CachedMessage.e2eeFailed) { - _entryFor(messageId).value = const MessageDecryption.wrongKey(); - return; - } - if (flag == CachedMessage.e2eeFile) { - _entryFor(messageId).value = const MessageDecryption.decrypted(''); - return; - } - if (flag != CachedMessage.e2eeNone || !E2eeService.instance.available) { - return; - } - switch (KometCrypto.classifyText(cipherText)) { - case TextClass.session: - _entryFor(messageId).value = const MessageDecryption.unavailable(); - case TextClass.offer: - case TextClass.answer: - _entryFor(messageId).value = MessageDecryption.decrypted( - cipherText.split('\n').first, + if (E2eeService.instance.isOn(accountId, chatId)) { + final row = await AppDatabase.loadMessage(accountId, chatId, messageId); + if (row == null) return null; + final flag = row['e2ee'] as int? ?? 0; + final sealed = row['text_sealed']; + if (flag == CachedMessage.e2eeText && sealed is Uint8List) { + final text = await E2eeService.instance.openText( + accountId, + chatId, + sealed, ); - case TextClass.legacy: - if (ChatCryptoService.instance.isEnabled(accountId, chatId)) { - await _resolve(accountId, chatId, messageId, cipherText); - } - case TextClass.none: - break; + return text == null + ? const MessageDecryption.unavailable() + : MessageDecryption.decrypted(text); + } + if (flag == CachedMessage.e2eeFailed) { + return const MessageDecryption.wrongKey(); + } + if (flag == CachedMessage.e2eeFile) { + return const MessageDecryption.decrypted(''); + } + if (flag != CachedMessage.e2eeNone || !E2eeService.instance.available) { + return null; + } + switch (KometCrypto.classifyText(cipherText)) { + case TextClass.session: + return const MessageDecryption.unavailable(); + case TextClass.offer: + case TextClass.answer: + return MessageDecryption.decrypted(cipherText.split('\n').first); + case TextClass.legacy: + break; + case TextClass.none: + return null; + } } - } - - Future _resolve( - int accountId, - int chatId, - String messageId, - String cipherText, - ) async { final crypto = ChatCryptoService.instance; + if (!crypto.isEnabled(accountId, chatId)) return null; final result = await crypto.decrypt(accountId, chatId, cipherText); - if (result.isOk) { - _entryFor(messageId).value = MessageDecryption.decrypted(result.text!); - return; - } - // #***! ключа нет показываем как неверный ключ только если текст правда похож на шифр - switch (result.failure) { - case CryptoFailure.wrongKey: - _entryFor(messageId).value = const MessageDecryption.wrongKey(); - case CryptoFailure.noKey: - if (crypto.looksEncrypted(cipherText)) { - _entryFor(messageId).value = const MessageDecryption.wrongKey(); - } - case CryptoFailure.notEncrypted: - case CryptoFailure.malformed: - case CryptoFailure.unavailable: - case null: - break; + if (result.isOk) return MessageDecryption.decrypted(result.text!); + if (result.failure == CryptoFailure.wrongKey || + (result.failure == CryptoFailure.noKey && + crypto.looksEncrypted(cipherText))) { + return const MessageDecryption.wrongKey(); } + return null; } void clear() { - _entries.clear(); + _generation++; + _cipherTexts.clear(); _inFlight.clear(); + _versions.clear(); + for (final entry in _entries.values.toList()) { + entry.value = null; + } } } diff --git a/lib/core/crypto/noise_png.dart b/lib/core/crypto/noise_png.dart index 62f23323..5cbccd19 100644 --- a/lib/core/crypto/noise_png.dart +++ b/lib/core/crypto/noise_png.dart @@ -5,8 +5,9 @@ import 'dart:typed_data'; // #***! шифрованное фото едет как валидный RGB8 PNG из шума, пиксели = байты блоба const int _channels = 3; const int _maxDimension = 16384; +const int noisePngMaxDecodedBytes = 32 * 1024 * 1024; // #***! zlib раздувает без предела, распаковываем порциями по бюджету из IHDR -const int _inflateChunk = 1 << 16; +const int _inflateChunk = 1 << 10; const List _signature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]; final Uint32List _crcTable = _buildCrcTable(); @@ -23,10 +24,12 @@ Uint32List _buildCrcTable() { return table; } -int _crc32(List bytes) { +int _crc32(List bytes, [List tail = const []]) { var crc = 0xFFFFFFFF; - for (final byte in bytes) { - crc = _crcTable[(crc ^ byte) & 0xFF] ^ (crc >> 8); + for (final part in [bytes, tail]) { + for (final byte in part) { + crc = _crcTable[(crc ^ byte) & 0xFF] ^ (crc >> 8); + } } return crc ^ 0xFFFFFFFF; } @@ -36,7 +39,7 @@ void _writeChunk(BytesBuilder out, String type, List data) { out.add(_be32(data.length)); out.add(typeBytes); out.add(data); - out.add(_be32(_crc32([...typeBytes, ...data]))); + out.add(_be32(_crc32(typeBytes, data))); } Uint8List _be32(int value) => Uint8List(4) @@ -58,6 +61,10 @@ Uint8List? wrapNoisePng(Uint8List blob, {Random? random}) { if (width > _maxDimension) return null; final height = max(1, (pixels + width - 1) ~/ width); final stride = width * _channels; + if (height > _maxDimension || + (stride + 1) * height > noisePngMaxDecodedBytes) { + return null; + } final raw = Uint8List((stride + 1) * height); var source = 0; for (var row = 0; row < height; row++) { @@ -71,15 +78,7 @@ Uint8List? wrapNoisePng(Uint8List blob, {Random? random}) { } final out = BytesBuilder(copy: false); out.add(_signature); - _writeChunk(out, 'IHDR', [ - ..._be32(width), - ..._be32(height), - 8, - 2, - 0, - 0, - 0, - ]); + _writeChunk(out, 'IHDR', [..._be32(width), ..._be32(height), 8, 2, 0, 0, 0]); _writeChunk(out, 'IDAT', ZLibEncoder(level: 1).convert(raw)); _writeChunk(out, 'IEND', const []); return out.toBytes(); @@ -87,7 +86,10 @@ Uint8List? wrapNoisePng(Uint8List blob, {Random? random}) { // #***! обратно из PNG в байты, null если это не наш RGB8 без interlace Uint8List? unwrapNoisePng(Uint8List png) { - if (png.length < _signature.length + 8) return null; + if (png.length < _signature.length + 8 || + png.length > noisePngMaxDecodedBytes + 1024 * 1024) { + return null; + } for (var i = 0; i < _signature.length; i++) { if (png[i] != _signature[i]) return null; } @@ -111,6 +113,9 @@ Uint8List? unwrapNoisePng(Uint8List png) { if (depth != 8 || color != 2 || interlace != 0) return null; if (width <= 0 || height <= 0) return null; if (width > _maxDimension || height > _maxDimension) return null; + if ((width * _channels + 1) * height > noisePngMaxDecodedBytes) { + return null; + } } else if (type == 'IDAT') { idat.add(Uint8List.sublistView(png, dataStart, dataEnd)); } else if (type == 'IEND') { diff --git a/lib/core/crypto/outgoing_message_policy.dart b/lib/core/crypto/outgoing_message_policy.dart new file mode 100644 index 00000000..3b57b550 --- /dev/null +++ b/lib/core/crypto/outgoing_message_policy.dart @@ -0,0 +1,41 @@ +import '../storage/chat_encryption_store.dart'; +import 'e2ee_service.dart'; + +class UnencryptedSendException implements Exception { + const UnencryptedSendException(); + @override + String toString() => + 'Этот способ отправки не поддерживает шифрование. Откройте чат и отправьте сообщение из него.'; +} + +class OutgoingMessagePolicy { + OutgoingMessagePolicy._(); + + static const List _encryptionControlPrefixes = [ + kE2eeOfferPrefix, + kE2eeAnswerPrefix, + kE2eeOfferDonePrefix, + ]; + + static bool requiresEncryption(int accountId, int chatId) => + ChatEncryptionStore.instance.isEnabled(accountId, chatId) || + E2eeService.instance.isActive(accountId, chatId); + + static bool isEncryptionControl(String text) => + _encryptionControlPrefixes.any(text.startsWith); + + static Future load(int accountId) async { + await ChatEncryptionStore.instance.load(); + await E2eeService.instance.ensureLoaded(accountId); + } + + static void requireSupported( + int accountId, + int chatId, { + bool encryptedPayload = false, + }) { + if (!encryptedPayload && requiresEncryption(accountId, chatId)) { + throw const UnencryptedSendException(); + } + } +} diff --git a/lib/core/media/gallery_source.dart b/lib/core/media/gallery_source.dart index f0acba2a..25b363aa 100644 --- a/lib/core/media/gallery_source.dart +++ b/lib/core/media/gallery_source.dart @@ -1,9 +1,9 @@ import 'dart:async'; import 'dart:io'; -import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:photo_manager/photo_manager.dart'; +import 'package:flutter/foundation.dart'; import 'desktop_video_probe.dart'; @@ -125,6 +125,15 @@ abstract class GallerySource { Future manageAccess(); // #***! альбом все спрашиваем один раз, дальше листаем диапазонами + @visibleForTesting + factory GallerySource.desktopForTesting( + List directories, { + Duration refreshInterval = const Duration(seconds: 30), + }) => _DesktopGallerySource( + directories: directories, + refreshInterval: refreshInterval, + ); + factory GallerySource.create() { if (Platform.isAndroid || Platform.isIOS) { return _PhotoManagerSource(); @@ -354,6 +363,12 @@ bool isImagePath(String path) => // #***! на десктопе галереи нет, сканируем стандартные папки class _DesktopGallerySource implements GallerySource { + _DesktopGallerySource({ + this.directories, + this.refreshInterval = const Duration(seconds: 30), + }); + final List? directories; + final Duration refreshInterval; @override Future ensurePermission() async => GalleryPermission.granted; @@ -372,16 +387,43 @@ class _DesktopGallerySource implements GallerySource { void setSort(GallerySort sort) { _sort = sort; _all = const []; + _scannedAt = null; } List<_FileGalleryItem> _all = const []; + Future? _loading; + DateTime? _scannedAt; + + Future _ensureIndex(int offset) async { + while (true) { + final scannedAt = _scannedAt; + if (scannedAt != null && + (offset != 0 || + DateTime.now().difference(scannedAt) < refreshInterval)) { + return; + } + await (_loading ??= _rescan().whenComplete(() => _loading = null)); + if (_scannedAt != null) return; + } + } + + Future _rescan() async { + final sort = _sort; + final paths = await compute(_scanDesktopGallery, ( + directories: _candidateDirs().map((dir) => dir.path).toList(), + sort: sort, + )); + if (!identical(sort, _sort)) return; + _all = paths.map((path) => _FileGalleryItem(File(path))).toList(); + _scannedAt = DateTime.now(); + } @override Future load({ int offset = 0, int limit = GallerySource.pageSize, }) async { - if (offset == 0 || _all.isEmpty) _all = _scan(); + await _ensureIndex(offset); if (offset >= _all.length) return GalleryPage.empty; final end = offset + limit < _all.length ? offset + limit : _all.length; final items = _all.sublist(offset, end); @@ -401,29 +443,6 @@ class _DesktopGallerySource implements GallerySource { return GalleryPage(items: items, hasMore: end < _all.length); } - List<_FileGalleryItem> _scan() { - final entries = <({File file, DateTime modified})>[]; - for (final dir in _candidateDirs()) { - if (!dir.existsSync()) continue; - try { - for (final entity in dir.listSync(followLinks: false)) { - if (entity is! File || !_isMedia(entity.path)) continue; - entries.add((file: entity, modified: entity.statSync().modified)); - } - } catch (_) {} - } - entries.sort((a, b) { - final order = switch (_sort.field) { - GallerySortField.date => a.modified.compareTo(b.modified), - GallerySortField.name => _baseName( - a.file.path, - ).toLowerCase().compareTo(_baseName(b.file.path).toLowerCase()), - }; - return _sort.ascending ? order : -order; - }); - return entries.map((e) => _FileGalleryItem(e.file)).toList(); - } - @override Future openSettings() async {} @@ -431,6 +450,7 @@ class _DesktopGallerySource implements GallerySource { Future manageAccess() async {} List _candidateDirs() { + if (directories != null) return directories!; final home = Platform.environment['HOME'] ?? Platform.environment['USERPROFILE']; if (home == null || home.isEmpty) return const []; @@ -443,12 +463,45 @@ class _DesktopGallerySource implements GallerySource { Directory('$home/Movies'), ]; } +} - bool _isMedia(String path) { - final ext = _fileExtension(path); - return kGalleryImageExtensions.contains(ext) || - kGalleryVideoExtensions.contains(ext); +List _scanDesktopGallery( + ({List directories, GallerySort sort}) request, +) { + final entries = <({String path, DateTime modified})>[]; + for (final path in request.directories) { + try { + final directory = Directory(path); + if (!directory.existsSync()) continue; + for (final entity in directory.listSync(followLinks: false)) { + if (entity is! File || + (!isImagePath(entity.path) && !isVideoPath(entity.path))) { + continue; + } + try { + entries.add(( + path: entity.path, + modified: entity.statSync().modified, + )); + } on FileSystemException { + continue; + } + } + } on FileSystemException { + continue; + } } + final sort = request.sort; + entries.sort((a, b) { + final order = switch (sort.field) { + GallerySortField.date => a.modified.compareTo(b.modified), + GallerySortField.name => _baseName( + a.path, + ).toLowerCase().compareTo(_baseName(b.path).toLowerCase()), + }; + return sort.ascending ? order : -order; + }); + return entries.map((entry) => entry.path).toList(); } // #***! обёртка над обычным файлом diff --git a/lib/core/plugins/plugin_host.dart b/lib/core/plugins/plugin_host.dart index db12f85b..1fcaf890 100644 --- a/lib/core/plugins/plugin_host.dart +++ b/lib/core/plugins/plugin_host.dart @@ -1,6 +1,7 @@ import 'dart:typed_data'; abstract interface class PluginHost { + int? get accountId; String get args; Map get arguments; Map? get replyMessage; diff --git a/lib/core/plugins/plugin_media_downloader.dart b/lib/core/plugins/plugin_media_downloader.dart index 75ea50c9..f51762c1 100644 --- a/lib/core/plugins/plugin_media_downloader.dart +++ b/lib/core/plugins/plugin_media_downloader.dart @@ -2,12 +2,13 @@ import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; +import 'plugin_network_policy.dart'; + class PluginMediaDownloader { PluginMediaDownloader._(); static const int _attempts = 3; static const int _maxRedirects = 5; - static const Duration _connectionTimeout = Duration(seconds: 10); static const Duration _responseTimeout = Duration(seconds: 20); static Future download( @@ -47,12 +48,14 @@ class PluginMediaDownloader { required int maxBytes, required bool allowHttpForTesting, }) async { - final client = HttpClient()..connectionTimeout = _connectionTimeout; + final client = PluginNetworkPolicy.createClient( + allowHttpForTesting: allowHttpForTesting, + ); try { var uri = initialUri; for (var redirect = 0; redirect <= _maxRedirects; redirect++) { _validateUri(uri, allowHttpForTesting: allowHttpForTesting); - final request = await client.getUrl(uri); + final request = await client.getUrl(uri).timeout(_responseTimeout); request ..followRedirects = false ..persistentConnection = false; @@ -66,7 +69,7 @@ class PluginMediaDownloader { final response = await request.close().timeout(_responseTimeout); if (response.isRedirect) { final location = response.headers.value(HttpHeaders.locationHeader); - await response.drain(); + await response.drain().timeout(_responseTimeout); if (location == null || redirect == _maxRedirects) { throw HttpException('Некорректный HTTP redirect', uri: uri); } @@ -74,20 +77,20 @@ class PluginMediaDownloader { continue; } if (response.statusCode < 200 || response.statusCode >= 300) { - await response.drain(); + await response.drain().timeout(_responseTimeout); throw HttpException('HTTP ${response.statusCode}', uri: uri); } final contentLength = response.contentLength; if (contentLength > maxBytes) { - await response.drain(); + await response.drain().timeout(_responseTimeout); throw const FormatException('Файл слишком большой'); } final bytes = []; await for (final chunk in response.timeout(_responseTimeout)) { - bytes.addAll(chunk); - if (bytes.length > maxBytes) { + if (bytes.length + chunk.length > maxBytes) { throw const FormatException('Файл слишком большой'); } + bytes.addAll(chunk); } if (contentLength >= 0 && bytes.length != contentLength) { throw HttpException( @@ -103,36 +106,9 @@ class PluginMediaDownloader { } } - static void _validateUri(Uri uri, {required bool allowHttpForTesting}) { - final validScheme = - uri.scheme == 'https' || (allowHttpForTesting && uri.scheme == 'http'); - if (!validScheme || uri.host.isEmpty) { - throw const FormatException('Разрешены только корректные HTTPS URL'); - } - if (allowHttpForTesting) return; - final host = uri.host.toLowerCase(); - if (host == 'localhost' || host.endsWith('.localhost')) { - throw const FormatException('Локальные адреса запрещены'); - } - final address = InternetAddress.tryParse(host); - if (address != null && _isPrivateAddress(address)) { - throw const FormatException('Локальные адреса запрещены'); - } - } - - static bool _isPrivateAddress(InternetAddress address) { - if (address.isLoopback || address.isLinkLocal) return true; - final bytes = address.rawAddress; - if (address.type == InternetAddressType.IPv4) { - return bytes[0] == 10 || - bytes[0] == 127 || - bytes[0] == 0 || - (bytes[0] == 169 && bytes[1] == 254) || - (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31) || - (bytes[0] == 192 && bytes[1] == 168); - } - return bytes.every((byte) => byte == 0) || - (bytes[0] & 0xfe) == 0xfc || - (bytes[0] == 0xfe && (bytes[1] & 0xc0) == 0x80); - } + static void _validateUri(Uri uri, {required bool allowHttpForTesting}) => + PluginNetworkPolicy.validateUri( + uri, + allowHttpForTesting: allowHttpForTesting, + ); } diff --git a/lib/core/plugins/plugin_network_policy.dart b/lib/core/plugins/plugin_network_policy.dart new file mode 100644 index 00000000..acdf1e0e --- /dev/null +++ b/lib/core/plugins/plugin_network_policy.dart @@ -0,0 +1,119 @@ +import 'dart:io'; + +class PluginNetworkPolicy { + PluginNetworkPolicy._(); + + static Uri httpsUri(String source) { + final uri = Uri.tryParse(source); + if (uri == null) throw const FormatException('Некорректный URL'); + validateUri(uri); + return uri; + } + + static void validateUri(Uri uri, {bool allowHttpForTesting = false}) { + if ((uri.scheme != 'https' && + !(allowHttpForTesting && uri.scheme == 'http')) || + uri.host.isEmpty || + uri.userInfo.isNotEmpty) { + throw const FormatException('Разрешены только корректные HTTPS URL'); + } + if (allowHttpForTesting) return; + final host = uri.host.toLowerCase(); + if (host == 'localhost' || host.endsWith('.localhost')) { + throw const FormatException('Локальные адреса запрещены'); + } + final literal = InternetAddress.tryParse(host); + if (literal != null) validateAddresses([literal]); + } + + static void validateAddresses(List addresses) { + if (addresses.isEmpty || addresses.any(isPrivateAddress)) { + throw const FormatException('Локальные адреса запрещены'); + } + } + + static bool isPrivateAddress(InternetAddress address) { + if (address.isLoopback || address.isLinkLocal) return true; + var bytes = address.rawAddress; + if (bytes.length == 16 && + bytes.take(10).every((b) => b == 0) && + bytes[10] == 255 && + bytes[11] == 255) { + bytes = bytes.sublist(12); + } + if (bytes.length == 4) { + return bytes[0] == 0 || + bytes[0] == 10 || + bytes[0] == 127 || + (bytes[0] == 169 && bytes[1] == 254) || + (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31) || + (bytes[0] == 192 && bytes[1] == 168) || + (bytes[0] == 198 && (bytes[1] == 18 || bytes[1] == 19)) || + (bytes[0] == 192 && bytes[1] == 0 && bytes[2] == 0) || + (bytes[0] == 100 && bytes[1] >= 64 && bytes[1] <= 127) || + bytes[0] >= 224; + } + return (bytes[0] & 0xe0) != 0x20 || + (bytes[0] == 0x20 && bytes[1] == 0x02) || + (bytes[0] == 0x20 && + bytes[1] == 0x01 && + bytes[2] == 0 && + bytes[3] == 0) || + bytes.every((b) => b == 0) || + (bytes[0] & 0xfe) == 0xfc || + (bytes[0] == 0xfe && (bytes[1] & 0xc0) == 0x80) || + bytes[0] == 0xff; + } + + static HttpClient createClient({ + bool allowHttpForTesting = false, + Future> Function(String host)? lookup, + }) { + final client = HttpClient() + ..connectionTimeout = const Duration(seconds: 10); + client.findProxy = (_) => 'DIRECT'; + client.connectionFactory = (uri, proxyHost, proxyPort) async { + validateUri(uri, allowHttpForTesting: allowHttpForTesting); + if (proxyHost != null) { + throw const FormatException('Proxy is not supported'); + } + final addresses = await (lookup ?? InternetAddress.lookup)( + uri.host, + ).timeout(const Duration(seconds: 10)); + if (!allowHttpForTesting) validateAddresses(addresses); + if (addresses.isEmpty) throw const SocketException('No address for host'); + ConnectionTask? attempt; + var cancelled = false; + Future connect() async { + Object? lastError; + for (final address in addresses) { + if (cancelled) throw const SocketException('Connection cancelled'); + try { + final task = await Socket.startConnect(address, uri.port); + attempt = task; + if (cancelled) { + task.cancel(); + throw const SocketException('Connection cancelled'); + } + return await task.socket.timeout( + const Duration(seconds: 10), + onTimeout: () { + task.cancel(); + throw const SocketException('Connection timed out'); + }, + ); + } on SocketException catch (error) { + lastError = error; + } + } + throw SocketException('Could not connect to host: $lastError'); + } + + return ConnectionTask.fromSocket(connect(), () { + cancelled = true; + attempt?.cancel(); + }); + }; + return client; + } +} diff --git a/lib/core/plugins/plugin_runtime.dart b/lib/core/plugins/plugin_runtime.dart index 5e64f429..c17e1bc5 100644 --- a/lib/core/plugins/plugin_runtime.dart +++ b/lib/core/plugins/plugin_runtime.dart @@ -9,8 +9,10 @@ import 'package:path/path.dart' as p; import 'plugin_host.dart'; import 'plugin_manifest.dart'; import 'plugin_media_downloader.dart'; +import 'plugin_network_policy.dart'; import 'plugin_models.dart'; import 'plugin_storage.dart'; +import '../storage/token_storage.dart'; class PluginRuntime { PluginRuntime._(); @@ -25,7 +27,9 @@ class PluginRuntime { ) async { await initialize(); final plugin = command.plugin; - final storage = PluginStorage(plugin.manifest.id); + final accountId = host.accountId; + if (accountId == null) throw StateError('Plugin account is unavailable'); + final storage = PluginStorage(plugin.manifest.id, accountId: accountId); final sentMessageIds = {}; final engine = await JsEngine.create( builtins: JsBuiltinOptions.none(), @@ -99,6 +103,7 @@ class PluginRuntime { JsValue value, ) async { try { + await _requireCurrentHost(host); final request = value.value; if (request is! Map) { throw const FormatException('Некорректный вызов API'); @@ -152,6 +157,15 @@ class PluginRuntime { } } + static Future _requireCurrentHost(PluginHost host) async { + if (!host.isActive || + host.accountId == null || + await TokenStorage.getActiveAccountId() != host.accountId || + !host.isActive) { + throw StateError('Контекст аккаунта изменился'); + } + } + static Future _sendText( PluginDescriptor plugin, PluginHost host, @@ -201,6 +215,7 @@ class PluginRuntime { options, maxBytes: 15 * 1024 * 1024, ); + await _requireCurrentHost(host); await host.sendPhoto( bytes, filename: _filename(options, 'plugin_photo.jpg'), @@ -220,6 +235,7 @@ class PluginRuntime { options, maxBytes: 25 * 1024 * 1024, ); + await _requireCurrentHost(host); await host.sendFile(bytes, filename: _filename(options, 'plugin_file.bin')); } @@ -237,10 +253,11 @@ class PluginRuntime { if (!const {'GET', 'POST', 'PUT', 'PATCH', 'DELETE'}.contains(method)) { throw const FormatException('Неподдерживаемый HTTP-метод'); } - final client = HttpClient() - ..connectionTimeout = const Duration(seconds: 10); + final client = PluginNetworkPolicy.createClient(); try { - final request = await client.openUrl(method, uri); + final request = await client + .openUrl(method, uri) + .timeout(const Duration(seconds: 15)); request.followRedirects = false; final rawHeaders = options['headers']; if (rawHeaders is Map) { @@ -256,7 +273,7 @@ class PluginRuntime { const Duration(seconds: 15), ); if (response.isRedirect) { - await response.drain(); + await response.drain().timeout(const Duration(seconds: 15)); throw const HttpException('HTTP redirects are disabled for plugins'); } final bytes = await _readLimited(response, 1024 * 1024); @@ -302,45 +319,15 @@ class PluginRuntime { ) async { final bytes = []; await for (final chunk in response.timeout(const Duration(seconds: 20))) { - bytes.addAll(chunk); - if (bytes.length > maxBytes) { + if (bytes.length + chunk.length > maxBytes) { throw const FormatException('Ответ слишком большой'); } + bytes.addAll(chunk); } return Uint8List.fromList(bytes); } - static Uri _httpsUri(String source) { - final uri = Uri.tryParse(source); - if (uri == null || uri.scheme != 'https' || uri.host.isEmpty) { - throw const FormatException('Разрешены только корректные HTTPS URL'); - } - final host = uri.host.toLowerCase(); - if (host == 'localhost' || host.endsWith('.localhost')) { - throw const FormatException('Локальные адреса запрещены'); - } - final address = InternetAddress.tryParse(host); - if (address != null && _isPrivateAddress(address)) { - throw const FormatException('Локальные адреса запрещены'); - } - return uri; - } - - static bool _isPrivateAddress(InternetAddress address) { - if (address.isLoopback || address.isLinkLocal) return true; - final bytes = address.rawAddress; - if (address.type == InternetAddressType.IPv4) { - return bytes[0] == 10 || - bytes[0] == 127 || - bytes[0] == 0 || - (bytes[0] == 169 && bytes[1] == 254) || - (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31) || - (bytes[0] == 192 && bytes[1] == 168); - } - return bytes.every((byte) => byte == 0) || - (bytes[0] & 0xfe) == 0xfc || - (bytes[0] == 0xfe && (bytes[1] & 0xc0) == 0x80); - } + static Uri _httpsUri(String source) => PluginNetworkPolicy.httpsUri(source); static bool _forbiddenHeader(String name) { final lower = name.toLowerCase(); diff --git a/lib/core/plugins/plugin_storage.dart b/lib/core/plugins/plugin_storage.dart index 9cd0b67a..2b018ae9 100644 --- a/lib/core/plugins/plugin_storage.dart +++ b/lib/core/plugins/plugin_storage.dart @@ -1,13 +1,24 @@ +import 'dart:async'; import 'dart:convert'; import 'package:shared_preferences/shared_preferences.dart'; class PluginStorage { - PluginStorage(this.pluginId); + PluginStorage(this.pluginId, {this.accountId}) { + _generation = _generations.putIfAbsent(_key, () => 0); + } final String pluginId; + final int? accountId; + static final Map> _pending = {}; + static final Map _generations = {}; + static final Set _erasingAccounts = {}; + static final Set _erasingPlugins = {}; + late final int _generation; - String get _key => 'plugin_storage_v1_$pluginId'; + String get _key => accountId == null + ? 'plugin_storage_v1_$pluginId' + : 'plugin_storage_v2_${accountId}_$pluginId'; Future> _readAll() async { final prefs = await SharedPreferences.getInstance(); @@ -21,28 +32,98 @@ class PluginStorage { } } - Future get(String key) async => (await _readAll())[key]; + Future _serialized(Future Function() action) { + final next = (_pending[_key] ?? Future.value()).then((_) { + if (_generation != _generations[_key] || + _erasingAccounts.contains(accountId) || + _erasingPlugins.contains(pluginId)) { + throw StateError('Plugin storage context was invalidated'); + } + return action(); + }); + final settled = next.then((_) {}, onError: (Object error) {}); + _pending[_key] = settled; + unawaited( + settled.whenComplete(() { + if (identical(_pending[_key], settled)) _pending.remove(_key); + }), + ); + return next; + } + + Future get(String key) => + _serialized(() async => (await _readAll())[key]); - Future set(String key, Object? value) async { + Future set(String key, Object? value) => _serialized(() async { final all = await _readAll(); all[key] = value; final encoded = jsonEncode(all); - if (encoded.length > 65536) { + if (utf8.encode(encoded).length > 65536) { throw const FormatException('Хранилище плагина переполнено'); } final prefs = await SharedPreferences.getInstance(); await prefs.setString(_key, encoded); - } + }); - Future remove(String key) async { + Future remove(String key) => _serialized(() async { final all = await _readAll(); - if (all.remove(key) == null) return; + if (!all.containsKey(key)) return; + all.remove(key); final prefs = await SharedPreferences.getInstance(); await prefs.setString(_key, jsonEncode(all)); - } + }); - Future clear() async { + Future clear() => _serialized(() async { final prefs = await SharedPreferences.getInstance(); await prefs.remove(_key); + }); + static Future _eraseKey(String key) async { + _generations[key] = (_generations[key] ?? 0) + 1; + final next = (_pending[key] ?? Future.value()).then((_) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(key); + }); + final settled = next.then( + (_) {}, + onError: (Object _, StackTrace _) {}, + ); + _pending[key] = settled; + try { + await next; + } finally { + if (identical(_pending[key], settled)) _pending.remove(key); + } + } + + static Future eraseAccount(int accountId) async { + _erasingAccounts.add(accountId); + try { + final prefs = await SharedPreferences.getInstance(); + final prefix = 'plugin_storage_v2_${accountId}_'; + final keys = {...prefs.getKeys(), ..._generations.keys, ..._pending.keys}; + for (final key in keys.where((key) => key.startsWith(prefix))) { + await _eraseKey(key); + } + } finally { + _erasingAccounts.remove(accountId); + } + } + + static Future erasePlugin(String pluginId) async { + _erasingPlugins.add(pluginId); + try { + final prefs = await SharedPreferences.getInstance(); + final keys = {...prefs.getKeys(), ..._generations.keys, ..._pending.keys}; + for (final key in keys.where( + (key) => + key == 'plugin_storage_v1_$pluginId' || + (key.startsWith('plugin_storage_v2_') && + key.endsWith('_$pluginId')), + )) { + await _eraseKey(key); + } + } finally { + _erasingPlugins.remove(pluginId); + } } } diff --git a/lib/core/plugins/plugin_store.dart b/lib/core/plugins/plugin_store.dart index 05a07ee4..5b725875 100644 --- a/lib/core/plugins/plugin_store.dart +++ b/lib/core/plugins/plugin_store.dart @@ -272,7 +272,7 @@ class PluginStore { if (await directory.exists()) await directory.delete(recursive: true); } _state.remove(pluginId); - await PluginStorage(pluginId).clear(); + await PluginStorage.erasePlugin(pluginId); await _persistState(); await refresh(); } diff --git a/lib/core/share/native_share_account_channel.dart b/lib/core/share/native_share_account_channel.dart index 8a5b22a1..b8dc3924 100644 --- a/lib/core/share/native_share_account_channel.dart +++ b/lib/core/share/native_share_account_channel.dart @@ -36,6 +36,7 @@ class NativeShareAccountChannel { } Future publish(ShareAccountSnapshot snapshot, int generation) { + _generations.putIfAbsent(snapshot.accountId, () => 0); if (!enabled) return Future.value(); return _enqueue(() async { if (this.generation(snapshot.accountId) != generation) return; @@ -43,6 +44,26 @@ class NativeShareAccountChannel { }); } + Future invalidateAll() { + for (final accountId in _generations.keys.toList()) { + _generations[accountId] = generation(accountId) + 1; + } + if (!enabled) return Future.value(); + return _enqueue( + () => channel.invokeMethod('invalidateShareAccounts'), + ); + } + + Future invalidate(int accountId) { + _generations[accountId] = generation(accountId) + 1; + if (!enabled) return Future.value(); + return _enqueue(() async { + await channel.invokeMethod('invalidateShareAccount', { + 'accountId': accountId.toString(), + }); + }); + } + Future remove(int accountId) { _generations[accountId] = generation(accountId) + 1; if (!enabled) return Future.value(); diff --git a/lib/core/share/native_share_account_sync.dart b/lib/core/share/native_share_account_sync.dart index 001830c0..814871e9 100644 --- a/lib/core/share/native_share_account_sync.dart +++ b/lib/core/share/native_share_account_sync.dart @@ -10,6 +10,7 @@ import '../../backend/modules/contacts.dart'; import '../../backend/modules/messages.dart'; import '../config/komet_settings.dart'; import '../crypto/e2ee_service.dart'; +import '../crypto/outgoing_message_policy.dart'; import '../storage/app_database.dart'; import '../storage/chat_encryption_store.dart'; import '../storage/token_storage.dart'; @@ -54,7 +55,16 @@ class NativeShareAccountSync with WidgetsBindingObserver { }); } - void _refreshPrivacy() => unawaited(refresh()); + void _refreshPrivacy() { + unawaited( + NativeShareAccountChannel.instance + .invalidateAll() + .then((_) => refresh()) + .catchError((Object error) { + logger.w('Share privacy invalidation failed: ${error.runtimeType}'); + }), + ); + } @override void didChangeAppLifecycleState(AppLifecycleState state) { @@ -137,11 +147,10 @@ class NativeShareAccountSync with WidgetsBindingObserver { } } final disabledReason = shareRecipientDisabledReason( - legacyEncryptionEnabled: ChatEncryptionStore.instance.isEnabled( + requiresEncryption: OutgoingMessagePolicy.requiresEncryption( accountId, chat.id, ), - e2eePhase: E2eeService.instance.phaseOf(accountId, chat.id), isChannel: chat.type == 'CHANNEL', canPostToChannel: chat.iAmAdmin(accountId), ); diff --git a/lib/core/share/share_recipient_eligibility.dart b/lib/core/share/share_recipient_eligibility.dart index aaa5de65..c1686940 100644 --- a/lib/core/share/share_recipient_eligibility.dart +++ b/lib/core/share/share_recipient_eligibility.dart @@ -1,12 +1,9 @@ -import '../crypto/e2ee_service.dart'; - String? shareRecipientDisabledReason({ - required bool legacyEncryptionEnabled, - required E2eePhase e2eePhase, + required bool requiresEncryption, required bool isChannel, required bool canPostToChannel, }) { - if (legacyEncryptionEnabled || e2eePhase != E2eePhase.none) { + if (requiresEncryption) { return 'Зашифрованный чат — отправляйте из Komet'; } if (isChannel && !canPostToChannel) { diff --git a/lib/core/storage/chat_encryption_store.dart b/lib/core/storage/chat_encryption_store.dart index cc54d456..15b1b23d 100644 --- a/lib/core/storage/chat_encryption_store.dart +++ b/lib/core/storage/chat_encryption_store.dart @@ -28,11 +28,30 @@ class ChatEncryptionStore extends PerChatJsonStore { Future writeKey(int accountId, int chatId, String key) async { if (accountId == 0) return; await TokenStorage.writeSecure(_secureKey(accountId, chatId), key); + revision.value++; } Future deleteKey(int accountId, int chatId) async { if (accountId == 0) return; await TokenStorage.deleteSecure(_secureKey(accountId, chatId)); + revision.value++; + } + + Future eraseAccount(int accountId) async { + await load(); + final chats = allEntries + .where((entry) => entry.key.startsWith('$accountId/')) + .map((entry) => int.parse(entry.key.split('/').last)) + .toList(); + for (final chatId in chats) { + await setEnabled(accountId, chatId, false); + } + for (final key in await TokenStorage.secureKeysWithPrefix( + '${_keyPrefix}_${accountId}_', + )) { + await TokenStorage.deleteSecure(key); + } + revision.value++; } String _secureKey(int accountId, int chatId) => diff --git a/lib/core/storage/temporary_password_recovery.dart b/lib/core/storage/temporary_password_recovery.dart new file mode 100644 index 00000000..591cb703 --- /dev/null +++ b/lib/core/storage/temporary_password_recovery.dart @@ -0,0 +1,87 @@ +import 'dart:convert'; +import 'dart:async'; +import 'dart:math'; + +import 'token_storage.dart'; + +class TemporaryPasswordRecovery { + const TemporaryPasswordRecovery({ + required this.accountId, + required this.operationId, + required this.password, + }); + + static final Map> _pending = {}; + + static Future _serialized(int accountId, Future Function() action) { + final next = (_pending[accountId] ?? Future.value()).then( + (_) => action(), + ); + final settled = next.then( + (_) {}, + onError: (Object _, StackTrace _) {}, + ); + _pending[accountId] = settled; + unawaited( + settled.whenComplete(() { + if (identical(_pending[accountId], settled)) _pending.remove(accountId); + }), + ); + return next; + } + + final int accountId; + final String operationId; + final String password; + + static String _key(int accountId) => 'temporary_2fa_recovery_$accountId'; + + static Future read(int accountId) async { + final raw = await TokenStorage.readSecure(_key(accountId)); + if (raw == null) return null; + final data = jsonDecode(raw) as Map; + if (data['accountId'] != accountId) { + throw const FormatException('Invalid recovery account'); + } + return TemporaryPasswordRecovery( + accountId: accountId, + operationId: data['operationId'] as String, + password: data['password'] as String, + ); + } + + static Future save( + int accountId, + String password, + ) => _serialized(accountId, () async { + if (await read(accountId) != null) { + throw StateError( + 'Сначала восстановите прежний временный пароль в настройках безопасности', + ); + } + final random = Random.secure(); + final operationId = base64UrlEncode( + List.generate(24, (_) => random.nextInt(256)), + ); + final recovery = TemporaryPasswordRecovery( + accountId: accountId, + operationId: operationId, + password: password, + ); + await TokenStorage.writeSecure( + _key(accountId), + jsonEncode({ + 'accountId': accountId, + 'operationId': operationId, + 'password': password, + }), + ); + return recovery; + }); + + Future clearAfterRollback() => _serialized(accountId, () async { + if ((await read(accountId))?.operationId == operationId) { + await TokenStorage.deleteSecure(_key(accountId)); + } + }); +} diff --git a/lib/core/storage/token_storage.dart b/lib/core/storage/token_storage.dart index 25fcb661..b713e8cf 100644 --- a/lib/core/storage/token_storage.dart +++ b/lib/core/storage/token_storage.dart @@ -7,6 +7,8 @@ import 'account_token_store.dart'; // #***! токены и активный аккаунт class TokenStorage { + static int _accountEpoch = 0; + static int get accountEpoch => _accountEpoch; static const _tokenPrefix = 'auth_token_'; static const _activeAccountKey = 'active_account_id'; @@ -98,11 +100,13 @@ class TokenStorage { // #***! активный аккаунт в обычных prefs, это не секрет static Future setActiveAccount(int accountId) async { + _accountEpoch++; final prefs = await SharedPreferences.getInstance(); await prefs.setString(_activeAccountKey, accountId.toString()); } static Future clearActiveAccount() async { + _accountEpoch++; final prefs = await SharedPreferences.getInstance(); await prefs.remove(_activeAccountKey); } @@ -120,6 +124,7 @@ class TokenStorage { } static Future deleteAccount(int accountId) async { + _accountEpoch++; await deleteToken(accountId); final activeId = await getActiveAccountId(); if (activeId == accountId) { diff --git a/lib/core/storage/webapp_storage.dart b/lib/core/storage/webapp_storage.dart index 52f0ce88..ac5da609 100644 --- a/lib/core/storage/webapp_storage.dart +++ b/lib/core/storage/webapp_storage.dart @@ -5,6 +5,17 @@ import 'token_storage.dart'; enum WebAppStorageBackend { device, secure } class WebAppStorage { + static Future eraseAccount(int accountId) async { + for (final prefix in [ + 'webapp_ss_${accountId}_', + 'webapp_bio_${accountId}_', + ]) { + for (final key in await TokenStorage.secureKeysWithPrefix(prefix)) { + await TokenStorage.deleteSecure(key); + } + } + } + // #***! лимиты ключей на бота чтоб не забил всё static const int deviceKeyLimit = 512; static const int secureKeyLimit = 128; diff --git a/lib/core/transport/wire_debug_log.dart b/lib/core/transport/wire_debug_log.dart index 15c932f1..8bed2868 100644 --- a/lib/core/transport/wire_debug_log.dart +++ b/lib/core/transport/wire_debug_log.dart @@ -3,6 +3,7 @@ import 'package:kolibri/kolibri.dart' show WireLogEvent; import '../config/launch_flags.dart'; import '../protocol/opcode_map.dart'; import '../utils/logger.dart'; +import '../utils/log_redact.dart'; class WireDebugLog { WireDebugLog._(); @@ -34,12 +35,5 @@ class WireDebugLog { return '$head $payload'; } - static final RegExp _passwordField = RegExp( - r'"(\w*[Pp]assword)"\s*:\s*"(?:[^"\\]|\\.)*"', - ); - - static String maskPasswords(String json) => json.replaceAllMapped( - _passwordField, - (match) => '"${match[1]}":"***"', - ); + static String maskPasswords(String json) => redactJsonForLog(json); } diff --git a/lib/core/utils/cache_notifier.dart b/lib/core/utils/cache_notifier.dart new file mode 100644 index 00000000..a95ee8b7 --- /dev/null +++ b/lib/core/utils/cache_notifier.dart @@ -0,0 +1,7 @@ +import 'package:flutter/foundation.dart'; + +class CacheNotifier extends ValueNotifier { + CacheNotifier(super.value); + + bool get isObserved => hasListeners; +} diff --git a/lib/core/utils/debug_session_log.dart b/lib/core/utils/debug_session_log.dart index 1f0e4f64..066cec60 100644 --- a/lib/core/utils/debug_session_log.dart +++ b/lib/core/utils/debug_session_log.dart @@ -265,8 +265,19 @@ class DebugSessionLog { } // #***! чистим ANSI цвета иначе в файле мусор + static String _redactWireLine(String line) { + final start = line.indexOf('WIRE ['); + if (start < 0) return line; + final match = RegExp(r'seq=\d+\s+').firstMatch(line.substring(start)); + if (match == null) return '${line.substring(0, start)}WIRE