Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add challenge pace, weekday averages, and time saved by speed to stats

Barnabas6ef85b61030e
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index deaf0764..34ed52e9 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -442,6 +442,12 @@
"statsSectionTimePeriods": "Time periods",
"statsHeatmapLess": "Less",
"statsHeatmapMore": "More",
+ "statsDayOfWeek": "Average by day of week",
+ "statsTimeSavedLabel": "Saved by speed",
+ "statsOnPaceFor": "On pace for {count} books",
+ "@statsOnPaceFor": {
+ "placeholders": { "count": { "type": "int" } }
+ },
"statsDaysActive": "Days Active",
"statsDailyAverage": "Daily Average",
"statsLast7Days": "Last 7 Days",
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index dab676d9..ab37d2d4 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -1636,6 +1636,24 @@ abstract class AppLocalizations {
/// **'More'**
String get statsHeatmapMore;
+ /// No description provided for @statsDayOfWeek.
+ ///
+ /// In en, this message translates to:
+ /// **'Average by day of week'**
+ String get statsDayOfWeek;
+
+ /// No description provided for @statsTimeSavedLabel.
+ ///
+ /// In en, this message translates to:
+ /// **'Saved by speed'**
+ String get statsTimeSavedLabel;
+
+ /// No description provided for @statsOnPaceFor.
+ ///
+ /// In en, this message translates to:
+ /// **'On pace for {count} books'**
+ String statsOnPaceFor(int count);
+
/// No description provided for @statsDaysActive.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index 137847d0..9199c5dd 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -850,6 +850,17 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get statsHeatmapMore => 'More';
+ @override
+ String get statsDayOfWeek => 'Average by day of week';
+
+ @override
+ String get statsTimeSavedLabel => 'Saved by speed';
+
+ @override
+ String statsOnPaceFor(int count) {
+ return 'On pace for $count books';
+ }
+
@override
String get statsDaysActive => 'Aktive Tage';
diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dart
index b9c66e28..01d67d24 100644
--- a/lib/l10n/app_localizations_el.dart
+++ b/lib/l10n/app_localizations_el.dart
@@ -845,6 +845,17 @@ class AppLocalizationsEl extends AppLocalizations {
@override
String get statsHeatmapMore => 'More';
+ @override
+ String get statsDayOfWeek => 'Average by day of week';
+
+ @override
+ String get statsTimeSavedLabel => 'Saved by speed';
+
+ @override
+ String statsOnPaceFor(int count) {
+ return 'On pace for $count books';
+ }
+
@override
String get statsDaysActive => 'Days Active';
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index f183e4a3..369f8be0 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -845,6 +845,17 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get statsHeatmapMore => 'More';
+ @override
+ String get statsDayOfWeek => 'Average by day of week';
+
+ @override
+ String get statsTimeSavedLabel => 'Saved by speed';
+
+ @override
+ String statsOnPaceFor(int count) {
+ return 'On pace for $count books';
+ }
+
@override
String get statsDaysActive => 'Days Active';
diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart
index 2d51a2a8..f120329f 100644
--- a/lib/l10n/app_localizations_es.dart
+++ b/lib/l10n/app_localizations_es.dart
@@ -845,6 +845,17 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get statsHeatmapMore => 'More';
+ @override
+ String get statsDayOfWeek => 'Average by day of week';
+
+ @override
+ String get statsTimeSavedLabel => 'Saved by speed';
+
+ @override
+ String statsOnPaceFor(int count) {
+ return 'On pace for $count books';
+ }
+
@override
String get statsDaysActive => 'Days Active';
diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart
index 81ff68f7..0f509b5b 100644
--- a/lib/l10n/app_localizations_fr.dart
+++ b/lib/l10n/app_localizations_fr.dart
@@ -847,6 +847,17 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get statsHeatmapMore => 'More';
+ @override
+ String get statsDayOfWeek => 'Average by day of week';
+
+ @override
+ String get statsTimeSavedLabel => 'Saved by speed';
+
+ @override
+ String statsOnPaceFor(int count) {
+ return 'On pace for $count books';
+ }
+
@override
String get statsDaysActive => 'Days Active';
diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart
index 38af1229..e3c7f153 100644
--- a/lib/l10n/app_localizations_it.dart
+++ b/lib/l10n/app_localizations_it.dart
@@ -845,6 +845,17 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get statsHeatmapMore => 'More';
+ @override
+ String get statsDayOfWeek => 'Average by day of week';
+
+ @override
+ String get statsTimeSavedLabel => 'Saved by speed';
+
+ @override
+ String statsOnPaceFor(int count) {
+ return 'On pace for $count books';
+ }
+
@override
String get statsDaysActive => 'Days Active';
diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart
index 3cc3d449..6fe59180 100644
--- a/lib/l10n/app_localizations_ja.dart
+++ b/lib/l10n/app_localizations_ja.dart
@@ -845,6 +845,17 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get statsHeatmapMore => 'More';
+ @override
+ String get statsDayOfWeek => 'Average by day of week';
+
+ @override
+ String get statsTimeSavedLabel => 'Saved by speed';
+
+ @override
+ String statsOnPaceFor(int count) {
+ return 'On pace for $count books';
+ }
+
@override
String get statsDaysActive => 'Days Active';
diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dart
index 46ce603e..320fbb3b 100644
--- a/lib/l10n/app_localizations_no.dart
+++ b/lib/l10n/app_localizations_no.dart
@@ -845,6 +845,17 @@ class AppLocalizationsNo extends AppLocalizations {
@override
String get statsHeatmapMore => 'More';
+ @override
+ String get statsDayOfWeek => 'Average by day of week';
+
+ @override
+ String get statsTimeSavedLabel => 'Saved by speed';
+
+ @override
+ String statsOnPaceFor(int count) {
+ return 'On pace for $count books';
+ }
+
@override
String get statsDaysActive => 'Days Active';
diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart
index 33c5d64e..3cbec407 100644
--- a/lib/l10n/app_localizations_pt.dart
+++ b/lib/l10n/app_localizations_pt.dart
@@ -845,6 +845,17 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get statsHeatmapMore => 'More';
+ @override
+ String get statsDayOfWeek => 'Average by day of week';
+
+ @override
+ String get statsTimeSavedLabel => 'Saved by speed';
+
+ @override
+ String statsOnPaceFor(int count) {
+ return 'On pace for $count books';
+ }
+
@override
String get statsDaysActive => 'Days Active';
diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dart
index ce9187c9..e8c8bb98 100644
--- a/lib/l10n/app_localizations_ro.dart
+++ b/lib/l10n/app_localizations_ro.dart
@@ -845,6 +845,17 @@ class AppLocalizationsRo extends AppLocalizations {
@override
String get statsHeatmapMore => 'More';
+ @override
+ String get statsDayOfWeek => 'Average by day of week';
+
+ @override
+ String get statsTimeSavedLabel => 'Saved by speed';
+
+ @override
+ String statsOnPaceFor(int count) {
+ return 'On pace for $count books';
+ }
+
@override
String get statsDaysActive => 'Days Active';
diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart
index f68d689d..c55ccdec 100644
--- a/lib/l10n/app_localizations_ru.dart
+++ b/lib/l10n/app_localizations_ru.dart
@@ -846,6 +846,17 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get statsHeatmapMore => 'More';
+ @override
+ String get statsDayOfWeek => 'Average by day of week';
+
+ @override
+ String get statsTimeSavedLabel => 'Saved by speed';
+
+ @override
+ String statsOnPaceFor(int count) {
+ return 'On pace for $count books';
+ }
+
@override
String get statsDaysActive => 'Days Active';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index 15730a30..b31a2c20 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -834,6 +834,17 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get statsHeatmapMore => 'More';
+ @override
+ String get statsDayOfWeek => 'Average by day of week';
+
+ @override
+ String get statsTimeSavedLabel => 'Saved by speed';
+
+ @override
+ String statsOnPaceFor(int count) {
+ return 'On pace for $count books';
+ }
+
@override
String get statsDaysActive => '活跃天数';
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index cd12503d..84fdf188 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -123,8 +123,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
List<String> _statsSectionOrder = [];
Set<String> _statsHiddenSections = {};
+ // Recent sessions is intentionally absent: it infinite-scrolls, so it is
+ // pinned to the bottom of the stats page and can't be reordered or hidden.
static const _statsSectionIds = [
- 'hero', 'goals', 'periods', 'activity', 'chart', 'top', 'sessions',
+ 'hero', 'goals', 'periods', 'activity', 'chart', 'dayofweek', 'top',
];
int _streamingCacheSizeMb = 0;
bool _localServerEnabled = false;
@@ -367,8 +369,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
case 'periods': return l.statsSectionTimePeriods;
case 'activity': return l.statsActivity;
case 'chart': return l.statsChartTitle;
+ case 'dayofweek': return l.statsDayOfWeek;
case 'top': return l.statsMostListened;
- case 'sessions': return l.statsRecentSessions;
}
return id;
}
@@ -380,8 +382,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
case 'periods': return Icons.date_range_rounded;
case 'activity': return Icons.local_fire_department_rounded;
case 'chart': return Icons.bar_chart_rounded;
+ case 'dayofweek': return Icons.view_week_rounded;
case 'top': return Icons.star_outline_rounded;
- case 'sessions': return Icons.history_rounded;
}
return Icons.widgets_outlined;
}
diff --git a/lib/screens/stats_screen.dart b/lib/screens/stats_screen.dart
index f1be53f6..422a0f09 100644
--- a/lib/screens/stats_screen.dart
+++ b/lib/screens/stats_screen.dart
@@ -40,10 +40,13 @@ class _StatsScreenState extends State<StatsScreen>
Set<String> _statsHidden = {};
String? _selectedDayKey;
double _selectedDaySeconds = 0;
+ double _timeSavedSeconds = 0;
late AnimationController _animController;
+ // Recent sessions stays out of the reorderable sections: it loads more as
+ // you scroll, so anything placed under it would never be reachable.
static const _defaultSectionOrder = [
- 'hero', 'goals', 'periods', 'activity', 'chart', 'top', 'sessions',
+ 'hero', 'goals', 'periods', 'activity', 'chart', 'dayofweek', 'top',
];
late Animation<double> _animValue;
@@ -113,6 +116,7 @@ class _StatsScreenState extends State<StatsScreen>
final chartRange = await PlayerSettings.getStatsChartRange();
final order = await PlayerSettings.getStatsSectionOrder();
final hidden = await PlayerSettings.getStatsHiddenSections();
+ final timeSaved = await PlayerSettings.getStatsTimeSaved();
if (!mounted) return;
setState(() {
if (chartStyle != _chartStyle || chartRange != _chartRange) {
@@ -125,6 +129,7 @@ class _StatsScreenState extends State<StatsScreen>
_chartRange = chartRange;
_statsOrder = order;
_statsHidden = hidden.toSet();
+ _timeSavedSeconds = timeSaved;
});
}
@@ -171,6 +176,13 @@ class _StatsScreenState extends State<StatsScreen>
final lib = context.read<LibraryProvider>();
final prefs = await SharedPreferences.getInstance();
+ // The saved-by-speed counter banks while listening, so re-read it on
+ // every load (incl. pull-to-refresh), not just at screen creation.
+ final timeSaved = await PlayerSettings.getStatsTimeSaved();
+ if (mounted && timeSaved != _timeSavedSeconds) {
+ setState(() => _timeSavedSeconds = timeSaved);
+ }
+
// Load cached data first so the page renders immediately even offline.
if (_isLoading) {
final cachedStats = prefs.getString(_kStats);
@@ -407,6 +419,15 @@ class _StatsScreenState extends State<StatsScreen>
child: _accentStatCard(tt, cs, Icons.speed_rounded, cs.tertiary,
_formatDuration(avgDaily), l.statsDailyAverage)),
]),
+ if (_timeSavedSeconds >= 60) ...[
+ const SizedBox(height: 8),
+ Row(children: [
+ Expanded(
+ child: _accentStatCard(tt, cs, Icons.fast_forward_rounded,
+ Colors.cyan, _formatDuration(_timeSavedSeconds),
+ l.statsTimeSavedLabel)),
+ ]),
+ ],
const SizedBox(height: 28),
],
'chart': [
@@ -421,6 +442,12 @@ class _StatsScreenState extends State<StatsScreen>
_selectedDayRow(cs, tt),
const SizedBox(height: 28),
],
+ 'dayofweek': [
+ _sectionTitle(tt, cs, l.statsDayOfWeek),
+ const SizedBox(height: 10),
+ _dayOfWeekChart(cs, tt, l, dailyMap),
+ const SizedBox(height: 28),
+ ],
'top': [
if (topItems.isNotEmpty) ...[
_sectionTitle(tt, cs, l.statsMostListened),
@@ -429,26 +456,6 @@ class _StatsScreenState extends State<StatsScreen>
const SizedBox(height: 28),
],
],
- 'sessions': [
- if (_sessions.isNotEmpty) ...[
- _sectionTitle(tt, cs, l.statsRecentSessions),
- const SizedBox(height: 10),
- ..._buildSessions(tt, cs, l),
- if (_isLoadingMoreSessions)
- Padding(
- padding: const EdgeInsets.symmetric(vertical: 16),
- child: Center(
- child: SizedBox(
- width: 20,
- height: 20,
- child: CircularProgressIndicator(
- strokeWidth: 2,
- color: cs.onSurface.withValues(alpha: 0.24)),
- ),
- ),
- ),
- ],
- ],
};
final order = [
@@ -467,6 +474,24 @@ class _StatsScreenState extends State<StatsScreen>
const SizedBox(height: 24),
for (final id in order)
if (!_statsHidden.contains(id)) ...sections[id]!,
+ if (_sessions.isNotEmpty) ...[
+ _sectionTitle(tt, cs, l.statsRecentSessions),
+ const SizedBox(height: 10),
+ ..._buildSessions(tt, cs, l),
+ if (_isLoadingMoreSessions)
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 16),
+ child: Center(
+ child: SizedBox(
+ width: 20,
+ height: 20,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: cs.onSurface.withValues(alpha: 0.24)),
+ ),
+ ),
+ ),
+ ],
],
);
}
@@ -500,6 +525,107 @@ class _StatsScreenState extends State<StatsScreen>
),
);
}
+ return _heatmapCard(cs, l, deco, dailyMap);
+ }
+
+ /// Average listening per weekday (across days that had any listening),
+ /// today's weekday highlighted. Averages instead of totals so a year of
+ /// Saturdays doesn't read like one monster day.
+ Widget _dayOfWeekChart(ColorScheme cs, TextTheme tt, AppLocalizations l,
+ Map<String, dynamic> dailyMap) {
+ final labels = [
+ l.statsScreenDayMon,
+ l.statsScreenDayTue,
+ l.statsScreenDayWed,
+ l.statsScreenDayThu,
+ l.statsScreenDayFri,
+ l.statsScreenDaySat,
+ l.statsScreenDaySun,
+ ];
+ final sums = List.filled(7, 0.0);
+ final counts = List.filled(7, 0);
+ for (final e in dailyMap.entries) {
+ final d = DateTime.tryParse(e.key);
+ if (d == null) continue;
+ final v = _safeNum(e.value);
+ if (v <= 0) continue;
+ sums[d.weekday - 1] += v;
+ counts[d.weekday - 1]++;
+ }
+ final values = [
+ for (var i = 0; i < 7; i++) counts[i] > 0 ? sums[i] / counts[i] : 0.0,
+ ];
+ final maxVal = values.fold(0.0, (a, b) => a > b ? a : b);
+ final barMax = maxVal > 0 ? maxVal : 1.0;
+ final todayIdx = DateTime.now().weekday - 1;
+ final anim = _animValue.value;
+
+ return Container(
+ padding: const EdgeInsets.fromLTRB(4, 16, 4, 8),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.03),
+ borderRadius: BorderRadius.circular(16),
+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.05)),
+ ),
+ child: Column(children: [
+ SizedBox(
+ height: 110,
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.end,
+ children: [
+ for (var i = 0; i < 7; i++)
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 3),
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ if (values[i] > 0)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 4),
+ child: Text(_formatDuration(values[i]),
+ textAlign: TextAlign.center,
+ style: TextStyle(
+ color: cs.onSurface.withValues(alpha: 0.35),
+ fontSize: 8,
+ fontWeight: FontWeight.w600))),
+ Container(
+ height: max(
+ (values[i] / barMax * anim).clamp(0.0, 1.0) * 72,
+ values[i] > 0 ? 4 : 2),
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(5),
+ color: i == todayIdx
+ ? cs.primary.withValues(alpha: 0.7)
+ : cs.onSurface.withValues(alpha: 0.12),
+ ),
+ ),
+ ]),
+ )),
+ ],
+ ),
+ ),
+ const SizedBox(height: 8),
+ Row(children: [
+ for (var i = 0; i < 7; i++)
+ Expanded(
+ child: Text(labels[i],
+ textAlign: TextAlign.center,
+ style: TextStyle(
+ color: i == todayIdx
+ ? cs.primary.withValues(alpha: 0.8)
+ : cs.onSurface.withValues(alpha: 0.25),
+ fontSize: 10,
+ fontWeight:
+ i == todayIdx ? FontWeight.w600 : FontWeight.w400,
+ ))),
+ ]),
+ ]),
+ );
+ }
+
+ Widget _heatmapCard(ColorScheme cs, AppLocalizations l, BoxDecoration deco,
+ Map<String, dynamic> dailyMap) {
final daily = <String, double>{
for (final e in dailyMap.entries) e.key: _safeNum(e.value),
};
@@ -567,6 +693,12 @@ class _StatsScreenState extends State<StatsScreen>
final double bookProgress =
hasBookGoal ? (_booksFinishedThisYear / _bookGoal).clamp(0.0, 1.0).toDouble() : 0.0;
final bookReached = hasBookGoal && _booksFinishedThisYear >= _bookGoal;
+ final now = DateTime.now();
+ final dayOfYear = now.difference(DateTime(now.year, 1, 1)).inDays + 1;
+ final daysInYear =
+ DateTime(now.year, 12, 31).difference(DateTime(now.year, 1, 1)).inDays + 1;
+ final projectedBooks = (_booksFinishedThisYear * daysInYear / dayOfYear).round();
+ final onTrack = projectedBooks >= _bookGoal;
return Container(
padding: const EdgeInsets.all(16),
@@ -642,6 +774,21 @@ class _StatsScreenState extends State<StatsScreen>
valueColor: AlwaysStoppedAnimation(bookReached ? doneColor : cs.primary),
),
),
+ if (!bookReached) ...[
+ const SizedBox(height: 6),
+ Row(children: [
+ Icon(
+ onTrack
+ ? Icons.trending_up_rounded
+ : Icons.trending_down_rounded,
+ size: 13,
+ color: onTrack ? doneColor : Colors.orange),
+ const SizedBox(width: 4),
+ Text(l.statsOnPaceFor(projectedBooks),
+ style: tt.labelSmall?.copyWith(
+ color: onTrack ? doneColor : Colors.orange)),
+ ]),
+ ],
]),
]),
);
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 7cfeda0f..4c278c62 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -3758,6 +3758,8 @@ class AudioPlayerService extends ChangeNotifier {
: _currentItemId!;
final offlineSeconds = sinceLastSync.clamp(0, 300);
_progressSync.addOfflineListeningTime(progressKey, offlineSeconds);
+ unawaited(_progressSync.addTimeSaved(
+ offlineSeconds, _player?.speed ?? 1.0));
// Widget ticks forward even when the server is unreachable.
unawaited(HomeWidgetService()
.addLocalListeningSeconds(offlineSeconds));
@@ -4104,6 +4106,9 @@ class AudioPlayerService extends ChangeNotifier {
final elapsed = timeListenedOverride ??
now.difference(_lastServerSync).inSeconds.clamp(0, 300);
_lastServerSync = now;
+ if (elapsed > 0) {
+ unawaited(_progressSync.addTimeSaved(elapsed.toInt(), _player?.speed ?? 1.0));
+ }
// Alpha: volume/sessionId piggybacked for GH #179 (volume falls off).
// We sample these on each sync tick so drift over time is visible.
final vol = _player?.volume;
diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dart
index 35204c33..548162e7 100644
--- a/lib/services/player_settings.dart
+++ b/lib/services/player_settings.dart
@@ -166,6 +166,10 @@ class PlayerSettings {
static Future<int> getStatsBookGoal() => _get('stats_book_goal', 0);
static Future<void> setStatsBookGoal(int value) => _set('stats_book_goal', value, notify: true);
+ /// Wall-clock seconds saved by listening above 1x. Banked live by the
+ /// player as listening time accrues; read-only here.
+ static Future<double> getStatsTimeSaved() => _get('stats_time_saved', 0.0);
+
/// Listening chart style on the stats page: 'bar' | 'line' | 'heatmap'.
static Future<String> getStatsChartStyle() => _get('stats_chart_style', 'bar');
static Future<void> setStatsChartStyle(String value) => _set('stats_chart_style', value, notify: true);
diff --git a/lib/services/progress_sync_service.dart b/lib/services/progress_sync_service.dart
index 73896327..2c67c77b 100644
--- a/lib/services/progress_sync_service.dart
+++ b/lib/services/progress_sync_service.dart
@@ -368,6 +368,21 @@ class ProgressSyncService {
}
}
+ /// Bank time saved by playback speed: [elapsedSeconds] of wall-clock
+ /// listening at [speed]. Exact even with constant speed changes because it
+ /// samples whatever speed is live each time listening accrues. Stored
+ /// per-account; shown on the stats page.
+ Future<void> addTimeSaved(int elapsedSeconds, double speed) async {
+ if (elapsedSeconds <= 0 || (speed - 1.0).abs() < 0.01) return;
+ final saved = elapsedSeconds * (speed - 1.0);
+ final current = await ScopedPrefs.getDouble('stats_time_saved') ?? 0.0;
+ await ScopedPrefs.setDouble('stats_time_saved', current + saved);
+ if (await ScopedPrefs.getInt('stats_time_saved_since') == null) {
+ await ScopedPrefs.setInt(
+ 'stats_time_saved_since', DateTime.now().millisecondsSinceEpoch);
+ }
+ }
+
/// Flush accumulated offline listening time to the server by creating
/// a session, syncing the accumulated time, and closing it.
/// Called externally (e.g. from library_provider) and also internally