A cross platform Audiobookshelf client for Android and iOS
Dart
Add advanced toggle to playback history sheet
Barnabas41d40ba592ad
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex 840000b8..3da2c8c9 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -404,7 +404,9 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {@overrideFuture<void> click([MediaButton button = MediaButton.media]) async {debugPrint('[Handler] click(button=$button) count=${_clickCount + 1} playing=${_player.playing}');- debugPrint('[ClickDebug] click arrival (button=$button): ${_clickDebugSnapshot()}');+ final snapshot = _clickDebugSnapshot();+ debugPrint('[ClickDebug] click arrival (button=$button): $snapshot');+ _service?._logEvent(PlaybackEventType.clickDebounce, detail: 'button=$button | $snapshot');if (button != MediaButton.media) {// Hardware next/prev button — set cooldown to ignore phantom media click@@ -1692,6 +1694,7 @@ class AudioPlayerService extends ChangeNotifier {if (sessionData != null) {_playbackSessionId = sessionData['id'] as String?;debugPrint('[Player] Got server session for local playback: $_playbackSessionId');+ _logEvent(PlaybackEventType.sessionStart, detail: 'local');// Alpha [PodDur]: which duration fields did the session response carry?// If the server ships a usable duration here and we ignore it, we@@ -1994,6 +1997,7 @@ class AudioPlayerService extends ChangeNotifier {_playbackSessionId = sessionData['id'] as String?;_lastServerSync = DateTime.now();debugPrint('[Player] Background session refreshed: $_playbackSessionId');+ _logEvent(PlaybackEventType.sessionStart, detail: 'refresh');// Update cached session with fresh track data in case it changedfinal audioTracks = sessionData['audioTracks'] as List<dynamic>?;@@ -2047,6 +2051,7 @@ class AudioPlayerService extends ChangeNotifier {_playbackSessionId = sessionData['id'] as String?;_lastServerSync = DateTime.now();+ _logEvent(PlaybackEventType.sessionStart, detail: 'stream');var audioTracks = sessionData['audioTracks'] as List<dynamic>?;if (audioTracks == null || audioTracks.isEmpty) {_clearState();@@ -2977,7 +2982,7 @@ class AudioPlayerService extends ChangeNotifier {}debugPrint('[Player] Book complete: $_currentTitle');- _logEvent(PlaybackEventType.pause, detail: 'Book finished');+ _logEvent(PlaybackEventType.bookFinished);// Stop immediately to prevent ExoPlayer from seeking back to position 0// (which triggers position-stream events that look like a restart).@@ -3032,6 +3037,7 @@ class AudioPlayerService extends ChangeNotifier {if (_playbackSessionId != null && _api != null) {final api = _api!;final sessionId = _playbackSessionId!;+ _logEvent(PlaybackEventType.sessionEnd, detail: 'book finished');unawaited(() async {try {debugPrint('[Player] Closing session (book finished)');@@ -3103,6 +3109,9 @@ class AudioPlayerService extends ChangeNotifier {// 15-min authoritative refreshes (which Android Doze throttles).unawaited(HomeWidgetService().addLocalListeningSeconds(elapsed));}+ if (ok) {+ _logEvent(PlaybackEventType.syncServer, detail: '+${elapsed}s');+ }if (!ok && !_syncRecoveryInProgress) {debugPrint('[Player] Session sync failed - attempting recovery');_syncRecoveryInProgress = true;@@ -3124,6 +3133,7 @@ class AudioPlayerService extends ChangeNotifier {if (sessionData != null) {_playbackSessionId = sessionData['id'] as String?;debugPrint('[Player] Recovered session: $_playbackSessionId');+ _logEvent(PlaybackEventType.sessionStart, detail: 'recovery');// Re-sync the lost time to the new sessionif (_playbackSessionId != null && lostTimeListened > 0) {await _api!.syncPlaybackSession(@@ -3401,6 +3411,7 @@ class AudioPlayerService extends ChangeNotifier {// been paused for the whole pause-timeout window - the wall-clock diff// would otherwise inflate server listening stats by up to 300s.if (_playbackSessionId != null && _api != null) {+ _logEvent(PlaybackEventType.sessionEnd, detail: 'pause timeout');try {await _syncToServer(position, timeListenedOverride: 0);debugPrint('[Player] Closing session (pause timeout)');@@ -3583,6 +3594,7 @@ class AudioPlayerService extends ChangeNotifier {// so the wall-clock diff doesn't inflate server listening stats.if (_playbackSessionId != null && _api != null) {final wasPlaying = _player?.playing ?? false;+ _logEvent(PlaybackEventType.sessionEnd, detail: 'stop');await _syncToServer(position,timeListenedOverride: wasPlaying ? null : 0);try {diff --git a/lib/services/playback_history_service.dart b/lib/services/playback_history_service.dartindex 69c7fc9f..dee4e50d 100644--- a/lib/services/playback_history_service.dart+++ b/lib/services/playback_history_service.dart@@ -13,8 +13,21 @@ enum PlaybackEventType {skipForward,skipBackward,speedChange,+ bookFinished,+ sessionStart,+ sessionEnd,+ clickDebounce,}+/// Events that only show in the sheet when the user enables advanced mode.+const Set<PlaybackEventType> kAdvancedHistoryEvents = {+ PlaybackEventType.syncLocal,+ PlaybackEventType.syncServer,+ PlaybackEventType.sessionStart,+ PlaybackEventType.sessionEnd,+ PlaybackEventType.clickDebounce,+};+/// A single playback event entry.class PlaybackEvent {final PlaybackEventType type;@@ -75,6 +88,17 @@ class PlaybackEvent {case PlaybackEventType.speedChange:if (detail != null && detail!.isNotEmpty) return 'Speed set to ${detail!}';return 'Speed changed';+ case PlaybackEventType.bookFinished:+ return 'Book finished';+ case PlaybackEventType.sessionStart:+ if (detail != null && detail!.isNotEmpty) return 'Session started ($detail)';+ return 'Session started';+ case PlaybackEventType.sessionEnd:+ if (detail != null && detail!.isNotEmpty) return 'Session ended ($detail)';+ return 'Session ended';+ case PlaybackEventType.clickDebounce:+ if (detail != null && detail!.isNotEmpty) return 'Media button: $detail';+ return 'Media button';}}@@ -98,6 +122,14 @@ class PlaybackEvent {return '⏮';case PlaybackEventType.speedChange:return '⚡';+ case PlaybackEventType.bookFinished:+ return '🏁';+ case PlaybackEventType.sessionStart:+ return '🟢';+ case PlaybackEventType.sessionEnd:+ return '🔴';+ case PlaybackEventType.clickDebounce:+ return '🖲';}}}@@ -108,7 +140,7 @@ class PlaybackHistoryService {factory PlaybackHistoryService() => _instance;PlaybackHistoryService._();- static const int _maxEventsPerBook = 200;+ static const int _maxEventsPerBook = 1000;/// Log an event for a book.Future<void> log({diff --git a/lib/widgets/absorbing_shared.dart b/lib/widgets/absorbing_shared.dartindex f4886af9..3ca2aaf3 100644--- a/lib/widgets/absorbing_shared.dart+++ b/lib/widgets/absorbing_shared.dart@@ -67,6 +67,10 @@ IconData historyIcon(PlaybackEventType type) {case PlaybackEventType.skipForward: return Icons.forward_30_rounded;case PlaybackEventType.skipBackward: return Icons.replay_10_rounded;case PlaybackEventType.speedChange: return Icons.speed_rounded;+ case PlaybackEventType.bookFinished: return Icons.flag_rounded;+ case PlaybackEventType.sessionStart: return Icons.fiber_manual_record_rounded;+ case PlaybackEventType.sessionEnd: return Icons.stop_circle_outlined;+ case PlaybackEventType.clickDebounce: return Icons.touch_app_rounded;}}diff --git a/lib/widgets/card_buttons.dart b/lib/widgets/card_buttons.dartindex 8771d5ce..b4e8a65c 100644--- a/lib/widgets/card_buttons.dart+++ b/lib/widgets/card_buttons.dart@@ -12,6 +12,7 @@ import '../services/chromecast_service.dart';import '../services/download_service.dart';import '../services/equalizer_service.dart';import '../services/playback_history_service.dart';+import '../services/scoped_prefs.dart';import '../services/sleep_timer_service.dart';import 'absorb_slider.dart';import 'absorbing_shared.dart';@@ -1786,85 +1787,20 @@ class CardActionDelegate {}void showHistory(BuildContext ctx, Color accent, TextTheme tt) {- final l = AppLocalizations.of(ctx)!;showModalBottomSheet(context: ctx, isScrollControlled: true, useSafeArea: true,backgroundColor: Colors.transparent,builder: (sheetCtx) => DraggableScrollableSheet(expand: false, initialChildSize: 0.6, minChildSize: 0.05, snap: true, maxChildSize: 0.9,- builder: (_, sc) => Container(- decoration: BoxDecoration(- color: Theme.of(ctx).bottomSheetTheme.backgroundColor,- borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),- border: Border(top: BorderSide(color: accent.withValues(alpha: 0.2), width: 1)),- ),- child: Column(children: [- Padding(padding: const EdgeInsets.symmetric(vertical: 12),- child: Container(width: 40, height: 4, decoration: BoxDecoration(color: Theme.of(ctx).colorScheme.onSurface.withValues(alpha: 0.24), borderRadius: BorderRadius.circular(2)))),- Padding(- padding: const EdgeInsets.symmetric(horizontal: 16),- child: Row(children: [- const Spacer(),- Text(l.playbackHistory, style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),- const Spacer(),- IconButton(- icon: Icon(Icons.delete_outline_rounded, size: 20, color: Theme.of(ctx).colorScheme.onSurfaceVariant),- onPressed: () async {- await PlaybackHistoryService().clearHistory(itemId);- if (sheetCtx.mounted) Navigator.pop(sheetCtx);- },- tooltip: l.clearHistoryTooltip,- ),- ]),- ),- if (isActive)- Padding(- padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),- child: Text(l.tapEventToJump,- style: tt.bodySmall?.copyWith(color: Theme.of(ctx).colorScheme.onSurfaceVariant.withValues(alpha: 0.6), fontStyle: FontStyle.italic)),- )- else- const SizedBox(height: 8),- Expanded(child: FutureBuilder<List<PlaybackEvent>>(- future: PlaybackHistoryService().getHistory(itemId),- builder: (futureCtx, snap) {- if (!snap.hasData) return const Center(child: CircularProgressIndicator(strokeWidth: 2));- final events = snap.data!;- if (events.isEmpty) return Center(child: Text(l.noHistoryYet, style: tt.bodyMedium?.copyWith(color: Theme.of(ctx).colorScheme.onSurfaceVariant)));-- final items = <Widget>[];- String? lastDate;- for (int i = 0; i < events.length; i++) {- final e = events[i];- final dl = dateLabel(e.timestamp);- if (dl != lastDate) {- lastDate = dl;- items.add(Padding(- padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),- child: Text(dl, style: tt.labelSmall?.copyWith(- color: accent.withValues(alpha: 0.6), fontWeight: FontWeight.w600, letterSpacing: 0.5)),- ));- }- final posLabel = fmtTime(e.positionSeconds);- final timeStr = timeOfDay(e.timestamp);- items.add(ListTile(- dense: true, visualDensity: const VisualDensity(vertical: -2),- leading: Icon(historyIcon(e.type), size: 18, color: accent.withValues(alpha: 0.7)),- title: Text(e.label, style: tt.bodySmall?.copyWith(color: Theme.of(ctx).colorScheme.onSurface.withValues(alpha: 0.7))),- subtitle: Text(l.atPosition(posLabel), style: tt.labelSmall?.copyWith(color: Theme.of(ctx).colorScheme.onSurfaceVariant)),- trailing: Text(timeStr, style: tt.labelSmall?.copyWith(color: Theme.of(ctx).colorScheme.onSurface.withValues(alpha: 0.3))),- onTap: isActive ? () {- player.seekTo(Duration(seconds: e.positionSeconds.round()));- Navigator.pop(futureCtx);- ScaffoldMessenger.of(ctx).showSnackBar(SnackBar(duration: const Duration(seconds: 3), content: Text(l.jumpedToPosition(posLabel))));- } : null,- ));- }-- return ListView(controller: sc, children: items);- },- )),- ]),+ builder: (_, sc) => _PlaybackHistoryBody(+ itemId: itemId,+ accent: accent,+ tt: tt,+ isActive: isActive,+ player: player,+ parentCtx: ctx,+ sheetCtx: sheetCtx,+ scrollController: sc,),),);@@ -1904,3 +1840,212 @@ class CardActionDelegate {};}}++const String _kAdvancedHistoryPrefKey = 'playback_history_advanced';++class _PlaybackHistoryBody extends StatefulWidget {+ final String itemId;+ final Color accent;+ final TextTheme tt;+ final bool isActive;+ final AudioPlayerService player;+ final BuildContext parentCtx;+ final BuildContext sheetCtx;+ final ScrollController scrollController;++ const _PlaybackHistoryBody({+ required this.itemId,+ required this.accent,+ required this.tt,+ required this.isActive,+ required this.player,+ required this.parentCtx,+ required this.sheetCtx,+ required this.scrollController,+ });++ @override+ State<_PlaybackHistoryBody> createState() => _PlaybackHistoryBodyState();+}++class _PlaybackHistoryBodyState extends State<_PlaybackHistoryBody> {+ bool _advanced = false;+ Future<List<PlaybackEvent>>? _future;++ @override+ void initState() {+ super.initState();+ _future = PlaybackHistoryService().getHistory(widget.itemId);+ ScopedPrefs.getBool(_kAdvancedHistoryPrefKey).then((v) {+ if (!mounted) return;+ setState(() => _advanced = v ?? false);+ });+ }++ Future<void> _toggleAdvanced() async {+ final next = !_advanced;+ setState(() => _advanced = next);+ await ScopedPrefs.setBool(_kAdvancedHistoryPrefKey, next);+ }++ @override+ Widget build(BuildContext context) {+ final l = AppLocalizations.of(widget.parentCtx)!;+ final cs = Theme.of(widget.parentCtx).colorScheme;+ return Container(+ decoration: BoxDecoration(+ color: Theme.of(widget.parentCtx).bottomSheetTheme.backgroundColor,+ borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),+ border: Border(top: BorderSide(color: widget.accent.withValues(alpha: 0.2), width: 1)),+ ),+ child: Column(children: [+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 12),+ child: Container(+ width: 40, height: 4,+ decoration: BoxDecoration(+ color: cs.onSurface.withValues(alpha: 0.24),+ borderRadius: BorderRadius.circular(2),+ ),+ ),+ ),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16),+ child: Row(children: [+ const Spacer(),+ Text(+ l.playbackHistory,+ style: widget.tt.titleMedium?.copyWith(fontWeight: FontWeight.w600),+ ),+ const Spacer(),+ IconButton(+ icon: Icon(Icons.delete_outline_rounded, size: 20, color: cs.onSurfaceVariant),+ onPressed: () async {+ await PlaybackHistoryService().clearHistory(widget.itemId);+ if (widget.sheetCtx.mounted) Navigator.pop(widget.sheetCtx);+ },+ tooltip: l.clearHistoryTooltip,+ ),+ ]),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 4, 16, 4),+ child: Row(children: [+ if (widget.isActive)+ Expanded(+ child: Text(+ l.tapEventToJump,+ style: widget.tt.bodySmall?.copyWith(+ color: cs.onSurfaceVariant.withValues(alpha: 0.6),+ fontStyle: FontStyle.italic,+ ),+ ),+ )+ else+ const Spacer(),+ Text(+ 'Show more',+ style: widget.tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),+ ),+ const SizedBox(width: 8),+ Transform.scale(+ scale: 0.8,+ child: Switch(+ value: _advanced,+ onChanged: (_) => _toggleAdvanced(),+ activeThumbColor: widget.accent,+ ),+ ),+ ]),+ ),+ Expanded(+ child: FutureBuilder<List<PlaybackEvent>>(+ future: _future,+ builder: (futureCtx, snap) {+ if (!snap.hasData) {+ return const Center(child: CircularProgressIndicator(strokeWidth: 2));+ }+ final all = snap.data!;+ final events = _advanced+ ? all+ : all.where((e) => !kAdvancedHistoryEvents.contains(e.type)).toList();+ if (events.isEmpty) {+ return Center(+ child: Text(+ l.noHistoryYet,+ style: widget.tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant),+ ),+ );+ }++ final items = <Widget>[];+ String? lastDate;+ for (int i = 0; i < events.length; i++) {+ final e = events[i];+ final dl = dateLabel(e.timestamp);+ if (dl != lastDate) {+ lastDate = dl;+ items.add(Padding(+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),+ child: Text(+ dl,+ style: widget.tt.labelSmall?.copyWith(+ color: widget.accent.withValues(alpha: 0.6),+ fontWeight: FontWeight.w600,+ letterSpacing: 0.5,+ ),+ ),+ ));+ }+ final posLabel = fmtTime(e.positionSeconds);+ final timeStr = timeOfDay(e.timestamp);+ final isAdvancedEvent = kAdvancedHistoryEvents.contains(e.type);+ items.add(ListTile(+ dense: true,+ visualDensity: const VisualDensity(vertical: -2),+ leading: Icon(+ historyIcon(e.type),+ size: 18,+ color: widget.accent.withValues(alpha: isAdvancedEvent ? 0.45 : 0.7),+ ),+ title: Text(+ e.label,+ style: widget.tt.bodySmall?.copyWith(+ color: cs.onSurface.withValues(alpha: isAdvancedEvent ? 0.55 : 0.7),+ ),+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ ),+ subtitle: Text(+ l.atPosition(posLabel),+ style: widget.tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),+ ),+ trailing: Text(+ timeStr,+ style: widget.tt.labelSmall?.copyWith(+ color: cs.onSurface.withValues(alpha: 0.3),+ ),+ ),+ onTap: widget.isActive+ ? () {+ widget.player.seekTo(Duration(seconds: e.positionSeconds.round()));+ Navigator.pop(futureCtx);+ ScaffoldMessenger.of(widget.parentCtx).showSnackBar(+ SnackBar(+ duration: const Duration(seconds: 3),+ content: Text(l.jumpedToPosition(posLabel)),+ ),+ );+ }+ : null,+ ));+ }++ return ListView(controller: widget.scrollController, children: items);+ },+ ),+ ),+ ]),+ );+ }+}