A cross platform Audiobookshelf client for Android and iOS
Dart
Remove BG-AUDIT logs, fix nav bar disappearing, bypass proxy on iOS too
Nathan Poulson89f650d1c7e9
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dartindex 83724a72..dc7a78a9 100644--- a/lib/providers/_lp_core.dart+++ b/lib/providers/_lp_core.dart@@ -618,7 +618,6 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {// ── Battery-saving lifecycle ──void onAppBackgrounded() {- debugPrint('[BG-AUDIT] LibraryProvider.onAppBackgrounded() playing=${AudioPlayerService().isPlaying}');_isBackgrounded = true;_stopServerPingTimer();_idleDisconnectTimer?.cancel(); // No timers in background@@ -627,7 +626,6 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {}void onAppForegrounded() {- debugPrint('[BG-AUDIT] LibraryProvider.onAppForegrounded()');_isBackgrounded = false;_softReconnectSocket();if (_networkOffline && _deviceHasConnectivity && !_manualOffline) {@@ -640,25 +638,20 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {_idleDisconnectTimer?.cancel();_idleDisconnectTimer = Timer(_StateMixin._idleTimeout, () {if (!AudioPlayerService().isPlaying && !ChromecastService().isPlaying) {- debugPrint('[BG-AUDIT] idleTimer disconnecting socket');_softDisconnectSocket();}});}void onPlaybackStarted() {- debugPrint('[BG-AUDIT] LibraryProvider.onPlaybackStarted() bg=$_isBackgrounded');if (!_isBackgrounded) {- debugPrint('[BG-AUDIT] socket reconnect (foreground playback start)');_softReconnectSocket();} else {- debugPrint('[BG-AUDIT] socket reconnect SKIPPED (backgrounded)');}_idleDisconnectTimer?.cancel();}void onPlaybackStopped() {- debugPrint('[BG-AUDIT] LibraryProvider.onPlaybackStopped() bg=$_isBackgrounded');if (_isBackgrounded) {_softDisconnectSocket();} else {@@ -667,7 +660,6 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {}void _softDisconnectSocket() {- debugPrint('[BG-AUDIT] _softDisconnectSocket() alreadyDisconnected=$_socketSoftDisconnected manualOffline=$_manualOffline');if (_socketSoftDisconnected || _manualOffline) return;_socketSoftDisconnected = true;SocketService().softDisconnect();@@ -1624,9 +1616,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {}void _checkRollingDownloads(String playingKey) async {- debugPrint('[BG-AUDIT] _checkRollingDownloads key=$playingKey api=${_api != null} offline=$isOffline series=${_rollingDownloadSeries.length}');if (_api == null || isOffline || _rollingDownloadSeries.isEmpty) {- debugPrint('[BG-AUDIT] _checkRollingDownloads BAILED early');return;}final count = await PlayerSettings.getRollingDownloadCount();@@ -1652,9 +1642,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {}void _checkQueueAutoDownloads(String playingKey) async {- debugPrint('[BG-AUDIT] _checkQueueAutoDownloads key=$playingKey');if (_api == null || isOffline) {- debugPrint('[BG-AUDIT] _checkQueueAutoDownloads BAILED (api/offline)');return;}final isPodcastKey = playingKey.length > 36;@@ -1662,7 +1650,6 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {? await PlayerSettings.getPodcastQueueMode(): await PlayerSettings.getBookQueueMode();if (queueMode != 'manual') {- debugPrint('[BG-AUDIT] _checkQueueAutoDownloads BAILED (queueMode=$queueMode)');return;}final enabled = await PlayerSettings.getQueueAutoDownload();@@ -1750,14 +1737,11 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {}void _checkAutoDownloadOnStream(String playingKey) async {- debugPrint('[BG-AUDIT] _checkAutoDownloadOnStream key=$playingKey');if (_api == null || isOffline) {- debugPrint('[BG-AUDIT] _checkAutoDownloadOnStream BAILED (api/offline)');return;}final enabled = await PlayerSettings.getAutoDownloadOnStream();if (!enabled) {- debugPrint('[BG-AUDIT] _checkAutoDownloadOnStream BAILED (disabled)');return;}diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex bc906542..4d59527b 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -72,11 +72,9 @@ class LibraryProvider extends ChangeNotifierAudioPlayerService.setOnBookFinishedCallback(markFinishedLocally);AudioPlayerService.setOnPlayStartedCallback((key) {- debugPrint('[BG-AUDIT] onPlayStarted key=$key - deferring download checks 30s');// Defer download checks to avoid a network burst at playback start.Future.delayed(const Duration(seconds: 30), () {final stillPlaying = AudioPlayerService().isPlaying;- debugPrint('[BG-AUDIT] deferred download checks firing: stillPlaying=$stillPlaying');if (!stillPlaying) return;_checkRollingDownloads(key);_checkQueueAutoDownloads(key);@@ -84,7 +82,6 @@ class LibraryProvider extends ChangeNotifier});});AudioPlayerService.setOnPlaybackStateChangedCallback((playing) {- debugPrint('[BG-AUDIT] onPlaybackStateChanged playing=$playing');if (playing) {onPlaybackStarted();} else {diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dartindex d1758ae1..c7a309f6 100644--- a/lib/screens/app_shell.dart+++ b/lib/screens/app_shell.dart@@ -132,7 +132,10 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Tickernotifier.addListener(_navBarListener!);_navBarListener!();} else {- _navBarAnimController.forward();+ // Not a scroll-hide tab - force nav bar visible immediately.+ // Use .value to snap instead of animate, avoiding races where+ // the controller gets stuck mid-animation.+ _navBarAnimController.value = 1.0;}}@@ -141,6 +144,8 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Tickervoid _detachNavBarListener() {if (_navBarListener != null && _activeBarNotifier != null) {_activeBarNotifier!.removeListener(_navBarListener!);+ // Reset the notifier so bars are visible when the user returns to this tab+ _activeBarNotifier!.value = true;}_navBarListener = null;_activeBarNotifier = null;@@ -394,7 +399,6 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker@overridevoid didChangeAppLifecycleState(AppLifecycleState state) {- debugPrint('[BG-AUDIT] AppShell lifecycle: $state');if (state == AppLifecycleState.resumed) {context.read<LibraryProvider>().onAppForegrounded();SleepTimerService().onAppForegrounded();diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex 4fed89d2..b2c7cd15 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -23,11 +23,10 @@ export 'player_settings.dart';class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {final AudioPlayer _player = AudioPlayer(handleInterruptions: false,- // Android: bypass the local HTTP proxy for auth headers — ExoPlayer- // supports headers natively via DefaultHttpDataSource, so the proxy- // just doubles the packet count for no benefit.- // iOS: keep the proxy — AVPlayer can't set custom headers natively.- useProxyForRequestHeaders: !Platform.isAndroid,+ // Bypass the local HTTP proxy — headers are sent natively on both+ // platforms (ExoPlayer via setDefaultRequestProperties, AVPlayer via+ // AVURLAssetHTTPHeaderFieldsKey). The proxy doubles the packet count.+ useProxyForRequestHeaders: false,audioLoadConfiguration: const AudioLoadConfiguration(androidLoadControl: AndroidLoadControl(bufferForPlaybackDuration: Duration(milliseconds: 500),@@ -1121,7 +1120,6 @@ class AudioPlayerService extends ChangeNotifier {/// MediaSession, leaving bluetooth / notification / widget controls dead./// Re-activating the audio session and re-pushing handler state recovers it.static void onAppBackgrounded() {- debugPrint('[BG-AUDIT] AudioPlayerService.onAppBackgrounded() playing=${_instance.isPlaying}');_instance._isBackgrounded = true;}@@ -1129,17 +1127,13 @@ class AudioPlayerService extends ChangeNotifier {final service = _instance;service._isBackgrounded = false;if (!service.hasBook) return;- debugPrint('[BG-AUDIT] AudioPlayerService.onAppForegrounded() playing=${service.isPlaying}');debugPrint('[MediaSession] Foregrounded - refreshing (playing=${service.isPlaying}, session=${service._playbackSessionId != null}, item=${service._currentItemId})');// Flush missed UI updates from background- debugPrint('[BG-AUDIT] notifyListeners() flush on foreground');service.notifyListeners();// Flush overdue server syncif (service.isPlaying && service._currentItemId != null) {final sinceSync = DateTime.now().difference(service._lastServerSync).inSeconds;- debugPrint('[BG-AUDIT] foreground sync check: sinceLastSync=${sinceSync}s');if (sinceSync > 60) {- debugPrint('[BG-AUDIT] foreground sync FLUSHING overdue sync');service._syncToServer(service.position);}}@@ -1924,12 +1918,6 @@ class AudioPlayerService extends ChangeNotifier {int _lastSyncSecond = -1;int _lastBgProcessedSec = -1;- // BG-AUDIT counters - compile per-second summaries instead of per-tick logs- int _auditTickCount = 0;- int _auditSkippedTicks = 0;- int _auditLastReportSec = -1;- int _auditNotifyCount = 0;- int _auditNotifySkipped = 0;StreamSubscription? _eqSessionSub;@@ -1986,12 +1974,10 @@ class AudioPlayerService extends ChangeNotifier {// listener saves every 5s; this only matters when that stream goes silent._bgSaveTimer = Timer.periodic(const Duration(seconds: 300), (_) async {- debugPrint('[BG-AUDIT] bgSaveTimer FIRED bg=$_isBackgrounded');if (_currentItemId == null || _player == null || !_player!.playing) return;final pos = position;final posSec = pos.inMilliseconds / 1000.0;if (posSec <= 0) return;- debugPrint('[BG-AUDIT] bgSaveTimer saving pos=${posSec.toStringAsFixed(1)}s');await _saveProgressLocal(pos);});@@ -2003,17 +1989,13 @@ class AudioPlayerService extends ChangeNotifier {// position-reset can confuse the position-based detection._completionSub = _player?.processingStateStream.listen((state) {if (state == ProcessingState.completed && _currentItemId != null) {- debugPrint('[BG-AUDIT] processingState=completed');_onPlaybackComplete();}// Notify UI when buffering/loading state changes so spinners update.// Skip when backgrounded - no visible UI to rebuild; flushed on foreground.if (!_isBackgrounded &&(state == ProcessingState.ready || state == ProcessingState.loading || state == ProcessingState.buffering)) {- _auditNotifyCount++;notifyListeners();- } else if (_isBackgrounded) {- _auditNotifySkipped++;}}, onError: (Object e, StackTrace st) {debugPrint('[Player] processingState stream error: $e');@@ -2044,24 +2026,11 @@ class AudioPlayerService extends ChangeNotifier {if (sec <= 0) return;- _auditTickCount++;// In background, only process once per second to save CPU.if (_isBackgrounded) {- if (sec == _lastBgProcessedSec) {- _auditSkippedTicks++;- return;- }+ if (sec == _lastBgProcessedSec) return;_lastBgProcessedSec = sec;}- // Log a compiled summary every 5 seconds- if (sec % 5 == 0 && sec != _auditLastReportSec) {- _auditLastReportSec = sec;- debugPrint('[BG-AUDIT] positionStream 5s summary: ticks=$_auditTickCount skipped=$_auditSkippedTicks processed=${_auditTickCount - _auditSkippedTicks} notifyListeners=$_auditNotifyCount notifySkipped=$_auditNotifySkipped bg=$_isBackgrounded pos=${posSec.toStringAsFixed(1)}s');- _auditTickCount = 0;- _auditSkippedTicks = 0;- _auditNotifyCount = 0;- _auditNotifySkipped = 0;- }// ─── Chapter change detection ──────────────────────────// Update notification subtitle when the chapter changes.@@ -2128,14 +2097,12 @@ class AudioPlayerService extends ChangeNotifier {// Save locally every 5 seconds (always works, even offline)if (sec % 5 == 0 && sec != _lastSyncSecond && _currentItemId != null) {_lastSyncSecond = sec;- debugPrint('[BG-AUDIT] localSave pos=${posSec.toStringAsFixed(1)}s bg=$_isBackgrounded');_saveProgressLocal(absolutePos);// Sync to server: 60s foreground, 300s backgroundfinal syncInterval = _isBackgrounded ? 300 : 60;final sinceLastSync = DateTime.now().difference(_lastServerSync).inSeconds;if (sinceLastSync >= syncInterval) {- debugPrint('[BG-AUDIT] serverSync FIRING interval=${syncInterval}s sinceLastSync=${sinceLastSync}s bg=$_isBackgrounded');final manualOffline = (_prefs ?? await SharedPreferences.getInstance()).getBool('manual_offline_mode') ?? false;@@ -2144,20 +2111,16 @@ class AudioPlayerService extends ChangeNotifier {final progressKey = _currentEpisodeId != null? '$_currentItemId-$_currentEpisodeId': _currentItemId!;- debugPrint('[BG-AUDIT] offlineAccumulate key=$progressKey secs=${sinceLastSync.clamp(0, 300)}');_progressSync.addOfflineListeningTime(progressKey, sinceLastSync.clamp(0, 300));}if (manualOffline) {- debugPrint('[BG-AUDIT] serverSync SKIPPED (manualOffline)');// Manual offline — local save only, no server sync} else if (!_isOfflineMode && _playbackSessionId != null) {// Streaming/local with session: sync via session- debugPrint('[BG-AUDIT] serverSync SESSION pos=${absolutePos.inSeconds}s');_syncToServer(absolutePos);} else if (!_isOfflineMode && _api != null && _currentItemId != null) {// No session but online — sync via progress update endpoint- debugPrint('[BG-AUDIT] serverSync NO-SESSION pos=${absolutePos.inSeconds}s');try {final syncKey = _currentEpisodeId != null? '$_currentItemId-$_currentEpisodeId'@@ -2580,21 +2543,17 @@ class AudioPlayerService extends ChangeNotifier {return;}_player?.play();- debugPrint('[BG-AUDIT] play() bg=$_isBackgrounded');_logEvent(PlaybackEventType.play);_onPlaybackStateChangedCallback?.call(true);// Restart safety-net save timer (stopped on pause to avoid background wakes)if (_bgSaveTimer == null || !_bgSaveTimer!.isActive) {- debugPrint('[BG-AUDIT] bgSaveTimer RESTARTED (300s)');_bgSaveTimer?.cancel();_bgSaveTimer = Timer.periodic(const Duration(seconds: 300), (_) async {- debugPrint('[BG-AUDIT] bgSaveTimer FIRED (play-restart) bg=$_isBackgrounded');if (_currentItemId == null || _player == null || !_player!.playing) return;final pos = position;final posSec = pos.inMilliseconds / 1000.0;if (posSec <= 0) return;- debugPrint('[BG-AUDIT] bgSaveTimer saving pos=${posSec.toStringAsFixed(1)}s');await _saveProgressLocal(pos);});}@@ -2611,7 +2570,6 @@ class AudioPlayerService extends ChangeNotifier {}Future<void> pause() async {- debugPrint('[BG-AUDIT] pause() bg=$_isBackgrounded');debugPrint('[Service] pause() called');_playVerifyTimer?.cancel();_wasPlayingBeforeInterrupt = false;diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dartindex 7fe24c29..95bc242c 100644--- a/lib/services/home_widget_service.dart+++ b/lib/services/home_widget_service.dart@@ -22,8 +22,6 @@ class HomeWidgetService {Timer? _progressTimer;Timer? _pendingUpdate;- int _auditPlayerChangedCount = 0;- int _auditThrottledCount = 0;String? _lastCoverItemId;DateTime? _lastUpdate;bool _initialized = false;@@ -160,13 +158,11 @@ class HomeWidgetService {}void _onPlayerChanged() {- _auditPlayerChangedCount++;// Throttle to max once per 2 seconds, but never drop an update —// schedule a deferred one so the final state always gets pushed.final now = DateTime.now();if (_lastUpdate != null &&now.difference(_lastUpdate!).inMilliseconds < 2000) {- _auditThrottledCount++;_pendingUpdate?.cancel();_pendingUpdate = Timer(const Duration(seconds: 2), _scheduleUpdate);return;@@ -177,7 +173,6 @@ class HomeWidgetService {/// Schedule an update on the next microtask so we never do async work/// inside the synchronous ChangeNotifier callback.void _scheduleUpdate() {- debugPrint('[BG-AUDIT] HomeWidget._scheduleUpdate() updating=$_updating');if (_updating) return;_updating = true;Future.microtask(() async {@@ -192,9 +187,6 @@ class HomeWidgetService {}Future<void> _updateWidgetData() async {- debugPrint('[BG-AUDIT] HomeWidget._updateWidgetData() playerChangedSinceLastUpdate=$_auditPlayerChangedCount throttled=$_auditThrottledCount');- _auditPlayerChangedCount = 0;- _auditThrottledCount = 0;_lastUpdate = DateTime.now();final player = AudioPlayerService();final hasBook = player.hasBook;@@ -273,7 +265,6 @@ class HomeWidgetService {// If no local cover, download from server to a temp file.if (coverPath == null) {if (coverUrl != null && coverUrl.isNotEmpty) {- debugPrint('[BG-AUDIT] HomeWidget._updateCoverArt HTTP FETCH $coverUrl');final cacheDir = await getTemporaryDirectory();final widgetCoverDir = Directory('${cacheDir.path}/widget_covers');if (!widgetCoverDir.existsSync()) {@@ -305,26 +296,21 @@ class HomeWidgetService {void _startProgressTimer() {if (_progressTimer?.isActive == true) return;- debugPrint('[BG-AUDIT] HomeWidget._startProgressTimer (120s)');_progressTimer = Timer.periodic(const Duration(seconds: 120), (_) {- debugPrint('[BG-AUDIT] HomeWidget progressTimer FIRED');_scheduleUpdate();});}void _stopProgressTimer() {- debugPrint('[BG-AUDIT] HomeWidget._stopProgressTimer');_progressTimer?.cancel();_progressTimer = null;}void onAppBackgrounded() {- debugPrint('[BG-AUDIT] HomeWidget.onAppBackgrounded()');_stopProgressTimer();}void onAppForegrounded() {- debugPrint('[BG-AUDIT] HomeWidget.onAppForegrounded() playing=${AudioPlayerService().isPlaying}');if (AudioPlayerService().isPlaying) {_startProgressTimer();_scheduleUpdate();diff --git a/lib/services/progress_sync_service.dart b/lib/services/progress_sync_service.dartindex a2e3f2bf..1923b103 100644--- a/lib/services/progress_sync_service.dart+++ b/lib/services/progress_sync_service.dart@@ -29,9 +29,7 @@ class ProgressSyncService {_connectivitySub = Connectivity().onConnectivityChanged.listen((result) {final wasOffline = !_isOnline;_isOnline = !result.contains(ConnectivityResult.none);- debugPrint('[BG-AUDIT] ProgressSync connectivity changed: online=$_isOnline wasOffline=$wasOffline');if (_isOnline && wasOffline) {- debugPrint('[BG-AUDIT] ProgressSync back online - flushing pending syncs');_consecutiveFailures = 0; // reset backoff on connectivity changeflushPendingSync();}@@ -179,7 +177,6 @@ class ProgressSyncService {/// Flush all pending syncs (call when coming back online)./// Compares local vs server timestamps — last-write-wins.Future<void> flushPendingSync({ApiService? api, int maxItems = 5}) async {- debugPrint('[BG-AUDIT] flushPendingSync online=$_isOnline api=${api != null}');if (!_isOnline || api == null) return;if (_isFlushing) {