A cross platform Audiobookshelf client for Android and iOS
Dart
Book details sheet changes
Barnabas6f8674afaa7e
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dartindex 656af022..64169deb 100644--- a/lib/providers/_lp_core.dart+++ b/lib/providers/_lp_core.dart@@ -656,6 +656,12 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {return (mp['ebookProgress'] as num?)?.toDouble() ?? 0;}+ /// The ebook's own reading progress, apart from any audio progress.+ double getEbookProgress(String? itemId) {+ if (itemId == null) return 0;+ return (_progressMap[itemId]?['ebookProgress'] as num?)?.toDouble() ?? 0;+ }+/// Reflect ebook reading progress in the in-memory map right away, so covers/// and the detail sheet update on return from the reader instead of waiting/// for the server round-trip / socket echo.diff --git a/lib/services/book_stats_service.dart b/lib/services/book_stats_service.dartnew file mode 100644index 00000000..5fb6b07e--- /dev/null+++ b/lib/services/book_stats_service.dart@@ -0,0 +1,277 @@+import 'dart:convert';++import 'package:flutter/foundation.dart';++import 'api_service.dart';+import 'scoped_prefs.dart';++/// One other user's standing on a book, from the admin scan.+class BookUserStat {+ final String username;+ final double progress;+ final bool finished;+ final int? finishedAt;++ /// When this user's progress on the item last moved. Cached alongside the+ /// total so a later visit can tell, without fetching anything heavy, that+ /// their sessions haven't changed.+ final int lastUpdate;+ double seconds = 0;+ BookUserStat(this.username, this.progress, this.finished, this.finishedAt,+ this.lastUpdate);++ Map<String, dynamic> toJson() => {+ 'u': username,+ 'p': progress,+ 'f': finished,+ 'fa': finishedAt,+ 'lu': lastUpdate,+ 's': seconds,+ };++ static BookUserStat fromJson(Map<String, dynamic> j) => BookUserStat(+ j['u'] as String? ?? '',+ (j['p'] as num?)?.toDouble() ?? 0,+ j['f'] == true,+ (j['fa'] as num?)?.toInt(),+ (j['lu'] as num?)?.toInt() ?? 0,+ )..seconds = (j['s'] as num?)?.toDouble() ?? 0;+}++/// Listening stats for one book (or podcast episode): the reader's own+/// sessions, and for admins a server-wide picture. Lives past any one sheet,+/// so the detail sheet can start the load the moment it opens and the stats+/// sheet finds the numbers ready, or already on their way.+class BookStats extends ChangeNotifier {+ final String itemId;+ final String? episodeId;+ BookStats(this.itemId, this.episodeId);++ bool loading = true;+ bool failed = false;++ /// Own sessions, newest first, as the server sent them.+ List<Map<String, dynamic>> sessions = const [];+ double mySeconds = 0;+ int mySessions = 0;+ int? myFirst;+ int? myLast;++ bool isAdmin = false;+ bool serverLoading = false;+ List<BookUserStat> users = [];++ /// Progress through the per-user session scan, for the wait message.+ int scanDone = 0;+ int scanTotal = 0;+ int? checkedAt;++ /// When the last full load finished, to skip a pointless repeat.+ DateTime? _loadedAt;+ Future<void>? _inFlight;++ String get cacheKey => episodeId != null+ ? 'bookStats_${itemId}_$episodeId'+ : 'bookStats_$itemId';++ /// Everyone from the scan except [me].+ int othersCount(String? me) =>+ users.where((u) => u.username != me).length;++ /// The service mutates the fields above and calls this after each step.+ void bump() => notifyListeners();+}++class BookStatsService {+ BookStatsService._();+ static final BookStatsService instance = BookStatsService._();++ static const Duration _freshFor = Duration(minutes: 5);++ final Map<String, BookStats> _books = {};++ static String _key(String itemId, String? episodeId) =>+ episodeId != null ? '$itemId-$episodeId' : itemId;++ BookStats stats(String itemId, {String? episodeId}) =>+ _books.putIfAbsent(+ _key(itemId, episodeId), () => BookStats(itemId, episodeId));++ /// Load [itemId]'s stats unless they are fresh or already loading; a+ /// caller arriving mid-load simply waits on the same work.+ Future<void> ensureLoaded(String itemId, ApiService api,+ {String? episodeId, required bool isAdmin, bool force = false}) {+ final s = stats(itemId, episodeId: episodeId);+ final inFlight = s._inFlight;+ if (inFlight != null) return inFlight;+ final loadedAt = s._loadedAt;+ if (!force &&+ loadedAt != null &&+ DateTime.now().difference(loadedAt) < _freshFor &&+ (!isAdmin || s.isAdmin)) {+ return Future.value();+ }+ final run = _load(s, api, isAdmin).whenComplete(() => s._inFlight = null);+ s._inFlight = run;+ return run;+ }++ Future<void> _load(BookStats s, ApiService api, bool isAdmin) async {+ await _loadCache(s);+ final sessions = await api.getMyItemListeningSessions(+ s.itemId,+ episodeId: s.episodeId,+ );+ var total = 0.0;+ int? first;+ int? last;+ final list = <Map<String, dynamic>>[];+ for (final raw in sessions) {+ if (raw is! Map) continue;+ final m = Map<String, dynamic>.from(raw);+ list.add(m);+ total += (m['timeListening'] as num?)?.toDouble() ?? 0;+ final at = (m['updatedAt'] as num?)?.toInt() ??+ (m['startedAt'] as num?)?.toInt();+ if (at != null) {+ if (first == null || at < first) first = at;+ if (last == null || at > last) last = at;+ }+ }+ list.sort((a, b) {+ final ta = (a['updatedAt'] as num?)?.toInt() ?? (a['startedAt'] as num?)?.toInt() ?? 0;+ final tb = (b['updatedAt'] as num?)?.toInt() ?? (b['startedAt'] as num?)?.toInt() ?? 0;+ return tb.compareTo(ta);+ });+ s.sessions = list;+ s.mySeconds = total;+ s.mySessions = list.length;+ s.myFirst = first;+ s.myLast = last;+ s.loading = false;+ s.failed = false;+ s.isAdmin = isAdmin;+ s.bump();+ if (isAdmin) {+ await _loadServerWide(s, api);+ } else {+ s.checkedAt = DateTime.now().millisecondsSinceEpoch;+ await _saveCache(s);+ }+ s._loadedAt = DateTime.now();+ s.bump();+ }++ /// Last visit's numbers, shown instantly so nothing is empty while the+ /// scan brings them up to date.+ Future<void> _loadCache(BookStats s) async {+ if (s.checkedAt != null) return;+ final raw = await ScopedPrefs.getString(s.cacheKey);+ if (raw == null || raw.isEmpty) return;+ try {+ final j = jsonDecode(raw) as Map<String, dynamic>;+ final me = j['me'] as Map<String, dynamic>?;+ s.checkedAt = (j['at'] as num?)?.toInt();+ if (me != null) {+ s.mySeconds = (me['s'] as num?)?.toDouble() ?? 0;+ s.mySessions = (me['n'] as num?)?.toInt() ?? 0;+ s.myFirst = (me['f'] as num?)?.toInt();+ s.myLast = (me['l'] as num?)?.toInt();+ }+ s.users = (j['users'] as List<dynamic>? ?? const [])+ .whereType<Map<String, dynamic>>()+ .map(BookUserStat.fromJson)+ .toList();+ s.loading = false;+ s.bump();+ } catch (_) {}+ }++ Future<void> _saveCache(BookStats s) async {+ final payload = jsonEncode({+ 'at': DateTime.now().millisecondsSinceEpoch,+ 'me': {+ 's': s.mySeconds,+ 'n': s.mySessions,+ 'f': s.myFirst,+ 'l': s.myLast,+ },+ 'users': [for (final u in s.users) u.toJson()],+ });+ await ScopedPrefs.setString(s.cacheKey, payload);+ }++ Future<void> _loadServerWide(BookStats s, ApiService api) async {+ s.serverLoading = true;+ s.bump();+ try {+ final userList = await api.getUsers();+ // Anything already scanned, keyed by name so a cached total can be+ // reused when that person's progress hasn't moved since.+ final cached = {for (final u in s.users) u.username: u};+ final found = <String, BookUserStat>{};+ for (final entry in userList) {+ if (entry is! Map) continue;+ final id = entry['id'] as String?;+ if (id == null) continue;+ // The users list is deliberately minimal server-side and carries no+ // progress at all - only the single-user endpoint returns it.+ final u = await api.getUser(id);+ if (u == null) continue;+ for (final p in (u['mediaProgress'] as List<dynamic>? ?? const [])) {+ if (p is! Map) continue;+ if (p['libraryItemId'] != s.itemId) continue;+ if (s.episodeId != null && p['episodeId'] != s.episodeId) continue;+ found[id] = BookUserStat(+ u['username'] as String? ?? '',+ (p['progress'] as num?)?.toDouble() ?? 0,+ p['isFinished'] == true,+ (p['finishedAt'] as num?)?.toInt(),+ (p['lastUpdate'] as num?)?.toInt() ?? 0,+ );+ break;+ }+ }+ // The session scan is the slow part, so skip anyone whose progress+ // hasn't moved since the last visit and reuse their stored total.+ final pending = <String, BookUserStat>{};+ for (final e in found.entries) {+ final was = cached[e.value.username];+ if (was != null && was.lastUpdate >= e.value.lastUpdate) {+ e.value.seconds = was.seconds;+ } else {+ pending[e.key] = e.value;+ }+ }+ s.scanDone = 0;+ s.scanTotal = pending.length;+ s.bump();+ for (final entry in pending.entries) {+ final payload =+ await api.getUserListeningSessions(entry.key, itemsPerPage: 1000);+ final sessions = (payload?['sessions'] as List<dynamic>?) ?? const [];+ var total = 0.0;+ for (final sess in sessions) {+ if (sess is! Map) continue;+ if (sess['libraryItemId'] != s.itemId) continue;+ if (s.episodeId != null && sess['episodeId'] != s.episodeId) continue;+ total += (sess['timeListening'] as num?)?.toDouble() ?? 0;+ }+ entry.value.seconds = total;+ s.scanDone++;+ s.bump();+ }+ debugPrint('[BookStats] item=${s.itemId} users=${userList.length} '+ 'withProgress=${found.length} rescanned=${pending.length}');+ s.users = found.values.toList()+ ..sort((a, b) => b.seconds.compareTo(a.seconds));+ s.checkedAt = DateTime.now().millisecondsSinceEpoch;+ await _saveCache(s);+ } catch (e) {+ debugPrint('[BookStats] server-wide scan failed for ${s.itemId}: $e');+ } finally {+ s.serverLoading = false;+ s.bump();+ }+ }+}diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex 2ebf8df0..69b94b4f 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -20,6 +20,7 @@ import 'package:webview_flutter/webview_flutter.dart';import 'package:intl/intl.dart';import '../l10n/app_localizations.dart';import 'book_stats_sheet.dart';+import '../services/book_stats_service.dart';import '../services/wording.dart';import '../providers/auth_provider.dart';import '../providers/library_provider.dart';@@ -188,7 +189,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {Map<String, dynamic>? _rating;String? _asin;bool _isLoading = true;- bool _chaptersExpanded = false;bool _bookmarksExpanded = false;BookmarkPreviewPlayer? _preview;bool? _loggedPreviewVisible;@@ -239,6 +239,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {}_loadItem();_loadBookmarks();+ _warmStats();SocketService().addItemUpdatedListener(_onSocketItemUpdated);PlayerSettings.getRectangleCovers().then((v) { if (mounted) setState(() => _squareCovers = !v); });PlayerSettings.getShowGoodreadsButton().then((v) { if (mounted) setState(() => _showGoodreads = v); });@@ -277,6 +278,165 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {});}+ bool _finishedChaptersExpanded = false;++ /// Start the stats load (own sessions, and the server-wide scan for+ /// admins) the moment the sheet opens, so the stats card fills in on its+ /// own and the stats sheet opens on numbers already fetched or already on+ /// their way instead of starting over.+ void _warmStats() {+ final auth = context.read<AuthProvider>();+ final api = auth.apiService;+ if (api == null) return;+ unawaited(BookStatsService.instance+ .ensureLoaded(widget.itemId, api, isAdmin: auth.isAdmin));+ }++ String _sessionDay(BuildContext context, int ms) {+ final d = DateTime.fromMillisecondsSinceEpoch(ms);+ final locale = Localizations.localeOf(context).toString();+ return d.year == DateTime.now().year+ ? DateFormat.MMMd(locale).format(d)+ : DateFormat.yMMMd(locale).format(d);+ }++ String _sessionWhen(BuildContext context, int ms) {+ final d = DateTime.fromMillisecondsSinceEpoch(ms);+ final locale = Localizations.localeOf(context).toString();+ return '${_sessionDay(context, ms)}, ${DateFormat.jm(locale).format(d)}';+ }++ Widget _listeningStatsBlock(BuildContext context, ColorScheme cs, TextTheme tt, Color accent, String title) {+ final l = AppLocalizations.of(context)!;+ final me = context.read<AuthProvider>().username;+ return ListenableBuilder(+ listenable: BookStatsService.instance.stats(widget.itemId),+ builder: (context, _) {+ final s = BookStatsService.instance.stats(widget.itemId);+ final sessions = s.sessions;+ Widget stat(String label, String value) => Expanded(+ child: Column(children: [+ Text(value, maxLines: 1, overflow: TextOverflow.ellipsis,+ style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w700, color: cs.onSurface)),+ const SizedBox(height: 2),+ Text(label, maxLines: 1, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center,+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),+ ]),+ );+ return Container(+ decoration: BoxDecoration(+ color: cs.onSurface.withValues(alpha: 0.04),+ borderRadius: BorderRadius.circular(16),+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),+ ),+ child: Column(children: [+ InkWell(+ borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),+ onTap: () => showBookStatsSheet(context, itemId: widget.itemId, title: title),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(14, 12, 10, 8),+ child: Row(children: [+ Icon(Icons.insights_rounded, size: 18, color: accent),+ const SizedBox(width: 8),+ Expanded(child: Text(l.bookStatsAction,+ style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w600, color: cs.onSurface))),+ // Admins: how many others are on this book. A spinner while+ // the first scan for it is still running.+ if (s.isAdmin && s.serverLoading && s.users.isEmpty && s.checkedAt == null)+ Padding(+ padding: const EdgeInsets.only(right: 6),+ child: SizedBox(width: 12, height: 12,+ child: CircularProgressIndicator(strokeWidth: 1.5, color: cs.onSurfaceVariant)),+ )+ else if (s.isAdmin && (s.checkedAt != null || s.users.isNotEmpty)) ...[+ Text(l.detailOtherListeners(s.othersCount(me)),+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),+ const SizedBox(width: 4),+ ],+ Icon(Icons.chevron_right_rounded, size: 20, color: cs.onSurface.withValues(alpha: 0.4)),+ ]),+ ),+ ),+ if (s.loading && !s.failed)+ const Padding(+ padding: EdgeInsets.fromLTRB(14, 0, 14, 14),+ child: LinearProgressIndicator(minHeight: 2),+ )+ else if (s.failed)+ Padding(+ padding: const EdgeInsets.fromLTRB(14, 0, 14, 14),+ child: Text(l.statsCouldNotLoad, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ )+ else if (sessions.isEmpty && s.mySessions == 0)+ Padding(+ padding: const EdgeInsets.fromLTRB(14, 0, 14, 14),+ child: Text(l.detailSessionsNone, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ )+ else ...[+ Padding(+ padding: const EdgeInsets.fromLTRB(8, 0, 8, 10),+ child: Row(children: [+ stat(l.bookStatsListened, formatHm(s.mySeconds)),+ stat(l.bookStatsSessions, '${s.mySessions}'),+ stat(l.bookStatsLast, s.myLast == null ? '-' : _sessionDay(context, s.myLast!)),+ ]),+ ),+ if (sessions.isNotEmpty) ...[+ Divider(height: 1, color: cs.onSurface.withValues(alpha: 0.08)),+ for (final sess in sessions.take(5)) _sessionRow(context, cs, tt, sess),+ ],+ if (sessions.length > 5)+ InkWell(+ borderRadius: const BorderRadius.vertical(bottom: Radius.circular(16)),+ onTap: () => showPlaybackHistorySheet(+ context,+ itemId: widget.itemId,+ initialTab: PlaybackHistoryTab.sessions,+ accent: accent,+ ),+ child: Padding(+ padding: const EdgeInsets.symmetric(vertical: 10),+ child: Center(child: Text(l.detailSessionsAll(sessions.length),+ style: tt.labelMedium?.copyWith(color: accent, fontWeight: FontWeight.w600))),+ ),+ )+ else+ const SizedBox(height: 6),+ ],+ ]),+ );+ },+ );+ }+ Widget _sessionRow(BuildContext context, ColorScheme cs, TextTheme tt, Map<String, dynamic> s) {+ final at = (s['updatedAt'] as num?)?.toInt() ?? (s['startedAt'] as num?)?.toInt();+ final listened = (s['timeListening'] as num?)?.toDouble() ?? 0;+ final start = (s['startTime'] as num?)?.toDouble() ?? 0;+ final end = (s['currentTime'] as num?)?.toDouble() ?? start;+ final device = s['deviceInfo'] as Map<String, dynamic>?;+ final where = (device?['deviceName'] as String?) ?? (device?['clientName'] as String?) ?? '';+ return Padding(+ padding: const EdgeInsets.fromLTRB(14, 8, 14, 8),+ child: Row(children: [+ Expanded(+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(at == null ? '-' : _sessionWhen(context, at),+ style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.8))),+ const SizedBox(height: 2),+ Text(+ '${formatHm(start / _displaySpeed)} - ${formatHm(end / _displaySpeed)}'+ '${where.isNotEmpty ? ' · $where' : ''}',+ maxLines: 1, overflow: TextOverflow.ellipsis,+ style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.4)),+ ),+ ]),+ ),+ const SizedBox(width: 8),+ Text(formatHm(listened), style: tt.labelMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.onSurfaceVariant)),+ ]),+ );+ }+Future<void> _loadBookmarks() async {final bm = await BookmarkService().getBookmarks(widget.itemId, sort: 'position');if (mounted) setState(() => _bookmarks = bm);@@ -661,15 +821,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {elseconst SizedBox(height: 20),const SizedBox(height: 12),- if (progress > 0 && !isFinished) ...[- ClipRRect(borderRadius: BorderRadius.circular(3),- child: LinearProgressIndicator(value: progress.clamp(0.0, 1.0), minHeight: 4,- backgroundColor: cs.onSurface.withValues(alpha: 0.1), valueColor: AlwaysStoppedAnimation(accent))),- const SizedBox(height: 4),- Text(l.percentComplete((progress * 100).toStringAsFixed(1)), textAlign: TextAlign.center,- style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),- const SizedBox(height: 12),- ],if (isEbookOnly && ebookFile != null && canReadEbook(ebookFile))SizedBox(height: 52, child: FilledButton.icon(onPressed: () => _openEbookReader(context, auth, ebookFile, title),@@ -706,58 +857,141 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {final isCurrentPlaying =player.currentItemId == widget.itemId && player.isPlaying;final showAbsorbingState = _isAbsorbing || isCurrentPlaying;-- return FilledButton.icon(- onPressed: showAbsorbingState- ? () async {- if (isCurrentPlaying) {- final lib = context.read<LibraryProvider>();- await _activateQueueSource();- unawaited(lib.syncQueueAutoDownloads());+ final onAccent = _coverScheme?.onPrimary ?? cs.onPrimary;+ // How far into the book you are fills the button from the left,+ // the way the download button fills while it fetches.+ final showFill = progress > 0 && !isFinished;++ return Material(+ color: accent,+ borderRadius: BorderRadius.circular(16),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: showAbsorbingState+ ? () async {+ if (isCurrentPlaying) {+ final lib = context.read<LibraryProvider>();+ await _activateQueueSource();+ unawaited(lib.syncQueueAutoDownloads());+ }+ if (!context.mounted) return;+ Navigator.of(context).popUntil((route) => route.isFirst);+ AppShell.goToAbsorbingGlobal();}- if (!context.mounted) return;- Navigator.of(context).popUntil((route) => route.isFirst);- AppShell.goToAbsorbingGlobal();- }- : () {- setState(() => _isAbsorbing = true);- _startAbsorb(- context,- auth: auth,- title: title,- author: authorName,- coverUrl: _coverUrl,- duration: duration,- chapters: chapters,- );- },- icon: showAbsorbingState- ? SizedBox(- width: 24,- height: 24,- child: AbsorbingWave(color: _coverScheme?.onPrimary ?? cs.onPrimary),- )- : isFinished- ? AbsorbReplayIcon(size: 24, color: _coverScheme?.onPrimary ?? cs.onPrimary)- : Icon(Icons.waves_rounded, size: 24, color: _coverScheme?.onPrimary ?? cs.onPrimary),- label: Text(- showAbsorbingState- ? Wording.of(context).absorbing- : isFinished- ? Wording.of(context).absorbAgain- : Wording.of(context).absorb,- style: tt.titleMedium- ?.copyWith(fontWeight: FontWeight.w600, color: _coverScheme?.onPrimary ?? cs.onPrimary),- ),- style: FilledButton.styleFrom(- backgroundColor: accent,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),+ : () {+ setState(() => _isAbsorbing = true);+ _startAbsorb(+ context,+ auth: auth,+ title: title,+ author: authorName,+ coverUrl: _coverUrl,+ duration: duration,+ chapters: chapters,+ );+ },+ child: Stack(children: [+ if (showFill)+ FractionallySizedBox(+ widthFactor: progress.clamp(0.0, 1.0),+ child: Container(color: onAccent.withValues(alpha: 0.22)),+ ),+ Center(+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ showAbsorbingState+ ? SizedBox(+ width: 24,+ height: 24,+ child: AbsorbingWave(color: onAccent),+ )+ : isFinished+ ? AbsorbReplayIcon(size: 24, color: onAccent)+ : Icon(Icons.waves_rounded, size: 24, color: onAccent),+ const SizedBox(width: 8),+ Text(+ showAbsorbingState+ ? Wording.of(context).absorbing+ : isFinished+ ? Wording.of(context).absorbAgain+ : Wording.of(context).absorb,+ style: tt.titleMedium+ ?.copyWith(fontWeight: FontWeight.w600, color: onAccent),+ ),+ ]),+ ),+ if (showFill)+ Positioned(+ right: 14,+ top: 0,+ bottom: 0,+ child: Center(+ child: Text(+ '${(progress * 100).toStringAsFixed(0)}%',+ style: tt.labelMedium?.copyWith(+ fontWeight: FontWeight.w700,+ color: onAccent.withValues(alpha: 0.85),+ ),+ ),+ ),+ ),+ ]),),);},),),- // Primary action row: Download | Fully Absorb | Read (when ebook)+ // A companion ebook gets its own, smaller button under Absorb with the+ // reading progress filled in the same way. Ebook-only books already+ // have Read as the big button above.+ if (!isEbookOnly && ebookFile != null && canReadEbook(ebookFile)) ...[+ const SizedBox(height: 8),+ Builder(builder: (context) {+ final ebookProgress = lib.getEbookProgress(widget.itemId);+ final showFill = ebookProgress > 0 && ebookProgress < 1;+ return SizedBox(+ height: 40,+ child: Material(+ color: accent.withValues(alpha: 0.14),+ borderRadius: BorderRadius.circular(14),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ onTap: () => _openEbookReader(context, auth, ebookFile, title),+ child: Stack(children: [+ if (showFill)+ FractionallySizedBox(+ widthFactor: ebookProgress.clamp(0.0, 1.0),+ child: Container(color: accent.withValues(alpha: 0.22)),+ ),+ Center(+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(Icons.menu_book_rounded, size: 18, color: accent),+ const SizedBox(width: 8),+ Text(l.readEbook,+ style: tt.labelLarge?.copyWith(fontWeight: FontWeight.w600, color: accent)),+ ]),+ ),+ if (showFill)+ Positioned(+ right: 14,+ top: 0,+ bottom: 0,+ child: Center(+ child: Text(+ '${(ebookProgress * 100).toStringAsFixed(0)}%',+ style: tt.labelSmall?.copyWith(+ fontWeight: FontWeight.w700,+ color: accent.withValues(alpha: 0.85),+ ),+ ),+ ),+ ),+ ]),+ ),+ ),+ );+ }),+ ],+ // Primary action row: Download | Fully Absorb | ebook download (ebook-only)const SizedBox(height: 12),Row(children: [if (!isEbookOnly) ...[@@ -792,14 +1026,14 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {]),),)),- if (ebookFile != null && canReadEbook(ebookFile)) ...[+ if (isEbookOnly && ebookFile != null && canReadEbook(ebookFile)) ...[const SizedBox(width: 8),// For ebook-only books the big button above is already "Read", so this// slot is the offline download (matching the audiobook download- // button's Saved/green styling). For audiobooks with a companion ebook- // it stays "Read" - the audio download already pulls the ebook along.- Expanded(child: isEbookOnly- ? ListenableBuilder(+ // button's Saved/green styling). Audiobooks with a companion ebook+ // have the Read button under Absorb instead, and the audio download+ // already pulls the ebook along.+ Expanded(child: ListenableBuilder(listenable: DownloadService(),builder: (_, __) {final saved = DownloadService().isDownloaded(widget.itemId);@@ -831,22 +1065,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {),);},- )- : GestureDetector(- onTap: () => _openEbookReader(context, auth, ebookFile, title),- child: Container(- height: 36,- decoration: BoxDecoration(- color: cs.onSurface.withValues(alpha: 0.06),- borderRadius: BorderRadius.circular(14),- border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),- ),- child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [- Icon(Icons.menu_book_rounded, size: 16, color: cs.onSurfaceVariant),- const SizedBox(width: 6),- Text(l.readEbook, style: TextStyle(color: cs.onSurfaceVariant, fontSize: 12, fontWeight: FontWeight.w500)),- ]),- ),)),],]),@@ -874,6 +1092,36 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {),),],+ // Series rows sit with the action buttons, same height as Preview and+ // More, so a series book's neighbours are one tap from the top.+ for (final s in seriesEntries) ...[+ const SizedBox(height: 8),+ Builder(builder: (context) {+ final name = s['name'] as String? ?? '';+ final seq = s['sequence'] as String? ?? '';+ final seriesId = s['id'] as String?;+ return GestureDetector(+ onTap: () => _openSeries(context, seriesId, name),+ child: Container(+ height: 36,+ padding: const EdgeInsets.symmetric(horizontal: 12),+ decoration: BoxDecoration(+ color: accent.withValues(alpha: 0.08),+ borderRadius: BorderRadius.circular(14),+ border: Border.all(color: accent.withValues(alpha: 0.15)),+ ),+ child: Row(children: [+ Icon(Icons.auto_stories_rounded, size: 16, color: accent.withValues(alpha: 0.7)),+ const SizedBox(width: 8),+ Expanded(child: Text('$name${seq.isNotEmpty ? ' #$seq' : ''}',+ maxLines: 1, overflow: TextOverflow.ellipsis,+ style: TextStyle(color: accent.withValues(alpha: 0.9), fontSize: 12, fontWeight: FontWeight.w500))),+ Icon(Icons.chevron_right_rounded, size: 18, color: accent.withValues(alpha: 0.5)),+ ]),+ ),+ );+ }),+ ],// More button below primary rowconst SizedBox(height: 8),GestureDetector(@@ -893,6 +1141,10 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {]),),),+ if (!lib.isOffline && !isEbookOnly) ...[+ const SizedBox(height: 16),+ _listeningStatsBlock(context, cs, tt, accent, title),+ ],const SizedBox(height: 16),Wrap(spacing: 8, runSpacing: 8, children: [if (year.isNotEmpty) _chip(Icons.calendar_today_rounded, year),@@ -938,31 +1190,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {startedAt: (progressData['startedAt'] as num).toInt(),finishedAt: (progressData['finishedAt'] as num).toInt())),]),- if (seriesEntries.isNotEmpty) ...[const SizedBox(height: 16),- ...seriesEntries.map((s) {- final name = s['name'] as String? ?? '';- final seq = s['sequence'] as String? ?? '';- final seriesId = s['id'] as String?;- return Padding(padding: const EdgeInsets.only(bottom: 4),- child: GestureDetector(- onTap: () => _openSeries(context, seriesId, name),- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),- decoration: BoxDecoration(- color: accent.withValues(alpha: 0.08),- borderRadius: BorderRadius.circular(12),- border: Border.all(color: accent.withValues(alpha: 0.15)),- ),- child: Row(children: [- Icon(Icons.auto_stories_rounded, size: 16, color: accent.withValues(alpha: 0.7)),- const SizedBox(width: 8),- Expanded(child: Text('$name${seq.isNotEmpty ? ' #$seq' : ''}',- style: tt.bodySmall?.copyWith(color: accent.withValues(alpha: 0.9), fontWeight: FontWeight.w500))),- Icon(Icons.chevron_right_rounded, size: 18, color: accent.withValues(alpha: 0.5)),- ]),- ),- ));- })],if (descRaw.isNotEmpty) ...[const SizedBox(height: 16),Text(l.aboutSection, style: tt.titleSmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),const SizedBox(height: 6),@@ -973,20 +1200,67 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {linkColor: accent,)],if (chapters.isNotEmpty) ...[const SizedBox(height: 16),- GestureDetector(onTap: () => setState(() => _chaptersExpanded = !_chaptersExpanded),- child: Row(children: [- Text(l.chaptersCount(chapters.length), style: tt.titleSmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),- const Spacer(), Icon(_chaptersExpanded ? Icons.expand_less : Icons.expand_more, color: cs.onSurface.withValues(alpha: 0.3), size: 20)])),- if (_chaptersExpanded) ...[const SizedBox(height: 8),- ...chapters.asMap().entries.map((e) {- final ch = e.value as Map<String, dynamic>;- return Padding(padding: const EdgeInsets.symmetric(vertical: 3),- child: Row(children: [- SizedBox(width: 28, child: Text('${e.key + 1}', style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3)))),- Expanded(child: Text(ch['title'] as String? ?? l.chapterNumber(e.key + 1), maxLines: 1, overflow: TextOverflow.ellipsis, style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.6)))),- Text(formatHm((((ch['end'] as num?)?.toDouble() ?? 0) - ((ch['start'] as num?)?.toDouble() ?? 0)) / _displaySpeed), style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3))),- ]));- })]],+ Text(l.chaptersCount(chapters.length), style: tt.titleSmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),+ const SizedBox(height: 4),+ // Always open, laid out like the card's chapter list: the chapter+ // you're in is lit, the ones behind you are ticked, and a tap jumps+ // there after a confirmation.+ ListenableBuilder(+ listenable: AudioPlayerService(),+ builder: (context, _) {+ final player = AudioPlayerService();+ final isActive = player.hasBook && player.currentItemId == widget.itemId;+ final pos = isActive ? player.position.inMilliseconds / 1000.0 : currentTime;+ // Chapters behind you fold into one row so the list opens on+ // where you are, not on what you've already heard.+ var done = 0;+ while (done < chapters.length &&+ pos >= (((chapters[done] as Map<String, dynamic>)['end'] as num?)?.toDouble() ?? 0)) {+ done++;+ }+ // Accordion open and close; instant on e-ink, where animation+ // only smears.+ final anim = PlayerSettings.einkMode+ ? Duration.zero+ : const Duration(milliseconds: 250);+ return Column(children: [+ if (done > 0) ...[+ InkWell(+ borderRadius: BorderRadius.circular(10),+ onTap: () => setState(() => _finishedChaptersExpanded = !_finishedChaptersExpanded),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 10),+ child: Row(children: [+ SizedBox(width: 28, child: AnimatedRotation(+ turns: _finishedChaptersExpanded ? 0.5 : 0,+ duration: anim,+ child: Icon(Icons.expand_more_rounded,+ size: 18, color: cs.onSurface.withValues(alpha: 0.4)))),+ Expanded(child: Text(l.detailChaptersFinished(done),+ style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.5)))),+ ]),+ ),+ ),+ ClipRect(+ child: AnimatedSize(+ duration: anim,+ curve: Curves.easeInOut,+ alignment: Alignment.topCenter,+ child: _finishedChaptersExpanded+ ? Column(children: [+ for (var i = 0; i < done; i++)+ _chapterRow(context, cs, tt, accent, auth, chapters, i, pos, isActive, title, authorName, duration),+ ])+ : const SizedBox(width: double.infinity),+ ),+ ),+ ],+ for (var i = done; i < chapters.length; i++)+ _chapterRow(context, cs, tt, accent, auth, chapters, i, pos, isActive, title, authorName, duration),+ ]);+ },+ ),+ ],if (_bookmarks.isNotEmpty) ...[const SizedBox(height: 16),GestureDetector(onTap: () => setState(() => _bookmarksExpanded = !_bookmarksExpanded),child: Row(children: [@@ -1006,17 +1280,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {]));})]],const SizedBox(height: 20),- if (!lib.isOffline) ...[const SizedBox(height: 8),- OutlinedButton.icon(- onPressed: () => showBookStatsSheet(context, itemId: widget.itemId, title: title),- icon: const Icon(Icons.insights_rounded, size: 18),- label: Text(l.bookStatsAction),- style: OutlinedButton.styleFrom(- foregroundColor: cs.onSurfaceVariant,- side: BorderSide(color: cs.onSurface.withValues(alpha: 0.15)),- minimumSize: const Size.fromHeight(44),- ),- )],]);}@@ -1086,7 +1349,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {// Primary actions: Absorb | Download side by sideif (!isEbookOnly)Row(children: [- Expanded(child: _quickAbsorbButton(context, cs, tt, auth, accent, onAccent, title, authorName, duration, chapters, isFinished)),+ Expanded(child: _quickAbsorbButton(context, cs, tt, auth, accent, onAccent, title, authorName, duration, chapters, isFinished, progress)),const SizedBox(width: 10),Expanded(child: DownloadWideButton(itemId: widget.itemId, coverUrl: _coverUrl, title: title, author: authorName, accent: accent)),])@@ -1256,7 +1519,8 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {}Widget _quickAbsorbButton(BuildContext context, ColorScheme cs, TextTheme tt, AuthProvider auth,- Color accent, Color onAccent, String title, String author, double duration, List<dynamic> chapters, bool isFinished) {+ Color accent, Color onAccent, String title, String author, double duration, List<dynamic> chapters, bool isFinished,+ double progress) {return ListenableBuilder(listenable: AudioPlayerService(),builder: (_, __) {@@ -1282,23 +1546,31 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {},child: Container(height: 36,+ clipBehavior: Clip.antiAlias,decoration: BoxDecoration(color: accent, borderRadius: BorderRadius.circular(14)),- child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [- showAbsorbingState- ? SizedBox(width: 16, height: 16, child: AbsorbingWave(color: onAccent))- : isFinished- ? AbsorbReplayIcon(size: 16, color: onAccent)- : Icon(Icons.waves_rounded, size: 16, color: onAccent),- const SizedBox(width: 8),- Flexible(child: Text(+ child: Stack(children: [+ if (progress > 0 && !isFinished)+ FractionallySizedBox(+ widthFactor: progress.clamp(0.0, 1.0),+ child: Container(color: onAccent.withValues(alpha: 0.22)),+ ),+ Row(mainAxisAlignment: MainAxisAlignment.center, children: [showAbsorbingState- ? Wording.of(context).absorbing+ ? SizedBox(width: 16, height: 16, child: AbsorbingWave(color: onAccent)): isFinished- ? Wording.of(context).absorbAgain- : Wording.of(context).absorb,- maxLines: 1, overflow: TextOverflow.ellipsis,- style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: onAccent),- )),+ ? AbsorbReplayIcon(size: 16, color: onAccent)+ : Icon(Icons.waves_rounded, size: 16, color: onAccent),+ const SizedBox(width: 8),+ Flexible(child: Text(+ showAbsorbingState+ ? Wording.of(context).absorbing+ : isFinished+ ? Wording.of(context).absorbAgain+ : Wording.of(context).absorb,+ maxLines: 1, overflow: TextOverflow.ellipsis,+ style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: onAccent),+ )),+ ]),]),),);@@ -2218,7 +2490,9 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {}}- Future<void> _startAbsorb(BuildContext context, {required AuthProvider auth, required String title, required String author, required String? coverUrl, required double duration, required List<dynamic> chapters}) async {+ /// [startTime] plays from there instead of the saved position (a chapter+ /// tapped in the list); on the live session it is a seek.+ Future<void> _startAbsorb(BuildContext context, {required AuthProvider auth, required String title, required String author, required String? coverUrl, required double duration, required List<dynamic> chapters, double? startTime}) async {// Discard, not stop: we're about to start playback ourselves, so briefly// resuming the previous book would just be an audible blip.await _preview?.discard();@@ -2229,6 +2503,9 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {if (player.currentItemId == widget.itemId) {await _activateQueueSource();+ if (startTime != null) {+ await player.seekTo(Duration(milliseconds: (startTime * 1000).round()));+ }if (!player.isPlaying) await player.play(fromUi: true);unawaited(lib.syncQueueAutoDownloads());rootNav.popUntil((route) => route.isFirst);@@ -2248,7 +2525,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {rootNav.popUntil((route) => route.isFirst);AppShell.goToAbsorbingGlobal();- final error = await player.playItem(api: api, itemId: widget.itemId, title: title, author: author, coverUrl: coverUrl, totalDuration: duration, chapters: chapters, libraryId: _item?['libraryId'] as String?, fromUi: true);+ final error = await player.playItem(api: api, itemId: widget.itemId, title: title, author: author, coverUrl: coverUrl, totalDuration: duration, chapters: chapters, libraryId: _item?['libraryId'] as String?, fromUi: true, startTime: startTime ?? 0, forceStartTime: startTime != null);if (error != null) {unawaited(_restoreActivatedQueueSource(queueModeBackup));final ctx = rootNavigatorKey.currentContext;@@ -2260,6 +2537,76 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {lib.refresh();}+ Widget _chapterRow(BuildContext context, ColorScheme cs, TextTheme tt, Color accent, AuthProvider auth,+ List<dynamic> chapters, int i, double pos, bool isActive, String title, String author, double duration) {+ final l = AppLocalizations.of(context)!;+ final ch = chapters[i] as Map<String, dynamic>;+ final chTitle = ch['title'] as String? ?? l.chapterNumber(i + 1);+ final start = (ch['start'] as num?)?.toDouble() ?? 0;+ final end = (ch['end'] as num?)?.toDouble() ?? 0;+ final isCurrent = pos >= start && pos < end;+ final done = pos >= end;+ final pct = duration > 0 ? (end / duration * 100).round() : 0;+ return ListTile(+ dense: true,+ contentPadding: const EdgeInsets.symmetric(horizontal: 4),+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),+ selected: isCurrent,+ selectedTileColor: accent.withValues(alpha: 0.1),+ leading: SizedBox(width: 28, child: done+ ? Icon(Icons.check_rounded, size: 16, color: cs.onSurfaceVariant.withValues(alpha: 0.4))+ : Text('${i + 1}', textAlign: TextAlign.center,+ style: tt.labelMedium?.copyWith(+ fontWeight: isCurrent ? FontWeight.w700 : FontWeight.w400,+ color: isCurrent ? accent : cs.onSurfaceVariant))),+ title: Text(chTitle, maxLines: 2, overflow: TextOverflow.ellipsis,+ style: tt.bodyMedium?.copyWith(+ fontWeight: isCurrent ? FontWeight.w600 : FontWeight.w400,+ color: isCurrent+ ? cs.onSurface+ : done+ ? cs.onSurface.withValues(alpha: 0.4)+ : cs.onSurface.withValues(alpha: 0.7))),+ trailing: Row(mainAxisSize: MainAxisSize.min, children: [+ Text('$pct%', style: tt.labelSmall?.copyWith(+ color: isCurrent ? accent.withValues(alpha: 0.7) : cs.onSurface.withValues(alpha: 0.24),+ fontSize: 10, fontWeight: FontWeight.w600)),+ const SizedBox(width: 8),+ Text(formatHm((end - start) / _displaySpeed), style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),+ ]),+ onTap: () => _jumpToChapter(context, auth, chTitle, start, isActive, title, author, duration, chapters),+ );+ }++ /// Confirm, then seek the live session or start the book at [start].+ Future<void> _jumpToChapter(BuildContext context, AuthProvider auth, String chTitle, double start,+ bool isActive, String title, String author, double duration, List<dynamic> chapters) async {+ final l = AppLocalizations.of(context)!;+ final confirmed = await showDialog<bool>(+ context: context,+ builder: (dlg) => AlertDialog(+ title: Text(isActive ? l.detailChaptersJumpTitle : l.cardChaptersPlayFromChapterTitle),+ content: Text(isActive+ ? l.detailChaptersJumpContent(chTitle)+ : l.cardChaptersPlayFromChapterContent(chTitle)),+ actions: [+ TextButton(onPressed: () => Navigator.pop(dlg, false), child: Text(l.cancel)),+ FilledButton(+ onPressed: () => Navigator.pop(dlg, true),+ child: Text(isActive ? l.detailChaptersJump : l.cardChaptersPlay)),+ ],+ ),+ );+ if (confirmed != true || !context.mounted) return;+ if (isActive) {+ await AudioPlayerService().seekTo(Duration(milliseconds: (start * 1000).round()));+ return;+ }+ setState(() => _isAbsorbing = true);+ await _startAbsorb(context, auth: auth, title: title, author: author,+ coverUrl: _coverUrl, duration: duration, chapters: chapters, startTime: start);+ }+Future<void> _markFinished(BuildContext context, AuthProvider auth, double duration) async {final l = AppLocalizations.of(context)!;final w = Wording.of(context);diff --git a/lib/widgets/book_stats_sheet.dart b/lib/widgets/book_stats_sheet.dartindex cc99e0c7..ab5872d4 100644--- a/lib/widgets/book_stats_sheet.dart+++ b/lib/widgets/book_stats_sheet.dart@@ -1,19 +1,15 @@-import 'dart:convert';-import 'package:flutter/material.dart';import 'package:provider/provider.dart';import '../l10n/app_localizations.dart';import '../providers/auth_provider.dart';-import '../services/scoped_prefs.dart';+import '../services/book_stats_service.dart';/// Listening stats for one book: always the reader's own, plus a server-wide/// picture for admins (who listened, who finished, how long altogether).///-/// The server has no per-item stats endpoint, so this adds up playback-/// sessions: the current user's own item sessions, and for admins the-/// sessions of each user whose progress mentions this book. Users who never-/// touched it are never fetched, which keeps the admin view to a handful of-/// requests on a normal server.+/// The numbers come from [BookStatsService], which the book detail sheet+/// starts loading as soon as it opens - so this sheet usually opens on data+/// that is ready, or joins a load already under way instead of starting one.Future<void> showBookStatsSheet(BuildContext context, {required String itemId,@@ -39,38 +35,6 @@ Future<void> showBookStatsSheet();}-class _UserStat {- final String username;- final double progress;- final bool finished;- final int? finishedAt;-- /// When this user's progress on the item last moved. Cached alongside the- /// total so a later visit can tell, without fetching anything heavy, that- /// their sessions haven't changed.- final int lastUpdate;- double seconds = 0;- _UserStat(this.username, this.progress, this.finished, this.finishedAt,- this.lastUpdate);-- Map<String, dynamic> toJson() => {- 'u': username,- 'p': progress,- 'f': finished,- 'fa': finishedAt,- 'lu': lastUpdate,- 's': seconds,- };-- static _UserStat fromJson(Map<String, dynamic> j) => _UserStat(- j['u'] as String? ?? '',- (j['p'] as num?)?.toDouble() ?? 0,- j['f'] == true,- (j['fa'] as num?)?.toInt(),- (j['lu'] as num?)?.toInt() ?? 0,- )..seconds = (j['s'] as num?)?.toDouble() ?? 0;-}-class _BookStatsSheet extends StatefulWidget {final String itemId;final String title;@@ -88,202 +52,25 @@ class _BookStatsSheet extends StatefulWidget {}class _BookStatsSheetState extends State<_BookStatsSheet> {- bool _loading = true;- bool _failed = false;-- double _mySeconds = 0;- int _mySessions = 0;- int? _myFirst;- int? _myLast;-- bool _isAdmin = false;- bool _serverLoading = false;- List<_UserStat> _users = [];-- /// Progress through the per-user session scan, for the wait message.- int _scanDone = 0;- int _scanTotal = 0;- int? _checkedAt;-- String get _cacheKey => widget.episodeId != null- ? 'bookStats_${widget.itemId}_${widget.episodeId}'- : 'bookStats_${widget.itemId}';+ late final BookStats _stats =+ BookStatsService.instance.stats(widget.itemId, episodeId: widget.episodeId);+ bool _noApi = false;@overridevoid initState() {super.initState();- _load();- }-- /// Last visit's numbers, shown instantly so the sheet is never empty while- /// the scan below brings them up to date.- Future<void> _loadCache() async {- final raw = await ScopedPrefs.getString(_cacheKey);- if (raw == null || raw.isEmpty || !mounted) return;- try {- final j = jsonDecode(raw) as Map<String, dynamic>;- final me = j['me'] as Map<String, dynamic>?;- final users = (j['users'] as List<dynamic>? ?? const [])- .whereType<Map<String, dynamic>>()- .map(_UserStat.fromJson)- .toList();- setState(() {- _checkedAt = (j['at'] as num?)?.toInt();- if (me != null) {- _mySeconds = (me['s'] as num?)?.toDouble() ?? 0;- _mySessions = (me['n'] as num?)?.toInt() ?? 0;- _myFirst = (me['f'] as num?)?.toInt();- _myLast = (me['l'] as num?)?.toInt();- }- _users = users;- _loading = false;- });- } catch (_) {}- }-- Future<void> _saveCache() async {- final payload = jsonEncode({- 'at': DateTime.now().millisecondsSinceEpoch,- 'me': {- 's': _mySeconds,- 'n': _mySessions,- 'f': _myFirst,- 'l': _myLast,- },- 'users': [for (final u in _users) u.toJson()],- });- await ScopedPrefs.setString(_cacheKey, payload);- }-- Future<void> _load() async {- await _loadCache();- if (!mounted) return;final auth = context.read<AuthProvider>();final api = auth.apiService;if (api == null) {- setState(() {- _loading = false;- _failed = _checkedAt == null;- });+ _noApi = true;return;}- final sessions = await api.getMyItemListeningSessions(+ BookStatsService.instance.ensureLoaded(widget.itemId,+ api,episodeId: widget.episodeId,+ isAdmin: auth.isAdmin,);- if (!mounted) return;- var total = 0.0;- int? first;- int? last;- for (final s in sessions) {- if (s is! Map) continue;- total += (s['timeListening'] as num?)?.toDouble() ?? 0;- final at = (s['updatedAt'] as num?)?.toInt() ??- (s['startedAt'] as num?)?.toInt();- if (at != null) {- if (first == null || at < first) first = at;- if (last == null || at > last) last = at;- }- }- setState(() {- _mySeconds = total;- _mySessions = sessions.length;- _myFirst = first;- _myLast = last;- _loading = false;- _isAdmin = auth.isAdmin;- });- if (auth.isAdmin) {- _loadServerWide();- } else {- _checkedAt = DateTime.now().millisecondsSinceEpoch;- await _saveCache();- }- }-- Future<void> _loadServerWide() async {- setState(() => _serverLoading = true);- final api = context.read<AuthProvider>().apiService;- if (api == null) {- if (mounted) setState(() => _serverLoading = false);- return;- }- final userList = await api.getUsers();- if (!mounted) return;- // Anything already scanned, keyed by name so a cached total can be reused- // when that person's progress hasn't moved since.- final cached = {for (final u in _users) u.username: u};- final stats = <String, _UserStat>{};- for (final entry in userList) {- if (entry is! Map) continue;- final id = entry['id'] as String?;- if (id == null) continue;- // The users list is deliberately minimal server-side and carries no- // progress at all - only the single-user endpoint returns it.- final u = await api.getUser(id);- if (!mounted) return;- if (u == null) continue;- for (final p in (u['mediaProgress'] as List<dynamic>? ?? const [])) {- if (p is! Map) continue;- if (p['libraryItemId'] != widget.itemId) continue;- if (widget.episodeId != null && p['episodeId'] != widget.episodeId) {- continue;- }- stats[id] = _UserStat(- u['username'] as String? ?? '',- (p['progress'] as num?)?.toDouble() ?? 0,- p['isFinished'] == true,- (p['finishedAt'] as num?)?.toInt(),- (p['lastUpdate'] as num?)?.toInt() ?? 0,- );- break;- }- }- // The session scan is the slow part, so skip anyone whose progress hasn't- // moved since the last visit and reuse their stored total.- final pending = <String, _UserStat>{};- for (final e in stats.entries) {- final was = cached[e.value.username];- if (was != null && was.lastUpdate >= e.value.lastUpdate) {- e.value.seconds = was.seconds;- } else {- pending[e.key] = e.value;- }- }- if (mounted) {- setState(() {- _scanDone = 0;- _scanTotal = pending.length;- });- }- for (final entry in pending.entries) {- final payload = await api.getUserListeningSessions(entry.key,- itemsPerPage: 1000);- if (!mounted) return;- final sessions = (payload?['sessions'] as List<dynamic>?) ?? const [];- var total = 0.0;- for (final s in sessions) {- if (s is! Map) continue;- if (s['libraryItemId'] != widget.itemId) continue;- if (widget.episodeId != null && s['episodeId'] != widget.episodeId) {- continue;- }- total += (s['timeListening'] as num?)?.toDouble() ?? 0;- }- entry.value.seconds = total;- if (mounted) setState(() => _scanDone++);- }- if (!mounted) return;- debugPrint('[BookStats] item=${widget.itemId} users=${userList.length} '- 'withProgress=${stats.length} rescanned=${pending.length}');- final list = stats.values.toList()- ..sort((a, b) => b.seconds.compareTo(a.seconds));- setState(() {- _users = list;- _serverLoading = false;- _checkedAt = DateTime.now().millisecondsSinceEpoch;- });- await _saveCache();}String _dur(double seconds, AppLocalizations l) {@@ -305,117 +92,123 @@ class _BookStatsSheetState extends State<_BookStatsSheet> {final l = AppLocalizations.of(context)!;final cs = Theme.of(context).colorScheme;final tt = Theme.of(context).textTheme;- return ListView(- controller: widget.scrollController,- padding: const EdgeInsets.fromLTRB(20, 0, 20, 24),- children: [- Text(widget.title,- style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),- const SizedBox(height: 16),- if (_loading)- const Padding(- padding: EdgeInsets.symmetric(vertical: 40),- child: Center(child: CircularProgressIndicator()),- )- else if (_failed)- Padding(- padding: const EdgeInsets.symmetric(vertical: 24),- child: Text(l.statsCouldNotLoad,- style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),- )- else ...[- Text(l.bookStatsYou.toUpperCase(),- style: tt.labelSmall?.copyWith(- color: cs.onSurfaceVariant, letterSpacing: 1)),- const SizedBox(height: 8),- _row(l.bookStatsListened, _dur(_mySeconds, l), cs, tt),- _row(l.bookStatsSessions, '$_mySessions', cs, tt),- if (_myFirst != null)- _row(l.bookStatsFirst, _date(_myFirst!), cs, tt),- if (_myLast != null) _row(l.bookStatsLast, _date(_myLast!), cs, tt),- if (_isAdmin) ...[- const SizedBox(height: 22),- Row(children: [- Text(l.bookStatsEveryone.toUpperCase(),- style: tt.labelSmall?.copyWith(- color: cs.onSurfaceVariant, letterSpacing: 1)),- const Spacer(),- // Cached numbers stay on screen while the rescan runs, so say- // when they were last brought up to date.- if (_serverLoading && _users.isNotEmpty)- SizedBox(- width: 14,- height: 14,- child: CircularProgressIndicator(- strokeWidth: 2, color: cs.onSurfaceVariant),- )- else if (_checkedAt != null)- Text(l.bookStatsLastChecked(_date(_checkedAt!)),- style:- tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),- ]),- const SizedBox(height: 8),- if (_serverLoading && _users.isEmpty)- Padding(- padding: const EdgeInsets.symmetric(vertical: 20),- child: Column(children: [- const CircularProgressIndicator(),- const SizedBox(height: 14),- Text(- _scanTotal > 0- ? l.bookStatsScanningCount(_scanDone, _scanTotal)- : l.bookStatsScanning,- textAlign: TextAlign.center,- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),- ),- ]),+ return ListenableBuilder(+ listenable: _stats,+ builder: (context, _) {+ final s = _stats;+ final failed = s.failed || (_noApi && s.checkedAt == null);+ return ListView(+ controller: widget.scrollController,+ padding: const EdgeInsets.fromLTRB(20, 0, 20, 24),+ children: [+ Text(widget.title,+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),+ const SizedBox(height: 16),+ if (s.loading && !failed)+ const Padding(+ padding: EdgeInsets.symmetric(vertical: 40),+ child: Center(child: CircularProgressIndicator()),)- else if (_users.isEmpty)+ else if (failed)Padding(- padding: const EdgeInsets.symmetric(vertical: 12),- child: Text(l.bookStatsNobody,- style:- tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),+ padding: const EdgeInsets.symmetric(vertical: 24),+ child: Text(l.statsCouldNotLoad,+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),)else ...[- _row(- l.bookStatsListeners, '${_users.length}', cs, tt),- _row(l.bookStatsFinishedCount,- '${_users.where((u) => u.finished).length}', cs, tt),- _row(- l.bookStatsTotalTime,- _dur(_users.fold(0.0, (a, u) => a + u.seconds), l),- cs,- tt),- const SizedBox(height: 12),- for (final u in _users)- Padding(- padding: const EdgeInsets.symmetric(vertical: 6),- child: Row(children: [- Icon(- u.finished- ? Icons.check_circle_rounded- : Icons.headphones_rounded,- size: 18,- color: u.finished ? cs.primary : cs.onSurfaceVariant,- ),- const SizedBox(width: 10),- Expanded(- child: Text(u.username,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: tt.bodyMedium),- ),- Text(- '${(u.progress * 100).clamp(0, 100).round()}% ${_dur(u.seconds, l)}',- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),+ Text(l.bookStatsYou.toUpperCase(),+ style: tt.labelSmall?.copyWith(+ color: cs.onSurfaceVariant, letterSpacing: 1)),+ const SizedBox(height: 8),+ _row(l.bookStatsListened, _dur(s.mySeconds, l), cs, tt),+ _row(l.bookStatsSessions, '${s.mySessions}', cs, tt),+ if (s.myFirst != null)+ _row(l.bookStatsFirst, _date(s.myFirst!), cs, tt),+ if (s.myLast != null) _row(l.bookStatsLast, _date(s.myLast!), cs, tt),+ if (s.isAdmin) ...[+ const SizedBox(height: 22),+ Row(children: [+ Text(l.bookStatsEveryone.toUpperCase(),+ style: tt.labelSmall?.copyWith(+ color: cs.onSurfaceVariant, letterSpacing: 1)),+ const Spacer(),+ // Cached numbers stay on screen while the rescan runs, so+ // say when they were last brought up to date.+ if (s.serverLoading && s.users.isNotEmpty)+ SizedBox(+ width: 14,+ height: 14,+ child: CircularProgressIndicator(+ strokeWidth: 2, color: cs.onSurfaceVariant),+ )+ else if (s.checkedAt != null)+ Text(l.bookStatsLastChecked(_date(s.checkedAt!)),+ style:+ tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),+ ]),+ const SizedBox(height: 8),+ if (s.serverLoading && s.users.isEmpty)+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 20),+ child: Column(children: [+ const CircularProgressIndicator(),+ const SizedBox(height: 14),+ Text(+ s.scanTotal > 0+ ? l.bookStatsScanningCount(s.scanDone, s.scanTotal)+ : l.bookStatsScanning,+ textAlign: TextAlign.center,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),+ ),+ ]),+ )+ else if (s.users.isEmpty)+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 12),+ child: Text(l.bookStatsNobody,+ style:+ tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),+ )+ else ...[+ _row(l.bookStatsListeners, '${s.users.length}', cs, tt),+ _row(l.bookStatsFinishedCount,+ '${s.users.where((u) => u.finished).length}', cs, tt),+ _row(+ l.bookStatsTotalTime,+ _dur(s.users.fold(0.0, (a, u) => a + u.seconds), l),+ cs,+ tt),+ const SizedBox(height: 12),+ for (final u in s.users)+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 6),+ child: Row(children: [+ Icon(+ u.finished+ ? Icons.check_circle_rounded+ : Icons.headphones_rounded,+ size: 18,+ color: u.finished ? cs.primary : cs.onSurfaceVariant,+ ),+ const SizedBox(width: 10),+ Expanded(+ child: Text(u.username,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: tt.bodyMedium),+ ),+ Text(+ '${(u.progress * 100).clamp(0, 100).round()}% ${_dur(u.seconds, l)}',+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),+ ),+ ]),),- ]),- ),+ ],+ ],],],- ],- ],+ );+ },);}