A cross platform Audiobookshelf client for Android and iOS
Dart
Catch AA-disconnect phantom clicks and surface SSO error details
Barnabas7603f25995e1
diff --git a/lib/screens/login_screen.dart b/lib/screens/login_screen.dartindex 8ca8aae2..093cb40a 100644--- a/lib/screens/login_screen.dart+++ b/lib/screens/login_screen.dart@@ -287,9 +287,17 @@ class _LoginScreenState extends State<LoginScreen>final oidc = OidcService();final callbackUri = await oidc.startLogin(fullUrl);if (callbackUri == null) {- if (mounted) setState(() {+ if (!mounted) return;+ // Quiet path: user just dismissed the popup. Don't surface an error.+ if (oidc.lastWasUserCancel) {+ setState(() => _isOidcLoading = false);+ return;+ }+ final base = AppLocalizations.of(context)!.loginSsoFailed;+ final detail = oidc.lastError;+ setState(() {_isOidcLoading = false;- _loginError = AppLocalizations.of(context)!.loginSsoFailed;+ _loginError = detail != null ? '$base\n\n$detail' : base;});return;}@@ -312,9 +320,11 @@ class _LoginScreenState extends State<LoginScreen>}}} else if (mounted) {+ final base = AppLocalizations.of(context)!.loginSsoAuthFailed;+ final detail = oidc.lastError;setState(() {_isOidcLoading = false;- _loginError = AppLocalizations.of(context)!.loginSsoAuthFailed;+ _loginError = detail != null ? '$base\n\n$detail' : base;});}}diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex 3da2c8c9..42ebc4f9 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -218,7 +218,9 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {@overrideFuture<void> play() async {debugPrint('[Handler] play() called - routing to service (state=${_player.processingState.name})');- debugPrint('[ClickDebug] play() entry: ${_clickDebugSnapshot()}');+ final entryBt = await AudioPlayerService._isBluetoothAudioConnected();+ if (entryBt) AudioPlayerService._lastPlayedOnBtAt = DateTime.now();+ debugPrint('[ClickDebug] play() entry: ${_clickDebugSnapshot(btNow: entryBt)}');// Mirror the click() guard: a raw play() arriving within 5s of a// headphone/AA/BT disconnect is almost always the platform echoing a// resume command, not the user. Drop it so playback doesn't jump to@@ -243,7 +245,8 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {@overrideFuture<void> pause() async {debugPrint('[Handler] pause() called - routing to service');- debugPrint('[ClickDebug] pause() entry: ${_clickDebugSnapshot()}');+ final pauseEntryBt = await AudioPlayerService._isBluetoothAudioConnected();+ debugPrint('[ClickDebug] pause() entry: ${_clickDebugSnapshot(btNow: pauseEntryBt)}');_lastHandlerPauseAt = DateTime.now();// Android Auto disconnect can dispatch both a MediaButton click and a// pause() action simultaneously. The click's 400ms debounce timer would@@ -365,7 +368,11 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {/// [ClickDebug] — one-line snapshot of state around a media-button event./// Helps diagnose phantom clicks after Android Auto disconnect.- String _clickDebugSnapshot() {+ ///+ /// `btNow` should be pre-fetched async by the caller when available so+ /// the AA-disconnect heuristic can be evaluated. When null, that flag+ /// is reported as `unknown`.+ String _clickDebugSnapshot({bool? btNow}) {final now = DateTime.now();int sincePrevPauseMs = -1;if (_lastHandlerPauseAt != null) {@@ -391,6 +398,21 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {&& sincePrevPlayMs < 5000&& _player.playing&& (backgrounded ?? false);+ // AA-disconnect fingerprint: BT/AA was the audio route within the last+ // 10 min, isn't anymore, and the click came in while bg + not playing.+ int sinceBtMs = -1;+ final lastBt = AudioPlayerService._lastPlayedOnBtAt;+ if (lastBt != null) sinceBtMs = now.difference(lastBt).inMilliseconds;+ final String aaDisconnect;+ if (btNow == null) {+ aaDisconnect = 'unknown';+ } else {+ final fired = lastBt != null+ && !btNow+ && sinceBtMs >= 0+ && sinceBtMs < 600000;+ aaDisconnect = fired ? 'true' : 'false';+ }return 'bg=$backgrounded, sincePrevPauseMs=$sincePrevPauseMs, ''sincePrevPlayMs=$sincePrevPlayMs, ''sinceForegroundMs=$sinceForegroundMs, '@@ -398,13 +420,18 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {'playing=${_player.playing}, ''processingState=${_player.processingState.name}, ''noisyPause=${AudioPlayerService._noisyPause}, '- 'phantomSuspect=$phantomSuspect';+ 'phantomSuspect=$phantomSuspect, '+ 'sinceBtMs=$sinceBtMs, btNow=${btNow ?? 'unknown'}, '+ 'aaDisconnectSuspect=$aaDisconnect';}@overrideFuture<void> click([MediaButton button = MediaButton.media]) async {debugPrint('[Handler] click(button=$button) count=${_clickCount + 1} playing=${_player.playing}');- final snapshot = _clickDebugSnapshot();+ // Pre-fetch BT-route state so the snapshot can fill in the AA-disconnect+ // heuristic and the suppression branch below has a value to test against.+ final btNow = await AudioPlayerService._isBluetoothAudioConnected();+ final snapshot = _clickDebugSnapshot(btNow: btNow);debugPrint('[ClickDebug] click arrival (button=$button): $snapshot');_service?._logEvent(PlaybackEventType.clickDebounce, detail: 'button=$button | $snapshot');@@ -442,13 +469,35 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {_noisyPauseAt = null;}+ // AA-disconnect phantom: a delayed MediaButton.media event arrives in+ // background, not playing, after we last played on BT/AA — and BT is+ // gone now. On devices where AA disconnect doesn't fire becomingNoisy+ // (Pixel 10 Pro / Android 16 observed), this is the only way to catch+ // the lingering MediaSession resume that the OS sends minutes later.+ final lastBt = AudioPlayerService._lastPlayedOnBtAt;+ final bg = _service?.isBackgrounded ?? false;+ if (bg && !_player.playing && lastBt != null && !btNow) {+ final ageMs = DateTime.now().difference(lastBt).inMilliseconds;+ if (ageMs < 600000) {+ debugPrint('[Handler] Ignoring phantom click after AA/BT disconnect '+ '(${ageMs}ms since last BT-on, btNow=false, bg=true, playing=false)');+ _service?._logEvent(PlaybackEventType.clickDebounce,+ detail: 'phantom AA/BT click suppressed | sinceBtMs=$ageMs');+ // Re-arm the 5s noisy guard so a follow-up click in the same+ // burst is also ignored, matching the BT-disconnect suppression flow.+ _noisyPauseAt = DateTime.now();+ return;+ }+ }+_clickCount++;_clickTimer?.cancel();_clickTimer = Timer(const Duration(milliseconds: 400), () async {final count = _clickCount;_clickCount = 0;debugPrint('[Handler] click resolved: count=$count playing=${_player.playing}');- debugPrint('[ClickDebug] click resolve (count=$count): ${_clickDebugSnapshot()}');+ final resolveBt = await AudioPlayerService._isBluetoothAudioConnected();+ debugPrint('[ClickDebug] click resolve (count=$count): ${_clickDebugSnapshot(btNow: resolveBt)}');switch (count) {case 1:_inClickResolver = true;@@ -1206,6 +1255,14 @@ class AudioPlayerService extends ChangeNotifier {// an app-foreground event — the fingerprint of an Android Auto disconnect// handing control back to the phone.static DateTime? _lastForegroundAt;+ // Last time we observed BT/AA to be the audio route while playing/pausing.+ // Stamped from interruption begin/end and from service.pause(). Used at+ // click arrival to detect the AA-disconnect phantom: BT was the route+ // recently, isn't now, click came in while bg + not playing. Some devices+ // (Pixel 10 Pro on Android 16 with Android Auto observed) never fire+ // becomingNoisy on AA disconnect, so the 5s _noisyPauseAt guard alone+ // can't catch the delayed phantom MediaButton.media event.+ static DateTime? _lastPlayedOnBtAt;static const _eqChannel = MethodChannel('com.absorb.equalizer');/// Check if BT audio (A2DP/SCO) is currently connected via native AudioManager.@@ -1259,6 +1316,7 @@ class AudioPlayerService extends ChangeNotifier {if (service.isPlaying) {debugPrint('[AudioSession] Interrupted (${event.type}) — pausing');_wasOnBluetooth = await _isBluetoothAudioConnected();+ if (_wasOnBluetooth) _lastPlayedOnBtAt = DateTime.now();debugPrint('[AudioSession] Was on BT: $_wasOnBluetooth');// Pause the underlying player directly — NOT service.pause() —// to keep the interruption lightweight. service.pause() saves progress,@@ -1294,9 +1352,10 @@ class AudioPlayerService extends ChangeNotifier {_noisyPause = true;return;}+ _lastPlayedOnBtAt = DateTime.now();}debugPrint('[AudioSession] Interruption ended — resuming');- await service.play();+ await service.play(logDetail: 'Auto-resumed after interruption');}}} catch (e) {@@ -3176,7 +3235,7 @@ class AudioPlayerService extends ChangeNotifier {return rewind.clamp(minRewind, maxRewind);}- Future<void> play() async {+ Future<void> play({String? logDetail}) async {debugPrint('[Service] play() called — lastPause=${_lastPauseTime != null}');// Cold-start play guard. If the OS killed absorb during a long pause@@ -3280,7 +3339,7 @@ class AudioPlayerService extends ChangeNotifier {// Start playback immediately — don't wait for server calls_player?.play();_scheduleAudioDiagnostics('resume');- _logEvent(PlaybackEventType.play);+ _logEvent(PlaybackEventType.play, detail: logDetail);_onPlaybackStateChangedCallback?.call(true);// Re-create server session and check progress in the background// so resume is instant instead of waiting for network round-trips@@ -3369,6 +3428,11 @@ class AudioPlayerService extends ChangeNotifier {_playVerifyTimer?.cancel();_wasPlayingBeforeInterrupt = false;_lastPauseTime = DateTime.now();+ // Stamp BT-route observation for AA-disconnect phantom-click detection.+ // Fire-and-forget: pause shouldn't block on a native call.+ unawaited(_isBluetoothAudioConnected().then((bt) {+ if (bt) _lastPlayedOnBtAt = DateTime.now();+ }));// Stop timers to avoid background wakes while pausedif (_bgSaveTimer != null) {_bgSaveTimer!.cancel();diff --git a/lib/services/oidc_service.dart b/lib/services/oidc_service.dartindex 1ce54be0..64839629 100644--- a/lib/services/oidc_service.dart+++ b/lib/services/oidc_service.dart@@ -2,6 +2,7 @@ import 'dart:convert';import 'dart:math';import 'package:crypto/crypto.dart';import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart' show PlatformException;import 'package:http/http.dart' as http;import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';import 'dart:io' show HttpClient, HttpHeaders;@@ -21,6 +22,19 @@ class OidcService {/// The raw cookie strings from the /auth/openid response.List<String> _rawCookies = [];+ /// Diagnostic message from the most recent failure. Cleared on each+ /// startLogin() call. Null when the last attempt succeeded or the user+ /// simply cancelled the popup. Surface to the UI so SSO failures aren't+ /// silently swallowed.+ String? _lastError;+ String? get lastError => _lastError;++ /// True when the most recent failure was the user dismissing the popup+ /// (vs. a real network/protocol error). Lets the UI suppress the snackbar+ /// for plain cancellations.+ bool _lastWasUserCancel = false;+ bool get lastWasUserCancel => _lastWasUserCancel;+static const _redirectUri = 'audiobookshelf://oauth';static const _clientId = 'Audiobookshelf-App';@@ -41,11 +55,15 @@ class OidcService {/// Start the OIDC login flow using a Chrome Custom Tab./// Returns the callback [Uri] on success, or null on failure/cancellation.+ /// On failure, [lastError] holds a diagnostic message and [lastWasUserCancel]+ /// distinguishes user-dismissed popups from real errors.Future<Uri?> startLogin(String serverUrl) async {_serverUrl = serverUrl.endsWith('/') ? serverUrl.substring(0, serverUrl.length - 1) : serverUrl;_generatePkce();_state = _generateRandom(16);_rawCookies = [];+ _lastError = null;+ _lastWasUserCancel = false;final authUrl = '$_serverUrl/auth/openid''?code_challenge=$_codeChallenge'@@ -57,13 +75,13 @@ class OidcService {debugPrint('[OIDC] Starting auth flow: $authUrl');+ String? providerUrl;try {// Pre-flight request to capture cookies and get the OIDC provider redirect URL.// ABS sets a session cookie that links the PKCE challenge to this flow.final client = HttpClient();client.connectionTimeout = const Duration(seconds: 15);- String? providerUrl;try {final request = await client.getUrl(Uri.parse(authUrl));request.followRedirects = false;@@ -93,34 +111,72 @@ class OidcService {} else {final body = await response.transform(utf8.decoder).join();debugPrint('[OIDC] Unexpected status ${response.statusCode}: $body');+ // Truncate body to keep the snackbar readable.+ final preview = body.length > 200 ? '${body.substring(0, 200)}…' : body;+ _lastError = 'Server returned HTTP ${response.statusCode} from /auth/openid '+ '(expected 302). Body: $preview';_cleanup();return null;}} finally {client.close();}+ } on Exception catch (e, st) {+ // TLS, connection, timeout, DNS — all surface here. Keep the message+ // verbatim so users can paste it back when reporting issues.+ debugPrint('[OIDC] Pre-flight error: $e\n$st');+ _lastError = 'Could not reach $_serverUrl/auth/openid: $e';+ _cleanup();+ return null;+ }- if (providerUrl == null || providerUrl.isEmpty) {- debugPrint('[OIDC] Server did not return a redirect URL');- _cleanup();- return null;- }+ if (providerUrl == null || providerUrl.isEmpty) {+ debugPrint('[OIDC] Server did not return a redirect URL');+ _lastError = 'Server accepted /auth/openid but did not return a Location '+ 'header. Check that the OIDC provider is configured in ABS.';+ _cleanup();+ return null;+ }- debugPrint('[OIDC] Opening Custom Tab for: $providerUrl');+ debugPrint('[OIDC] Opening Custom Tab for: $providerUrl');- // Open the OIDC provider in a Chrome Custom Tab. This blocks until the- // provider redirects back to audiobookshelf://oauth, which the Custom Tab- // intercepts and returns. Unlike an external browser, Custom Tabs won't- // be hijacked by PWAs or other apps registered for the provider's domain.+ // Open the OIDC provider in an in-app browser tab. On Android this is a+ // Chrome Custom Tab; on iOS, ASWebAuthenticationSession. Both intercept+ // the audiobookshelf:// callback and return it to us. Unlike an external+ // browser, neither can be hijacked by PWAs or other apps registered for+ // the provider's domain.+ try {final resultUrl = await FlutterWebAuth2.authenticate(url: providerUrl,callbackUrlScheme: 'audiobookshelf',);-debugPrint('[OIDC] Custom Tab returned: $resultUrl');return Uri.parse(resultUrl);- } catch (e) {- debugPrint('[OIDC] Error during login: $e');+ } on PlatformException catch (e) {+ // Cancellation arrives as PlatformException. Both plugins use code+ // CANCELED, but iOS occasionally surfaces the underlying ASWeb error+ // code (e.g. canceledLogin = 1). Treat the well-known cancel codes+ // as a quiet cancel and anything else as a real error.+ final code = e.code.toUpperCase();+ final msg = (e.message ?? '').toLowerCase();+ final isCancel = code == 'CANCELED'+ || code == 'CANCELLED'+ || code == 'USER_CANCELED'+ || msg.contains('canceled')+ || msg.contains('cancelled');+ if (isCancel) {+ debugPrint('[OIDC] User cancelled the popup');+ _lastWasUserCancel = true;+ } else {+ debugPrint('[OIDC] Auth session error: ${e.code} ${e.message}');+ _lastError = 'In-app browser failed: ${e.code}'+ '${e.message != null ? ' — ${e.message}' : ''}';+ }+ _cleanup();+ return null;+ } catch (e, st) {+ debugPrint('[OIDC] Auth session unexpected error: $e\n$st');+ _lastError = 'In-app browser failed: $e';_cleanup();return null;}@@ -132,6 +188,8 @@ class OidcService {/// Handle the callback URI returned from the Custom Tab./// Returns the user login response (same as /login) or null on failure.Future<Map<String, dynamic>?> handleCallback(Uri uri) async {+ _lastError = null;+ _lastWasUserCancel = false;final code = uri.queryParameters['code'];final state = uri.queryParameters['state'];@@ -139,17 +197,23 @@ class OidcService {if (code == null || code.isEmpty) {debugPrint('[OIDC] No code in callback');+ _lastError = 'OIDC provider returned no authorization code. '+ 'Check the provider logs for an "invalid redirect_uri" or '+ '"invalid client" error.';return null;}// Verify state matchesif (state != _state) {debugPrint('[OIDC] State mismatch: expected=$_state, got=$state');+ _lastError = 'OIDC state mismatch — possible session expiry or '+ 'cross-tab interference. Try again.';return null;}if (_serverUrl == null || _codeVerifier == null) {debugPrint('[OIDC] Missing server URL or code verifier');+ _lastError = 'OIDC flow state was lost between popup and callback.';return null;}@@ -187,6 +251,9 @@ class OidcService {return data;} else {debugPrint('[OIDC] Callback error: $body');+ final preview = body.length > 200 ? '${body.substring(0, 200)}…' : body;+ _lastError = 'ABS callback returned HTTP ${response.statusCode}'+ '${preview.isNotEmpty ? ': $preview' : ''}';return null;}} finally {@@ -194,6 +261,7 @@ class OidcService {}} catch (e) {debugPrint('[OIDC] Callback exception: $e');+ _lastError = 'ABS callback request failed: $e';return null;}}