Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Redesign stats page, scope all settings per-user, show active downloads

Nathan Poulson7faf53cffb6d
diff --git a/lib/screens/downloads_screen.dart b/lib/screens/downloads_screen.dart
index 4f2ac94b..7d9e476a 100644
--- a/lib/screens/downloads_screen.dart
+++ b/lib/screens/downloads_screen.dart
@@ -195,60 +195,104 @@ class _DownloadsScreenState extends State<DownloadsScreen> {
const SizedBox(height: 12),
// Content
- if (_items.isEmpty)
- Expanded(
- child: Center(
- child: Column(
- mainAxisSize: MainAxisSize.min,
+ Expanded(
+ child: ListenableBuilder(
+ listenable: DownloadService(),
+ builder: (ctx, _) {
+ final ds = DownloadService();
+ final active = ds.activeDownloads;
+ final queued = ds.queuedDownloads;
+ final completed = ds.downloadedItems;
+ final hasAny = active.isNotEmpty || queued.isNotEmpty || completed.isNotEmpty;
+
+ if (!hasAny) {
+ return Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.download_done_rounded,
+ size: 48,
+ color: cs.onSurfaceVariant
+ .withValues(alpha: 0.4)),
+ const SizedBox(height: 12),
+ Text('No downloads',
+ style: tt.bodyLarge?.copyWith(
+ color: cs.onSurfaceVariant)),
+ ],
+ ),
+ );
+ }
+
+ return ListView(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),
children: [
- Icon(Icons.download_done_rounded,
- size: 48,
- color: cs.onSurfaceVariant
- .withValues(alpha: 0.4)),
- const SizedBox(height: 12),
- Text('No downloads',
- style: tt.bodyLarge?.copyWith(
- color: cs.onSurfaceVariant)),
+ // Active downloads
+ if (active.isNotEmpty) ...[
+ Padding(
+ padding: const EdgeInsets.only(left: 4, bottom: 8),
+ child: Text('Downloading',
+ style: tt.labelMedium?.copyWith(
+ color: cs.primary,
+ fontWeight: FontWeight.w600)),
+ ),
+ for (final info in active)
+ _ActiveDownloadCard(
+ info: info,
+ cs: cs,
+ tt: tt,
+ onCancel: () => ds.cancelDownload(info.itemId),
+ mediaHeaders: context.read<LibraryProvider>().mediaHeaders,
+ ),
+ ],
+ // Queued downloads
+ if (queued.isNotEmpty) ...[
+ Padding(
+ padding: const EdgeInsets.only(left: 4, top: 4, bottom: 8),
+ child: Text('Queued',
+ style: tt.labelMedium?.copyWith(
+ color: cs.onSurfaceVariant,
+ fontWeight: FontWeight.w600)),
+ ),
+ for (final info in queued)
+ _ActiveDownloadCard(
+ info: info,
+ cs: cs,
+ tt: tt,
+ isQueued: true,
+ onCancel: () => ds.cancelDownload(info.itemId),
+ mediaHeaders: context.read<LibraryProvider>().mediaHeaders,
+ ),
+ ],
+ // Completed downloads
+ if (completed.isNotEmpty) ...[
+ if (active.isNotEmpty || queued.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.only(left: 4, top: 4, bottom: 8),
+ child: Text('Completed',
+ style: tt.labelMedium?.copyWith(
+ color: cs.onSurfaceVariant,
+ fontWeight: FontWeight.w600)),
+ ),
+ for (final info in completed)
+ _DownloadCard(
+ info: info,
+ fileSize: _fileSizes[info.itemId] ?? 0,
+ cs: cs,
+ tt: tt,
+ selecting: _selecting,
+ isSelected: _selected.contains(info.itemId),
+ onToggle: () => _toggleSelect(info.itemId),
+ onLongPress: () => _enterSelection(info.itemId),
+ onDelete: () => _deleteSingle(info),
+ formatBytes: _formatBytes,
+ mediaHeaders: context.read<LibraryProvider>().mediaHeaders,
+ ),
+ ],
],
- ),
- ),
- )
- else
- Expanded(
- child: ListenableBuilder(
- listenable: DownloadService(),
- builder: (ctx, _) {
- final items = DownloadService().downloadedItems;
- return ListView.builder(
- padding:
- const EdgeInsets.fromLTRB(16, 0, 16, 24),
- itemCount: items.length,
- itemBuilder: (ctx, index) {
- final info = items[index];
- return _DownloadCard(
- info: info,
- fileSize:
- _fileSizes[info.itemId] ?? 0,
- cs: cs,
- tt: tt,
- selecting: _selecting,
- isSelected:
- _selected.contains(info.itemId),
- onToggle: () =>
- _toggleSelect(info.itemId),
- onLongPress: () =>
- _enterSelection(info.itemId),
- onDelete: () => _deleteSingle(info),
- formatBytes: _formatBytes,
- mediaHeaders: context
- .read<LibraryProvider>()
- .mediaHeaders,
- );
- },
- );
- },
- ),
+ );
+ },
),
+ ),
// Bottom delete bar
if (_selecting && _selected.isNotEmpty)
@@ -456,3 +500,133 @@ class _DownloadCard extends StatelessWidget {
);
}
}
+
+class _ActiveDownloadCard extends StatelessWidget {
+ final DownloadInfo info;
+ final ColorScheme cs;
+ final TextTheme tt;
+ final bool isQueued;
+ final VoidCallback onCancel;
+ final Map<String, String> mediaHeaders;
+
+ const _ActiveDownloadCard({
+ required this.info,
+ required this.cs,
+ required this.tt,
+ this.isQueued = false,
+ required this.onCancel,
+ required this.mediaHeaders,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final progress = info.progress;
+ final pct = (progress * 100).round();
+
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Card(
+ elevation: 0,
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
+ child: Padding(
+ padding: const EdgeInsets.all(12),
+ child: Row(
+ children: [
+ // Cover art
+ ClipRRect(
+ borderRadius: BorderRadius.circular(8),
+ child: SizedBox(
+ width: 48,
+ height: 48,
+ child: _buildCover(),
+ ),
+ ),
+ const SizedBox(width: 12),
+ // Title, status, progress
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ info.title ?? 'Unknown',
+ style: tt.titleSmall?.copyWith(fontWeight: FontWeight.w600),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ const SizedBox(height: 4),
+ if (isQueued)
+ Text('Waiting...',
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant))
+ else ...[
+ Row(
+ children: [
+ Expanded(
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(4),
+ child: LinearProgressIndicator(
+ value: progress,
+ minHeight: 6,
+ backgroundColor: cs.surfaceContainerHighest,
+ valueColor: AlwaysStoppedAnimation(cs.primary),
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ Text('$pct%',
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant,
+ fontWeight: FontWeight.w600)),
+ ],
+ ),
+ ],
+ ],
+ ),
+ ),
+ const SizedBox(width: 4),
+ IconButton(
+ icon: Icon(Icons.close_rounded,
+ color: cs.onSurfaceVariant, size: 20),
+ tooltip: 'Cancel',
+ onPressed: onCancel,
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _buildCover() {
+ if (info.coverUrl != null && info.coverUrl!.isNotEmpty) {
+ if (info.coverUrl!.startsWith('/')) {
+ final file = File(info.coverUrl!);
+ if (file.existsSync()) {
+ return Image.file(file,
+ fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _coverPlaceholder());
+ }
+ return _coverPlaceholder();
+ }
+ return CachedNetworkImage(
+ imageUrl: info.coverUrl!,
+ fit: BoxFit.cover,
+ httpHeaders: mediaHeaders,
+ placeholder: (_, __) => _coverPlaceholder(),
+ errorWidget: (_, __, ___) => _coverPlaceholder(),
+ );
+ }
+ return _coverPlaceholder();
+ }
+
+ Widget _coverPlaceholder() {
+ return Container(
+ color: cs.surfaceContainerHighest,
+ child: Center(
+ child: Icon(Icons.headphones_rounded,
+ size: 24, color: cs.onSurfaceVariant.withValues(alpha: 0.4)),
+ ),
+ );
+ }
+}
diff --git a/lib/screens/stats_screen.dart b/lib/screens/stats_screen.dart
index e7d76ca3..d8e57f12 100644
--- a/lib/screens/stats_screen.dart
+++ b/lib/screens/stats_screen.dart
@@ -15,6 +15,7 @@ class _StatsScreenState extends State<StatsScreen> with SingleTickerProviderStat
Map<String, dynamic>? _stats;
List<dynamic> _sessions = [];
bool _isLoading = true;
+ int _booksFinished = 0;
late AnimationController _animController;
late Animation<double> _animValue;
@@ -32,26 +33,23 @@ class _StatsScreenState extends State<StatsScreen> with SingleTickerProviderStat
super.dispose();
}
- int _booksFinished = 0;
-
Future<void> _loadStats() async {
final api = context.read<AuthProvider>().apiService;
if (api == null) return;
- final statsFuture = api.getListeningStats();
- final sessionsFuture = api.getListeningSessions(itemsPerPage: 25);
- final meFuture = api.getMe();
- final stats = await statsFuture;
- final sessionsData = await sessionsFuture;
- final meData = await meFuture;
-
- // Count finished from mediaProgress
+ final results = await Future.wait([
+ api.getListeningStats(),
+ api.getListeningSessions(itemsPerPage: 50),
+ api.getMe(),
+ ]);
+ final stats = results[0];
+ final sessionsData = results[1];
+ final meData = results[2];
+
int finished = 0;
if (meData != null) {
final progress = meData['mediaProgress'] as List<dynamic>? ?? [];
for (final p in progress) {
- if (p is Map<String, dynamic> && p['isFinished'] == true) {
- finished++;
- }
+ if (p is Map<String, dynamic> && p['isFinished'] == true) finished++;
}
}
@@ -89,29 +87,28 @@ class _StatsScreenState extends State<StatsScreen> with SingleTickerProviderStat
),
),
child: SafeArea(
- child: _isLoading
- ? Center(child: CircularProgressIndicator(strokeWidth: 2, color: cs.onSurface.withValues(alpha: 0.24)))
- : _stats == null
- ? _errorState(tt)
- : RefreshIndicator(
- onRefresh: () async {
- setState(() => _isLoading = true);
- await _loadStats();
- },
- color: cs.primary,
- backgroundColor: Theme.of(context).colorScheme.surfaceContainerHigh,
- child: AnimatedBuilder(
- animation: _animValue,
- builder: (_, __) => _buildContent(cs, tt),
+ child: _isLoading
+ ? Center(child: CircularProgressIndicator(strokeWidth: 2, color: cs.onSurface.withValues(alpha: 0.24)))
+ : _stats == null
+ ? _errorState(tt, cs)
+ : RefreshIndicator(
+ onRefresh: () async {
+ setState(() => _isLoading = true);
+ await _loadStats();
+ },
+ color: cs.primary,
+ backgroundColor: cs.surfaceContainerHigh,
+ child: AnimatedBuilder(
+ animation: _animValue,
+ builder: (_, __) => _buildContent(cs, tt),
+ ),
),
- ),
- ),
+ ),
),
);
}
- Widget _errorState(TextTheme tt) {
- final cs = Theme.of(context).colorScheme;
+ Widget _errorState(TextTheme tt, ColorScheme cs) {
return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
Icon(Icons.signal_wifi_off_rounded, size: 48, color: cs.onSurface.withValues(alpha: 0.15)),
const SizedBox(height: 12),
@@ -131,74 +128,96 @@ class _StatsScreenState extends State<StatsScreen> with SingleTickerProviderStat
final streak = _currentStreak(dailyMap);
final longestStreak = _longestStreak(dailyMap);
final weekData = _last7Days(dailyMap);
- final monthData = _last30Days(dailyMap);
-
- // Count finished books — loaded from /api/me mediaProgress
- final booksFinished = _booksFinished;
+ final activeDays = _activeDayCount(dailyMap);
+ final avgDaily = _averageDailySeconds(dailyMap);
+ final topItems = _topItems();
return ListView(
padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
children: [
- // Header
const AbsorbPageHeader(
title: 'Your Stats',
padding: EdgeInsets.only(top: 4),
),
const SizedBox(height: 24),
- // ── Hero stat ──
+ // -- Hero stat --
_heroStat(tt, cs, totalSeconds),
- const SizedBox(height: 24),
+ const SizedBox(height: 16),
- // ── Quick stats row ──
+ // -- Time periods --
Row(children: [
- Expanded(child: _statCard(tt, cs, Icons.local_fire_department_rounded, Colors.orange,
- '${streak}d', 'Current\nStreak')),
- const SizedBox(width: 10),
- Expanded(child: _statCard(tt, cs, Icons.emoji_events_rounded, Colors.amber,
- '${longestStreak}d', 'Longest\nStreak')),
- const SizedBox(width: 10),
- Expanded(child: _statCard(tt, cs, Icons.check_circle_rounded, Colors.green,
- '$booksFinished', 'Books\nFinished')),
+ Expanded(child: _periodCard(tt, cs, 'Today', today)),
+ const SizedBox(width: 8),
+ Expanded(child: _periodCard(tt, cs, 'This Week', thisWeek)),
+ const SizedBox(width: 8),
+ Expanded(child: _periodCard(tt, cs, 'This Month', thisMonth)),
]),
const SizedBox(height: 24),
- // ── Time periods ──
+ // -- Activity stats --
+ _sectionTitle(tt, cs, 'Activity'),
+ const SizedBox(height: 10),
Row(children: [
- Expanded(child: _periodCard(tt, cs, 'Today', today)),
- const SizedBox(width: 10),
- Expanded(child: _periodCard(tt, cs, 'This Week', thisWeek)),
- const SizedBox(width: 10),
- Expanded(child: _periodCard(tt, cs, 'This Month', thisMonth)),
+ Expanded(child: _accentStatCard(tt, cs,
+ Icons.local_fire_department_rounded, Colors.orange,
+ '${streak}d', 'Current Streak')),
+ const SizedBox(width: 8),
+ Expanded(child: _accentStatCard(tt, cs,
+ Icons.emoji_events_rounded, Colors.amber.shade600,
+ '${longestStreak}d', 'Best Streak')),
+ ]),
+ const SizedBox(height: 8),
+ Row(children: [
+ Expanded(child: _accentStatCard(tt, cs,
+ Icons.check_circle_rounded, Colors.green,
+ '$_booksFinished', 'Finished')),
+ const SizedBox(width: 8),
+ Expanded(child: _accentStatCard(tt, cs,
+ Icons.calendar_today_rounded, cs.primary,
+ '$activeDays', 'Days Active')),
]),
+ const SizedBox(height: 8),
+ _accentStatCard(tt, cs,
+ Icons.speed_rounded, cs.tertiary,
+ _formatDuration(avgDaily), 'Daily Average'),
const SizedBox(height: 28),
- // ── Last 7 days chart ──
- Text('Last 7 Days', style: tt.titleSmall?.copyWith(
- color: cs.onSurface.withValues(alpha: 0.6), fontWeight: FontWeight.w600)),
- const SizedBox(height: 12),
- _barChart(weekData, cs),
+ // -- Last 7 days chart --
+ _sectionTitle(tt, cs, 'Last 7 Days'),
+ const SizedBox(height: 10),
+ _barChart(weekData, cs, tt),
const SizedBox(height: 28),
- // ── Last 30 days chart ──
- Text('Last 30 Days', style: tt.titleSmall?.copyWith(
- color: cs.onSurface.withValues(alpha: 0.6), fontWeight: FontWeight.w600)),
- const SizedBox(height: 12),
- _heatMap(monthData, tt, cs),
- const SizedBox(height: 28),
+ // -- Top items --
+ if (topItems.isNotEmpty) ...[
+ _sectionTitle(tt, cs, 'Most Listened'),
+ const SizedBox(height: 10),
+ ...topItems.map((item) => _topItemCard(tt, cs, item)),
+ const SizedBox(height: 28),
+ ],
- // ── Recent Sessions ──
+ // -- Recent Sessions --
if (_sessions.isNotEmpty) ...[
- Text('Recent Sessions', style: tt.titleSmall?.copyWith(
- color: cs.onSurface.withValues(alpha: 0.6), fontWeight: FontWeight.w600)),
- const SizedBox(height: 12),
+ _sectionTitle(tt, cs, 'Recent Sessions'),
+ const SizedBox(height: 10),
..._buildSessions(tt, cs),
],
],
);
}
- // ─── HERO STAT ──────────────────────────────────────────────
+ // --- SECTION TITLE ---
+
+ Widget _sectionTitle(TextTheme tt, ColorScheme cs, String title) {
+ return Text(title, style: tt.titleSmall?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.5),
+ fontWeight: FontWeight.w600,
+ letterSpacing: 0.5,
+ ));
+ }
+
+ // --- HERO STAT ---
Widget _heroStat(TextTheme tt, ColorScheme cs, double totalSeconds) {
final hours = (totalSeconds / 3600).floor();
@@ -212,32 +231,41 @@ class _StatsScreenState extends State<StatsScreen> with SingleTickerProviderStat
gradient: LinearGradient(
begin: Alignment.topLeft, end: Alignment.bottomRight,
colors: [
- cs.onSurface.withValues(alpha: 0.06),
- cs.onSurface.withValues(alpha: 0.02),
+ cs.primary.withValues(alpha: 0.12),
+ cs.primary.withValues(alpha: 0.04),
],
),
- border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),
+ border: Border.all(color: cs.primary.withValues(alpha: 0.15)),
),
child: Column(children: [
- Text('Total Listening Time', style: tt.labelMedium?.copyWith(
- color: cs.onSurface.withValues(alpha: 0.38), letterSpacing: 1.5, fontWeight: FontWeight.w500)),
- const SizedBox(height: 12),
- Row(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, children: [
- Text('${(hours * anim).round()}',
- style: tt.displayLarge?.copyWith(
- fontWeight: FontWeight.w800, color: cs.onSurface, fontSize: 56, height: 1)),
- Padding(padding: const EdgeInsets.only(bottom: 8),
- child: Text('h', style: tt.headlineSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.38), fontWeight: FontWeight.w300))),
- const SizedBox(width: 8),
- Text('${(minutes * anim).round()}',
- style: tt.displayLarge?.copyWith(
- fontWeight: FontWeight.w800, color: cs.onSurface, fontSize: 56, height: 1)),
- Padding(padding: const EdgeInsets.only(bottom: 8),
- child: Text('m', style: tt.headlineSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.38), fontWeight: FontWeight.w300))),
- ]),
- const SizedBox(height: 8),
+ Text('TOTAL LISTENING TIME', style: tt.labelSmall?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.35),
+ letterSpacing: 2,
+ fontWeight: FontWeight.w500,
+ fontSize: 10,
+ )),
+ const SizedBox(height: 14),
+ Row(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.baseline,
+ textBaseline: TextBaseline.alphabetic,
+ children: [
+ Text('${(hours * anim).round()}',
+ style: tt.displayLarge?.copyWith(
+ fontWeight: FontWeight.w800, color: cs.onSurface, fontSize: 52, height: 1)),
+ const SizedBox(width: 2),
+ Text('h', style: tt.titleLarge?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.3), fontWeight: FontWeight.w300)),
+ const SizedBox(width: 12),
+ Text('${(minutes * anim).round()}',
+ style: tt.displayLarge?.copyWith(
+ fontWeight: FontWeight.w800, color: cs.onSurface, fontSize: 52, height: 1)),
+ const SizedBox(width: 2),
+ Text('m', style: tt.titleLarge?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.3), fontWeight: FontWeight.w300)),
+ ],
+ ),
+ const SizedBox(height: 10),
Text(_daysEquivalent(totalSeconds),
- style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.24))),
+ style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.25))),
]),
);
}
@@ -249,203 +277,240 @@ class _StatsScreenState extends State<StatsScreen> with SingleTickerProviderStat
return 'That\'s ${hours.toStringAsFixed(1)} hours of audio';
}
- // ─── STAT CARD ──────────────────────────────────────────────
+ // --- ACCENT STAT CARD ---
- Widget _statCard(TextTheme tt, ColorScheme cs, IconData icon, Color color, String value, String label) {
+ Widget _accentStatCard(TextTheme tt, ColorScheme cs, IconData icon, Color accent,
+ String value, String label) {
return Container(
- padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
+ padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 14),
decoration: BoxDecoration(
color: cs.onSurface.withValues(alpha: 0.04),
- borderRadius: BorderRadius.circular(16),
+ borderRadius: BorderRadius.circular(14),
border: Border.all(color: cs.onSurface.withValues(alpha: 0.06)),
),
- child: Column(children: [
- Icon(icon, color: color.withValues(alpha: 0.8), size: 22),
- const SizedBox(height: 8),
- Text(value, style: tt.headlineSmall?.copyWith(
- fontWeight: FontWeight.w800, color: cs.onSurface, height: 1)),
- const SizedBox(height: 4),
- Text(label, textAlign: TextAlign.center, style: tt.labelSmall?.copyWith(
- color: cs.onSurface.withValues(alpha: 0.3), fontSize: 10, height: 1.2)),
+ child: Row(children: [
+ Container(
+ width: 36, height: 36,
+ decoration: BoxDecoration(
+ color: accent.withValues(alpha: 0.12),
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Icon(icon, color: accent.withValues(alpha: 0.8), size: 18),
+ ),
+ const SizedBox(width: 12),
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(value, style: tt.titleMedium?.copyWith(
+ fontWeight: FontWeight.w700, color: cs.onSurface, height: 1)),
+ const SizedBox(height: 2),
+ Text(label, style: tt.labelSmall?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.35), fontSize: 11)),
+ ])),
]),
);
}
- // ─── PERIOD CARD ────────────────────────────────────────────
+ // --- PERIOD CARD ---
Widget _periodCard(TextTheme tt, ColorScheme cs, String label, double seconds) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 10),
decoration: BoxDecoration(
color: cs.onSurface.withValues(alpha: 0.04),
- borderRadius: BorderRadius.circular(16),
+ borderRadius: BorderRadius.circular(14),
border: Border.all(color: cs.onSurface.withValues(alpha: 0.06)),
),
child: Column(children: [
Text(_formatDuration(seconds), style: tt.titleMedium?.copyWith(
fontWeight: FontWeight.w700, color: cs.onSurface, height: 1)),
const SizedBox(height: 4),
- Text(label, style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3), fontSize: 10)),
+ Text(label, style: tt.labelSmall?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.35), fontSize: 10)),
]),
);
}
- // ─── BAR CHART (7 days) ─────────────────────────────────────
+ // --- BAR CHART (7 days) ---
- Widget _barChart(List<_DayData> data, ColorScheme cs) {
+ Widget _barChart(List<_DayData> data, ColorScheme cs, TextTheme tt) {
final maxVal = data.map((d) => d.seconds).fold(0.0, (a, b) => a > b ? a : b);
final barMax = maxVal > 0 ? maxVal : 1.0;
final anim = _animValue.value;
return Container(
- height: 140,
- padding: const EdgeInsets.fromLTRB(0, 8, 0, 0),
+ padding: const EdgeInsets.fromLTRB(4, 16, 4, 8),
decoration: BoxDecoration(
color: cs.onSurface.withValues(alpha: 0.03),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: cs.onSurface.withValues(alpha: 0.05)),
),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.end,
- children: data.map((d) {
- final ratio = (d.seconds / barMax * anim).clamp(0.0, 1.0);
- final isToday = d.label == _dayLabel(DateTime.now());
- return Expanded(child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 4),
- child: Column(mainAxisAlignment: MainAxisAlignment.end, children: [
- if (d.seconds > 0)
- Padding(padding: const EdgeInsets.only(bottom: 4),
- child: Text(_shortDuration(d.seconds), style: TextStyle(
- color: cs.onSurface.withValues(alpha: 0.3), fontSize: 9, fontWeight: FontWeight.w500))),
- AnimatedContainer(
- duration: const Duration(milliseconds: 600),
- curve: Curves.easeOutCubic,
- height: (ratio * 80).clamp(2.0, 80.0),
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(4),
- color: isToday ? cs.onSurface.withValues(alpha: 0.5) : cs.onSurface.withValues(alpha: 0.15),
- ),
- ),
- const SizedBox(height: 6),
- Text(d.label, style: TextStyle(
- color: isToday ? cs.onSurface.withValues(alpha: 0.6) : cs.onSurface.withValues(alpha: 0.2),
- fontSize: 10, fontWeight: isToday ? FontWeight.w600 : FontWeight.w400)),
- const SizedBox(height: 8),
- ]),
- ));
- }).toList(),
- ),
+ child: Column(children: [
+ SizedBox(
+ height: 120,
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.end,
+ children: data.map((d) {
+ final ratio = (d.seconds / barMax * anim).clamp(0.0, 1.0);
+ final isToday = d.fullLabel == _dateKey(DateTime.now());
+ return Expanded(child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 3),
+ child: Column(mainAxisAlignment: MainAxisAlignment.end, children: [
+ if (d.seconds > 0)
+ Padding(padding: const EdgeInsets.only(bottom: 4),
+ child: Text(_shortDuration(d.seconds), style: TextStyle(
+ color: cs.onSurface.withValues(alpha: 0.35), fontSize: 9, fontWeight: FontWeight.w600))),
+ Container(
+ height: max(ratio * 80, d.seconds > 0 ? 4 : 2),
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(5),
+ color: isToday
+ ? cs.primary.withValues(alpha: 0.7)
+ : cs.onSurface.withValues(alpha: 0.12),
+ ),
+ ),
+ ]),
+ ));
+ }).toList(),
+ ),
+ ),
+ const SizedBox(height: 8),
+ Row(children: data.map((d) {
+ final isToday = d.fullLabel == _dateKey(DateTime.now());
+ return Expanded(child: Text(d.label, textAlign: TextAlign.center,
+ style: TextStyle(
+ color: isToday ? cs.primary.withValues(alpha: 0.8) : cs.onSurface.withValues(alpha: 0.25),
+ fontSize: 10,
+ fontWeight: isToday ? FontWeight.w600 : FontWeight.w400,
+ )));
+ }).toList()),
+ ]),
);
}
- // ─── HEAT MAP (30 days) ─────────────────────────────────────
+ // --- TOP ITEMS ---
- Widget _heatMap(List<_DayData> data, TextTheme tt, ColorScheme cs) {
- final maxVal = data.map((d) => d.seconds).fold(0.0, (a, b) => a > b ? a : b);
+ List<_TopItem> _topItems() {
+ final Map<String, _TopItem> byTitle = {};
+ for (final s in _sessions) {
+ if (s is! Map<String, dynamic>) continue;
+ final rawTitle = s['displayTitle'] as String?;
+ final meta = s['mediaMetadata'] as Map<String, dynamic>?;
+ final title = (rawTitle != null && !_looksLikeId(rawTitle))
+ ? rawTitle
+ : meta?['title'] as String? ?? '';
+ if (title.isEmpty) continue;
+ final rawAuthor = s['displayAuthor'] as String?;
+ final author = (rawAuthor != null && !_looksLikeId(rawAuthor))
+ ? rawAuthor
+ : meta?['authorName'] as String? ?? '';
+ final duration = _safeNum(s['timeListening']);
+ final existing = byTitle[title];
+ if (existing != null) {
+ existing.totalSeconds += duration;
+ existing.sessionCount++;
+ } else {
+ byTitle[title] = _TopItem(title: title, author: author, totalSeconds: duration, sessionCount: 1);
+ }
+ }
+ final items = byTitle.values.toList()
+ ..sort((a, b) => b.totalSeconds.compareTo(a.totalSeconds));
+ return items.take(5).toList();
+ }
- return Wrap(
- spacing: 3, runSpacing: 3,
- children: data.map((d) {
- final intensity = maxVal > 0 ? (d.seconds / maxVal).clamp(0.0, 1.0) : 0.0;
- return Tooltip(
- message: '${d.fullLabel}: ${_formatDuration(d.seconds)}',
- child: Container(
- width: 18, height: 18,
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(3),
- color: intensity > 0
- ? cs.onSurface.withValues(alpha: 0.08 + intensity * 0.4)
- : cs.onSurface.withValues(alpha: 0.03),
- ),
- ),
- );
- }).toList(),
+ Widget _topItemCard(TextTheme tt, ColorScheme cs, _TopItem item) {
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Container(
+ padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 14),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.04),
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.05)),
+ ),
+ child: Row(children: [
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(item.title, maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.8), fontWeight: FontWeight.w600)),
+ if (item.author.isNotEmpty)
+ Text(item.author, maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.3), fontSize: 10)),
+ ])),
+ const SizedBox(width: 12),
+ Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
+ Text(_formatDuration(item.totalSeconds),
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.5), fontWeight: FontWeight.w700)),
+ Text('${item.sessionCount} ${item.sessionCount == 1 ? 'session' : 'sessions'}',
+ style: TextStyle(color: cs.onSurface.withValues(alpha: 0.2), fontSize: 9)),
+ ]),
+ ]),
+ ),
);
}
- // ─── SESSIONS ───────────────────────────────────────────────
+ // --- SESSIONS ---
List<Widget> _buildSessions(TextTheme tt, ColorScheme cs) {
- return _sessions.take(15).map((s) {
+ return _sessions.take(10).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? ?? 'Unknown';
- final author = (rawAuthor != null && !_looksLikeId(rawAuthor)) ? rawAuthor
- : meta?['authorName'] as String? ?? '';
+ final title = (rawTitle != null && !_looksLikeId(rawTitle))
+ ? rawTitle : meta?['title'] as String? ?? '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;
- // Device / app info
final deviceInfo = s['deviceInfo'] as Map<String, dynamic>? ?? {};
final clientName = deviceInfo['clientName'] as String? ??
deviceInfo['deviceName'] as String? ?? '';
- final manufacturer = deviceInfo['manufacturer'] as String? ?? '';
- final model = deviceInfo['model'] as String? ?? '';
- final deviceStr = [manufacturer, model].where((s) => s.isNotEmpty).join(' ');
- final appLabel = clientName.isNotEmpty ? clientName : 'Unknown Client';
-
- // Pick an icon based on client name
final isAbsorb = clientName.toLowerCase().contains('absorb');
- final icon = _clientIcon(clientName);
- final iconColor = _clientColor(clientName, cs);
return Padding(
- padding: const EdgeInsets.only(bottom: 8),
+ padding: const EdgeInsets.only(bottom: 6),
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
- color: cs.onSurface.withValues(alpha: 0.04),
+ color: cs.onSurface.withValues(alpha: 0.03),
borderRadius: BorderRadius.circular(12),
- border: Border.all(color: cs.onSurface.withValues(alpha: 0.06)),
+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.05)),
),
- child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
- // App icon
+ child: Row(children: [
Container(
- width: 36, height: 36,
+ width: 32, height: 32,
decoration: BoxDecoration(
- color: iconColor.withValues(alpha: 0.15),
+ color: (isAbsorb ? Colors.tealAccent : cs.onSurfaceVariant).withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(8),
),
child: Center(
child: isAbsorb
- ? AbsorbWaveIcon(size: 20, color: iconColor.withValues(alpha: 0.8))
- : Icon(icon, size: 18, color: iconColor.withValues(alpha: 0.8)),
+ ? AbsorbWaveIcon(size: 16, color: Colors.tealAccent.withValues(alpha: 0.7))
+ : Icon(_clientIcon(clientName), size: 15,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.6)),
),
),
- const SizedBox(width: 12),
- // Title + author + app
+ const SizedBox(width: 10),
Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(title, maxLines: 1, overflow: TextOverflow.ellipsis,
- style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.7), fontWeight: FontWeight.w600)),
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.7), fontWeight: FontWeight.w600, fontSize: 12)),
if (author.isNotEmpty)
Text(author, maxLines: 1, overflow: TextOverflow.ellipsis,
- style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.3), fontSize: 10)),
- const SizedBox(height: 4),
- Row(children: [
- isAbsorb
- ? AbsorbWaveIcon(size: 10, color: iconColor.withValues(alpha: 0.5))
- : Icon(icon, size: 10, color: iconColor.withValues(alpha: 0.5)),
- const SizedBox(width: 4),
- Flexible(child: Text(
- deviceStr.isNotEmpty ? '$appLabel · $deviceStr' : appLabel,
- maxLines: 1, overflow: TextOverflow.ellipsis,
- style: TextStyle(color: cs.onSurface.withValues(alpha: 0.2), fontSize: 9),
- )),
- ]),
+ style: TextStyle(color: cs.onSurface.withValues(alpha: 0.25), fontSize: 10)),
])),
const SizedBox(width: 8),
- // Duration + time
Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
Text(_formatDuration(duration),
- style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.38), fontWeight: FontWeight.w600)),
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.4), fontWeight: FontWeight.w600, fontSize: 11)),
if (updatedAt != null)
Text(_relativeDate(updatedAt),
- style: tt.labelSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.2), fontSize: 9)),
+ style: TextStyle(color: cs.onSurface.withValues(alpha: 0.18), fontSize: 9)),
]),
]),
),
@@ -455,7 +520,6 @@ class _StatsScreenState extends State<StatsScreen> with SingleTickerProviderStat
IconData _clientIcon(String clientName) {
final lower = clientName.toLowerCase();
- if (lower.contains('absorb')) return Icons.waves_rounded;
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;
@@ -464,22 +528,10 @@ class _StatsScreenState extends State<StatsScreen> with SingleTickerProviderStat
return Icons.devices_rounded;
}
- Color _clientColor(String clientName, ColorScheme cs) {
- final lower = clientName.toLowerCase();
- if (lower.contains('absorb')) return Colors.tealAccent;
- if (lower.contains('audiobookshelf') || lower.contains('abs')) return Colors.deepPurple;
- if (lower.contains('web') || lower.contains('browser')) return Colors.blue;
- if (lower.contains('ios') || lower.contains('apple')) return Colors.grey;
- if (lower.contains('android')) return Colors.green;
- return cs.onSurfaceVariant;
- }
-
- // ─── HELPERS ────────────────────────────────────────────────
+ // --- HELPERS ---
static double _safeNum(dynamic val) => val is num ? val.toDouble() : 0;
- /// Detects UUIDs and ABS prefixed IDs (li_, ep_, etc.) that the server
- /// sometimes stores as displayTitle/displayAuthor for admin accounts.
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,
@@ -494,10 +546,8 @@ class _StatsScreenState extends State<StatsScreen> with SingleTickerProviderStat
return {};
}
- double _todaySeconds(Map<String, dynamic> dailyMap) {
- final key = _dateKey(DateTime.now());
- return _daySeconds(dailyMap, key);
- }
+ double _todaySeconds(Map<String, dynamic> dailyMap) =>
+ _daySeconds(dailyMap, _dateKey(DateTime.now()));
double _weekSeconds(Map<String, dynamic> dailyMap) {
final now = DateTime.now();
@@ -530,11 +580,9 @@ class _StatsScreenState extends State<StatsScreen> with SingleTickerProviderStat
int _currentStreak(Map<String, dynamic> dailyMap) {
int streak = 0;
final now = DateTime.now();
- // Start from yesterday if today has no listening yet
int startOffset = _daySeconds(dailyMap, _dateKey(now)) > 0 ? 0 : 1;
for (int i = startOffset; i < 365; i++) {
- final key = _dateKey(now.subtract(Duration(days: i)));
- if (_daySeconds(dailyMap, key) > 0) {
+ if (_daySeconds(dailyMap, _dateKey(now.subtract(Duration(days: i)))) > 0) {
streak++;
} else {
break;
@@ -545,14 +593,10 @@ class _StatsScreenState extends State<StatsScreen> with SingleTickerProviderStat
int _longestStreak(Map<String, dynamic> dailyMap) {
int longest = 0, current = 0;
- // Sort days and iterate
final keys = dailyMap.keys.toList()..sort();
DateTime? lastDate;
for (final key in keys) {
- final val = _daySeconds(dailyMap, key);
- if (val <= 0) continue;
- final parts = key.split('-');
- if (parts.length != 3) continue;
+ if (_daySeconds(dailyMap, key) <= 0) continue;
final date = DateTime.tryParse(key);
if (date == null) continue;
if (lastDate != null && date.difference(lastDate).inDays == 1) {
@@ -566,22 +610,33 @@ class _StatsScreenState extends State<StatsScreen> with SingleTickerProviderStat
return longest;
}
- List<_DayData> _last7Days(Map<String, dynamic> dailyMap) {
+ int _activeDayCount(Map<String, dynamic> dailyMap) {
+ int count = 0;
+ for (final key in dailyMap.keys) {
+ if (_daySeconds(dailyMap, key) > 0) count++;
+ }
+ return count;
+ }
+
+ double _averageDailySeconds(Map<String, dynamic> dailyMap) {
+ // Average over the last 30 days
final now = DateTime.now();
- return List.generate(7, (i) {
- final date = now.subtract(Duration(days: 6 - i));
- return _DayData(
- label: _dayLabel(date),
- fullLabel: _dateKey(date),
- seconds: _daySeconds(dailyMap, _dateKey(date)),
- );
- });
+ double total = 0;
+ int daysWithData = 0;
+ for (int i = 0; i < 30; i++) {
+ final s = _daySeconds(dailyMap, _dateKey(now.subtract(Duration(days: i))));
+ if (s > 0) {
+ total += s;
+ daysWithData++;
+ }
+ }
+ return daysWithData > 0 ? total / daysWithData : 0;
}
- List<_DayData> _last30Days(Map<String, dynamic> dailyMap) {
+ List<_DayData> _last7Days(Map<String, dynamic> dailyMap) {
final now = DateTime.now();
- return List.generate(30, (i) {
- final date = now.subtract(Duration(days: 29 - i));
+ return List.generate(7, (i) {
+ final date = now.subtract(Duration(days: 6 - i));
return _DayData(
label: _dayLabel(date),
fullLabel: _dateKey(date),
@@ -626,3 +681,11 @@ class _DayData {
final double seconds;
const _DayData({required this.label, required this.fullLabel, required this.seconds});
}
+
+class _TopItem {
+ final String title;
+ final String author;
+ double totalSeconds;
+ int sessionCount;
+ _TopItem({required this.title, required this.author, required this.totalSeconds, required this.sessionCount});
+}
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index cb08572f..d565f678 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -14,6 +14,7 @@ import 'sleep_timer_service.dart';
import 'equalizer_service.dart';
import 'android_auto_service.dart';
import 'chromecast_service.dart';
+import 'scoped_prefs.dart';
// ─── Auto-rewind settings ───
@@ -31,21 +32,19 @@ class AutoRewindSettings {
});
static Future<AutoRewindSettings> load() async {
- final prefs = await SharedPreferences.getInstance();
return AutoRewindSettings(
- enabled: prefs.getBool('autoRewind_enabled') ?? true,
- minRewind: prefs.getDouble('autoRewind_min') ?? 1.0,
- maxRewind: prefs.getDouble('autoRewind_max') ?? 30.0,
- activationDelay: prefs.getDouble('autoRewind_delay') ?? 0.0,
+ enabled: await ScopedPrefs.getBool('autoRewind_enabled') ?? true,
+ minRewind: await ScopedPrefs.getDouble('autoRewind_min') ?? 1.0,
+ maxRewind: await ScopedPrefs.getDouble('autoRewind_max') ?? 30.0,
+ activationDelay: await ScopedPrefs.getDouble('autoRewind_delay') ?? 0.0,
);
}
Future<void> save() async {
- final prefs = await SharedPreferences.getInstance();
- await prefs.setBool('autoRewind_enabled', enabled);
- await prefs.setDouble('autoRewind_min', minRewind);
- await prefs.setDouble('autoRewind_max', maxRewind);
- await prefs.setDouble('autoRewind_delay', activationDelay);
+ await ScopedPrefs.setBool('autoRewind_enabled', enabled);
+ await ScopedPrefs.setDouble('autoRewind_min', minRewind);
+ await ScopedPrefs.setDouble('autoRewind_max', maxRewind);
+ await ScopedPrefs.setDouble('autoRewind_delay', activationDelay);
}
}
@@ -61,22 +60,29 @@ class PlayerSettings {
// ── Private helpers to eliminate boilerplate ──
static Future<T> _get<T>(String key, T defaultValue) async {
- final prefs = await SharedPreferences.getInstance();
- final value = prefs.get(key);
+ Object? value;
+ if (defaultValue is bool) {
+ value = await ScopedPrefs.getBool(key);
+ } else if (defaultValue is int) {
+ value = await ScopedPrefs.getInt(key);
+ } else if (defaultValue is double) {
+ value = await ScopedPrefs.getDouble(key);
+ } else if (defaultValue is String) {
+ value = await ScopedPrefs.getString(key);
+ }
if (value is T) return value;
return defaultValue;
}
static Future<void> _set<T>(String key, T value, {bool notify = false}) async {
- final prefs = await SharedPreferences.getInstance();
if (value is bool) {
- await prefs.setBool(key, value);
+ await ScopedPrefs.setBool(key, value);
} else if (value is int) {
- await prefs.setInt(key, value);
+ await ScopedPrefs.setInt(key, value);
} else if (value is double) {
- await prefs.setDouble(key, value);
+ await ScopedPrefs.setDouble(key, value);
} else if (value is String) {
- await prefs.setString(key, value);
+ await ScopedPrefs.setString(key, value);
}
if (notify) _notify();
}
@@ -111,11 +117,10 @@ class PlayerSettings {
/// One-time migration from the old boolean auto-play settings to queueMode.
static Future<void> migrateQueueMode() async {
- final prefs = await SharedPreferences.getInstance();
- if (prefs.containsKey('queueMode')) return;
- final autoBook = prefs.getBool('autoPlayNextBook') ?? false;
- final autoPod = prefs.getBool('autoPlayNextPodcast') ?? false;
- await prefs.setString('queueMode', (autoBook || autoPod) ? 'auto_next' : 'off');
+ if (await ScopedPrefs.containsKey('queueMode')) return;
+ final autoBook = await ScopedPrefs.getBool('autoPlayNextBook') ?? false;
+ final autoPod = await ScopedPrefs.getBool('autoPlayNextPodcast') ?? false;
+ await ScopedPrefs.setString('queueMode', (autoBook || autoPod) ? 'auto_next' : 'off');
}
// Legacy getters kept for backup service compatibility
@@ -182,8 +187,14 @@ class PlayerSettings {
static Future<bool> getShowGoodreadsButton() => _get('showGoodreadsButton', false);
static Future<void> setShowGoodreadsButton(bool value) => _set('showGoodreadsButton', value);
- static Future<bool> getLoggingEnabled() => _get('loggingEnabled', false);
- static Future<void> setLoggingEnabled(bool value) => _set('loggingEnabled', value);
+ static Future<bool> getLoggingEnabled() async {
+ final prefs = await SharedPreferences.getInstance();
+ return prefs.getBool('loggingEnabled') ?? false;
+ }
+ static Future<void> setLoggingEnabled(bool value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool('loggingEnabled', value);
+ }
static Future<bool> getFullScreenPlayer() => _get('fullScreenPlayer', false);
static Future<void> setFullScreenPlayer(bool value) => _set('fullScreenPlayer', value);
@@ -193,15 +204,13 @@ class PlayerSettings {
static const defaultButtonOrder = ['chapters', 'speed', 'sleep', 'bookmarks', 'details', 'equalizer', 'cast', 'history', 'remove'];
static Future<List<String>> getCardButtonOrder() async {
- final prefs = await SharedPreferences.getInstance();
- final stored = prefs.getStringList('card_button_order');
- if (stored != null && stored.length == defaultButtonOrder.length) return stored;
+ final stored = await ScopedPrefs.getStringList('card_button_order');
+ if (stored.isNotEmpty && stored.length == defaultButtonOrder.length) return stored;
return List.from(defaultButtonOrder);
}
static Future<void> setCardButtonOrder(List<String> order) async {
- final prefs = await SharedPreferences.getInstance();
- await prefs.setStringList('card_button_order', order);
+ await ScopedPrefs.setStringList('card_button_order', order);
_notify();
}
@@ -231,10 +240,8 @@ class PlayerSettings {
// ── Per-book speed persistence ──
- static Future<double?> getBookSpeed(String itemId) async {
- final prefs = await SharedPreferences.getInstance();
- return prefs.getDouble('bookSpeed_$itemId');
- }
+ static Future<double?> getBookSpeed(String itemId) =>
+ ScopedPrefs.getDouble('bookSpeed_$itemId');
static Future<void> setBookSpeed(String itemId, double speed) =>
_set('bookSpeed_$itemId', speed);
diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart
index fcf7053c..33683663 100644
--- a/lib/services/backup_service.dart
+++ b/lib/services/backup_service.dart
@@ -13,7 +13,7 @@ class BackupService {
final prefs = await SharedPreferences.getInstance();
final pkgInfo = await PackageInfo.fromPlatform();
- // PlayerSettings
+ // PlayerSettings (all scoped per-user now)
final settings = <String, dynamic>{
'defaultSpeed': await PlayerSettings.getDefaultSpeed(),
'wifiOnlyDownloads': await PlayerSettings.getWifiOnlyDownloads(),
@@ -48,7 +48,7 @@ class BackupService {
'maxConcurrentDownloads': await PlayerSettings.getMaxConcurrentDownloads(),
};
- // AutoRewind
+ // AutoRewind (scoped)
final rewind = await AutoRewindSettings.load();
final autoRewind = <String, dynamic>{
'enabled': rewind.enabled,
@@ -57,7 +57,7 @@ class BackupService {
'delay': rewind.activationDelay,
};
- // AutoSleep
+ // AutoSleep (scoped)
final sleep = await AutoSleepSettings.load();
final autoSleep = <String, dynamic>{
'enabled': sleep.enabled,
@@ -68,32 +68,33 @@ class BackupService {
'durationMinutes': sleep.durationMinutes,
};
- // Equalizer
+ // Equalizer (scoped)
final equalizer = <String, dynamic>{
- 'enabled': prefs.getBool('eq_enabled') ?? false,
- 'preset': prefs.getString('eq_preset') ?? 'flat',
- 'bassBoost': prefs.getDouble('eq_bassBoost') ?? 0.0,
- 'virtualizer': prefs.getDouble('eq_virtualizer') ?? 0.0,
- 'loudnessGain': prefs.getDouble('eq_loudnessGain') ?? 0.0,
- 'bands': prefs.getString('eq_bands'),
+ 'enabled': await ScopedPrefs.getBool('eq_enabled') ?? false,
+ 'preset': await ScopedPrefs.getString('eq_preset') ?? 'flat',
+ 'bassBoost': await ScopedPrefs.getDouble('eq_bassBoost') ?? 0.0,
+ 'virtualizer': await ScopedPrefs.getDouble('eq_virtualizer') ?? 0.0,
+ 'loudnessGain': await ScopedPrefs.getDouble('eq_loudnessGain') ?? 0.0,
+ 'bands': await ScopedPrefs.getString('eq_bands'),
};
- // Per-book speeds
+ // Per-book speeds (scoped - scan scoped keys)
final bookSpeeds = <String, double>{};
+ final scope = UserAccountService().activeScopeKey;
+ final speedPrefix = scope.isNotEmpty ? '$scope:bookSpeed_' : 'bookSpeed_';
for (final key in prefs.getKeys()) {
- if (key.startsWith('bookSpeed_')) {
- final itemId = key.substring('bookSpeed_'.length);
+ if (key.startsWith(speedPrefix)) {
+ final itemId = key.substring(speedPrefix.length);
final speed = prefs.getDouble(key);
if (speed != null) bookSpeeds[itemId] = speed;
}
}
- // Offline mode
+ // Offline mode (global)
final offlineMode = prefs.getBool('manual_offline_mode') ?? false;
- // Bookmarks for current account (always included — not sensitive)
+ // Bookmarks for current account (scoped)
final bookmarks = <String, List<String>>{};
- final scope = UserAccountService().activeScopeKey;
final bmPrefix = scope.isNotEmpty ? '$scope:bookmarks_' : 'bookmarks_';
for (final key in prefs.getKeys()) {
if (key.startsWith(bmPrefix)) {
@@ -103,10 +104,13 @@ class BackupService {
}
}
- // Rolling download series (per-account, like bookmarks)
+ // Saved ebooks (scoped)
+ final savedEbooks = await ScopedPrefs.getStringList('saved_ebooks');
+
+ // Rolling download series (scoped)
final rollingDownloadSeries = await ScopedPrefs.getStringList('rolling_download_series');
- // Accounts & custom headers (optional — contain auth data)
+ // Accounts & custom headers (optional - contain auth data)
List<Map<String, dynamic>>? accounts;
Map<String, String>? customHeaders;
if (includeAccounts) {
@@ -123,7 +127,7 @@ class BackupService {
}
return {
- 'version': 1,
+ 'version': 2,
'createdAt': DateTime.now().toIso8601String(),
'appVersion': pkgInfo.version,
'settings': settings,
@@ -133,6 +137,7 @@ class BackupService {
'bookSpeeds': bookSpeeds,
'offlineMode': offlineMode,
'bookmarks': bookmarks,
+ 'savedEbooks': savedEbooks,
'rollingDownloadSeries': rollingDownloadSeries,
'accounts': accounts,
'customHeaders': customHeaders,
@@ -142,14 +147,14 @@ class BackupService {
static Future<void> importSettings(Map<String, dynamic> data) async {
final prefs = await SharedPreferences.getInstance();
- // PlayerSettings
+ // PlayerSettings (all go through scoped setters now)
final s = data['settings'] as Map<String, dynamic>? ?? {};
if (s['defaultSpeed'] != null) PlayerSettings.setDefaultSpeed((s['defaultSpeed'] as num).toDouble());
if (s['wifiOnlyDownloads'] != null) PlayerSettings.setWifiOnlyDownloads(s['wifiOnlyDownloads'] as bool);
if (s['queueMode'] != null) {
PlayerSettings.setQueueMode(s['queueMode'] as String);
} else {
- // Legacy backup — migrate the old booleans
+ // Legacy backup - migrate the old booleans
final autoBook = s['autoPlayNextBook'] as bool? ?? false;
final autoPod = s['autoPlayNextPodcast'] as bool? ?? false;
PlayerSettings.setQueueMode((autoBook || autoPod) ? 'auto_next' : 'off');
@@ -184,7 +189,7 @@ class BackupService {
if (s['mergeAbsorbingLibraries'] != null) PlayerSettings.setMergeAbsorbingLibraries(s['mergeAbsorbingLibraries'] as bool);
if (s['maxConcurrentDownloads'] != null) PlayerSettings.setMaxConcurrentDownloads(s['maxConcurrentDownloads'] as int);
- // AutoRewind
+ // AutoRewind (scoped via save())
final r = data['autoRewind'] as Map<String, dynamic>?;
if (r != null) {
await AutoRewindSettings(
@@ -195,7 +200,7 @@ class BackupService {
).save();
}
- // AutoSleep
+ // AutoSleep (scoped via save())
final sl = data['autoSleep'] as Map<String, dynamic>?;
if (sl != null) {
await AutoSleepSettings(
@@ -208,20 +213,20 @@ class BackupService {
).save();
}
- // Equalizer
+ // Equalizer (scoped)
final eq = data['equalizer'] as Map<String, dynamic>?;
if (eq != null) {
- await prefs.setBool('eq_enabled', eq['enabled'] as bool? ?? false);
- await prefs.setString('eq_preset', eq['preset'] as String? ?? 'flat');
- await prefs.setDouble('eq_bassBoost', (eq['bassBoost'] as num?)?.toDouble() ?? 0.0);
- await prefs.setDouble('eq_virtualizer', (eq['virtualizer'] as num?)?.toDouble() ?? 0.0);
- await prefs.setDouble('eq_loudnessGain', (eq['loudnessGain'] as num?)?.toDouble() ?? 0.0);
+ await ScopedPrefs.setBool('eq_enabled', eq['enabled'] as bool? ?? false);
+ await ScopedPrefs.setString('eq_preset', eq['preset'] as String? ?? 'flat');
+ await ScopedPrefs.setDouble('eq_bassBoost', (eq['bassBoost'] as num?)?.toDouble() ?? 0.0);
+ await ScopedPrefs.setDouble('eq_virtualizer', (eq['virtualizer'] as num?)?.toDouble() ?? 0.0);
+ await ScopedPrefs.setDouble('eq_loudnessGain', (eq['loudnessGain'] as num?)?.toDouble() ?? 0.0);
if (eq['bands'] != null) {
- await prefs.setString('eq_bands', eq['bands'] as String);
+ await ScopedPrefs.setString('eq_bands', eq['bands'] as String);
}
}
- // Per-book speeds
+ // Per-book speeds (scoped)
final bookSpeeds = data['bookSpeeds'] as Map<String, dynamic>?;
if (bookSpeeds != null) {
for (final entry in bookSpeeds.entries) {
@@ -229,12 +234,12 @@ class BackupService {
}
}
- // Offline mode
+ // Offline mode (global)
if (data['offlineMode'] != null) {
await prefs.setBool('manual_offline_mode', data['offlineMode'] as bool);
}
- // Bookmarks (import into current account scope)
+ // Bookmarks (scoped)
final bookmarks = data['bookmarks'] as Map<String, dynamic>?;
if (bookmarks != null) {
for (final entry in bookmarks.entries) {
@@ -243,7 +248,13 @@ class BackupService {
}
}
- // Rolling download series (per-account)
+ // Saved ebooks (scoped)
+ final savedEbooks = data['savedEbooks'] as List<dynamic>?;
+ if (savedEbooks != null && savedEbooks.isNotEmpty) {
+ await ScopedPrefs.setStringList('saved_ebooks', savedEbooks.cast<String>());
+ }
+
+ // Rolling download series (scoped)
final rollingDownloadSeries = data['rollingDownloadSeries'] as List<dynamic>?;
if (rollingDownloadSeries != null && rollingDownloadSeries.isNotEmpty) {
await ScopedPrefs.setStringList(
diff --git a/lib/services/download_service.dart b/lib/services/download_service.dart
index 4ee30436..f9c04d84 100644
--- a/lib/services/download_service.dart
+++ b/lib/services/download_service.dart
@@ -250,6 +250,16 @@ class DownloadService extends ChangeNotifier {
.where((d) => d.status == DownloadStatus.downloaded)
.toList();
+ /// Get actively downloading items (in progress right now).
+ List<DownloadInfo> get activeDownloads =>
+ _downloads.values
+ .where((d) => d.status == DownloadStatus.downloading && _activeDownloadIds.contains(d.itemId))
+ .toList();
+
+ /// Get queued items (waiting for a download slot).
+ List<DownloadInfo> get queuedDownloads =>
+ _queue.map((q) => _downloads[q.itemId]).whereType<DownloadInfo>().toList();
+
Future<void> init() async {
final prefs = await SharedPreferences.getInstance();
_customDownloadPath = prefs.getString('custom_download_path');
diff --git a/lib/services/equalizer_service.dart b/lib/services/equalizer_service.dart
index 210ee695..50d22499 100644
--- a/lib/services/equalizer_service.dart
+++ b/lib/services/equalizer_service.dart
@@ -1,7 +1,7 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
-import 'package:shared_preferences/shared_preferences.dart';
+import 'scoped_prefs.dart';
/// Android AudioEffect equalizer bands and presets via platform channels.
/// Falls back gracefully on unsupported devices.
@@ -225,14 +225,13 @@ class EqualizerService extends ChangeNotifier {
// ── Persistence ──
Future<void> _loadSettings() async {
- final prefs = await SharedPreferences.getInstance();
- _enabled = prefs.getBool('eq_enabled') ?? false;
- _activePreset = prefs.getString('eq_preset') ?? 'flat';
- _bassBoost = prefs.getDouble('eq_bassBoost') ?? 0.0;
- _virtualizer = prefs.getDouble('eq_virtualizer') ?? 0.0;
- _loudnessGain = prefs.getDouble('eq_loudnessGain') ?? 0.0;
+ _enabled = await ScopedPrefs.getBool('eq_enabled') ?? false;
+ _activePreset = await ScopedPrefs.getString('eq_preset') ?? 'flat';
+ _bassBoost = await ScopedPrefs.getDouble('eq_bassBoost') ?? 0.0;
+ _virtualizer = await ScopedPrefs.getDouble('eq_virtualizer') ?? 0.0;
+ _loudnessGain = await ScopedPrefs.getDouble('eq_loudnessGain') ?? 0.0;
- final bandStr = prefs.getString('eq_bands');
+ final bandStr = await ScopedPrefs.getString('eq_bands');
if (bandStr != null) {
_bandLevels = bandStr.split(',')
.map((s) => double.tryParse(s) ?? 0.0)
@@ -241,13 +240,12 @@ class EqualizerService extends ChangeNotifier {
}
Future<void> _saveSettings() async {
- final prefs = await SharedPreferences.getInstance();
- await prefs.setBool('eq_enabled', _enabled);
- await prefs.setString('eq_preset', _activePreset);
- await prefs.setDouble('eq_bassBoost', _bassBoost);
- await prefs.setDouble('eq_virtualizer', _virtualizer);
- await prefs.setDouble('eq_loudnessGain', _loudnessGain);
- await prefs.setString('eq_bands', _bandLevels.map((l) => l.toStringAsFixed(1)).join(','));
+ await ScopedPrefs.setBool('eq_enabled', _enabled);
+ await ScopedPrefs.setString('eq_preset', _activePreset);
+ await ScopedPrefs.setDouble('eq_bassBoost', _bassBoost);
+ await ScopedPrefs.setDouble('eq_virtualizer', _virtualizer);
+ await ScopedPrefs.setDouble('eq_loudnessGain', _loudnessGain);
+ await ScopedPrefs.setString('eq_bands', _bandLevels.map((l) => l.toStringAsFixed(1)).join(','));
}
/// Formatted frequency label.
diff --git a/lib/services/playback_history_service.dart b/lib/services/playback_history_service.dart
index 4ef33047..69c7fc9f 100644
--- a/lib/services/playback_history_service.dart
+++ b/lib/services/playback_history_service.dart
@@ -1,6 +1,6 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
-import 'package:shared_preferences/shared_preferences.dart';
+import 'scoped_prefs.dart';
/// Types of playback events we track.
enum PlaybackEventType {
@@ -124,9 +124,8 @@ class PlaybackHistoryService {
detail: detail,
);
- final prefs = await SharedPreferences.getInstance();
final key = 'playback_history_$itemId';
- final existing = prefs.getStringList(key) ?? [];
+ final existing = await ScopedPrefs.getStringList(key);
existing.add(jsonEncode(event.toJson()));
@@ -135,14 +134,13 @@ class PlaybackHistoryService {
existing.removeRange(0, existing.length - _maxEventsPerBook);
}
- await prefs.setStringList(key, existing);
+ await ScopedPrefs.setStringList(key, existing);
}
/// Get all events for a book, newest first.
Future<List<PlaybackEvent>> getHistory(String itemId) async {
- final prefs = await SharedPreferences.getInstance();
final key = 'playback_history_$itemId';
- final stored = prefs.getStringList(key) ?? [];
+ final stored = await ScopedPrefs.getStringList(key);
final events = <PlaybackEvent>[];
for (final json in stored) {
@@ -158,7 +156,6 @@ class PlaybackHistoryService {
/// Clear history for a book.
Future<void> clearHistory(String itemId) async {
- final prefs = await SharedPreferences.getInstance();
- await prefs.remove('playback_history_$itemId');
+ await ScopedPrefs.remove('playback_history_$itemId');
}
}
diff --git a/lib/services/sleep_timer_service.dart b/lib/services/sleep_timer_service.dart
index ad1eda03..21523738 100644
--- a/lib/services/sleep_timer_service.dart
+++ b/lib/services/sleep_timer_service.dart
@@ -3,7 +3,7 @@ import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:sensors_plus/sensors_plus.dart';
-import 'package:shared_preferences/shared_preferences.dart';
+import 'scoped_prefs.dart';
import 'audio_player_service.dart';
import 'chromecast_service.dart';
@@ -53,25 +53,23 @@ class AutoSleepSettings {
}
static Future<AutoSleepSettings> load() async {
- final prefs = await SharedPreferences.getInstance();
return AutoSleepSettings(
- enabled: prefs.getBool('autoSleep_enabled') ?? false,
- startHour: prefs.getInt('autoSleep_startHour') ?? 22,
- startMinute: prefs.getInt('autoSleep_startMinute') ?? 0,
- endHour: prefs.getInt('autoSleep_endHour') ?? 6,
- endMinute: prefs.getInt('autoSleep_endMinute') ?? 0,
- durationMinutes: prefs.getInt('autoSleep_duration') ?? 30,
+ enabled: await ScopedPrefs.getBool('autoSleep_enabled') ?? false,
+ startHour: await ScopedPrefs.getInt('autoSleep_startHour') ?? 22,
+ startMinute: await ScopedPrefs.getInt('autoSleep_startMinute') ?? 0,
+ endHour: await ScopedPrefs.getInt('autoSleep_endHour') ?? 6,
+ endMinute: await ScopedPrefs.getInt('autoSleep_endMinute') ?? 0,
+ durationMinutes: await ScopedPrefs.getInt('autoSleep_duration') ?? 30,
);
}
Future<void> save() async {
- final prefs = await SharedPreferences.getInstance();
- await prefs.setBool('autoSleep_enabled', enabled);
- await prefs.setInt('autoSleep_startHour', startHour);
- await prefs.setInt('autoSleep_startMinute', startMinute);
- await prefs.setInt('autoSleep_endHour', endHour);
- await prefs.setInt('autoSleep_endMinute', endMinute);
- await prefs.setInt('autoSleep_duration', durationMinutes);
+ await ScopedPrefs.setBool('autoSleep_enabled', enabled);
+ await ScopedPrefs.setInt('autoSleep_startHour', startHour);
+ await ScopedPrefs.setInt('autoSleep_startMinute', startMinute);
+ await ScopedPrefs.setInt('autoSleep_endHour', endHour);
+ await ScopedPrefs.setInt('autoSleep_endMinute', endMinute);
+ await ScopedPrefs.setInt('autoSleep_duration', durationMinutes);
}
}
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index 8a30fe8c..5eaade29 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -8,7 +8,6 @@ import 'package:cached_network_image/cached_network_image.dart';
import 'package:path_provider/path_provider.dart';
import 'package:file_picker/file_picker.dart';
import 'package:http/http.dart' as http;
-import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
@@ -18,6 +17,7 @@ import '../services/api_service.dart';
import '../services/download_service.dart';
import '../services/progress_sync_service.dart';
import '../services/metadata_override_service.dart';
+import '../services/scoped_prefs.dart';
import '../screens/app_shell.dart';
import 'series_books_sheet.dart';
import 'absorbing_shared.dart';
@@ -58,8 +58,8 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
super.initState();
_loadItem();
PlayerSettings.getShowGoodreadsButton().then((v) { if (mounted) setState(() => _showGoodreads = v); });
- SharedPreferences.getInstance().then((p) {
- if (mounted && (p.getStringList('saved_ebooks') ?? []).contains(widget.itemId)) {
+ ScopedPrefs.getStringList('saved_ebooks').then((list) {
+ if (mounted && list.contains(widget.itemId)) {
setState(() => _ebookSaved = true);
}
});
@@ -655,11 +655,10 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
if (savedPath == null) return; // user cancelled
// Track that this ebook has been saved
- final prefs = await SharedPreferences.getInstance();
- final saved = prefs.getStringList('saved_ebooks') ?? [];
+ final saved = await ScopedPrefs.getStringList('saved_ebooks');
if (!saved.contains(widget.itemId)) {
saved.add(widget.itemId);
- await prefs.setStringList('saved_ebooks', saved);
+ await ScopedPrefs.setStringList('saved_ebooks', saved);
}
if (mounted) setState(() => _ebookSaved = true);
diff --git a/pubspec.yaml b/pubspec.yaml
index f636172a..3733e3cf 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,7 +1,7 @@
name: absorb
description: A Material 3 Audiobookshelf client for Android.
publish_to: 'none'
-version: 1.8.4+35
+version: 1.8.5+35
environment:
sdk: '>=3.1.0 <4.0.0'