A cross platform Audiobookshelf client for Android and iOS
Dart
Add rolling auto-download for series and podcasts
Nathan Poulsonf4f40401d726
diff --git a/lib/main.dart b/lib/main.dartindex c0efdfa5..bc5303e2 100644--- a/lib/main.dart+++ b/lib/main.dart@@ -26,6 +26,10 @@ import 'widgets/absorb_wave_icon.dart';/// Global notifier so any widget (e.g. settings) can change the theme instantly.final ValueNotifier<ThemeMode> themeNotifier = ValueNotifier(ThemeMode.dark);+/// Global key so non-widget code (e.g. providers) can show snackbars.+final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =+ GlobalKey<ScaffoldMessengerState>();+ThemeMode parseThemeMode(String value) {switch (value) {case 'light': return ThemeMode.light;@@ -143,6 +147,7 @@ class AbsorbApp extends StatelessWidget {);return MaterialApp(+ scaffoldMessengerKey: scaffoldMessengerKey,title: 'Absorb',debugShowCheckedModeBanner: false,themeMode: currentMode,diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex be425025..e967c040 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -12,6 +12,7 @@ import '../services/progress_sync_service.dart';import '../services/download_service.dart';import '../services/android_auto_service.dart';import '../services/chromecast_service.dart';+import '../main.dart' show scaffoldMessengerKey;/// Holds library data and personalized home sections.class LibraryProvider extends ChangeNotifier {@@ -97,6 +98,9 @@ class LibraryProvider extends ChangeNotifier {} else if (!offline && wasOffline && !_manualOffline) {// Came back online — stop pinging, flush pending syncs, then refresh_stopServerPingTimer();+ // Clear in-memory image cache so CachedNetworkImage retries covers+ // that failed while offline instead of showing the cached error.+ PaintingBinding.instance.imageCache.clear();if (_api != null) {debugPrint('[Library] Back online — flushing pending syncs');ProgressSyncService().flushPendingSync(api: _api!);@@ -128,25 +132,51 @@ class LibraryProvider extends ChangeNotifier {// Try to extract duration from cached session datadouble duration = 0;List<dynamic> chapters = [];+ String? episodeTitle;if (dl.sessionData != null) {try {final session = jsonDecode(dl.sessionData!) as Map<String, dynamic>;duration = (session['duration'] as num?)?.toDouble() ?? 0;chapters = session['chapters'] as List<dynamic>? ?? [];+ episodeTitle = session['episodeTitle'] as String?+ ?? session['displayTitle'] as String?;} catch (_) {}}- entities.add({- 'id': dl.itemId,- 'media': {- 'metadata': {- 'title': dl.title ?? 'Unknown Title',- 'authorName': dl.author ?? '',+ // Podcast downloads use compound key "showId-episodeId"+ final isCompound = dl.itemId.length > 36;+ if (isCompound) {+ final showId = dl.itemId.substring(0, 36);+ final episodeId = dl.itemId.substring(37);+ entities.add({+ 'id': showId,+ '_absorbingKey': dl.itemId,+ 'recentEpisode': {+ 'id': episodeId,+ 'title': episodeTitle ?? dl.title ?? 'Episode',},- 'duration': duration,- 'chapters': chapters,- },- });+ 'media': {+ 'metadata': {+ 'title': dl.title ?? 'Unknown Title',+ 'authorName': dl.author ?? '',+ },+ 'duration': duration,+ 'chapters': chapters,+ },+ });+ } else {+ entities.add({+ 'id': dl.itemId,+ 'media': {+ 'metadata': {+ 'title': dl.title ?? 'Unknown Title',+ 'authorName': dl.author ?? '',+ },+ 'duration': duration,+ 'chapters': chapters,+ },+ });+ }}final isPodcast = isPodcastLibrary;@@ -348,6 +378,7 @@ class LibraryProvider extends ChangeNotifier {// Restore manual offline preference and start connectivity monitoring// Must complete before loading libraries so offline state is correctAudioPlayerService.setOnBookFinishedCallback(markFinishedLocally);+ AudioPlayerService.setOnPlayStartedCallback(_checkRollingDownloads);ChromecastService.setOnBookFinishedCallback(markFinishedLocally);restoreOfflineMode().then((_) {@@ -379,6 +410,7 @@ class LibraryProvider extends ChangeNotifier {} else {_lastAuthKey = null;AudioPlayerService.setOnBookFinishedCallback(null);+ AudioPlayerService.setOnPlayStartedCallback(null);ChromecastService.setOnBookFinishedCallback(null);_libraries = [];_personalizedSections = [];@@ -980,6 +1012,11 @@ class LibraryProvider extends ChangeNotifier {if (newContinueSeriesKey != null && _api != null) {PlayerSettings.getAutoPlayNextBook().then((autoPlay) {if (!autoPlay) return;+ // Don't auto-play if BT/headphones just disconnected — the server+ // refresh is async and may return after the user left the car.+ if (AudioPlayerService.wasNoisyPause) return;+ // Skip if local auto-advance already started playback+ if (AudioPlayerService().isPlaying) return;final cached = _absorbingItemCache[newContinueSeriesKey];if (cached == null) return;final media = cached['media'] as Map<String, dynamic>? ?? {};@@ -1252,6 +1289,22 @@ class LibraryProvider extends ChangeNotifier {}notifyListeners();+ // Instant local auto-advance — uses cached metadata + download info,+ // no server call needed. Fires first so playback starts immediately,+ // then the server refresh still runs in the background when online.+ _autoAdvanceOffline(itemId);++ // Auto-delete finished download when rolling delete is enabled+ PlayerSettings.getRollingDownload().then((rolling) {+ if (!rolling) return;+ PlayerSettings.getRollingDownloadDeleteFinished().then((delete) {+ if (delete && DownloadService().isDownloaded(itemId)) {+ DownloadService().deleteDownload(itemId);+ _showRollingSnackBar('Deleted finished download');+ }+ });+ });+// For podcast episodes, fetch the next episode and THEN refresh.// This avoids a race where the refresh prunes the newly added episode.final isCompound = itemId.length > 36;@@ -1279,6 +1332,12 @@ class LibraryProvider extends ChangeNotifier {});});}++ if (isOffline) {+ PlayerSettings.getWhenFinished().then((mode) {+ if (mode == 'auto_remove') removeFromAbsorbing(itemId);+ });+ }}/// Fetch the podcast show's episode list and insert the next episode@@ -1332,7 +1391,9 @@ class LibraryProvider extends ChangeNotifier {notifyListeners();// Auto-play the next episode if the setting is enabled.- if (await PlayerSettings.getAutoPlayNextPodcast() && _api != null) {+ // Skip if local auto-advance already started playback.+ if (await PlayerSettings.getAutoPlayNextPodcast() && _api != null &&+ !AudioPlayerService().isPlaying) {final metadata = media['metadata'] as Map<String, dynamic>? ?? {};final title = metadata['title'] as String? ?? '';final author = metadata['authorName'] as String? ?? '';@@ -1353,6 +1414,361 @@ class LibraryProvider extends ChangeNotifier {} catch (_) {}}+ /// Offline auto-advance: find the next downloaded book in series or next+ /// downloaded podcast episode and auto-play it without any server calls.+ void _autoAdvanceOffline(String finishedKey) {+ if (AudioPlayerService.wasNoisyPause) return;++ final isCompound = finishedKey.length > 36;+ if (isCompound) {+ _autoAdvanceOfflinePodcast(finishedKey);+ } else {+ _autoAdvanceOfflineBook(finishedKey);+ }+ }++ /// Extract series metadata from an item map (cache entry or session libraryItem).+ /// Returns (seriesId, sequence) for the first series found, or (null, null).+ static (String?, double?) _extractSeries(Map<String, dynamic> item) {+ final media = item['media'] as Map<String, dynamic>? ?? {};+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ final seriesRaw = metadata['series'];+ if (seriesRaw is List) {+ for (final s in seriesRaw) {+ if (s is Map<String, dynamic>) {+ final id = s['id'] as String?;+ final seq = double.tryParse((s['sequence'] ?? '').toString());+ if (id != null && seq != null) return (id, seq);+ }+ }+ } else if (seriesRaw is Map<String, dynamic>) {+ final id = seriesRaw['id'] as String?;+ final seq = double.tryParse((seriesRaw['sequence'] ?? '').toString());+ if (id != null && seq != null) return (id, seq);+ }+ return (null, null);+ }++ /// Try to get item metadata from the absorbing cache, falling back to+ /// the download session's libraryItem if the cache entry is missing or+ /// has no series info.+ Map<String, dynamic>? _itemDataWithSeries(String itemId) {+ final cached = _absorbingItemCache[itemId];+ if (cached != null) {+ final (sid, _) = _extractSeries(cached);+ if (sid != null) return cached;+ }+ // Fallback: parse the download session's embedded libraryItem+ final dl = DownloadService().getInfo(itemId);+ if (dl.sessionData == null) return cached;+ try {+ final session = jsonDecode(dl.sessionData!) as Map<String, dynamic>;+ final libItem = session['libraryItem'] as Map<String, dynamic>?;+ if (libItem != null) {+ final (sid, _) = _extractSeries(libItem);+ if (sid != null) return libItem;+ }+ } catch (_) {}+ return cached;+ }++ void _autoAdvanceOfflineBook(String finishedBookId) {+ PlayerSettings.getAutoPlayNextBook().then((autoPlay) {+ if (!autoPlay) return;+ if (AudioPlayerService.wasNoisyPause) return;++ final finished = _itemDataWithSeries(finishedBookId);+ if (finished == null) return;+ final (seriesId, currentSeq) = _extractSeries(finished);+ if (seriesId == null || currentSeq == null) return;++ // Scan all downloaded books for the next in this series+ final dl = DownloadService();+ final candidates = <double, MapEntry<String, Map<String, dynamic>>>{};+ for (final dlInfo in dl.downloadedItems) {+ final id = dlInfo.itemId;+ if (id == finishedBookId) continue;+ if (id.length > 36) continue; // skip podcast episodes+ if (_progressMap[id]?['isFinished'] == true) continue;++ final data = _itemDataWithSeries(id);+ if (data == null) continue;+ final (sid, seq) = _extractSeries(data);+ if (sid != seriesId || seq == null || seq <= currentSeq) continue;+ candidates[seq] = MapEntry(id, data);+ }+ if (candidates.isEmpty) return;++ // Pick the lowest sequence number above the finished book+ final nextSeq = candidates.keys.toList()..sort();+ final next = candidates[nextSeq.first]!;+ final nextKey = next.key;+ final nextData = next.value;++ // Position it after the finished book on the absorbing list+ _absorbingIdsAdd(nextKey, afterKey: finishedBookId);+ _absorbingItemCache[nextKey] = nextData;+ _saveManualAbsorbing();+ notifyListeners();++ final nextMedia = nextData['media'] as Map<String, dynamic>? ?? {};+ final nextMeta = nextMedia['metadata'] as Map<String, dynamic>? ?? {};+ AudioPlayerService().playItem(+ api: _api ?? ApiService(baseUrl: '', token: ''),+ itemId: nextKey,+ title: nextMeta['title'] as String? ?? '',+ author: nextMeta['authorName'] as String? ?? '',+ coverUrl: getCoverUrl(nextKey),+ totalDuration: (nextMedia['duration'] as num?)?.toDouble() ?? 0,+ chapters: nextMedia['chapters'] as List<dynamic>? ?? [],+ );+ });+ }++ void _autoAdvanceOfflinePodcast(String finishedKey) {+ PlayerSettings.getAutoPlayNextPodcast().then((autoPlay) {+ if (!autoPlay) return;+ if (AudioPlayerService.wasNoisyPause) return;++ final showId = finishedKey.substring(0, 36);+ final finishedEpId = finishedKey.substring(37);++ // Find all downloaded episodes for this show from the cache+ final dl = DownloadService();+ final episodes = <int, MapEntry<String, Map<String, dynamic>>>{};+ int? finishedTimestamp;++ for (final entry in _absorbingItemCache.entries) {+ if (!entry.key.startsWith('$showId-')) continue;+ final ep = entry.value['recentEpisode'] as Map<String, dynamic>?;+ if (ep == null) continue;+ final epId = ep['id'] as String?;+ if (epId == null) continue;+ final publishedAt = (ep['publishedAt'] as num?)?.toInt() ?? 0;++ if (epId == finishedEpId) {+ finishedTimestamp = publishedAt;+ } else if (!(_progressMap[entry.key]?['isFinished'] == true) &&+ dl.isDownloaded(entry.key)) {+ episodes[publishedAt] = entry;+ }+ }+ if (finishedTimestamp == null || episodes.isEmpty) return;++ // Find the next episode after the finished one (ascending publishedAt)+ final sorted = episodes.keys.toList()..sort();+ final nextTimestamp = sorted.where((t) => t > finishedTimestamp!).firstOrNull;+ if (nextTimestamp == null) return;++ final nextEntry = episodes[nextTimestamp]!;+ final nextKey = nextEntry.key;+ final nextData = nextEntry.value;+ final ep = nextData['recentEpisode'] as Map<String, dynamic>;+ final nextEpId = ep['id'] as String;++ // Position it after the finished episode on the absorbing list+ _absorbingIdsAdd(nextKey, afterKey: finishedKey);+ _saveManualAbsorbing();+ notifyListeners();++ final media = nextData['media'] as Map<String, dynamic>? ?? {};+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ final duration = (ep['duration'] as num?)?.toDouble()+ ?? (ep['audioFile'] as Map<String, dynamic>?)?['duration'] as double? ?? 0;+ AudioPlayerService().playItem(+ api: _api ?? ApiService(baseUrl: '', token: ''),+ itemId: showId,+ title: metadata['title'] as String? ?? '',+ author: metadata['authorName'] as String? ?? '',+ coverUrl: getCoverUrl(showId),+ totalDuration: duration,+ chapters: [],+ episodeId: nextEpId,+ episodeTitle: ep['title'] as String?,+ );+ });+ }++ // ── Rolling auto-download ──────────────────────────────────────────────++ /// Called when a new item starts playing. If rolling downloads are enabled,+ /// ensures the next N-1 items in the same series/podcast are downloaded.+ void _checkRollingDownloads(String playingKey) {+ PlayerSettings.getRollingDownload().then((enabled) async {+ if (!enabled || _api == null || isOffline) return;+ final count = await PlayerSettings.getRollingDownloadCount();+ if (playingKey.length > 36) {+ _rollingDownloadPodcast(playingKey, count);+ } else {+ _rollingDownloadBook(playingKey, count);+ }+ });+ }++ /// 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+ var data = _itemDataWithSeries(bookId);+ var (seriesId, currentSeq) = data != null ? _extractSeries(data) : (null, null);+ if (seriesId == null || currentSeq == null) {+ final fullItem = await _api!.getLibraryItem(bookId);+ if (fullItem == null) return;+ data = fullItem;+ (seriesId, currentSeq) = _extractSeries(fullItem);+ }+ if (seriesId == null || currentSeq == null) return;++ final books = await _api!.getBooksBySeries(+ _selectedLibraryId ?? '', seriesId, limit: 100,+ );+ if (books.isEmpty) return;++ final dl = DownloadService();+ int queued = 0;+ int newDownloads = 0;++ // Download the currently-playing book too if not already downloaded+ if (!dl.isDownloaded(bookId) && !dl.isDownloading(bookId)) {+ final media = data!['media'] as Map<String, dynamic>? ?? {};+ final md = media['metadata'] as Map<String, dynamic>? ?? {};+ dl.downloadItem(+ api: _api!,+ itemId: bookId,+ title: md['title'] as String? ?? '',+ author: md['authorName'] as String? ?? '',+ coverUrl: getCoverUrl(bookId),+ );+ newDownloads++;+ }+ queued++; // Count current book toward the window++ for (final book in books) {+ if (queued >= count) break;+ final bookMap = book as Map<String, dynamic>;+ final id = bookMap['id'] as String?;+ if (id == null || id == bookId) continue;++ // Find this book's sequence in the target series.+ // ABS returns series as a Map (single) or List depending on endpoint.+ final media = bookMap['media'] as Map<String, dynamic>? ?? {};+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ final seriesRaw = metadata['series'];+ double? seq;+ if (seriesRaw is Map<String, dynamic> && seriesRaw['id'] == seriesId) {+ seq = double.tryParse((seriesRaw['sequence'] ?? '').toString());+ } else if (seriesRaw is List) {+ for (final s in seriesRaw) {+ if (s is Map<String, dynamic> && s['id'] == seriesId) {+ seq = double.tryParse((s['sequence'] ?? '').toString());+ break;+ }+ }+ }+ if (seq == null || seq <= currentSeq) continue;++ if (dl.isDownloaded(id) || dl.isDownloading(id)) {+ queued++;+ continue;+ }+ if (_progressMap[id]?['isFinished'] == true) continue;++ dl.downloadItem(+ api: _api!,+ itemId: id,+ title: metadata['title'] as String? ?? '',+ author: metadata['authorName'] as String? ?? '',+ coverUrl: getCoverUrl(id),+ );+ queued++;+ newDownloads++;+ }++ if (newDownloads > 0) {+ _showRollingSnackBar('Downloading $newDownloads book${newDownloads == 1 ? '' : 's'}');+ }+ }++ /// Download the next [count]-1 episodes in the same podcast as [compoundKey].+ Future<void> _rollingDownloadPodcast(String compoundKey, int count) async {+ final showId = compoundKey.substring(0, 36);+ final episodeId = compoundKey.substring(37);++ final fullItem = await _api!.getLibraryItem(showId);+ if (fullItem == null) return;+ final media = fullItem['media'] as Map<String, dynamic>? ?? {};+ final episodes = List<dynamic>.from(media['episodes'] as List<dynamic>? ?? []);+ if (episodes.isEmpty) return;++ // Sort oldest-first (ascending publishedAt) so "next" = index + 1+ episodes.sort((a, b) {+ final aTime = (a['publishedAt'] as num?)?.toInt() ?? 0;+ final bTime = (b['publishedAt'] as num?)?.toInt() ?? 0;+ return aTime.compareTo(bTime);+ });++ final currentIdx = episodes.indexWhere(+ (e) => e is Map<String, dynamic> && (e['id'] as String?) == episodeId,+ );+ if (currentIdx < 0) return;++ final dl = DownloadService();+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ int queued = 0;+ int newDownloads = 0;++ // Download the currently-playing episode too if not already downloaded+ if (!dl.isDownloaded(compoundKey) && !dl.isDownloading(compoundKey)) {+ final curEp = episodes[currentIdx] as Map<String, dynamic>;+ dl.downloadItem(+ api: _api!,+ itemId: compoundKey,+ title: curEp['title'] as String? ?? 'Episode',+ author: metadata['title'] as String? ?? '',+ coverUrl: getCoverUrl(showId),+ episodeId: episodeId,+ );+ newDownloads++;+ }+ queued++; // Count current episode toward the window++ for (int i = currentIdx + 1; i < episodes.length && queued < count; i++) {+ final ep = episodes[i] as Map<String, dynamic>;+ final epId = ep['id'] as String?;+ if (epId == null) continue;+ final key = '$showId-$epId';++ if (dl.isDownloaded(key) || dl.isDownloading(key)) {+ queued++;+ continue;+ }+ if (_progressMap[key]?['isFinished'] == true) continue;++ dl.downloadItem(+ api: _api!,+ itemId: key,+ title: ep['title'] as String? ?? 'Episode',+ author: metadata['title'] as String? ?? '',+ coverUrl: getCoverUrl(showId),+ episodeId: epId,+ );+ queued++;+ newDownloads++;+ }++ if (newDownloads > 0) {+ _showRollingSnackBar('Downloading $newDownloads episode${newDownloads == 1 ? '' : 's'}');+ }+ }++ void _showRollingSnackBar(String message) {+ scaffoldMessengerKey.currentState+ ?..clearSnackBars()+ ..showSnackBar(SnackBar(+ content: Text(message),+ duration: const Duration(seconds: 3),+ ));+ }+/// Check if a book/episode is on the absorbing page (persisted local list, not removed)./// [key] can be a plain itemId (books) or compound "itemId-episodeId" (podcasts).bool isOnAbsorbingList(String key) {diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dartindex 49628284..3c6755c8 100644--- a/lib/screens/absorbing_screen.dart+++ b/lib/screens/absorbing_screen.dart@@ -423,7 +423,8 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {}books = books.where((b) {if (activeKey != null && _absorbingKey(b) == activeKey) return true;- return dl.isDownloaded(b['id'] as String? ?? '');+ final dlKey = _absorbingKey(b);+ return dl.isDownloaded(dlKey);}).toList();}@@ -454,7 +455,18 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {onTap: () {final newVal = !lib.isManualOffline;lib.setManualOffline(newVal);- if (newVal) _stopAndRefresh(lib);+ if (newVal) {+ // Only stop playback if the current item isn't downloaded+ final dl = DownloadService();+ final itemId = _player.currentItemId;+ final epId = _player.currentEpisodeId;+ final dlKey = epId != null && itemId != null+ ? '$itemId-$epId'+ : itemId;+ if (dlKey == null || !dl.isDownloaded(dlKey)) {+ _stopAndRefresh(lib);+ }+ }},child: AnimatedContainer(duration: const Duration(milliseconds: 300),diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dartindex d944b86a..ba7a6cb0 100644--- a/lib/screens/settings_screen.dart+++ b/lib/screens/settings_screen.dart@@ -34,6 +34,9 @@ class _SettingsScreenState extends State<SettingsScreen> {AutoRewindSettings _rewindSettings = const AutoRewindSettings();double _defaultSpeed = 1.0;bool _wifiOnlyDownloads = false;+ bool _rollingDownload = false;+ int _rollingDownloadCount = 3;+ bool _rollingDownloadDeleteFinished = false;bool _showBookSlider = false;bool _speedAdjustedTime = true;int _forwardSkip = 30;@@ -67,6 +70,9 @@ class _SettingsScreenState extends State<SettingsScreen> {final s = await AutoRewindSettings.load();final speed = await PlayerSettings.getDefaultSpeed();final wifiOnly = await PlayerSettings.getWifiOnlyDownloads();+ final rolling = await PlayerSettings.getRollingDownload();+ final rollingCount = await PlayerSettings.getRollingDownloadCount();+ final rollingDelete = await PlayerSettings.getRollingDownloadDeleteFinished();final bookSlider = await PlayerSettings.getShowBookSlider();final speedAdj = await PlayerSettings.getSpeedAdjustedTime();final fwd = await PlayerSettings.getForwardSkip();@@ -92,6 +98,9 @@ class _SettingsScreenState extends State<SettingsScreen> {_rewindSettings = s;_defaultSpeed = speed;_wifiOnlyDownloads = wifiOnly;+ _rollingDownload = rolling;+ _rollingDownloadCount = rollingCount;+ _rollingDownloadDeleteFinished = rollingDelete;_showBookSlider = bookSlider;_speedAdjustedTime = speedAdj;_forwardSkip = fwd;@@ -422,7 +431,7 @@ class _SettingsScreenState extends State<SettingsScreen> {title: 'Appearance',cs: cs,isExpanded: _expandedSection == 'Appearance',- onExpansionChanged: (v) => setState(() => _expandedSection = v ? 'Appearance' : null),+ onExpansionChanged: (v) => setState(() { if (v) _expandedSection = 'Appearance'; else if (_expandedSection == 'Appearance') _expandedSection = null; }),children: [Padding(padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),@@ -464,7 +473,7 @@ class _SettingsScreenState extends State<SettingsScreen> {title: 'Absorbing Cards',cs: cs,isExpanded: _expandedSection == 'Absorbing Cards',- onExpansionChanged: (v) => setState(() => _expandedSection = v ? 'Absorbing Cards' : null),+ onExpansionChanged: (v) => setState(() { if (v) _expandedSection = 'Absorbing Cards'; else if (_expandedSection == 'Absorbing Cards') _expandedSection = null; }),children: [SwitchListTile(title: const Text('Full screen player'),@@ -558,7 +567,7 @@ class _SettingsScreenState extends State<SettingsScreen> {title: 'Playback',cs: cs,isExpanded: _expandedSection == 'Playback',- onExpansionChanged: (v) => setState(() => _expandedSection = v ? 'Playback' : null),+ onExpansionChanged: (v) => setState(() { if (v) _expandedSection = 'Playback'; else if (_expandedSection == 'Playback') _expandedSection = null; }),children: [// Default speedPadding(@@ -752,7 +761,7 @@ class _SettingsScreenState extends State<SettingsScreen> {title: 'Sleep Timer',cs: cs,isExpanded: _expandedSection == 'Sleep Timer',- onExpansionChanged: (v) => setState(() => _expandedSection = v ? 'Sleep Timer' : null),+ onExpansionChanged: (v) => setState(() { if (v) _expandedSection = 'Sleep Timer'; else if (_expandedSection == 'Sleep Timer') _expandedSection = null; }),children: [SwitchListTile(title: const Text('Shake to add time'),@@ -935,7 +944,7 @@ class _SettingsScreenState extends State<SettingsScreen> {title: 'Downloads & Storage',cs: cs,isExpanded: _expandedSection == 'Downloads & Storage',- onExpansionChanged: (v) => setState(() => _expandedSection = v ? 'Downloads & Storage' : null),+ onExpansionChanged: (v) => setState(() { if (v) _expandedSection = 'Downloads & Storage'; else if (_expandedSection == 'Downloads & Storage') _expandedSection = null; }),children: [SwitchListTile(title: const Text('Download over Wi-Fi only'),@@ -949,6 +958,59 @@ class _SettingsScreenState extends State<SettingsScreen> {} : null,),const Divider(height: 1, indent: 16, endIndent: 16),+ SwitchListTile(+ title: const Text('Rolling downloads'),+ subtitle: Text(+ _rollingDownload+ ? 'Auto-download next items in a series or podcast'+ : 'Off — manual downloads only',+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ value: _rollingDownload,+ onChanged: _loaded ? (v) {+ setState(() => _rollingDownload = v);+ PlayerSettings.setRollingDownload(v);+ } : null,+ ),+ if (_rollingDownload) ...[+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text('Keep next', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),+ const SizedBox(height: 8),+ SizedBox(width: double.infinity, child: SegmentedButton<int>(+ segments: const [+ ButtonSegment(value: 2, label: Text('2')),+ ButtonSegment(value: 3, label: Text('3')),+ ButtonSegment(value: 4, label: Text('4')),+ ButtonSegment(value: 5, label: Text('5')),+ ],+ selected: {_rollingDownloadCount},+ onSelectionChanged: (v) {+ setState(() => _rollingDownloadCount = v.first);+ PlayerSettings.setRollingDownloadCount(v.first);+ },+ )),+ const SizedBox(height: 8),+ ],+ ),+ ),+ SwitchListTile(+ title: const Text('Delete finished downloads'),+ subtitle: Text(+ _rollingDownloadDeleteFinished+ ? 'Finished items are removed to save space'+ : 'Off — finished downloads kept',+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ value: _rollingDownloadDeleteFinished,+ onChanged: _loaded ? (v) {+ setState(() => _rollingDownloadDeleteFinished = v);+ PlayerSettings.setRollingDownloadDeleteFinished(v);+ } : null,+ ),+ ],+ const Divider(height: 1, indent: 16, endIndent: 16),ListTile(leading: Icon(Icons.folder_outlined, color: cs.primary),title: const Text('Download location'),@@ -988,7 +1050,7 @@ class _SettingsScreenState extends State<SettingsScreen> {title: 'Library',cs: cs,isExpanded: _expandedSection == 'Library',- onExpansionChanged: (v) => setState(() => _expandedSection = v ? 'Library' : null),+ onExpansionChanged: (v) => setState(() { if (v) _expandedSection = 'Library'; else if (_expandedSection == 'Library') _expandedSection = null; }),children: [SwitchListTile(title: const Text('Hide eBook-only titles'),@@ -1045,7 +1107,7 @@ class _SettingsScreenState extends State<SettingsScreen> {title: 'Permissions',cs: cs,isExpanded: _expandedSection == 'Permissions',- onExpansionChanged: (v) => setState(() => _expandedSection = v ? 'Permissions' : null),+ onExpansionChanged: (v) => setState(() { if (v) _expandedSection = 'Permissions'; else if (_expandedSection == 'Permissions') _expandedSection = null; }),children: [ListTile(leading: const Icon(Icons.notifications_outlined),@@ -1106,7 +1168,7 @@ class _SettingsScreenState extends State<SettingsScreen> {title: 'Issues & Support',cs: cs,isExpanded: _expandedSection == 'Issues & Support',- onExpansionChanged: (v) => setState(() => _expandedSection = v ? 'Issues & Support' : null),+ onExpansionChanged: (v) => setState(() { if (v) _expandedSection = 'Issues & Support'; else if (_expandedSection == 'Issues & Support') _expandedSection = null; }),children: [ListTile(leading: Icon(Icons.bug_report_outlined, color: cs.onSurfaceVariant),diff --git a/lib/services/api_service.dart b/lib/services/api_service.dartindex f4d077bc..cf12dafe 100644--- a/lib/services/api_service.dart+++ b/lib/services/api_service.dart@@ -372,9 +372,10 @@ class ApiService {/// Start a playback session for a library item./// POST /api/items/:id/play/// Returns the full session object including audioTracks with contentUrl.- Future<Map<String, dynamic>?> startPlaybackSession(String itemId) async {+ Future<Map<String, dynamic>?> startPlaybackSession(String itemId, {String? episodeId}) async {try {- final url = '$_cleanBaseUrl/api/items/$itemId/play';+ final epPath = episodeId != null ? '/$episodeId' : '';+ final url = '$_cleanBaseUrl/api/items/$itemId/play$epPath';debugPrint('[ABS] Starting playback session: POST $url');final response = await http.post(Uri.parse(url),@@ -464,8 +465,13 @@ class ApiService {/// GET /api/me/progress/:idFuture<Map<String, dynamic>?> getItemProgress(String itemId) async {try {+ // Podcast episodes use compound key "showId-episodeId" →+ // ABS endpoint: /api/me/progress/{showId}/{episodeId}+ final progressPath = itemId.length > 36+ ? '${itemId.substring(0, 36)}/${itemId.substring(37)}'+ : itemId;final resp = await http.get(- Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId'),+ Uri.parse('$_cleanBaseUrl/api/me/progress/$progressPath'),headers: _headers,).timeout(const Duration(seconds: 10));if (resp.statusCode == 200) {@@ -490,10 +496,13 @@ class ApiService {'progress': duration > 0 ? currentTime / duration : 0,'isFinished': isFinished,});- debugPrint('[API] updateProgress PATCH /api/me/progress/$itemId');+ final progressPath = itemId.length > 36+ ? '${itemId.substring(0, 36)}/${itemId.substring(37)}'+ : itemId;+ debugPrint('[API] updateProgress PATCH /api/me/progress/$progressPath');debugPrint('[API] updateProgress body: currentTime=$currentTime');final resp = await http.patch(- Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId'),+ Uri.parse('$_cleanBaseUrl/api/me/progress/$progressPath'),headers: _headers,body: body,).timeout(const Duration(seconds: 10));@@ -530,8 +539,11 @@ class ApiService {/// DELETE /api/me/progress/:id — fully remove progress entryFuture<bool> deleteProgress(String itemId) async {try {+ final progressPath = itemId.length > 36+ ? '${itemId.substring(0, 36)}/${itemId.substring(37)}'+ : itemId;final resp = await http.delete(- Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId'),+ Uri.parse('$_cleanBaseUrl/api/me/progress/$progressPath'),headers: _headers,).timeout(const Duration(seconds: 10));debugPrint('[API] deleteProgress response: ${resp.statusCode} ${resp.body}');@@ -545,14 +557,21 @@ class ApiService {/// Reset progress to zero.Future<bool> resetProgress(String itemId, double duration) async {try {+ final progressPath = itemId.length > 36+ ? '${itemId.substring(0, 36)}/${itemId.substring(37)}'+ : itemId;+ final isCompound = itemId.length > 36;+ final apiItemId = isCompound ? itemId.substring(0, 36) : itemId;+ final episodeId = isCompound ? itemId.substring(37) : null;+// DELETE progress entryawait http.delete(- Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId'),+ Uri.parse('$_cleanBaseUrl/api/me/progress/$progressPath'),headers: _headers,).timeout(const Duration(seconds: 10));// Start session at 0 and close — forces server to update position- final sessionData = await startPlaybackSession(itemId);+ final sessionData = await startPlaybackSession(apiItemId, episodeId: episodeId);if (sessionData != null) {final sessionId = sessionData['id'] as String?;if (sessionId != null) {@@ -563,7 +582,7 @@ class ApiService {// PATCH last to hide from continue listening (after session sync)await http.patch(- Uri.parse('$_cleanBaseUrl/api/me/progress/$itemId'),+ Uri.parse('$_cleanBaseUrl/api/me/progress/$progressPath'),headers: _headers,body: jsonEncode({'currentTime': 0,diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex a46a77c8..03d73fc6 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -89,6 +89,15 @@ class PlayerSettings {static Future<bool> getWifiOnlyDownloads() => _get('wifiOnlyDownloads', false);static Future<void> setWifiOnlyDownloads(bool value) => _set('wifiOnlyDownloads', value);+ static Future<bool> getRollingDownload() => _get('rollingDownload', false);+ static Future<void> setRollingDownload(bool value) => _set('rollingDownload', value);++ static Future<int> getRollingDownloadCount() => _get('rollingDownloadCount', 3);+ static Future<void> setRollingDownloadCount(int value) => _set('rollingDownloadCount', value);++ static Future<bool> getRollingDownloadDeleteFinished() => _get('rollingDownloadDeleteFinished', false);+ static Future<void> setRollingDownloadDeleteFinished(bool value) => _set('rollingDownloadDeleteFinished', value);+static Future<bool> getAutoPlayNextBook() => _get('autoPlayNextBook', false);static Future<void> setAutoPlayNextBook(bool value) => _set('autoPlayNextBook', value);@@ -697,6 +706,13 @@ class AudioPlayerService extends ChangeNotifier {_onBookFinishedCallback = cb;}+ /// Called when a new item starts playing. Used by LibraryProvider to trigger+ /// rolling downloads for the next items in a series/podcast.+ static void Function(String key)? _onPlayStartedCallback;+ static void setOnPlayStartedCallback(void Function(String key)? cb) {+ _onPlayStartedCallback = cb;+ }+/// Called when a podcast episode starts playing. Used by AppShell to/// auto-navigate to the Absorbing tab.static void Function()? _onEpisodePlayStartedCallback;@@ -931,6 +947,9 @@ class AudioPlayerService extends ChangeNotifier {// Set true when BT/headphones disconnect so the interruption handler// won't auto-resume playback onto the phone speaker.static bool _noisyPause = false;+ /// True when BT/headphones just disconnected — callers can check before+ /// starting new playback to avoid blasting audio on the phone speaker.+ static bool get wasNoisyPause => _noisyPause;static Future<void> _configureAudioSession() async {final session = await AudioSession.instance;@@ -1036,6 +1055,9 @@ class AudioPlayerService extends ChangeNotifier {// Progress key: compound for episodes, plain for booksfinal progressKey = episodeId != null ? '$itemId-$episodeId' : itemId;+ // Notify rolling download listener that a new item is playing+ _onPlayStartedCallback?.call(progressKey);+// Check for local saved position (always prefer local — it's the freshest)final localPos = await _progressSync.getSavedPosition(progressKey);if (localPos > 0 && startTime == 0) {diff --git a/lib/services/download_service.dart b/lib/services/download_service.dartindex 11acc918..81393f4a 100644--- a/lib/services/download_service.dart+++ b/lib/services/download_service.dart@@ -222,6 +222,7 @@ class DownloadService extends ChangeNotifier {if (json != null) {try {final map = jsonDecode(json) as Map<String, dynamic>;+ final orphanIds = <String>[];for (final entry in map.entries) {final info =DownloadInfo.fromJson(entry.value as Map<String, dynamic>);@@ -239,7 +240,28 @@ class DownloadService extends ChangeNotifier {}if (allExist) {_downloads[entry.key] = info;+ } else {+ orphanIds.add(entry.key);}+ } else {+ // Stale downloading/error entries from a previous crash+ orphanIds.add(entry.key);+ }+ }+ // Clean up partial/orphaned files on disk+ if (orphanIds.isNotEmpty) {+ final basePath = await downloadBasePath;+ final internalBase = await _internalBasePath;+ for (final id in orphanIds) {+ debugPrint('[Download] Cleaning up orphaned entry: $id');+ try {+ final dir = Directory('$basePath/$id');+ if (dir.existsSync()) dir.deleteSync(recursive: true);+ } catch (_) {}+ try {+ final coverDir = Directory('$internalBase/$id');+ if (coverDir.existsSync()) coverDir.deleteSync(recursive: true);+ } catch (_) {}}}} catch (e) {@@ -625,15 +647,16 @@ class DownloadService extends ChangeNotifier {final totalBytes = response.contentLength ?? -1;int receivedBytes = 0;final sink = file.openWrite();-- await for (final chunk in response.stream.timeout(const Duration(seconds: 60))) {- sink.add(chunk);- receivedBytes += chunk.length;- trackProgress[i] = totalBytes > 0 ? receivedBytes / totalBytes : 0.5;- _updateProgress();+ try {+ await for (final chunk in response.stream.timeout(const Duration(seconds: 60))) {+ sink.add(chunk);+ receivedBytes += chunk.length;+ trackProgress[i] = totalBytes > 0 ? receivedBytes / totalBytes : 0.5;+ _updateProgress();+ }+ } finally {+ await sink.close();}-- await sink.close();localPaths[i] = filePath;}@@ -694,14 +717,22 @@ class DownloadService extends ChangeNotifier {debugPrint('[Download] Complete: $title (${completedPaths.length} files)');} catch (e) {- if (_cancelled) {- debugPrint('[Download] Cancelled: $title');- _downloads.remove(itemId);- // Clean up partial files+ // Clean up partial files on any failure+ try {final basePath = await downloadBasePath;final bookDir = Directory('$basePath/$itemId');if (bookDir.existsSync()) bookDir.deleteSync(recursive: true);+ } catch (_) {}++ if (_cancelled) {+ debugPrint('[Download] Cancelled: $title');+ _downloads.remove(itemId);} else {+ final isStorageFull = e.toString().contains('No space left') ||+ e.toString().contains('ENOSPC');+ final errorMsg = isStorageFull+ ? 'Not enough storage space'+ : 'Download failed';debugPrint('[Download] Error: $e');_downloads[itemId] = DownloadInfo(itemId: itemId,@@ -712,7 +743,7 @@ class DownloadService extends ChangeNotifier {);// Show error notificationtry {- await notif.showError(title: title, message: 'Download failed: $title');+ await notif.showError(title: title, message: '$errorMsg: $title');} catch (notifErr) {debugPrint('[Download] showError non-fatal error: $notifErr');}@@ -729,6 +760,13 @@ class DownloadService extends ChangeNotifier {final info = _downloads[itemId];if (info == null) return;+ // Stop playback if this item is currently playing to avoid crashes+ final player = AudioPlayerService();+ if (player.currentItemId == itemId ||+ (itemId.length > 36 && player.currentItemId == itemId.substring(0, 36))) {+ await player.stop();+ }+for (final path in info.localPaths) {try {final file = File(path);@@ -742,6 +780,13 @@ class DownloadService extends ChangeNotifier {if (bookDir.existsSync()) bookDir.deleteSync(recursive: true);} catch (_) {}+ // Clean up cached cover image (stored separately in internal storage)+ try {+ final internalBase = await _internalBasePath;+ final coverDir = Directory('$internalBase/$itemId');+ if (coverDir.existsSync()) coverDir.deleteSync(recursive: true);+ } catch (_) {}+_downloads.remove(itemId);await _save();notifyListeners();diff --git a/lib/services/progress_sync_service.dart b/lib/services/progress_sync_service.dartindex 4c1a190d..e12a8801 100644--- a/lib/services/progress_sync_service.dart+++ b/lib/services/progress_sync_service.dart@@ -192,7 +192,12 @@ class ProgressSyncService {debugPrint('[Sync] Local is newer for $itemId: local=$localTime s ($localTimestamp) vs server=$serverTime s ($serverTimestamp) — pushing');}- final session = await api.startPlaybackSession(itemId);+ // Podcast episodes use compound key "showId-episodeId"+ final isCompound = itemId.length > 36;+ final apiItemId = isCompound ? itemId.substring(0, 36) : itemId;+ final episodeId = isCompound ? itemId.substring(37) : null;++ final session = await api.startPlaybackSession(apiItemId, episodeId: episodeId);if (session != null) {final sessionId = session['id'] as String?;if (sessionId != null) {