Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Keep StatsWidget fresh by ticking it with each playback sync

Barnabasd606be54891d
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index ba4d0f55..e3c9e513 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -19,6 +19,7 @@ import 'chapter_lookup.dart';
import 'cold_start_play_policy.dart';
import 'player_settings.dart';
import 'session_cache.dart';
+import 'home_widget_service.dart';
export 'player_settings.dart';
// ─── AudioHandler (runs in background, controls notification) ───
@@ -2689,7 +2690,11 @@ class AudioPlayerService extends ChangeNotifier {
final progressKey = _currentEpisodeId != null
? '$_currentItemId-$_currentEpisodeId'
: _currentItemId!;
- _progressSync.addOfflineListeningTime(progressKey, sinceLastSync.clamp(0, 300));
+ final offlineSeconds = sinceLastSync.clamp(0, 300);
+ _progressSync.addOfflineListeningTime(progressKey, offlineSeconds);
+ // Widget ticks forward even when the server is unreachable.
+ unawaited(HomeWidgetService()
+ .addLocalListeningSeconds(offlineSeconds));
// Reset the sync clock so the next tick waits a full interval
// before accumulating again.
_lastServerSync = DateTime.now();
@@ -2986,6 +2991,11 @@ class AudioPlayerService extends ChangeNotifier {
duration: _totalDuration,
timeListened: elapsed,
);
+ if (ok && elapsed > 0) {
+ // Tick the StatsWidget forward locally so "today" stays fresh between
+ // 15-min authoritative refreshes (which Android Doze throttles).
+ unawaited(HomeWidgetService().addLocalListeningSeconds(elapsed));
+ }
if (!ok && !_syncRecoveryInProgress) {
debugPrint('[Player] Session sync failed - attempting recovery');
_syncRecoveryInProgress = true;
diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dart
index 2c5b5dea..955ad0e7 100644
--- a/lib/services/home_widget_service.dart
+++ b/lib/services/home_widget_service.dart
@@ -33,6 +33,15 @@ class HomeWidgetService {
bool _refreshingStats = false;
StreamSubscription? _clickSub;
+ // Last authoritative values from the server, plus local additions since
+ // then. Lets us tick the widget forward on every playback sync without a
+ // network round-trip; refreshStats overwrites the base and resets the
+ // accumulators so drift is corrected on every successful server fetch.
+ int _todayBase = 0;
+ int _weekBase = 0;
+ int _localAddedToday = 0;
+ int _localAddedWeek = 0;
+
/// Call after AudioPlayerService is initialized to start pushing state.
Future<void> init() async {
if (_initialized) return;
@@ -325,6 +334,11 @@ class HomeWidgetService {
debugPrint('[StatsWidget] Computed: today=${today}s week=${week}s streak=${streak}d booksThisYear=$booksYear (dailyMapKeys=${dailyMap.length})');
+ _todayBase = today;
+ _weekBase = week;
+ _localAddedToday = 0;
+ _localAddedWeek = 0;
+
await HomeWidget.saveWidgetData<int>('widget_stats_today', today);
await HomeWidget.saveWidgetData<int>('widget_stats_week', week);
await HomeWidget.saveWidgetData<int>('widget_stats_streak', streak);
@@ -338,6 +352,25 @@ class HomeWidgetService {
}
}
+ /// Tick the widget's "today" and "this week" totals forward without hitting
+ /// the server. Called from the player's sync path after real playing time
+ /// accumulates, so the widget stays fresh while the app is backgrounded and
+ /// the 15-min stats timer is throttled by Android Doze.
+ Future<void> addLocalListeningSeconds(int seconds) async {
+ if (seconds <= 0) return;
+ _localAddedToday += seconds;
+ _localAddedWeek += seconds;
+ try {
+ await HomeWidget.saveWidgetData<int>(
+ 'widget_stats_today', _todayBase + _localAddedToday);
+ await HomeWidget.saveWidgetData<int>(
+ 'widget_stats_week', _weekBase + _localAddedWeek);
+ await HomeWidget.updateWidget(name: _androidWidgetStatsName);
+ } catch (e) {
+ debugPrint('[StatsWidget] Local add failed: $e');
+ }
+ }
+
Future<ApiService?> _buildApiService() async {
final prefs = await SharedPreferences.getInstance();
final serverUrl = prefs.getString('server_url');