Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Show listening sessions for books and podcasts and stop duplicate detail sheets

Barnabasa98c8eb7462d
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index 938dd7bf..62d53719 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -1326,6 +1326,10 @@
"bookmarkAdded": "Bookmark added",
"startPlayingSomethingFirst": "Start playing something first",
"playbackHistory": "Playback History",
+ "historyLocalTab": "History",
+ "historyServerTab": "Sessions",
+ "historyNoServerSessions": "No server sessions for this item yet",
+ "historyServerLoadFailed": "Could not load server sessions",
"clearHistoryTooltip": "Clear history",
"tapEventToJump": "Tap an event to jump to that position",
"noHistoryYet": "No history yet",
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index fb7a473d..ebb014fc 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -4876,6 +4876,30 @@ abstract class AppLocalizations {
/// **'Playback History'**
String get playbackHistory;
+ /// No description provided for @historyLocalTab.
+ ///
+ /// In en, this message translates to:
+ /// **'History'**
+ String get historyLocalTab;
+
+ /// No description provided for @historyServerTab.
+ ///
+ /// In en, this message translates to:
+ /// **'Sessions'**
+ String get historyServerTab;
+
+ /// No description provided for @historyNoServerSessions.
+ ///
+ /// In en, this message translates to:
+ /// **'No server sessions for this item yet'**
+ String get historyNoServerSessions;
+
+ /// No description provided for @historyServerLoadFailed.
+ ///
+ /// In en, this message translates to:
+ /// **'Could not load server sessions'**
+ String get historyServerLoadFailed;
+
/// No description provided for @clearHistoryTooltip.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index 5e79199a..5ab6fe1b 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -2688,6 +2688,18 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get playbackHistory => 'Wiedergabeverlauf';
+ @override
+ String get historyLocalTab => 'History';
+
+ @override
+ String get historyServerTab => 'Sessions';
+
+ @override
+ String get historyNoServerSessions => 'No server sessions for this item yet';
+
+ @override
+ String get historyServerLoadFailed => 'Could not load server sessions';
+
@override
String get clearHistoryTooltip => 'Verlauf löschen';
diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dart
index 0547569d..f63497ce 100644
--- a/lib/l10n/app_localizations_el.dart
+++ b/lib/l10n/app_localizations_el.dart
@@ -2664,6 +2664,18 @@ class AppLocalizationsEl extends AppLocalizations {
@override
String get playbackHistory => 'Playback History';
+ @override
+ String get historyLocalTab => 'History';
+
+ @override
+ String get historyServerTab => 'Sessions';
+
+ @override
+ String get historyNoServerSessions => 'No server sessions for this item yet';
+
+ @override
+ String get historyServerLoadFailed => 'Could not load server sessions';
+
@override
String get clearHistoryTooltip => 'Clear history';
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index 2b321886..e36362e0 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -2664,6 +2664,18 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get playbackHistory => 'Playback History';
+ @override
+ String get historyLocalTab => 'History';
+
+ @override
+ String get historyServerTab => 'Sessions';
+
+ @override
+ String get historyNoServerSessions => 'No server sessions for this item yet';
+
+ @override
+ String get historyServerLoadFailed => 'Could not load server sessions';
+
@override
String get clearHistoryTooltip => 'Clear history';
diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart
index 3a771bad..da0189ef 100644
--- a/lib/l10n/app_localizations_es.dart
+++ b/lib/l10n/app_localizations_es.dart
@@ -2664,6 +2664,18 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get playbackHistory => 'Playback History';
+ @override
+ String get historyLocalTab => 'History';
+
+ @override
+ String get historyServerTab => 'Sessions';
+
+ @override
+ String get historyNoServerSessions => 'No server sessions for this item yet';
+
+ @override
+ String get historyServerLoadFailed => 'Could not load server sessions';
+
@override
String get clearHistoryTooltip => 'Clear history';
diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart
index f64e4044..f492ba06 100644
--- a/lib/l10n/app_localizations_fr.dart
+++ b/lib/l10n/app_localizations_fr.dart
@@ -2666,6 +2666,18 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get playbackHistory => 'Playback History';
+ @override
+ String get historyLocalTab => 'History';
+
+ @override
+ String get historyServerTab => 'Sessions';
+
+ @override
+ String get historyNoServerSessions => 'No server sessions for this item yet';
+
+ @override
+ String get historyServerLoadFailed => 'Could not load server sessions';
+
@override
String get clearHistoryTooltip => 'Clear history';
diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart
index ad55d18a..a934b826 100644
--- a/lib/l10n/app_localizations_it.dart
+++ b/lib/l10n/app_localizations_it.dart
@@ -2664,6 +2664,18 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get playbackHistory => 'Playback History';
+ @override
+ String get historyLocalTab => 'History';
+
+ @override
+ String get historyServerTab => 'Sessions';
+
+ @override
+ String get historyNoServerSessions => 'No server sessions for this item yet';
+
+ @override
+ String get historyServerLoadFailed => 'Could not load server sessions';
+
@override
String get clearHistoryTooltip => 'Clear history';
diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart
index 8c1bc29b..5ef08074 100644
--- a/lib/l10n/app_localizations_ja.dart
+++ b/lib/l10n/app_localizations_ja.dart
@@ -2664,6 +2664,18 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get playbackHistory => 'Playback History';
+ @override
+ String get historyLocalTab => 'History';
+
+ @override
+ String get historyServerTab => 'Sessions';
+
+ @override
+ String get historyNoServerSessions => 'No server sessions for this item yet';
+
+ @override
+ String get historyServerLoadFailed => 'Could not load server sessions';
+
@override
String get clearHistoryTooltip => 'Clear history';
diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dart
index ea26b0a7..9d6c950f 100644
--- a/lib/l10n/app_localizations_no.dart
+++ b/lib/l10n/app_localizations_no.dart
@@ -2664,6 +2664,18 @@ class AppLocalizationsNo extends AppLocalizations {
@override
String get playbackHistory => 'Playback History';
+ @override
+ String get historyLocalTab => 'History';
+
+ @override
+ String get historyServerTab => 'Sessions';
+
+ @override
+ String get historyNoServerSessions => 'No server sessions for this item yet';
+
+ @override
+ String get historyServerLoadFailed => 'Could not load server sessions';
+
@override
String get clearHistoryTooltip => 'Clear history';
diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart
index 3b092a7d..04fa02e5 100644
--- a/lib/l10n/app_localizations_pt.dart
+++ b/lib/l10n/app_localizations_pt.dart
@@ -2664,6 +2664,18 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get playbackHistory => 'Playback History';
+ @override
+ String get historyLocalTab => 'History';
+
+ @override
+ String get historyServerTab => 'Sessions';
+
+ @override
+ String get historyNoServerSessions => 'No server sessions for this item yet';
+
+ @override
+ String get historyServerLoadFailed => 'Could not load server sessions';
+
@override
String get clearHistoryTooltip => 'Clear history';
diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dart
index 3a09fbe1..572c4b2e 100644
--- a/lib/l10n/app_localizations_ro.dart
+++ b/lib/l10n/app_localizations_ro.dart
@@ -2664,6 +2664,18 @@ class AppLocalizationsRo extends AppLocalizations {
@override
String get playbackHistory => 'Playback History';
+ @override
+ String get historyLocalTab => 'History';
+
+ @override
+ String get historyServerTab => 'Sessions';
+
+ @override
+ String get historyNoServerSessions => 'No server sessions for this item yet';
+
+ @override
+ String get historyServerLoadFailed => 'Could not load server sessions';
+
@override
String get clearHistoryTooltip => 'Clear history';
diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart
index fcdeb73c..97b0f725 100644
--- a/lib/l10n/app_localizations_ru.dart
+++ b/lib/l10n/app_localizations_ru.dart
@@ -2667,6 +2667,18 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get playbackHistory => 'Playback History';
+ @override
+ String get historyLocalTab => 'History';
+
+ @override
+ String get historyServerTab => 'Sessions';
+
+ @override
+ String get historyNoServerSessions => 'No server sessions for this item yet';
+
+ @override
+ String get historyServerLoadFailed => 'Could not load server sessions';
+
@override
String get clearHistoryTooltip => 'Clear history';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index 265303c6..a0aa3237 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -2597,6 +2597,18 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get playbackHistory => '播放历史';
+ @override
+ String get historyLocalTab => 'History';
+
+ @override
+ String get historyServerTab => 'Sessions';
+
+ @override
+ String get historyNoServerSessions => 'No server sessions for this item yet';
+
+ @override
+ String get historyServerLoadFailed => 'Could not load server sessions';
+
@override
String get clearHistoryTooltip => '清除历史';
diff --git a/lib/screens/stats_screen.dart b/lib/screens/stats_screen.dart
index 7c9342d6..641883c8 100644
--- a/lib/screens/stats_screen.dart
+++ b/lib/screens/stats_screen.dart
@@ -10,8 +10,7 @@ import '../services/audio_player_service.dart';
import '../widgets/absorb_page_header.dart';
import '../widgets/finished_books_this_year_sheet.dart';
import '../widgets/stats_charts.dart';
-import '../widgets/absorb_wave_icon.dart';
-import '../widgets/card_buttons.dart';
+import '../widgets/listening_session_card.dart';
import '../widgets/overlay_toast.dart';
import '../main.dart' show flatNotifier, gradientIntensityNotifier;
import 'app_shell.dart';
@@ -586,7 +585,7 @@ class _StatsScreenState extends State<StatsScreen>
if (_sessions.isNotEmpty) ...[
_sectionTitle(tt, cs, l.statsRecentSessions),
const SizedBox(height: 10),
- ..._buildSessions(tt, cs, l),
+ ..._buildSessions(),
if (_isLoadingMoreSessions)
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
@@ -1456,103 +1455,12 @@ class _StatsScreenState extends State<StatsScreen>
// --- SESSIONS ---
- List<Widget> _buildSessions(TextTheme tt, ColorScheme cs, AppLocalizations l) {
+ List<Widget> _buildSessions() {
return _sessions.map((s) {
if (s is! Map<String, dynamic>) return const SizedBox.shrink();
- final rawTitle = s['displayTitle'] as String?;
- final rawAuthor = s['displayAuthor'] as String?;
- final meta = s['mediaMetadata'] as Map<String, dynamic>?;
- final title = (rawTitle != null && !_looksLikeId(rawTitle))
- ? rawTitle
- : meta?['title'] as String? ?? l.unknown;
- final author = (rawAuthor != null && !_looksLikeId(rawAuthor))
- ? rawAuthor
- : meta?['authorName'] as String? ?? '';
- final duration = _safeNum(s['timeListening']);
- final updatedAt = s['updatedAt'] is num
- ? DateTime.fromMillisecondsSinceEpoch((s['updatedAt'] as num).toInt())
- : null;
-
- final deviceInfo = s['deviceInfo'] as Map<String, dynamic>? ?? {};
- final clientName = deviceInfo['clientName'] as String? ??
- deviceInfo['deviceName'] as String? ??
- '';
- final isAbsorb = clientName.toLowerCase().contains('absorb');
-
- return Padding(
- padding: const EdgeInsets.only(bottom: 6),
- child: Material(
- color: Colors.transparent,
- child: InkWell(
- onTap: () => _showSessionDetails(s),
- borderRadius: BorderRadius.circular(12),
- child: Ink(
- padding: const EdgeInsets.all(12),
- decoration: BoxDecoration(
- color: cs.onSurface.withValues(alpha: 0.05),
- borderRadius: BorderRadius.circular(12),
- border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),
- ),
- child: Row(children: [
- Container(
- width: 36,
- height: 36,
- decoration: BoxDecoration(
- color: (isAbsorb ? Colors.tealAccent : cs.onSurfaceVariant)
- .withValues(alpha: 0.18),
- borderRadius: BorderRadius.circular(9),
- ),
- child: Center(
- child: isAbsorb
- ? AbsorbWaveIcon(
- size: 18,
- color: Colors.tealAccent.withValues(alpha: 0.9))
- : Icon(_clientIcon(clientName),
- size: 17,
- color: cs.onSurfaceVariant.withValues(alpha: 0.85)),
- ),
- ),
- const SizedBox(width: 12),
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(title,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurface,
- fontWeight: FontWeight.w600,
- fontSize: 14)),
- if (author.isNotEmpty) ...[
- const SizedBox(height: 2),
- Text(author,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: cs.onSurface.withValues(alpha: 0.6),
- fontSize: 12)),
- ],
- ])),
- const SizedBox(width: 10),
- Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
- Text(_formatDuration(duration),
- style: tt.labelMedium?.copyWith(
- color: cs.onSurface.withValues(alpha: 0.85),
- fontWeight: FontWeight.w700,
- fontSize: 13)),
- if (updatedAt != null) ...[
- const SizedBox(height: 2),
- Text(_relativeDate(updatedAt),
- style: TextStyle(
- color: cs.onSurface.withValues(alpha: 0.5),
- fontSize: 11)),
- ],
- ]),
- ]),
- ),
- ),
- ),
+ return ListeningSessionCard(
+ session: s,
+ onTap: () => _showSessionDetails(s),
);
}).toList();
}
@@ -1570,20 +1478,6 @@ class _StatsScreenState extends State<StatsScreen>
}
}
- IconData _clientIcon(String clientName) {
- final lower = clientName.toLowerCase();
- if (lower.contains('audiobookshelf') || lower.contains('abs'))
- return Icons.headphones_rounded;
- if (lower.contains('web') || lower.contains('browser'))
- return Icons.language_rounded;
- if (lower.contains('ios') || lower.contains('apple'))
- return Icons.phone_iphone_rounded;
- if (lower.contains('android')) return Icons.phone_android_rounded;
- if (lower.contains('sonos') || lower.contains('cast'))
- return Icons.speaker_rounded;
- return Icons.devices_rounded;
- }
-
// --- HELPERS ---
static double _safeNum(dynamic val) => val is num ? val.toDouble() : 0;
@@ -1738,14 +1632,6 @@ class _StatsScreenState extends State<StatsScreen>
return l.statsScreenDurationShortM(m);
}
- String _relativeDate(DateTime date) {
- final l = AppLocalizations.of(context)!;
- final diff = DateTime.now().difference(date);
- if (diff.inMinutes < 60) return l.minutesAgo(diff.inMinutes);
- if (diff.inHours < 24) return l.hoursAgo(diff.inHours);
- if (diff.inDays < 7) return l.daysAgo(diff.inDays);
- return '${date.month}/${date.day}';
- }
}
class _DayData {
@@ -1774,7 +1660,13 @@ class SessionDetailsSheet extends StatefulWidget {
/// viewing another user's session (the only edit path would write to the
/// admin's own progress).
final bool allowEdit;
- const SessionDetailsSheet({super.key, required this.session, this.allowEdit = true});
+ final VoidCallback? onJumped;
+ const SessionDetailsSheet({
+ super.key,
+ required this.session,
+ this.allowEdit = true,
+ this.onJumped,
+ });
@override
State<SessionDetailsSheet> createState() => SessionDetailsSheetState();
@@ -2006,8 +1898,8 @@ class SessionDetailsSheetState extends State<SessionDetailsSheet> {
player.currentEpisodeId == episodeId) {
await player.seekTo(Duration(seconds: startTime.round()));
if (!player.isPlaying) player.play();
- if (mounted) Navigator.pop(context);
- AppShell.goToAbsorbingGlobal();
+ if (!mounted) return;
+ _finishJump();
return;
}
@@ -2107,10 +1999,19 @@ class SessionDetailsSheetState extends State<SessionDetailsSheet> {
if (!mounted) return;
if (error != null) {
setState(() => _jumping = false);
- showErrorSnackBar(context, error);
+ showOverlayToast(
+ context,
+ error,
+ icon: Icons.error_outline_rounded,
+ );
return;
}
+ _finishJump();
+ }
+
+ void _finishJump() {
Navigator.pop(context);
+ widget.onJumped?.call();
AppShell.goToAbsorbingGlobal();
}
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 3a723c6f..267b887e 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -554,6 +554,48 @@ class ApiService {
return null;
}
+ Future<List<Map<String, dynamic>>?> getItemListeningSessions(
+ String libraryItemId, {
+ String? episodeId,
+ }) async {
+ const itemsPerPage = 100;
+ final itemPath = Uri.encodeComponent(libraryItemId);
+ final episodePath = episodeId == null
+ ? ''
+ : '/${Uri.encodeComponent(episodeId)}';
+ final endpoint =
+ '$_cleanBaseUrl/api/me/item/listening-sessions/$itemPath$episodePath';
+ final sessions = <Map<String, dynamic>>[];
+ var page = 0;
+
+ try {
+ while (true) {
+ final uri = Uri.parse(endpoint).replace(queryParameters: {
+ 'itemsPerPage': '$itemsPerPage',
+ 'page': '$page',
+ });
+ final response = await _authGet(
+ uri,
+ timeout: const Duration(seconds: 10),
+ );
+ if (response.statusCode != 200) return null;
+
+ final data = jsonDecode(response.body) as Map<String, dynamic>;
+ final pageSessions = (data['sessions'] as List<dynamic>? ?? const [])
+ .whereType<Map<String, dynamic>>()
+ .toList();
+ sessions.addAll(pageSessions);
+
+ final numPages = (data['numPages'] as num?)?.toInt() ?? 1;
+ if (pageSessions.isEmpty || page + 1 >= numPages) break;
+ page++;
+ }
+ return sessions;
+ } catch (_) {
+ return null;
+ }
+ }
+
/// Get a specific user's listening sessions (admin, paginated).
Future<Map<String, dynamic>?> getUserListeningSessions(String userId, {int page = 0, int itemsPerPage = 10}) async {
try {
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index 4a212a1e..f55b1050 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -948,6 +948,18 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
if (!lib.isOffline) {
add(Icons.playlist_add_rounded, l.addToPlaylist, () => PlaylistPickerSheet.show(context, widget.itemId));
}
+ if (!includeOpenDetails && !lib.isOffline) {
+ add(
+ Icons.history_rounded,
+ l.historyServerTab,
+ () => showPlaybackHistorySheet(
+ context,
+ itemId: widget.itemId,
+ initialTab: PlaybackHistoryTab.sessions,
+ accent: _coverScheme?.primary ?? cs.primary,
+ ),
+ );
+ }
if (!lib.isOffline && !lib.isPodcastLibrary && auth.isAdmin) {
add(Icons.collections_bookmark_rounded, l.addToCollection, () => CollectionPickerSheet.show(context, widget.itemId));
}
diff --git a/lib/widgets/card_buttons.dart b/lib/widgets/card_buttons.dart
index 31e383dd..1f016aad 100644
--- a/lib/widgets/card_buttons.dart
+++ b/lib/widgets/card_buttons.dart
@@ -7,6 +7,8 @@ import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
import '../screens/app_shell.dart';
import '../screens/car_mode_screen.dart';
+import '../screens/stats_screen.dart';
+import '../services/api_service.dart';
import '../services/audio_player_service.dart';
import '../services/bookmark_service.dart';
import '../services/chromecast_service.dart';
@@ -26,6 +28,7 @@ import 'episode_detail_sheet.dart';
import 'episode_list_sheet.dart';
import 'equalizer_sheet.dart';
import 'feature_hint.dart';
+import 'listening_session_card.dart';
import 'notes_sheet.dart';
import 'overlay_toast.dart';
import 'sleep_timer_sheet.dart';
@@ -915,23 +918,19 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
],
])),
const SizedBox(width: 8),
- GestureDetector(
- onTap: () async {
- final confirmed = await showDialog<bool>(context: context, builder: (dlg) => AlertDialog(
- title: Text(l.deleteBookmarkQuestion),
- content: Text(l.bookmarksJumpShortContent(bm.title, bm.formattedPosition)),
- actions: [
- TextButton(onPressed: () => Navigator.pop(dlg, false), child: Text(l.cancel)),
- TextButton(onPressed: () => Navigator.pop(dlg, true), child: Text(l.delete, style: TextStyle(color: Colors.red.shade300))),
- ],
- ));
- if (confirmed != true) return;
- await BookmarkService().deleteBookmark(itemId: widget.itemId, bookmarkId: bm.id, api: AudioPlayerService().currentApi);
- _load();
- },
- child: Padding(
- padding: const EdgeInsets.all(10),
- child: Icon(Icons.delete_outline_rounded, size: 22, color: cs.onSurface.withValues(alpha: 0.35)),
+ IconButton(
+ key: ValueKey('bookmark-delete-${bm.id}'),
+ tooltip: l.delete,
+ onPressed: () => _confirmDeleteBookmark(bm),
+ padding: const EdgeInsets.all(12),
+ constraints: const BoxConstraints.tightFor(
+ width: 48,
+ height: 48,
+ ),
+ icon: Icon(
+ Icons.delete_outline_rounded,
+ size: 22,
+ color: cs.onSurface.withValues(alpha: 0.35),
),
),
]),
@@ -942,6 +941,37 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
);
}
+ Future<void> _confirmDeleteBookmark(Bookmark bookmark) async {
+ final l = AppLocalizations.of(context)!;
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (dialogContext) => AlertDialog(
+ title: Text(l.deleteBookmarkQuestion),
+ content: Text(l.bookmarksJumpShortContent(
+ bookmark.title,
+ bookmark.formattedPosition,
+ )),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(dialogContext, false),
+ child: Text(l.cancel),
+ ),
+ TextButton(
+ onPressed: () => Navigator.pop(dialogContext, true),
+ child: Text(l.delete, style: TextStyle(color: Colors.red.shade300)),
+ ),
+ ],
+ ),
+ );
+ if (!mounted || confirmed != true) return;
+ await BookmarkService().deleteBookmark(
+ itemId: widget.itemId,
+ bookmarkId: bookmark.id,
+ api: AudioPlayerService().currentApi,
+ );
+ if (mounted) await _load();
+ }
+
bool get _isCasting {
final cast = ChromecastService();
return cast.isCasting && cast.castingItemId == widget.itemId;
@@ -1935,22 +1965,16 @@ class CardActionDelegate {
}
void showHistory(BuildContext ctx, Color accent, TextTheme tt) {
- 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) => _PlaybackHistoryBody(
- itemId: itemId,
- accent: accent,
- tt: tt,
- isActive: isActive,
- player: player,
- parentCtx: ctx,
- sheetCtx: sheetCtx,
- scrollController: sc,
- ),
- ),
+ final historyEpisodeId = episodeId ??
+ (isPodcastEpisode ? player.currentEpisodeId : null);
+ showPlaybackHistorySheet(
+ ctx,
+ itemId: itemId,
+ episodeId: historyEpisodeId,
+ accent: accent,
+ textTheme: tt,
+ player: player,
+ isActive: isActive,
);
}
@@ -1969,6 +1993,11 @@ class CardActionDelegate {
for (final ep in episodes) {
if (ep is Map<String, dynamic> && ep['id'] == epId) return ep;
}
+ final cachedEpisode = recentEpisode;
+ if (cachedEpisode != null &&
+ (epId == null || cachedEpisode['id'] == epId)) {
+ return cachedEpisode;
+ }
final api = context.read<AuthProvider>().apiService;
if (api != null) {
final fullItem = await api.getLibraryItem(itemId);
@@ -1980,7 +2009,7 @@ class CardActionDelegate {
}
}
}
- if (recentEpisode != null) return recentEpisode!;
+ if (cachedEpisode != null) return cachedEpisode;
return {
'id': epId,
'title': player.currentEpisodeTitle,
@@ -1989,47 +2018,144 @@ class CardActionDelegate {
}
}
+enum PlaybackHistoryTab { history, sessions }
+
+void showPlaybackHistorySheet(
+ BuildContext context, {
+ required String itemId,
+ String? episodeId,
+ PlaybackHistoryTab initialTab = PlaybackHistoryTab.history,
+ Color? accent,
+ TextTheme? textTheme,
+ AudioPlayerService? player,
+ bool? isActive,
+}) {
+ final resolvedPlayer = player ?? AudioPlayerService();
+ final resolvedIsActive = isActive ??
+ (resolvedPlayer.currentItemId == itemId &&
+ (episodeId == null ||
+ resolvedPlayer.currentEpisodeId == episodeId));
+ final theme = Theme.of(context);
+ showModalBottomSheet(
+ context: context,
+ isScrollControlled: true,
+ useSafeArea: true,
+ backgroundColor: Colors.transparent,
+ builder: (_) => DraggableScrollableSheet(
+ expand: false,
+ initialChildSize: 0.6,
+ minChildSize: 0.05,
+ snap: true,
+ maxChildSize: 0.9,
+ builder: (_, scrollController) => _PlaybackHistoryBody(
+ itemId: itemId,
+ episodeId: episodeId,
+ api: context.read<AuthProvider>().apiService,
+ accent: accent ?? theme.colorScheme.primary,
+ tt: textTheme ?? theme.textTheme,
+ isActive: resolvedIsActive,
+ player: resolvedPlayer,
+ parentCtx: context,
+ scrollController: scrollController,
+ initialTab: initialTab,
+ ),
+ ),
+ );
+}
+
const String _kAdvancedHistoryPrefKey = 'playback_history_advanced';
class _PlaybackHistoryBody extends StatefulWidget {
final String itemId;
+ final String? episodeId;
+ final ApiService? api;
final Color accent;
final TextTheme tt;
final bool isActive;
final AudioPlayerService player;
final BuildContext parentCtx;
- final BuildContext sheetCtx;
final ScrollController scrollController;
+ final PlaybackHistoryTab initialTab;
const _PlaybackHistoryBody({
required this.itemId,
+ this.episodeId,
+ required this.api,
required this.accent,
required this.tt,
required this.isActive,
required this.player,
required this.parentCtx,
- required this.sheetCtx,
required this.scrollController,
+ required this.initialTab,
});
@override
- State<_PlaybackHistoryBody> createState() => _PlaybackHistoryBodyState();
+ State<_PlaybackHistoryBody> createState() =>
+ _PlaybackHistorySheetBodyState();
}
-class _PlaybackHistoryBodyState extends State<_PlaybackHistoryBody> {
+class _PlaybackHistorySheetBodyState extends State<_PlaybackHistoryBody>
+ with SingleTickerProviderStateMixin {
bool _advanced = false;
- Future<List<PlaybackEvent>>? _future;
+ late int _selectedTab;
+ late final TabController _tabController;
+ late final Future<List<PlaybackEvent>> _localFuture;
+ Future<List<Map<String, dynamic>>?>? _serverFuture;
@override
void initState() {
super.initState();
- _future = PlaybackHistoryService().getHistory(widget.itemId);
+ _selectedTab = widget.initialTab.index;
+ _tabController = TabController(
+ length: 2,
+ initialIndex: _selectedTab,
+ vsync: this,
+ )
+ ..addListener(_onTabChanged);
+ _localFuture = PlaybackHistoryService().getHistory(widget.itemId);
+ if (_selectedTab == PlaybackHistoryTab.sessions.index) {
+ _serverFuture = _fetchServerSessions();
+ }
ScopedPrefs.getBool(_kAdvancedHistoryPrefKey).then((v) {
if (!mounted) return;
setState(() => _advanced = v ?? false);
});
}
+ @override
+ void dispose() {
+ _tabController
+ ..removeListener(_onTabChanged)
+ ..dispose();
+ super.dispose();
+ }
+
+ void _onTabChanged() {
+ final selected = _tabController.index;
+ if (selected == _selectedTab) return;
+ final serverFuture = selected == 1 && _serverFuture == null
+ ? _fetchServerSessions()
+ : null;
+ setState(() {
+ _selectedTab = selected;
+ if (serverFuture != null) _serverFuture = serverFuture;
+ });
+ }
+
+ Future<List<Map<String, dynamic>>?> _fetchServerSessions() {
+ final api = widget.api;
+ if (api == null) return Future.value(null);
+ return api.getItemListeningSessions(
+ widget.itemId,
+ episodeId: widget.episodeId,
+ );
+ }
+
+ void _retryServerSessions() {
+ setState(() => _serverFuture = _fetchServerSessions());
+ }
+
Future<void> _toggleAdvanced() async {
final next = !_advanced;
setState(() => _advanced = next);
@@ -2038,11 +2164,11 @@ class _PlaybackHistoryBodyState extends State<_PlaybackHistoryBody> {
@override
Widget build(BuildContext context) {
- final l = AppLocalizations.of(widget.parentCtx)!;
- final cs = Theme.of(widget.parentCtx).colorScheme;
+ final l = AppLocalizations.of(context)!;
+ final cs = Theme.of(context).colorScheme;
return Container(
decoration: BoxDecoration(
- color: Theme.of(widget.parentCtx).bottomSheetTheme.backgroundColor,
+ color: Theme.of(context).bottomSheetTheme.backgroundColor,
borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
border: Border(top: BorderSide(color: widget.accent.withValues(alpha: 0.2), width: 1)),
),
@@ -2060,140 +2186,308 @@ class _PlaybackHistoryBodyState extends State<_PlaybackHistoryBody> {
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(children: [
- const Spacer(),
- Text(
- l.playbackHistory,
- style: widget.tt.titleMedium?.copyWith(fontWeight: FontWeight.w600),
+ const SizedBox(width: 48),
+ Expanded(
+ child: Text(
+ l.playbackHistory,
+ textAlign: TextAlign.center,
+ 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,
+ SizedBox.square(
+ dimension: 48,
+ child: _selectedTab == 0
+ ? IconButton(
+ icon: Icon(
+ Icons.delete_outline_rounded,
+ size: 20,
+ color: cs.onSurfaceVariant,
+ ),
+ onPressed: () async {
+ await PlaybackHistoryService()
+ .clearHistory(widget.itemId);
+ if (context.mounted) Navigator.maybePop(context);
+ },
+ tooltip: l.clearHistoryTooltip,
+ )
+ : null,
),
]),
),
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,
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: TabBar(
+ controller: _tabController,
+ indicatorColor: widget.accent,
+ labelColor: widget.accent,
+ unselectedLabelColor: cs.onSurfaceVariant,
+ dividerColor: cs.onSurface.withValues(alpha: 0.08),
+ tabs: [
+ Tab(
+ key: const ValueKey('playback-history-local-tab'),
+ text: l.historyLocalTab,
),
- ),
- ]),
+ Tab(
+ key: const ValueKey('playback-history-server-tab'),
+ text: l.historyServerTab,
+ ),
+ ],
+ ),
),
+ if (_selectedTab == 0) _buildLocalOptions(l, cs),
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,
- ));
- }
+ child: _selectedTab == 0
+ ? _buildLocalHistory(l, cs)
+ : _buildServerHistory(l, cs),
+ ),
+ ]),
+ );
+ }
- return ListView(controller: widget.scrollController, children: items);
- },
+ Widget _buildLocalOptions(AppLocalizations l, ColorScheme cs) {
+ return 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,
),
),
]),
);
}
+
+ Widget _buildLocalHistory(AppLocalizations l, ColorScheme cs) {
+ return FutureBuilder<List<PlaybackEvent>>(
+ future: _localFuture,
+ builder: (futureContext, snapshot) {
+ if (!snapshot.hasData) {
+ return const Center(
+ child: CircularProgressIndicator(strokeWidth: 2),
+ );
+ }
+ final all = snapshot.data!;
+ final events = _advanced
+ ? all
+ : all
+ .where((event) =>
+ !kAdvancedHistoryEvents.contains(event.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 (final event in events) {
+ final eventDate = dateLabel(event.timestamp, l);
+ if (eventDate != lastDate) {
+ lastDate = eventDate;
+ items.add(_dateHeader(eventDate));
+ }
+ final positionLabel = fmtTime(event.positionSeconds);
+ final isAdvancedEvent =
+ kAdvancedHistoryEvents.contains(event.type);
+ items.add(ListTile(
+ dense: true,
+ visualDensity: const VisualDensity(vertical: -2),
+ leading: Icon(
+ historyIcon(event.type),
+ size: 18,
+ color: widget.accent.withValues(
+ alpha: isAdvancedEvent ? 0.45 : 0.7,
+ ),
+ ),
+ title: Text(
+ event.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(positionLabel),
+ style: widget.tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant,
+ ),
+ ),
+ trailing: Text(
+ timeOfDay(event.timestamp, l),
+ style: widget.tt.labelSmall?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.3),
+ ),
+ ),
+ onTap: widget.isActive
+ ? () {
+ widget.player.seekTo(
+ Duration(seconds: event.positionSeconds.round()),
+ );
+ Navigator.pop(futureContext);
+ ScaffoldMessenger.of(widget.parentCtx).showSnackBar(
+ SnackBar(
+ duration: const Duration(seconds: 3),
+ content: Text(l.jumpedToPosition(positionLabel)),
+ ),
+ );
+ }
+ : null,
+ ));
+ }
+
+ return ListView(
+ controller: widget.scrollController,
+ children: items,
+ );
+ },
+ );
+ }
+
+ Widget _buildServerHistory(AppLocalizations l, ColorScheme cs) {
+ final future = _serverFuture;
+ if (future == null) {
+ return const Center(child: CircularProgressIndicator(strokeWidth: 2));
+ }
+ return FutureBuilder<List<Map<String, dynamic>>?>(
+ future: future,
+ builder: (context, snapshot) {
+ if (snapshot.connectionState != ConnectionState.done) {
+ return const Center(
+ child: CircularProgressIndicator(strokeWidth: 2),
+ );
+ }
+ final sessions = snapshot.data;
+ if (snapshot.hasError || sessions == null) {
+ return _serverMessage(
+ widget.api == null
+ ? l.bookmarksNotConnected
+ : l.historyServerLoadFailed,
+ l,
+ cs,
+ showRetry: widget.api != null,
+ );
+ }
+ if (sessions.isEmpty) {
+ return _serverMessage(l.historyNoServerSessions, l, cs);
+ }
+
+ return ListView(
+ controller: widget.scrollController,
+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 24),
+ children: [
+ for (final session in sessions)
+ ListeningSessionCard(
+ session: session,
+ onTap: () => _showServerSessionDetails(session),
+ ),
+ ],
+ );
+ },
+ );
+ }
+
+ Future<void> _showServerSessionDetails(
+ Map<String, dynamic> session,
+ ) async {
+ final changed = await showModalBottomSheet<bool>(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: Colors.transparent,
+ builder: (_) => SessionDetailsSheet(
+ session: session,
+ onJumped: () {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) Navigator.maybePop(context);
+ });
+ },
+ ),
+ );
+ if (changed == true && mounted) {
+ setState(() => _serverFuture = _fetchServerSessions());
+ }
+ }
+
+ Widget _serverMessage(
+ String message,
+ AppLocalizations l,
+ ColorScheme cs, {
+ bool showRetry = false,
+ }) {
+ return Center(
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ Icons.cloud_outlined,
+ size: 36,
+ color: cs.onSurface.withValues(alpha: 0.18),
+ ),
+ const SizedBox(height: 10),
+ Text(
+ message,
+ textAlign: TextAlign.center,
+ style: widget.tt.bodyMedium?.copyWith(
+ color: cs.onSurfaceVariant,
+ ),
+ ),
+ if (showRetry) ...[
+ const SizedBox(height: 12),
+ OutlinedButton(
+ onPressed: _retryServerSessions,
+ child: Text(l.retry),
+ ),
+ ],
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _dateHeader(String label) {
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Text(
+ label,
+ style: widget.tt.labelSmall?.copyWith(
+ color: widget.accent.withValues(alpha: 0.6),
+ fontWeight: FontWeight.w600,
+ letterSpacing: 0.5,
+ ),
+ ),
+ );
+ }
+
}
diff --git a/lib/widgets/episode_detail_sheet.dart b/lib/widgets/episode_detail_sheet.dart
index ec10bde6..6ad48006 100644
--- a/lib/widgets/episode_detail_sheet.dart
+++ b/lib/widgets/episode_detail_sheet.dart
@@ -21,6 +21,8 @@ import 'episode_list_sheet.dart';
import '../utils/duration_format.dart';
class EpisodeDetailSheet extends StatefulWidget {
+ static final Set<String> _openEpisodeKeys = <String>{};
+
final Map<String, dynamic> podcastItem;
final Map<String, dynamic> episode;
final ScrollController? scrollController;
@@ -39,7 +41,12 @@ class EpisodeDetailSheet extends StatefulWidget {
}) : super(key: null);
static void show(BuildContext context, Map<String, dynamic> podcastItem, Map<String, dynamic> episode) {
- showStackableSheet(
+ final itemKey = podcastItem['id'] ?? identityHashCode(podcastItem);
+ final episodeKey = episode['id'] ?? identityHashCode(episode);
+ final openKey = '$itemKey::$episodeKey';
+ if (!_openEpisodeKeys.add(openKey)) return;
+
+ showStackableSheet<void>(
context: context,
useSafeArea: true,
initialChildSize: 0.75,
@@ -49,7 +56,7 @@ class EpisodeDetailSheet extends StatefulWidget {
episode: episode,
scrollController: scrollController,
),
- );
+ ).whenComplete(() => _openEpisodeKeys.remove(openKey));
}
/// Long-press shortcut: a compact quick-actions sheet for one episode.
@@ -664,6 +671,20 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {
episodeId: widget.episode['id'] as String?,
);
}),
+ if (!includeOpenDetails && !lib.isOffline)
+ ActionPillData(
+ icon: Icons.history_rounded,
+ label: l.historyServerTab,
+ onTap: () {
+ dismiss();
+ showPlaybackHistorySheet(
+ context,
+ itemId: _itemId,
+ episodeId: _episodeId,
+ initialTab: PlaybackHistoryTab.sessions,
+ );
+ },
+ ),
if (progress > 0 || isFinished)
ActionPillData(icon: Icons.restart_alt_rounded, label: l.resetProgress,
onTap: () { dismiss(); _resetProgress(context); }),
diff --git a/lib/widgets/listening_session_card.dart b/lib/widgets/listening_session_card.dart
new file mode 100644
index 00000000..fcd1159c
--- /dev/null
+++ b/lib/widgets/listening_session_card.dart
@@ -0,0 +1,184 @@
+import 'package:flutter/material.dart';
+
+import '../l10n/app_localizations.dart';
+import 'absorb_wave_icon.dart';
+
+class ListeningSessionCard extends StatelessWidget {
+ const ListeningSessionCard({
+ super.key,
+ required this.session,
+ required this.onTap,
+ });
+
+ final Map<String, dynamic> session;
+ final VoidCallback onTap;
+
+ static final _idPattern = RegExp(
+ r'^([a-z]{2,4}_)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$',
+ caseSensitive: false,
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final l = AppLocalizations.of(context)!;
+ final rawTitle = session['displayTitle'] as String?;
+ final rawAuthor = session['displayAuthor'] as String?;
+ final metadata = session['mediaMetadata'] as Map<String, dynamic>?;
+ final title = rawTitle != null && !_idPattern.hasMatch(rawTitle)
+ ? rawTitle
+ : metadata?['title'] as String? ?? l.unknown;
+ final author = rawAuthor != null && !_idPattern.hasMatch(rawAuthor)
+ ? rawAuthor
+ : metadata?['authorName'] as String? ?? '';
+ final duration = session['timeListening'] is num
+ ? (session['timeListening'] as num).toDouble()
+ : 0.0;
+ final updatedAt = session['updatedAt'] is num
+ ? DateTime.fromMillisecondsSinceEpoch(
+ (session['updatedAt'] as num).toInt(),
+ )
+ : null;
+ final deviceInfo =
+ session['deviceInfo'] as Map<String, dynamic>? ?? const {};
+ final clientName =
+ deviceInfo['clientName'] as String? ??
+ deviceInfo['deviceName'] as String? ??
+ '';
+ final isAbsorb = clientName.toLowerCase().contains('absorb');
+
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Material(
+ color: Colors.transparent,
+ child: InkWell(
+ onTap: onTap,
+ borderRadius: BorderRadius.circular(12),
+ child: Ink(
+ padding: const EdgeInsets.all(12),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.05),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),
+ ),
+ child: Row(
+ children: [
+ Container(
+ width: 36,
+ height: 36,
+ decoration: BoxDecoration(
+ color: (isAbsorb ? Colors.tealAccent : cs.onSurfaceVariant)
+ .withValues(alpha: 0.18),
+ borderRadius: BorderRadius.circular(9),
+ ),
+ child: Center(
+ child: isAbsorb
+ ? AbsorbWaveIcon(
+ size: 18,
+ color: Colors.tealAccent.withValues(alpha: 0.9),
+ )
+ : Icon(
+ _clientIcon(clientName),
+ size: 17,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.85),
+ ),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium?.copyWith(
+ color: cs.onSurface,
+ fontWeight: FontWeight.w600,
+ fontSize: 14,
+ ),
+ ),
+ if (author.isNotEmpty) ...[
+ const SizedBox(height: 2),
+ Text(
+ author,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: TextStyle(
+ color: cs.onSurface.withValues(alpha: 0.6),
+ fontSize: 12,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ const SizedBox(width: 10),
+ Column(
+ crossAxisAlignment: CrossAxisAlignment.end,
+ children: [
+ Text(
+ _formatDuration(duration, l),
+ style: tt.labelMedium?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.85),
+ fontWeight: FontWeight.w700,
+ fontSize: 13,
+ ),
+ ),
+ if (updatedAt != null) ...[
+ const SizedBox(height: 2),
+ Text(
+ _relativeDate(updatedAt, l),
+ style: TextStyle(
+ color: cs.onSurface.withValues(alpha: 0.5),
+ fontSize: 11,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ static IconData _clientIcon(String clientName) {
+ final lower = clientName.toLowerCase();
+ if (lower.contains('audiobookshelf') || lower.contains('abs')) {
+ return Icons.headphones_rounded;
+ }
+ if (lower.contains('web') || lower.contains('browser')) {
+ return Icons.language_rounded;
+ }
+ if (lower.contains('ios') || lower.contains('apple')) {
+ return Icons.phone_iphone_rounded;
+ }
+ if (lower.contains('android')) return Icons.phone_android_rounded;
+ if (lower.contains('sonos') || lower.contains('cast')) {
+ return Icons.speaker_rounded;
+ }
+ return Icons.devices_rounded;
+ }
+
+ static String _formatDuration(double seconds, AppLocalizations l) {
+ final hours = (seconds / 3600).floor();
+ final minutes = ((seconds % 3600) / 60).floor();
+ if (hours > 0) return l.statsScreenDurationHm(hours, minutes);
+ if (minutes > 0) return l.statsScreenDurationM(minutes);
+ if (seconds > 0) return l.statsScreenDurationLessThanMin;
+ return l.statsScreenDurationZero;
+ }
+
+ static String _relativeDate(DateTime date, AppLocalizations l) {
+ final difference = DateTime.now().difference(date);
+ if (difference.inMinutes < 60) return l.minutesAgo(difference.inMinutes);
+ if (difference.inHours < 24) return l.hoursAgo(difference.inHours);
+ if (difference.inDays < 7) return l.daysAgo(difference.inDays);
+ return '${date.month}/${date.day}';
+ }
+}