Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Fix cover color source not loading on startup, add missing backup settings

Nathan Poulsona948e0e7c1e2
diff --git a/lib/main.dart b/lib/main.dart
index 03b4064d..f8f14dc8 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -37,6 +37,13 @@ final ValueNotifier<bool> oledNotifier = ValueNotifier(false);
/// Whether to disable the fade animation when switching bottom nav tabs.
final ValueNotifier<bool> snappyTransitionsNotifier = ValueNotifier(false);
+/// Color source: 'wallpaper' (system dynamic) or 'cover' (playing book art).
+final ValueNotifier<String> colorSourceNotifier = ValueNotifier('wallpaper');
+
+/// Cover-art-derived ColorScheme for the currently playing item.
+/// null when nothing is playing or cover hasn't loaded yet.
+final ValueNotifier<ColorScheme?> coverSchemeNotifier = ValueNotifier(null);
+
/// Global key so non-widget code (e.g. providers) can show snackbars.
final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =
GlobalKey<ScaffoldMessengerState>();
@@ -78,6 +85,7 @@ void main() async {
final savedTheme = await PlayerSettings.getThemeMode();
applyThemeMode(savedTheme);
snappyTransitionsNotifier.value = await PlayerSettings.getSnappyTransitions();
+ colorSourceNotifier.value = await PlayerSettings.getColorSource();
} catch (_) {}
// Capture Flutter framework errors (widget build failures, etc.)
@@ -122,6 +130,12 @@ class AbsorbApp extends StatelessWidget {
return ValueListenableBuilder<bool>(
valueListenable: oledNotifier,
builder: (context, isOled, _) {
+ return ValueListenableBuilder<String>(
+ valueListenable: colorSourceNotifier,
+ builder: (context, colorSource, _) {
+ return ValueListenableBuilder<ColorScheme?>(
+ valueListenable: coverSchemeNotifier,
+ builder: (context, coverScheme, _) {
// Set system chrome to match active theme
final isDark = currentMode == ThemeMode.dark ||
(currentMode == ThemeMode.system &&
@@ -134,11 +148,18 @@ class AbsorbApp extends StatelessWidget {
systemNavigationBarIconBrightness: isDark ? Brightness.light : Brightness.dark,
));
+ final useCover = colorSource == 'cover' && coverScheme != null;
+
return DynamicColorBuilder(
builder: (ColorScheme? lightDynamic, ColorScheme? darkDynamic) {
// Absorb is dark-first — use dynamic dark colors or our custom palette
ColorScheme darkScheme;
- if (darkDynamic != null) {
+ if (useCover) {
+ darkScheme = ColorScheme.fromSeed(
+ seedColor: coverScheme.primary,
+ brightness: Brightness.dark,
+ );
+ } else if (darkDynamic != null) {
darkScheme = darkDynamic.harmonized();
} else {
darkScheme = ColorScheme.fromSeed(
@@ -161,7 +182,12 @@ class AbsorbApp extends StatelessWidget {
// Light scheme for users who prefer it
ColorScheme lightScheme;
- if (lightDynamic != null) {
+ if (useCover) {
+ lightScheme = ColorScheme.fromSeed(
+ seedColor: coverScheme.primary,
+ brightness: Brightness.light,
+ );
+ } else if (lightDynamic != null) {
lightScheme = lightDynamic.harmonized();
} else {
lightScheme = ColorScheme.fromSeed(
@@ -296,6 +322,10 @@ class AbsorbApp extends StatelessWidget {
);
},
);
+ },
+ );
+ },
+ );
},
);
}
@@ -335,6 +365,11 @@ class _AuthGateState extends State<AuthGate> {
// keys (before scope was active) to the current user's scoped keys.
await ScopedPrefs.migrateToScope();
+ // Reload settings that were read in main() before scope was active
+ applyThemeMode(await PlayerSettings.getThemeMode());
+ snappyTransitionsNotifier.value = await PlayerSettings.getSnappyTransitions();
+ colorSourceNotifier.value = await PlayerSettings.getColorSource();
+
// Start auth restoration immediately — it doesn't depend on audio/cast/
// download services and must not be blocked by a hanging service init.
if (mounted) {
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 26fad93a..71e217f3 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -447,6 +447,7 @@ class LibraryProvider extends ChangeNotifier {
AudioPlayerService.setOnPlayStartedCallback((key) {
_checkRollingDownloads(key);
_checkQueueAutoDownloads(key);
+ _checkAutoDownloadOnStream(key);
});
AudioPlayerService.setOnPlaybackStateChangedCallback((playing) {
if (playing) {
@@ -2322,6 +2323,32 @@ class LibraryProvider extends ChangeNotifier {
_checkQueueAutoDownloads(key);
}
+ /// Auto-download the currently streaming item if on WiFi.
+ void _checkAutoDownloadOnStream(String playingKey) async {
+ if (_api == null || isOffline) return;
+ final enabled = await PlayerSettings.getAutoDownloadOnStream();
+ if (!enabled) return;
+
+ final connectivity = await Connectivity().checkConnectivity();
+ if (!connectivity.contains(ConnectivityResult.wifi)) return;
+
+ final dl = DownloadService();
+ if (dl.isDownloaded(playingKey) || dl.isDownloading(playingKey)) return;
+
+ final player = AudioPlayerService();
+ final itemId = player.currentItemId;
+ if (itemId == null) return;
+
+ dl.downloadItem(
+ api: _api!,
+ itemId: itemId,
+ title: player.currentTitle ?? '',
+ author: player.currentAuthor ?? '',
+ coverUrl: player.currentCoverUrl,
+ episodeId: player.currentEpisodeId,
+ );
+ }
+
/// Download the next [count]-1 books in the same series as [bookId].
Future<void> _rollingDownloadBook(String bookId, int count) async {
// Try local cache first, then fetch from server if series info is missing
diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dart
index f7a05bec..c584b497 100644
--- a/lib/screens/absorbing_screen.dart
+++ b/lib/screens/absorbing_screen.dart
@@ -8,6 +8,7 @@ import '../services/chromecast_service.dart';
import '../services/download_service.dart';
import '../services/scoped_prefs.dart';
import '../widgets/absorb_page_header.dart';
+import '../main.dart' show oledNotifier;
import '../widgets/absorbing_card.dart';
class AbsorbingScreen extends StatefulWidget {
@@ -413,6 +414,8 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
_loadMergeLibraries(); // refresh in case setting changed
final cs = Theme.of(context).colorScheme;
final tt = Theme.of(context).textTheme;
+ final scaffoldBg = Theme.of(context).scaffoldBackgroundColor;
+ final lowerFade = Color.lerp(cs.surface, scaffoldBg, 0.55) ?? scaffoldBg;
final lib = context.watch<LibraryProvider>();
final dl = DownloadService();
var books = _getAbsorbingBooks(lib);
@@ -449,8 +452,22 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
final subtleBorder = cs.onSurface.withValues(alpha: 0.08);
return Scaffold(
- backgroundColor: Theme.of(context).scaffoldBackgroundColor,
- body: SafeArea(
+ backgroundColor: scaffoldBg,
+ body: Container(
+ decoration: oledNotifier.value ? null : BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ stops: const [0.0, 0.22, 0.72, 1.0],
+ colors: [
+ cs.primary.withValues(alpha: 0.06),
+ cs.surface,
+ lowerFade,
+ scaffoldBg,
+ ],
+ ),
+ ),
+ child: SafeArea(
child: Column(
children: [
// ── Header ──
@@ -669,6 +686,7 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {
],
),
),
+ ),
);
}
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
index bda82cb0..040a86bf 100644
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@ -7,7 +7,9 @@ import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
import '../services/chromecast_service.dart';
import '../services/sleep_timer_service.dart';
-import '../main.dart' show snappyTransitionsNotifier;
+import 'dart:io';
+import 'package:cached_network_image/cached_network_image.dart';
+import '../main.dart' show snappyTransitionsNotifier, colorSourceNotifier, coverSchemeNotifier;
import '../services/android_auto_service.dart';
import '../widgets/expanded_card.dart';
import 'absorbing_screen.dart';
@@ -53,6 +55,7 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
bool _expandedIsOpen = false;
bool _wasCasting = false;
DateTime? _lastBackPress;
+ String? _lastCoverItemId; // tracks which item's cover we derived the scheme from
// Lazily build tabs so startup on Absorbing does not initialize Home/Library
// work until the user actually visits those tabs.
@@ -131,6 +134,10 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
_player.addListener(_onPlayerChanged);
_wasCasting = _cast.isCasting;
_cast.addListener(_onCastChanged);
+ colorSourceNotifier.addListener(_onColorSourceChanged);
+ // Try immediately; _onLibraryChanged picks it up once data loads.
+ _deriveCoverScheme();
+ context.read<LibraryProvider>().addListener(_onLibraryChanged);
}
@override
@@ -138,11 +145,73 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
_fadeController.dispose();
_player.removeListener(_onPlayerChanged);
_cast.removeListener(_onCastChanged);
+ colorSourceNotifier.removeListener(_onColorSourceChanged);
+ try { context.read<LibraryProvider>().removeListener(_onLibraryChanged); } catch (_) {}
if (_instance == this) _instance = null;
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
+ void _onColorSourceChanged() {
+ if (colorSourceNotifier.value == 'cover') {
+ _lastCoverItemId = null; // force re-derive
+ _deriveCoverScheme();
+ } else {
+ coverSchemeNotifier.value = null;
+ }
+ }
+
+ void _onLibraryChanged() {
+ // Once absorbing list loads, derive cover scheme if we haven't yet
+ if (colorSourceNotifier.value == 'cover' && coverSchemeNotifier.value == null) {
+ _deriveCoverScheme();
+ }
+ }
+
+ /// Attempt to derive cover scheme. Returns true if successful.
+ bool _deriveCoverScheme() {
+ if (colorSourceNotifier.value != 'cover') return false;
+ // Use player's current item, or fall back to absorbing list's first item
+ var itemId = _player.currentItemId;
+ if (itemId == null) {
+ final lib = context.read<LibraryProvider>();
+ final ids = lib.absorbingBookIds;
+ if (ids.isNotEmpty) {
+ final key = ids.first;
+ // Composite keys are "itemId-episodeId"; extract the item ID
+ itemId = key.length > 36 ? key.substring(0, 36) : key;
+ }
+ }
+ if (itemId == null) {
+ return false;
+ }
+ if (itemId == _lastCoverItemId && coverSchemeNotifier.value != null) return true;
+
+ final lib = context.read<LibraryProvider>();
+ final coverUrl = lib.getCoverUrl(itemId, width: 400);
+ if (coverUrl == null) {
+ return false;
+ }
+ _lastCoverItemId = itemId;
+
+ final ImageProvider provider;
+ if (coverUrl.startsWith('/')) {
+ provider = FileImage(File(coverUrl));
+ } else {
+ provider = CachedNetworkImageProvider(coverUrl, headers: lib.mediaHeaders);
+ }
+
+ final brightness = Theme.of(context).brightness;
+ ColorScheme.fromImageProvider(provider: provider, brightness: brightness)
+ .then((scheme) {
+ coverSchemeNotifier.value = scheme;
+ }).catchError((_) {
+ // Image load failed - allow retry
+ _lastCoverItemId = null;
+ });
+ return true; // cover URL found, image load in progress
+ }
+
void _onPlayerChanged() {
final hasBook = _player.hasBook;
final playing = _player.isPlaying;
@@ -157,6 +226,8 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
_wasPlaying = playing;
_lastItemId = itemId;
+ if (itemChanged || newBook) _deriveCoverScheme();
+
if ((newBook || playStarted || itemChanged) && !_expandedIsOpen) {
_maybeAutoExpand();
}
diff --git a/lib/screens/bookmarks_screen.dart b/lib/screens/bookmarks_screen.dart
index 0e51f797..608cc368 100644
--- a/lib/screens/bookmarks_screen.dart
+++ b/lib/screens/bookmarks_screen.dart
@@ -21,17 +21,23 @@ class _BookmarksScreenState extends State<BookmarksScreen> {
bool _loading = true;
Map<String, List<Bookmark>> _allBookmarks = {};
bool _selecting = false;
+ String _sort = 'newest';
// Selected bookmarks as "itemId::bookmarkId" keys
final Set<String> _selected = {};
@override
void initState() {
super.initState();
+ _loadSort();
+ }
+
+ Future<void> _loadSort() async {
+ _sort = await PlayerSettings.getBookmarkSort();
_load();
}
Future<void> _load() async {
- final all = await BookmarkService().getAllBookmarks();
+ final all = await BookmarkService().getAllBookmarks(sort: _sort);
if (mounted) setState(() { _allBookmarks = all; _loading = false; });
}
@@ -248,12 +254,23 @@ class _BookmarksScreenState extends State<BookmarksScreen> {
onPressed: _exitSelection,
)
else ...[
- if (_allBookmarks.isNotEmpty)
+ if (_allBookmarks.isNotEmpty) ...[
+ IconButton(
+ icon: Icon(_sort == 'newest' ? Icons.schedule_rounded : Icons.sort_rounded, color: cs.onSurfaceVariant),
+ tooltip: _sort == 'newest' ? 'Sorted by newest' : 'Sorted by position',
+ onPressed: () {
+ final next = _sort == 'newest' ? 'position' : 'newest';
+ setState(() => _sort = next);
+ PlayerSettings.setBookmarkSort(next);
+ _load();
+ },
+ ),
IconButton(
icon: Icon(Icons.checklist_rounded, color: cs.onSurfaceVariant),
tooltip: 'Select',
onPressed: () => setState(() => _selecting = true),
),
+ ],
IconButton(
icon: Icon(Icons.close_rounded, color: cs.onSurfaceVariant),
onPressed: () => Navigator.pop(context),
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dart
index 475a5bff..dde13e49 100644
--- a/lib/screens/library_screen.dart
+++ b/lib/screens/library_screen.dart
@@ -11,6 +11,7 @@ import '../services/audio_player_service.dart';
import '../widgets/absorb_page_header.dart';
import '../widgets/library_grid_tiles.dart';
import '../widgets/library_search_results.dart';
+import '../main.dart' show oledNotifier;
import '../widgets/library_sort_filter_sheet.dart';
// ─── Sort modes ──────────────────────────────────────────────
@@ -909,6 +910,8 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
final tt = Theme.of(context).textTheme;
+ final scaffoldBg = Theme.of(context).scaffoldBackgroundColor;
+ final lowerFade = Color.lerp(cs.surface, scaffoldBg, 0.55) ?? scaffoldBg;
final lib = context.watch<LibraryProvider>();
final allLibraries = lib.libraries;
final hasMultipleLibraries = allLibraries.length > 1;
@@ -916,7 +919,22 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
final hasTabs = _tabController != null && !_isInSearchMode;
return Scaffold(
- body: SafeArea(
+ backgroundColor: scaffoldBg,
+ body: Container(
+ decoration: oledNotifier.value ? null : BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ stops: const [0.0, 0.22, 0.72, 1.0],
+ colors: [
+ cs.primary.withValues(alpha: 0.06),
+ cs.surface,
+ lowerFade,
+ scaffoldBg,
+ ],
+ ),
+ ),
+ child: SafeArea(
child: Column(
children: [
AbsorbPageHeader(
@@ -974,6 +992,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
],
onChanged: _onSearchChanged,
padding: const WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 8)),
+ side: WidgetStatePropertyAll(
+ BorderSide(color: cs.onSurface.withValues(alpha: 0.08)),
+ ),
),
),
@@ -1009,6 +1030,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
],
),
),
+ ),
);
}
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index 809b4ae4..ba2563e6 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -22,7 +22,7 @@ import '../screens/app_shell.dart';
import '../screens/admin_screen.dart';
import '../screens/downloads_screen.dart';
import '../screens/bookmarks_screen.dart';
-import '../main.dart' show applyThemeMode, oledNotifier, snappyTransitionsNotifier;
+import '../main.dart' show applyThemeMode, oledNotifier, snappyTransitionsNotifier, colorSourceNotifier;
import '../widgets/absorb_page_header.dart';
import '../widgets/absorb_slider.dart';
@@ -37,6 +37,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
AutoRewindSettings _rewindSettings = const AutoRewindSettings();
double _defaultSpeed = 1.0;
bool _wifiOnlyDownloads = false;
+ bool _autoDownloadOnStream = false;
int _rollingDownloadCount = 3;
bool _rollingDownloadDeleteFinished = false;
bool _showBookSlider = false;
@@ -59,6 +60,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
bool _fullScreenPlayer = false;
bool _snappyTransitions = false;
String _themeMode = 'dark';
+ String _colorSource = 'wallpaper';
int _streamingCacheSizeMb = 0;
bool _localServerEnabled = false;
String _localServerUrl = '';
@@ -136,6 +138,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
PlayerSettings.getLocalServerEnabled(), // 31
PlayerSettings.getLocalServerUrl(), // 32
PlayerSettings.getDisableAudioFocus(), // 33
+ PlayerSettings.getAutoDownloadOnStream(), // 34
+ PlayerSettings.getColorSource(), // 35
]);
final s = results[0] as AutoRewindSettings;
final speed = results[1] as double;
@@ -171,10 +175,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
final localEnabled = results[31] as bool;
final localUrl = results[32] as String;
final audioFocusOff = results[33] as bool;
+ final autoDlStream = results[34] as bool;
+ final colorSource = results[35] as String;
if (mounted) setState(() {
_rewindSettings = s;
_defaultSpeed = speed;
_wifiOnlyDownloads = wifiOnly;
+ _autoDownloadOnStream = autoDlStream;
_rollingDownloadCount = rollingCount;
_rollingDownloadDeleteFinished = rollingDelete;
_showBookSlider = bookSlider;
@@ -197,6 +204,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
_fullScreenPlayer = fullScreen;
_snappyTransitions = snappyTrans;
_themeMode = theme;
+ _colorSource = colorSource;
_downloadLocationLabel = dlLabel;
_totalDownloadSizeBytes = dlSize;
if (deviceStorage != null) {
@@ -537,6 +545,36 @@ class _SettingsScreenState extends State<SettingsScreen> {
),
),
),
+ const SizedBox(height: 16),
+ Text('Color source', style: tt.titleSmall),
+ const SizedBox(height: 4),
+ Text(
+ _colorSource == 'cover'
+ ? 'App colors follow the currently playing book cover'
+ : 'App colors follow your system wallpaper',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ const SizedBox(height: 12),
+ SizedBox(
+ width: double.infinity,
+ child: SegmentedButton<String>(
+ showSelectedIcon: false,
+ segments: const [
+ ButtonSegment(value: 'wallpaper', label: Text('Wallpaper')),
+ ButtonSegment(value: 'cover', label: Text('Now Playing')),
+ ],
+ selected: {_colorSource},
+ onSelectionChanged: _loaded ? (selected) {
+ final source = selected.first;
+ setState(() => _colorSource = source);
+ PlayerSettings.setColorSource(source);
+ colorSourceNotifier.value = source;
+ } : null,
+ style: const ButtonStyle(
+ visualDensity: VisualDensity.compact,
+ ),
+ ),
+ ),
],
),
),
@@ -1140,6 +1178,20 @@ class _SettingsScreenState extends State<SettingsScreen> {
} : null,
),
const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: const Text('Auto download on Wi-Fi'),
+ subtitle: Text(
+ _autoDownloadOnStream
+ ? 'Books download in the background when you start streaming on Wi-Fi'
+ : 'Off',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _autoDownloadOnStream,
+ onChanged: _loaded ? (v) {
+ setState(() => _autoDownloadOnStream = v);
+ PlayerSettings.setAutoDownloadOnStream(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 8d0f6f01..bac61f5d 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -106,6 +106,13 @@ class PlayerSettings {
static Future<bool> getQueueAutoDownload() => _get('queueAutoDownload', false);
static Future<void> setQueueAutoDownload(bool value) => _set('queueAutoDownload', value);
+ static Future<bool> getAutoDownloadOnStream() => _get('autoDownloadOnStream', false);
+ static Future<void> setAutoDownloadOnStream(bool value) => _set('autoDownloadOnStream', value);
+
+ /// Bookmark sort: 'newest' (default) or 'position'
+ static Future<String> getBookmarkSort() => _get('bookmarkSort', 'newest');
+ static Future<void> setBookmarkSort(String value) => _set('bookmarkSort', value);
+
static Future<bool> getMergeAbsorbingLibraries() => _get('mergeAbsorbingLibraries', false);
static Future<void> setMergeAbsorbingLibraries(bool value) => _set('mergeAbsorbingLibraries', value);
@@ -286,6 +293,9 @@ class PlayerSettings {
static Future<String> getThemeMode() => _get('themeMode', 'dark');
static Future<void> setThemeMode(String value) => _set('themeMode', value);
+ static Future<String> getColorSource() => _get('colorSource', 'wallpaper');
+ static Future<void> setColorSource(String value) => _set('colorSource', value);
+
/// Check if an item has no audio content.
/// For minified responses (library list), duration == 0 means no audio files.
/// For full responses (detail sheet), we also check ebookFile + audioFiles.
@@ -1217,24 +1227,10 @@ class AudioPlayerService extends ChangeNotifier {
));
debugPrint('[AudioSession] Audio focus disabled - mixing with other apps');
- // Still pause for phone calls (AudioInterruptionType.pause)
+ // Ignore all interruption events - can't distinguish Spotify from
+ // phone calls, so disable everything when user opts out of audio focus
_interruptSub?.cancel();
- _interruptSub = session.interruptionEventStream.listen((event) async {
- final service = _instance;
- if (event.type != AudioInterruptionType.pause) return;
- if (event.begin) {
- if (service.isPlaying) {
- debugPrint('[AudioSession] Phone call - pausing');
- await service._player?.pause();
- service._wasPlayingBeforeInterrupt = true;
- }
- } else if (service._wasPlayingBeforeInterrupt) {
- service._wasPlayingBeforeInterrupt = false;
- await Future.delayed(const Duration(milliseconds: 600));
- debugPrint('[AudioSession] Phone call ended - resuming');
- await service.play();
- }
- });
+ _interruptSub = null;
// Still pause when headphones/BT disconnect
_noisySub?.cancel();
diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dart
index 29399543..9e258b88 100644
--- a/lib/services/backup_service.dart
+++ b/lib/services/backup_service.dart
@@ -48,6 +48,21 @@ class BackupService {
'queueAutoDownload': await PlayerSettings.getQueueAutoDownload(),
'mergeAbsorbingLibraries': await PlayerSettings.getMergeAbsorbingLibraries(),
'maxConcurrentDownloads': await PlayerSettings.getMaxConcurrentDownloads(),
+ 'colorSource': await PlayerSettings.getColorSource(),
+ 'snappyTransitions': await PlayerSettings.getSnappyTransitions(),
+ 'bookmarkSort': await PlayerSettings.getBookmarkSort(),
+ 'autoDownloadOnStream': await PlayerSettings.getAutoDownloadOnStream(),
+ 'notificationChapterProgress': await PlayerSettings.getNotificationChapterProgress(),
+ 'sleepTimerMinutes': await PlayerSettings.getSleepTimerMinutes(),
+ 'sleepTimerChapters': await PlayerSettings.getSleepTimerChapters(),
+ 'streamingCacheSizeMb': await PlayerSettings.getStreamingCacheSizeMb(),
+ 'seriesSort': await PlayerSettings.getSeriesSort(),
+ 'seriesSortAsc': await PlayerSettings.getSeriesSortAsc(),
+ 'authorSort': await PlayerSettings.getAuthorSort(),
+ 'authorSortAsc': await PlayerSettings.getAuthorSortAsc(),
+ 'disableAudioFocus': await PlayerSettings.getDisableAudioFocus(),
+ 'localServerEnabled': await PlayerSettings.getLocalServerEnabled(),
+ 'localServerUrl': await PlayerSettings.getLocalServerUrl(),
};
// AutoRewind (scoped)
@@ -196,6 +211,21 @@ class BackupService {
if (s['queueAutoDownload'] != null) PlayerSettings.setQueueAutoDownload(s['queueAutoDownload'] as bool);
if (s['mergeAbsorbingLibraries'] != null) PlayerSettings.setMergeAbsorbingLibraries(s['mergeAbsorbingLibraries'] as bool);
if (s['maxConcurrentDownloads'] != null) PlayerSettings.setMaxConcurrentDownloads(s['maxConcurrentDownloads'] as int);
+ if (s['colorSource'] != null) PlayerSettings.setColorSource(s['colorSource'] as String);
+ if (s['snappyTransitions'] != null) PlayerSettings.setSnappyTransitions(s['snappyTransitions'] as bool);
+ if (s['bookmarkSort'] != null) PlayerSettings.setBookmarkSort(s['bookmarkSort'] as String);
+ if (s['autoDownloadOnStream'] != null) PlayerSettings.setAutoDownloadOnStream(s['autoDownloadOnStream'] as bool);
+ if (s['notificationChapterProgress'] != null) PlayerSettings.setNotificationChapterProgress(s['notificationChapterProgress'] as bool);
+ if (s['sleepTimerMinutes'] != null) PlayerSettings.setSleepTimerMinutes(s['sleepTimerMinutes'] as int);
+ if (s['sleepTimerChapters'] != null) PlayerSettings.setSleepTimerChapters(s['sleepTimerChapters'] as int);
+ if (s['streamingCacheSizeMb'] != null) PlayerSettings.setStreamingCacheSizeMb(s['streamingCacheSizeMb'] as int);
+ if (s['seriesSort'] != null) PlayerSettings.setSeriesSort(s['seriesSort'] as String);
+ if (s['seriesSortAsc'] != null) PlayerSettings.setSeriesSortAsc(s['seriesSortAsc'] as bool);
+ if (s['authorSort'] != null) PlayerSettings.setAuthorSort(s['authorSort'] as String);
+ if (s['authorSortAsc'] != null) PlayerSettings.setAuthorSortAsc(s['authorSortAsc'] as bool);
+ if (s['disableAudioFocus'] != null) PlayerSettings.setDisableAudioFocus(s['disableAudioFocus'] as bool);
+ if (s['localServerEnabled'] != null) PlayerSettings.setLocalServerEnabled(s['localServerEnabled'] as bool);
+ if (s['localServerUrl'] != null) PlayerSettings.setLocalServerUrl(s['localServerUrl'] as String);
// AutoRewind (scoped via save())
final r = data['autoRewind'] as Map<String, dynamic>?;
diff --git a/lib/services/bookmark_service.dart b/lib/services/bookmark_service.dart
index 0dbb655e..81ff3d21 100644
--- a/lib/services/bookmark_service.dart
+++ b/lib/services/bookmark_service.dart
@@ -59,8 +59,9 @@ class BookmarkService {
static const _keyPrefix = 'bookmarks_';
- /// Get all bookmarks for a book, sorted by position.
- Future<List<Bookmark>> getBookmarks(String itemId) async {
+ /// Get all bookmarks for a book.
+ /// [sort] is 'newest' (by creation time, newest first) or 'position' (by book position).
+ Future<List<Bookmark>> getBookmarks(String itemId, {String sort = 'newest'}) async {
final stored = await ScopedPrefs.getStringList('$_keyPrefix$itemId');
final bookmarks = <Bookmark>[];
@@ -72,7 +73,11 @@ class BookmarkService {
}
}
- bookmarks.sort((a, b) => a.positionSeconds.compareTo(b.positionSeconds));
+ if (sort == 'position') {
+ bookmarks.sort((a, b) => a.positionSeconds.compareTo(b.positionSeconds));
+ } else {
+ bookmarks.sort((a, b) => b.created.compareTo(a.created));
+ }
return bookmarks;
}
@@ -160,7 +165,8 @@ class BookmarkService {
}
/// Get all bookmarks across all books for the current account, keyed by itemId.
- Future<Map<String, List<Bookmark>>> getAllBookmarks() async {
+ /// [sort] is 'newest' (by creation time, newest first) or 'position' (by book position).
+ Future<Map<String, List<Bookmark>>> getAllBookmarks({String sort = 'newest'}) async {
final prefs = await SharedPreferences.getInstance();
final scope = UserAccountService().activeScopeKey;
final scopedPrefix = scope.isNotEmpty ? '$scope:$_keyPrefix' : _keyPrefix;
@@ -177,11 +183,23 @@ class BookmarkService {
} catch (_) {}
}
if (bookmarks.isNotEmpty) {
- bookmarks.sort((a, b) => a.positionSeconds.compareTo(b.positionSeconds));
+ if (sort == 'position') {
+ bookmarks.sort((a, b) => a.positionSeconds.compareTo(b.positionSeconds));
+ } else {
+ bookmarks.sort((a, b) => b.created.compareTo(a.created));
+ }
result[itemId] = bookmarks;
}
}
+ // Sort book groups by most recent bookmark when in newest mode
+ if (sort == 'newest') {
+ final sorted = Map.fromEntries(
+ result.entries.toList()..sort((a, b) => b.value.first.created.compareTo(a.value.first.created)),
+ );
+ return sorted;
+ }
+
return result;
}
diff --git a/lib/services/download_service.dart b/lib/services/download_service.dart
index ad183109..901e0fa9 100644
--- a/lib/services/download_service.dart
+++ b/lib/services/download_service.dart
@@ -24,6 +24,7 @@ class DownloadInfo {
final String? author;
final String? coverUrl;
final String? localCoverPath;
+ final String? localDirPath;
DownloadInfo({
required this.itemId,
@@ -35,6 +36,7 @@ class DownloadInfo {
this.author,
this.coverUrl,
this.localCoverPath,
+ this.localDirPath,
});
Map<String, dynamic> toJson() => {
@@ -46,6 +48,7 @@ class DownloadInfo {
'author': author,
'coverUrl': coverUrl,
'localCoverPath': localCoverPath,
+ if (localDirPath != null) 'localDirPath': localDirPath,
};
factory DownloadInfo.fromJson(Map<String, dynamic> json) {
@@ -89,6 +92,7 @@ class DownloadInfo {
author: author,
coverUrl: coverUrl,
localCoverPath: json['localCoverPath'] as String?,
+ localDirPath: json['localDirPath'] as String?,
);
}
}
@@ -111,6 +115,19 @@ class _QueuedDownload {
});
}
+/// Sanitize a string for use as a filesystem directory/file name.
+String _sanitizePath(String name) {
+ // Replace filesystem-illegal characters with underscore
+ var s = name.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_');
+ // Collapse multiple underscores/spaces
+ s = s.replaceAll(RegExp(r'[_\s]+'), ' ').trim();
+ // Fallback for empty result
+ if (s.isEmpty) s = 'Unknown';
+ // Limit length to avoid filesystem issues
+ if (s.length > 100) s = s.substring(0, 100).trim();
+ return s;
+}
+
class DownloadService extends ChangeNotifier {
static final DownloadService _instance = DownloadService._();
factory DownloadService() => _instance;
@@ -580,6 +597,7 @@ class DownloadService extends ChangeNotifier {
debugPrint('[Download] startDownload non-fatal error: $e');
}
+ Directory? bookDir;
try {
// For episodes, itemId is a composite key like 'podcastId-episodeId'.
// Extract the real library item ID for the API call.
@@ -597,7 +615,10 @@ class DownloadService extends ChangeNotifier {
}
final basePath = await downloadBasePath;
- final bookDir = Directory('$basePath/$itemId');
+ final dirName = (author != null && author.isNotEmpty)
+ ? '${_sanitizePath(author)}/${_sanitizePath(title)}'
+ : _sanitizePath(title);
+ bookDir = Directory('$basePath/$dirName');
if (!bookDir.existsSync()) {
bookDir.createSync(recursive: true);
}
@@ -672,17 +693,33 @@ class DownloadService extends ChangeNotifier {
final contentUrl = track['contentUrl'] as String? ?? '';
final fullUrl = api.buildTrackUrl(contentUrl);
- final mimeType = track['mimeType'] as String? ?? 'audio/mpeg';
- final ext = mimeType.contains('mp4')
- ? 'm4a'
- : mimeType.contains('flac')
- ? 'flac'
- : mimeType.contains('ogg')
- ? 'ogg'
- : 'mp3';
-
- final filePath =
- '${bookDir.path}/track_${i.toString().padLeft(3, '0')}.$ext';
+ // Try to get the original filename from track metadata first
+ final trackMeta = track['metadata'] as Map<String, dynamic>?;
+ var originalName = trackMeta?['filename'] as String? ?? '';
+ // Fallback: extract from contentUrl path
+ if (originalName.isEmpty) {
+ final contentPath = Uri.tryParse(contentUrl)?.path ?? contentUrl;
+ originalName = Uri.decodeComponent(contentPath.split('/').last);
+ if (originalName.contains('?')) originalName = originalName.split('?').first;
+ }
+
+ final String fileName;
+ if (originalName.isNotEmpty && originalName.contains('.')) {
+ fileName = _sanitizePath(originalName.replaceAll(RegExp(r'\.[^.]+$'), ''))
+ + originalName.substring(originalName.lastIndexOf('.'));
+ } else {
+ final mimeType = track['mimeType'] as String? ?? 'audio/mpeg';
+ final ext = mimeType.contains('mp4')
+ ? 'm4a'
+ : mimeType.contains('flac')
+ ? 'flac'
+ : mimeType.contains('ogg')
+ ? 'ogg'
+ : 'mp3';
+ fileName = 'track_${i.toString().padLeft(3, '0')}.$ext';
+ }
+
+ final filePath = '${bookDir!.path}/$fileName';
final file = File(filePath);
debugPrint('[Download] Track ${i + 1}/${audioTracks.length}: $fullUrl');
@@ -751,6 +788,7 @@ class DownloadService extends ChangeNotifier {
author: author,
coverUrl: coverUrl,
localCoverPath: localCoverPath,
+ localDirPath: bookDir.path,
);
await _save();
notifyListeners();
@@ -772,9 +810,13 @@ class DownloadService extends ChangeNotifier {
} catch (e) {
// Clean up partial files on any failure
try {
- final basePath = await downloadBasePath;
- final bookDir = Directory('$basePath/$itemId');
- if (bookDir.existsSync()) bookDir.deleteSync(recursive: true);
+ if (bookDir != null && bookDir.existsSync()) {
+ bookDir.deleteSync(recursive: true);
+ final parent = bookDir.parent;
+ if (parent.existsSync() && parent.listSync().isEmpty) {
+ parent.deleteSync();
+ }
+ }
} catch (_) {}
if (_cancelledIds.contains(itemId)) {
@@ -848,10 +890,22 @@ class DownloadService extends ChangeNotifier {
} catch (_) {}
}
+ // Remove the download directory (new-style path from DownloadInfo, or legacy UUID path)
try {
- final basePath = await downloadBasePath;
- final bookDir = Directory('$basePath/$itemId');
- if (bookDir.existsSync()) bookDir.deleteSync(recursive: true);
+ final dirPath = info.localDirPath;
+ if (dirPath != null && Directory(dirPath).existsSync()) {
+ Directory(dirPath).deleteSync(recursive: true);
+ // Clean up empty parent (Author folder) if it's now empty
+ final parent = Directory(dirPath).parent;
+ if (parent.existsSync() && parent.listSync().isEmpty) {
+ parent.deleteSync();
+ }
+ } else {
+ // Legacy fallback: UUID-based directory
+ final basePath = await downloadBasePath;
+ final bookDir = Directory('$basePath/$itemId');
+ if (bookDir.existsSync()) bookDir.deleteSync(recursive: true);
+ }
} catch (_) {}
// Clean up cached cover image (stored separately in internal storage)
diff --git a/lib/widgets/card_buttons.dart b/lib/widgets/card_buttons.dart
index 7b7ef21c..f4fd84b1 100644
--- a/lib/widgets/card_buttons.dart
+++ b/lib/widgets/card_buttons.dart
@@ -425,9 +425,14 @@ class SimpleBookmarkSheet extends StatefulWidget {
class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
List<Bookmark>? _bookmarks;
- @override void initState() { super.initState(); _load(); }
+ String _sort = 'newest';
+ @override void initState() { super.initState(); _loadSort(); }
+ Future<void> _loadSort() async {
+ _sort = await PlayerSettings.getBookmarkSort();
+ _load();
+ }
Future<void> _load() async {
- final bm = await BookmarkService().getBookmarks(widget.itemId);
+ final bm = await BookmarkService().getBookmarks(widget.itemId, sort: _sort);
if (mounted) setState(() => _bookmarks = bm);
widget.onChanged();
}
@@ -445,6 +450,19 @@ class _SimpleBookmarkSheetState extends State<SimpleBookmarkSheet> {
Padding(padding: const EdgeInsets.symmetric(vertical: 12),
child: Container(width: 40, height: 4, decoration: BoxDecoration(color: cs.onSurface.withValues(alpha: 0.24), borderRadius: BorderRadius.circular(2)))),
Padding(padding: const EdgeInsets.symmetric(horizontal: 20), child: Row(children: [
+ GestureDetector(
+ onTap: () {
+ final next = _sort == 'newest' ? 'position' : 'newest';
+ setState(() => _sort = next);
+ PlayerSettings.setBookmarkSort(next);
+ _load();
+ },
+ child: Container(
+ width: 36, height: 36,
+ decoration: BoxDecoration(color: cs.onSurface.withValues(alpha: 0.06), borderRadius: BorderRadius.circular(10)),
+ child: Icon(_sort == 'newest' ? Icons.schedule_rounded : Icons.sort_rounded, color: cs.onSurfaceVariant, size: 20),
+ ),
+ ),
const Spacer(),
Text('Bookmarks', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),
const Spacer(),
diff --git a/lib/widgets/card_progress_bar.dart b/lib/widgets/card_progress_bar.dart
index 205029c3..7a618c1a 100644
--- a/lib/widgets/card_progress_bar.dart
+++ b/lib/widgets/card_progress_bar.dart
@@ -244,6 +244,7 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr
final chapterPos = (posS - chapterStart).clamp(0.0, chapterDur);
final chapterProgress = chapterDur > 0 ? chapterPos / chapterDur : 0.0;
final speedDiv = _speedAdjustedTime ? speed : 1.0;
+ final bookElapsed = posS / speedDiv;
final bookRemaining = (totalDur - posS) / speedDiv;
final chapterRemaining = (chapterDur - chapterPos) / speedDiv;
final chapterElapsed = chapterPos / speedDiv;
@@ -269,13 +270,13 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with TickerPr
Padding(padding: const EdgeInsets.only(top: 2, bottom: 6), child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
- Text(_fmt(_bookDragValue != null ? _bookDragValue! * totalDur : posS), style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 12, fontWeight: FontWeight.w600, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),
+ Text(_fmt(_bookDragValue != null ? _bookDragValue! * totalDur : bookElapsed), style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 12, fontWeight: FontWeight.w600, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),
Text('-${_fmt(_bookDragValue != null ? (1.0 - _bookDragValue!) * totalDur : bookRemaining)}', style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 12, fontWeight: FontWeight.w600, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),
],
)),
] else ...[
Row(children: [
- Text(_fmt(_bookDragValue != null ? _bookDragValue! * totalDur : posS), style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.6) : cs.onSurface.withValues(alpha: 0.5), fontSize: 11, fontWeight: FontWeight.w500, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),
+ Text(_fmt(_bookDragValue != null ? _bookDragValue! * totalDur : bookElapsed), style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.6) : cs.onSurface.withValues(alpha: 0.5), fontSize: 11, fontWeight: FontWeight.w500, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),
const SizedBox(width: 8),
Expanded(child: ClipRRect(borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(value: bookProgress, minHeight: 3, backgroundColor: cs.onSurface.withValues(alpha: 0.08), valueColor: AlwaysStoppedAnimation(widget.accent.withValues(alpha: 0.5))))),