A cross platform Audiobookshelf client for Android and iOS
Dart
Improve podcast episode handling on absorbing page
Nathan Poulson5c98175dbbb4
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex b397f0c9..37233026 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -197,14 +197,22 @@ class LibraryProvider extends ChangeNotifier {Map<String, dynamic>? getProgressData(String? itemId) {if (itemId == null) return null;if (_resetItems.contains(itemId)) return null;- return _progressMap[itemId];+ final data = _progressMap[itemId];+ if (_locallyFinishedItems.contains(itemId)) {+ return {...?data, 'isFinished': true};+ }+ return data;}/// Get raw progress data for a podcast episode.Map<String, dynamic>? getEpisodeProgressData(String itemId, String episodeId) {final key = '$itemId-$episodeId';if (_resetItems.contains(key)) return null;- return _progressMap[key];+ final data = _progressMap[key];+ if (_locallyFinishedItems.contains(key)) {+ return {...?data, 'isFinished': true};+ }+ return data;}/// Count of books marked as finished in the progress map.@@ -251,6 +259,7 @@ class LibraryProvider extends ChangeNotifier {void resetProgressFor(String itemId) {_progressMap.remove(itemId);_localProgressOverrides.remove(itemId);+ _locallyFinishedItems.remove(itemId);_resetItems.add(itemId);notifyListeners();}@@ -592,6 +601,12 @@ class LibraryProvider extends ChangeNotifier {if (me != null) {final progressList = me['mediaProgress'] as List<dynamic>?;if (progressList != null) {+ // Preserve locally-set isFinished flags that the server may not+ // have processed yet (e.g. episode just finished, server lags).+ final localFinished = <String, Map<String, dynamic>>{};+ if (_lastFinishedItemId != null && _progressMap.containsKey(_lastFinishedItemId!)) {+ localFinished[_lastFinishedItemId!] = _progressMap[_lastFinishedItemId!]!;+ }_progressMap = {};for (final mp in progressList) {if (mp is Map<String, dynamic>) {@@ -603,6 +618,14 @@ class LibraryProvider extends ChangeNotifier {}}}+ // Re-apply local finished state if the server hasn't caught up+ for (final entry in localFinished.entries) {+ final serverEntry = _progressMap[entry.key];+ final serverHasFinished = serverEntry?['isFinished'] == true;+ if (serverEntry == null || !serverHasFinished) {+ _progressMap[entry.key] = {...?serverEntry, ...entry.value};+ }+ }}}} catch (_) {}@@ -677,12 +700,10 @@ class LibraryProvider extends ChangeNotifier {String? getCoverUrl(String? itemId, {int width = 400}) {if (itemId == null) return null;- // For podcast episodes stored under composite keys like "showId-ep_xxx",+ // For podcast episodes stored under composite keys ("showUUID-episodeId"),// extract the show ID for API calls so the server returns the show cover.- final isCompositeKey = itemId.contains('-ep_');- final apiItemId = isCompositeKey- ? itemId.substring(0, itemId.indexOf('-ep_'))- : itemId;+ final isCompositeKey = itemId.length > 36;+ final apiItemId = isCompositeKey ? itemId.substring(0, 36) : itemId;// Try API first when onlineif (_api != null && !isOffline) {@@ -725,6 +746,8 @@ class LibraryProvider extends ChangeNotifier {Map<String, Map<String, dynamic>> _absorbingItemCache = {};// Track last finished item so we can insert next-in-series after itString? _lastFinishedItemId;+ // Robust local finished state — survives _refreshProgress rebuilds+ final Set<String> _locallyFinishedItems = {};Set<String> get manualAbsorbAdds => _manualAbsorbAdds;Set<String> get manualAbsorbRemoves => _manualAbsorbRemoves;@@ -856,8 +879,8 @@ class LibraryProvider extends ChangeNotifier {// Collect show IDs we know about (from sections or cache)final knownShowIds = <String>{};for (final key in _absorbingBookIds) {- if (key.contains('-')) {- knownShowIds.add(key.split('-').first);+ if (key.length > 36) {+ knownShowIds.add(key.substring(0, 36));}}// Also add show entities from sections@@ -865,15 +888,14 @@ class LibraryProvider extends ChangeNotifier {for (final entry in _progressMap.entries) {final key = entry.key;- if (!key.contains('-')) continue; // not an episode entry+ if (key.length <= 36) continue; // not an episode entry (plain UUID)final mp = entry.value;if (mp['isFinished'] == true) continue; // skip finished episodesfinal progress = (mp['progress'] as num?)?.toDouble() ?? 0;if (progress <= 0) continue; // never actually played- final parts = key.split('-');- final showId = parts[0];- final episodeId = parts.sublist(1).join('-');+ final showId = key.substring(0, 36);+ final episodeId = key.substring(37);if (_absorbingBookIds.contains(key)) continue; // already have itif (_manualAbsorbRemoves.contains(key)) continue; // user removed it@@ -916,7 +938,7 @@ class LibraryProvider extends ChangeNotifier {if (allowedKeys.contains(key)) continue; // still in a live sectionif (_manualAbsorbAdds.contains(key)) continue; // user explicitly added it// Keep if there is any recorded progress- final hasProgress = key.contains('-')+ final hasProgress = key.length > 36? _progressMap.containsKey(key): _progressMap.keys.any((k) => k == key || k.startsWith('$key-'));if (!hasProgress) toRemove.add(key);@@ -931,7 +953,7 @@ class LibraryProvider extends ChangeNotifier {final migrateRemove = <String>[];final migrateAdd = <String, Map<String, dynamic>>{};for (final key in _absorbingBookIds) {- if (key.contains('-')) continue; // already compound+ if (key.length > 36) continue; // already compoundfinal cached = _absorbingItemCache[key];if (cached == null) continue;final re = cached['recentEpisode'] as Map<String, dynamic>?;@@ -1010,19 +1032,36 @@ class LibraryProvider extends ChangeNotifier {/// Re-allow an item that was previously removed, so it can reappear in Absorbing./// Called when the user explicitly plays an item that they had removed./// [key] can be a plain itemId (books) or compound "itemId-episodeId" (podcasts).- void unblockFromAbsorbing(String key) {+ void unblockFromAbsorbing(String key, {String? episodeTitle, double? episodeDuration}) {+ // Clear stale finished state so the overlay doesn't persist when replaying+ _localProgressOverrides.remove(key);+ _locallyFinishedItems.remove(key);+ final pm = _progressMap[key];+ if (pm != null && pm['isFinished'] == true) {+ _progressMap[key] = {...pm, 'isFinished': false};+ }bool changed = _manualAbsorbRemoves.remove(key);+ final isCompound = key.length > 36;if (!_absorbingBookIds.contains(key)) {_absorbingIdsAdd(key);changed = true;// Populate the cache from current sections if available- final isCompound = key.contains('-');- final showId = isCompound ? key.split('-').first : key;+ final showId = isCompound ? key.substring(0, 36) : key;for (final section in _personalizedSections) {for (final e in (section['entities'] as List<dynamic>? ?? [])) {if (e is Map<String, dynamic> && (e['id'] as String?) == showId) {if (isCompound) {- _absorbingItemCache[key] = {...e, '_absorbingKey': key};+ final episodeId = key.substring(37);+ final cached = Map<String, dynamic>.from(e);+ cached['_absorbingKey'] = key;+ // Ensure recentEpisode points to the correct episode+ cached['recentEpisode'] = {+ ...?(cached['recentEpisode'] as Map<String, dynamic>?),+ 'id': episodeId,+ if (episodeTitle != null) 'title': episodeTitle,+ if (episodeDuration != null && episodeDuration > 0) 'duration': episodeDuration,+ };+ _absorbingItemCache[key] = cached;} else {_absorbingItemCache[key] = e;}@@ -1031,6 +1070,23 @@ class LibraryProvider extends ChangeNotifier {}}}+ // Ensure existing cache entry has _absorbingKey and correct recentEpisode+ if (isCompound && _absorbingItemCache.containsKey(key)) {+ final cached = _absorbingItemCache[key]!;+ if (cached['_absorbingKey'] == null) cached['_absorbingKey'] = key;+ final episodeId = key.substring(37);+ final re = cached['recentEpisode'] as Map<String, dynamic>?;+ if (re == null || (re['id'] as String?) != episodeId) {+ cached['recentEpisode'] = {+ ...?re,+ 'id': episodeId,+ if (episodeTitle != null) 'title': episodeTitle,+ if (episodeDuration != null && episodeDuration > 0) 'duration': episodeDuration,+ };+ } else if (episodeTitle != null && re['title'] == null) {+ cached['recentEpisode'] = {...re, 'title': episodeTitle};+ }+ }if (changed) _saveManualAbsorbing();}@@ -1047,6 +1103,7 @@ class LibraryProvider extends ChangeNotifier {/// Mark an item as finished locally so the overlay appears immediately,/// before the next server refresh confirms isFinished.+ /// [itemId] can be a plain book ID or a compound "showId-episodeId" key./// If [skipRefresh] is true, the caller handles refreshing (e.g./// book_detail_sheet calls refresh() after api.markFinished).void markFinishedLocally(String itemId, {bool skipRefresh = false}) {@@ -1055,10 +1112,34 @@ class LibraryProvider extends ChangeNotifier {_progressMap[itemId] = {...existing, 'isFinished': true};_localProgressOverrides[itemId] = 1.0;_lastFinishedItemId = itemId;- // Move finished book to front so the series continuation lands at index 1+ _locallyFinishedItems.add(itemId);+ // Move finished item to front so the next-in-series/episode lands at index 1_absorbingBookIds.remove(itemId);_absorbingBookIds.insert(0, itemId);+ // Ensure cache entry has _absorbingKey so the card can extract the episode ID+ if (itemId.length > 36) {+ final cached = _absorbingItemCache[itemId];+ if (cached != null && cached['_absorbingKey'] == null) {+ cached['_absorbingKey'] = itemId;+ }+ }notifyListeners();++ // 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;+ if (isCompound && !skipRefresh && _api != null && !isOffline) {+ // UUIDs are always 36 chars; compound key = "showUUID-episodeId"+ final showId = itemId.substring(0, 36);+ final episodeId = itemId.substring(37);+ _addNextPodcastEpisode(showId, episodeId, itemId).then((_) {+ if (_selectedLibraryId != null && !isOffline) {+ loadPersonalizedView(force: true);+ }+ });+ return; // skip the default refresh below — handled above+ }+if (!skipRefresh && _api != null && _selectedLibraryId != null && !isOffline) {// Brief delay so the server has time to populate continue-seriesFuture.delayed(const Duration(milliseconds: 500), () {@@ -1067,6 +1148,58 @@ class LibraryProvider extends ChangeNotifier {}}+ /// Fetch the podcast show's episode list and insert the next episode+ /// (chronologically after the finished one) into the absorbing list.+ Future<void> _addNextPodcastEpisode(String showId, String finishedEpisodeId, String finishedKey) async {+ // Brief delay so the server has time to register the finished state+ await Future.delayed(const Duration(milliseconds: 500));+ try {+ 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?) == finishedEpisodeId,+ );+ if (currentIdx < 0 || currentIdx >= episodes.length - 1) return;++ final nextEp = episodes[currentIdx + 1] as Map<String, dynamic>;+ final nextEpId = nextEp['id'] as String?;+ if (nextEpId == null) return;++ final nextKey = '$showId-$nextEpId';+ if (_manualAbsorbRemoves.contains(nextKey)) return;+ if (_progressMap[nextKey]?['isFinished'] == true) return;++ // Build a synthetic cache entry from the show data+ final showData = _absorbingItemCache.values+ .cast<Map<String, dynamic>?>()+ .firstWhere(+ (c) => c != null && (c['id'] as String?) == showId,+ orElse: () => null,+ ) ?? fullItem;+ final syntheticEntry = Map<String, dynamic>.from(showData);+ syntheticEntry['recentEpisode'] = Map<String, dynamic>.from(nextEp);+ syntheticEntry['_absorbingKey'] = nextKey;++ // Mark as manually added so pruning won't remove it (no progress yet)+ _manualAbsorbAdds.add(nextKey);+ _absorbingIdsAdd(nextKey, afterKey: finishedKey);+ _absorbingItemCache[nextKey] = syntheticEntry;+ await _saveManualAbsorbing();+ notifyListeners();+ } catch (_) {}+ }+/// 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 fd26ae51..79a8450a 100644--- a/lib/screens/absorbing_screen.dart+++ b/lib/screens/absorbing_screen.dart@@ -82,7 +82,10 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {final playingKey = _player.currentEpisodeId != null? '${_player.currentItemId!}-${_player.currentEpisodeId!}': _player.currentItemId!;- lib.unblockFromAbsorbing(playingKey);+ lib.unblockFromAbsorbing(playingKey,+ episodeTitle: _player.currentEpisodeTitle,+ episodeDuration: _player.currentEpisodeId != null ? _player.totalDuration : null,+ );// Persist so this item stays at front even if the app is killed_lastFinishedId = playingKey;ScopedPrefs.setString('absorbing_last_finished', playingKey);@@ -272,8 +275,9 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {// absorbingBookIds now contains compound keys for podcast episodes.final selectedLibraryId = lib.selectedLibraryId;final items = <Map<String, dynamic>>[];+ final skippedKeys = <String, String>{};for (final key in lib.absorbingBookIds) {- if (removes.contains(key)) continue;+ if (removes.contains(key)) { skippedKeys[key] = 'removed'; continue; }// Prefer fresh data from current library's sectionsfinal fromSection = sectionLookup[key];if (fromSection != null) {@@ -286,10 +290,13 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {final itemLibId = cached['libraryId'] as String?;if (selectedLibraryId == null || itemLibId == null || itemLibId == selectedLibraryId) {items.add(cached);+ } else {+ skippedKeys[key] = 'wrong library (item=$itemLibId, selected=$selectedLibraryId)';}+ } else {+ skippedKeys[key] = 'not in section or cache';}}-// If the currently playing/casting item isn't in the list, add it at the front.// For podcast episodes, match by compound key.// Skip if the playing item belongs to a different library type.diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex febc3c23..fd5bd85c 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -1437,9 +1437,9 @@ class AudioPlayerService extends ChangeNotifier {}// Notify LibraryProvider before clearing state so it can update isFinished locally.- // Episodes don't mark the whole show as finished.- if (itemId != null && episodeId == null) {- _onBookFinishedCallback?.call(itemId);+ if (itemId != null) {+ final key = episodeId != null ? '$itemId-$episodeId' : itemId;+ _onBookFinishedCallback?.call(key);}// Clear state (player already stopped at top of method)diff --git a/lib/services/chromecast_service.dart b/lib/services/chromecast_service.dartindex cbd265f3..f33eb8be 100644--- a/lib/services/chromecast_service.dart+++ b/lib/services/chromecast_service.dart@@ -542,9 +542,10 @@ class ChromecastService extends ChangeNotifier {);}- // Notify LibraryProvider (episodes don't mark the whole show as finished)- if (itemId != null && episodeId == null) {- _onBookFinishedCallback?.call(itemId);+ // Notify LibraryProvider so it can update isFinished locally+ if (itemId != null) {+ final key = episodeId != null ? '$itemId-$episodeId' : itemId;+ _onBookFinishedCallback?.call(key);}// Clear casting state but keep connectiondiff --git a/lib/services/download_service.dart b/lib/services/download_service.dartindex 85b0ba77..876f2973 100644--- a/lib/services/download_service.dart+++ b/lib/services/download_service.dart@@ -265,10 +265,10 @@ class DownloadService extends ChangeNotifier {String? coverUrl = info.coverUrl;String? localCoverPath = info.localCoverPath;- // For podcast episodes, the itemId is a composite "showId-episodeId".- // Extract the library item ID for API calls.- final apiItemId = info.itemId.contains('-ep_')- ? info.itemId.substring(0, info.itemId.indexOf('-ep_'))+ // For podcast episodes, the itemId is a composite "showUUID-episodeId".+ // Extract the library item ID (first 36 chars = UUID) for API calls.+ final apiItemId = info.itemId.length > 36+ ? info.itemId.substring(0, 36): info.itemId;// Enrich missing title/author from serverdiff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dartindex 7b29bd3e..9a2f222a 100644--- a/lib/widgets/absorbing_card.dart+++ b/lib/widgets/absorbing_card.dart@@ -74,7 +74,15 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli// For inactive podcast show cards: recentEpisode is embedded in the continue-listening entityMap<String, dynamic>? get _recentEpisode => widget.item['recentEpisode'] as Map<String, dynamic>?;- String? get _episodeId => _recentEpisode?['id'] as String?;+ // Episode ID: prefer recentEpisode, fall back to compound absorbing key+ String? get _episodeId {+ final re = _recentEpisode;+ if (re != null) return re['id'] as String?;+ // Compound absorbing keys are "showUUID-episodeId" (>36 chars)+ final absKey = widget.item['_absorbingKey'] as String?;+ if (absKey != null && absKey.length > 36) return absKey.substring(37);+ return null;+ }// Use episode duration for inactive podcast show cards (show duration is aggregate/incorrect)double get _effectiveDuration {if (!_isActive && _recentEpisode != null) {@@ -637,7 +645,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli// ── Chapter pill-scrubber (same width as book bar) ──Padding(padding: const EdgeInsets.symmetric(horizontal: 20),- child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: _isPodcastEpisode ? 0.0 : progress, staticDuration: _isPodcastEpisode ? widget.player.totalDuration : _effectiveDuration, chapters: _chapters, showBookBar: false, showChapterBar: true, chapterName: _isPodcastEpisode ? (widget.player.currentEpisodeTitle ?? widget.player.currentTitle ?? _title) : (_episodeId != null && !_isActive ? (_recentEpisode!['title'] as String? ?? _title) : _chapterName(chapterIdx)), chapterIndex: chapterIdx, totalChapters: totalChapters, itemId: _itemId),+ child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: _isPodcastEpisode ? 0.0 : progress, staticDuration: _isPodcastEpisode ? widget.player.totalDuration : _effectiveDuration, chapters: _chapters, showBookBar: false, showChapterBar: true, chapterName: _isPodcastEpisode ? (widget.player.currentEpisodeTitle ?? widget.player.currentTitle ?? _title) : (_episodeId != null && !_isActive ? (_recentEpisode?['title'] as String? ?? _title) : _chapterName(chapterIdx)), chapterIndex: chapterIdx, totalChapters: totalChapters, itemId: _itemId),),// ── Controls + buttons ──Expanded(@@ -824,14 +832,23 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClifinal api = auth.apiService;if (api == null) { setState(() => _isStarting = false); return; }final lib = context.read<LibraryProvider>();- await api.resetProgress(_itemId, _duration);- lib.resetProgressFor(_itemId);+ final progressKey = _episodeId != null ? '$_itemId-$_episodeId' : _itemId;+ if (_episodeId != null) {+ await api.updateEpisodeProgress(_itemId, _episodeId!,+ currentTime: 0, duration: _effectiveDuration, isFinished: false);+ } else {+ await api.resetProgress(_itemId, _duration);+ }+ lib.resetProgressFor(progressKey);// Clear the locally saved position so playItem() doesn't override startTime- // back to the end of the book (where it was saved on completion)- await ProgressSyncService().deleteLocal(_itemId);+ // back to the end (where it was saved on completion)+ await ProgressSyncService().deleteLocal(progressKey);await widget.player.playItem(api: api, itemId: _itemId, title: _title, author: _author,- coverUrl: _coverUrl, totalDuration: _duration, chapters: _chapters,+ coverUrl: _coverUrl, totalDuration: _episodeId != null ? _effectiveDuration : _duration,+ chapters: _chapters,+ episodeId: _episodeId,+ episodeTitle: _recentEpisode?['title'] as String?,);if (mounted) setState(() => _isStarting = false);}diff --git a/lib/widgets/expanded_card.dart b/lib/widgets/expanded_card.dartindex b64cd5fe..5666d401 100644--- a/lib/widgets/expanded_card.dart+++ b/lib/widgets/expanded_card.dart@@ -122,7 +122,14 @@ class _ExpandedCardState extends State<ExpandedCard> {bool get _isPodcastEpisode => _isActive && widget.player.currentEpisodeId != null;Map<String, dynamic>? get _recentEpisode => _item['recentEpisode'] as Map<String, dynamic>?;- String? get _episodeId => _recentEpisode?['id'] as String?;+ // Episode ID: prefer recentEpisode, fall back to compound absorbing key+ String? get _episodeId {+ final re = _recentEpisode;+ if (re != null) return re['id'] as String?;+ final absKey = _item['_absorbingKey'] as String?;+ if (absKey != null && absKey.length > 36) return absKey.substring(37);+ return null;+ }double get _effectiveDuration {if (!_isActive && _recentEpisode != null) {final epDur = (_recentEpisode!['duration'] as num?)?.toDouble();@@ -722,7 +729,7 @@ class _ExpandedCardState extends State<ExpandedCard> {// ── Chapter scrubber ──Padding(padding: const EdgeInsets.symmetric(horizontal: 20),- child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: _isPodcastEpisode ? 0.0 : progress, staticDuration: _isPodcastEpisode ? widget.player.totalDuration : _effectiveDuration, chapters: _chapters, showBookBar: false, showChapterBar: true, chapterName: _isPodcastEpisode ? (widget.player.currentEpisodeTitle ?? widget.player.currentTitle ?? _title) : (_episodeId != null && !_isActive ? (_recentEpisode!['title'] as String? ?? _title) : _chapterName(chapterIdx)), chapterIndex: chapterIdx, totalChapters: totalChapters, itemId: _itemId),+ child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: _isPodcastEpisode ? 0.0 : progress, staticDuration: _isPodcastEpisode ? widget.player.totalDuration : _effectiveDuration, chapters: _chapters, showBookBar: false, showChapterBar: true, chapterName: _isPodcastEpisode ? (widget.player.currentEpisodeTitle ?? widget.player.currentTitle ?? _title) : (_episodeId != null && !_isActive ? (_recentEpisode?['title'] as String? ?? _title) : _chapterName(chapterIdx)), chapterIndex: chapterIdx, totalChapters: totalChapters, itemId: _itemId),),// ── Controls + buttons ──Expanded(