A cross platform Audiobookshelf client for Android and iOS
Dart
Fix podcast queue Up Next and show episodes in the queue sheet
Barnabasf6beb1fbac6d
diff --git a/lib/providers/_lp_absorbing.dart b/lib/providers/_lp_absorbing.dartindex 1857eda5..a433322b 100644--- a/lib/providers/_lp_absorbing.dart+++ b/lib/providers/_lp_absorbing.dart@@ -1361,7 +1361,7 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {// auto_nextif (isPodCurrent) {- return _peekNextPodcastEpisode(currentItemId);+ return await _peekNextPodcastEpisode(currentItemId);}return await _peekNextBookInSeries(currentItemId);}@@ -1428,29 +1428,51 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {return _entryTitle(next);}- String? _peekNextPodcastEpisode(String currentCompoundKey) {+ Future<String?> _peekNextPodcastEpisode(String currentCompoundKey) async {if (currentCompoundKey.length < 37) return null;final showId = currentCompoundKey.substring(0, 36);final currentEpId = currentCompoundKey.substring(37);- final showCached = _absorbingItemCache.values.cast<Map<String, dynamic>>().where((e) {- final mt = e['mediaType'] as String?;- return mt == 'podcast' && (e['id'] as String?) == showId;- }).firstOrNull;- if (showCached == null) return null;- final media = showCached['media'] as Map<String, dynamic>? ?? const {};- final eps = (media['episodes'] as List<dynamic>? ?? const [])- .whereType<Map<String, dynamic>>()- .toList();- if (eps.isEmpty) return null;final self = this as LibraryProvider;- final currentIdx = eps.indexWhere((e) => e['id'] == currentEpId);++ // Mirror _addNextPodcastEpisode: the absorbing cache stores per-episode+ // synthetic entries (recentEpisode), not the full episodes list, so read+ // the full list from a cached entry that has it or fall back to the API,+ // then sort by the same advance direction. Without this the peek looks at+ // the raw API order and shows nothing even though advancing works.+ List<dynamic> eps = const [];+ final showCached = _absorbingItemCache.values+ .cast<Map<String, dynamic>>()+ .where((e) => (e['id'] as String?) == showId)+ .firstOrNull;+ final cachedEps = (showCached?['media'] as Map<String, dynamic>?)?['episodes']+ as List<dynamic>?;+ if (cachedEps != null && cachedEps.isNotEmpty) {+ eps = cachedEps;+ } else if (_api != null) {+ final fullItem = await _api!.getLibraryItem(showId);+ final media = fullItem?['media'] as Map<String, dynamic>? ?? const {};+ eps = media['episodes'] as List<dynamic>? ?? const [];+ }+ final episodes = eps.whereType<Map<String, dynamic>>().toList();+ if (episodes.isEmpty) return null;++ final prefs = await SharedPreferences.getInstance();+ final advanceNewestFirst =+ (prefs.getString('podcast_advance_dir_$showId') ?? 'oldest_first') ==+ 'newest_first';+ episodes.sort((a, b) {+ final aTime = (a['publishedAt'] as num?)?.toInt() ?? 0;+ final bTime = (b['publishedAt'] as num?)?.toInt() ?? 0;+ return advanceNewestFirst ? bTime.compareTo(aTime) : aTime.compareTo(bTime);+ });++ final currentIdx = episodes.indexWhere((e) => e['id'] == currentEpId);final start = currentIdx >= 0 ? currentIdx + 1 : 0;- for (var i = start; i < eps.length; i++) {- final ep = eps[i];- final epId = ep['id'] as String?;+ for (var i = start; i < episodes.length; i++) {+ final epId = episodes[i]['id'] as String?;if (epId == null) continue;if (self.isItemFinishedByKey('$showId-$epId')) continue;- return ep['title'] as String?;+ return episodes[i]['title'] as String?;}return null;}diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dartindex 2c4b65a1..79e555c6 100644--- a/lib/screens/absorbing_screen.dart+++ b/lib/screens/absorbing_screen.dart@@ -15,6 +15,7 @@ import '../widgets/offline_status_icon.dart';import '../widgets/overlay_toast.dart';import '../widgets/series_books_sheet.dart';import '../widgets/playlist_detail_sheet.dart';+import '../widgets/episode_list_sheet.dart';import '../l10n/app_localizations.dart';import '../services/wording.dart';@@ -58,6 +59,12 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {final _cast = ChromecastService();String _queueMode = 'off';+ // Raw per-type modes behind the derived _queueMode. peekUpNext keys off these+ // (and the merge flag) directly, so the Up Next stamp must too - otherwise a+ // change to the podcast mode that leaves the derived mode unchanged (e.g. the+ // second of two sequential writes when merged) never triggers a recompute.+ String _bookQueueMode = 'off';+ String _podcastQueueMode = 'off';String? _queuePlaylistId;@override@@ -118,6 +125,8 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {if (mounted) {setState(() {_queueMode = mode;+ _bookQueueMode = bm;+ _podcastQueueMode = pm;_queuePlaylistId = qpId;_showUpNextLabel = showUpNext;});@@ -133,8 +142,12 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {final currentId = _player.currentEpisodeId != null? '${_player.currentItemId}-${_player.currentEpisodeId}': _player.currentItemId;- final firstKey = lib.absorbingBookIds.isNotEmpty ? lib.absorbingBookIds.first : '';- final stamp = '$_queueMode|$_queuePlaylistId|$currentId|$firstKey';+ // Key off the whole queue order, not just the first item - manual mode+ // walks the queue from the current item forward, so reordering items after+ // the front changes what's up next without changing the first key.+ final queueOrder = lib.absorbingBookIds.join(',');+ final stamp = '$_queueMode|$_bookQueueMode|$_podcastQueueMode|$_mergeLibraries'+ '|$_queuePlaylistId|$currentId|$queueOrder';if (stamp == _upNextComputedFor) return;_upNextComputedFor = stamp;final label = await lib.peekUpNext(currentItemId: currentId);@@ -166,6 +179,7 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {bool _mergeLibraries = false;bool? _lastSeenHasBook;bool? _lastSeenIsPlaying;+ bool? _lastSeenActiveSession;String? _lastSeenLibraryId;void _rebuild() {@@ -173,9 +187,14 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {final hasBookChanged = _player.hasBook != _lastSeenHasBook;final isPlayingChanged = _player.isPlaying != _lastSeenIsPlaying;+ // Stopping while already paused changes neither hasBook nor isPlaying, so+ // track the active-session flag too or the Up Next label can linger.+ final activeSessionChanged =+ _player.hasActiveSession != _lastSeenActiveSession;_lastSeenHasBook = _player.hasBook;_lastSeenIsPlaying = _player.isPlaying;- var shouldRebuild = hasBookChanged || isPlayingChanged;+ _lastSeenActiveSession = _player.hasActiveSession;+ var shouldRebuild = hasBookChanged || isPlayingChanged || activeSessionChanged;// Detect item or episode change (same show, different episode counts as a change)final itemChanged = _player.currentItemId != _lastPlayingId;@@ -749,7 +768,11 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {// Phone landscape uses the compact single-row header; everything// else (portrait, tablets in any orientation) keeps the full header.if (isPhoneLandscape) landscapeHeader else portraitHeader,- if (_showUpNextLabel && _queueMode != 'off' && books.isNotEmpty)+ // Hide Up Next when the session is stopped (not merely paused) -+ // hasActiveSession stays true while paused but goes false once the+ // engine is stopped, so a stopped session with items still in the+ // queue won't show a confusing "Nothing is up next".+ if (_player.hasActiveSession && _showUpNextLabel && _queueMode != 'off' && books.isNotEmpty)Padding(padding: const EdgeInsets.fromLTRB(20, 0, 20, 2),child: Align(@@ -1043,10 +1066,26 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {PlayerSettings.getShowUpNextLabel().then((v) {if (mounted) setState(() => _showUpNext = v);});+ final showId = _currentPodcastShowId;+ if (showId != null) {+ PlayerSettings.getPodcastAdvanceDir(showId).then((v) {+ if (mounted) setState(() => _podcastAdvanceDir = v);+ });+ }_loadModeContent();}bool _showUpNext = true;+ String _podcastAdvanceDir = 'oldest_first';++ // Show id of the currently playing podcast, or null if a book (or nothing)+ // is playing. currentItemId is the compound "<itemId>-<episodeId>" key for+ // podcasts, so a length past 36 means an episode is playing.+ String? get _currentPodcastShowId {+ final id = widget.currentItemId;+ if (id == null || id.length <= 36) return null;+ return id.substring(0, 36);+ }// Stage 3: mode-aware rendering. For auto_next we show the active series'// books; for playlist we show the active playlist's items. Cached here so@@ -1057,15 +1096,46 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {List<Map<String, dynamic>>? _playlistItems;String? _playlistId;String? _playlistName;+ // Podcast auto_next: the current show's episodes (unsorted - the list sorts+ // by _podcastAdvanceDir at build so flipping the toggle reorders live).+ List<Map<String, dynamic>>? _showEpisodes;+ Map<String, dynamic>? _showItem;+ String? _showName;Future<void> _loadModeContent() async {- if (_queueMode == 'auto_next' && !widget.isPodcast) {- await _loadSeriesBooks();+ if (_queueMode == 'auto_next') {+ // Discriminate on the playing item, not the library: a podcast can be+ // playing inside a book library (and vice versa). Podcast auto advances+ // within the current show; books advance through the series.+ if (_currentPodcastShowId != null) {+ await _loadShowEpisodes();+ } else if (!widget.isPodcast) {+ await _loadSeriesBooks();+ }} else if (_queueMode == 'playlist') {await _loadPlaylistContent();}}+ Future<void> _loadShowEpisodes() async {+ final showId = _currentPodcastShowId;+ if (showId == null) return;+ // The absorbing cache only holds per-episode synthetic entries, so fetch+ // the show fresh to get the full episode list.+ final item = await widget.lib.fetchLibraryItem(showId);+ if (!mounted || item == null) return;+ final media = item['media'] as Map<String, dynamic>? ?? const {};+ final eps = (media['episodes'] as List<dynamic>? ?? const [])+ .whereType<Map<String, dynamic>>()+ .toList();+ final metadata = media['metadata'] as Map<String, dynamic>? ?? const {};+ setState(() {+ _showItem = item;+ _showEpisodes = eps;+ _showName = metadata['title'] as String?;+ });+ }+Future<void> _loadSeriesBooks() async {final currentId = widget.currentItemId;if (currentId == null) return;@@ -1222,6 +1292,33 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {),]),),+ if (_queueMode == 'auto_next' && _currentPodcastShowId != null)+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),+ child: Row(children: [+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(l.reversePlayOrder,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ Text(+ _podcastAdvanceDir == 'newest_first'+ ? l.episodeListPlaysNewerToOlder+ : l.episodeListPlaysOlderToNewer,+ style: tt.bodySmall?.copyWith(+ color: cs.onSurfaceVariant, fontSize: 11.5),+ ),+ ])),+ Switch(+ value: _podcastAdvanceDir == 'newest_first',+ onChanged: (v) {+ final dir = v ? 'newest_first' : 'oldest_first';+ setState(() => _podcastAdvanceDir = dir);+ PlayerSettings.setPodcastAdvanceDir(+ _currentPodcastShowId!, dir);+ },+ materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,+ ),+ ]),+ ),if (_queueMode == 'auto_next' && !widget.isPodcast && _seriesId != null)_modeHeaderButton(cs, tt,@@ -1243,6 +1340,18 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {);},),+ if (_queueMode == 'auto_next' && _currentPodcastShowId != null && _showItem != null)+ _modeHeaderButton(+ cs, tt,+ label: l.allEpisodes,+ subtitle: _showName,+ icon: Icons.podcasts_rounded,+ onTap: () {+ final outer = rootNavigatorKey.currentContext ?? context;+ Navigator.pop(context);+ EpisodeListSheet.show(outer, _showItem!);+ },+ ),if (_queueMode == 'playlist' && _playlistId != null)_modeHeaderButton(cs, tt,@@ -1307,8 +1416,16 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {}Widget _buildQueueList(ColorScheme cs, TextTheme tt, AppLocalizations l, double bottomInset) {- if (_queueMode == 'auto_next' && !widget.isPodcast) {- return _buildSeriesList(cs, tt, l, bottomInset);+ if (_queueMode == 'auto_next') {+ if (_currentPodcastShowId != null) {+ return _buildShowEpisodesList(cs, tt, l, bottomInset);+ }+ // A book library with nothing playing has no series context to load, so+ // fall through to the manual queue rather than spinning forever.+ if (!widget.isPodcast && widget.currentItemId != null) {+ return _buildSeriesList(cs, tt, l, bottomInset);+ }+ return _buildManualList(cs, tt, l, bottomInset);}if (_queueMode == 'playlist') {return _buildPlaylistList(cs, tt, l, bottomInset);@@ -1316,6 +1433,44 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {return _buildManualList(cs, tt, l, bottomInset);}+ Widget _buildShowEpisodesList(ColorScheme cs, TextTheme tt, AppLocalizations l, double bottomInset) {+ final eps = _showEpisodes;+ if (eps == null) {+ return const Center(child: CircularProgressIndicator(strokeWidth: 2));+ }+ if (eps.isEmpty) {+ return Center(+ child: Padding(+ padding: const EdgeInsets.all(24),+ child: Text(l.absorbingNothingAbsorbingYet,+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),+ ),+ );+ }+ final showId = _currentPodcastShowId;+ final newestFirst = _podcastAdvanceDir == 'newest_first';+ final sorted = [...eps]..sort((a, b) {+ final at = (a['publishedAt'] as num?)?.toInt() ?? 0;+ final bt = (b['publishedAt'] as num?)?.toInt() ?? 0;+ return newestFirst ? bt.compareTo(at) : at.compareTo(bt);+ });+ return ListView.builder(+ padding: EdgeInsets.only(bottom: bottomInset + 16),+ itemCount: sorted.length,+ itemBuilder: (context, i) {+ final ep = sorted[i];+ final epId = ep['id'] as String? ?? '';+ return _readOnlyQueueItem(+ cs, tt, l,+ key: '$showId-$epId',+ book: _showItem ?? const {},+ index: i,+ episodeOverride: ep,+ );+ },+ );+ }+Widget _buildSeriesList(ColorScheme cs, TextTheme tt, AppLocalizations l, double bottomInset) {final books = _seriesBooks;if (books == null) {diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex b66ea612..5ad90765 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -1151,6 +1151,12 @@ class AudioPlayerService extends ChangeNotifier {notifyListeners();}bool get hasBook => _currentItemId != null;+ /// True when a loaded item is in an active session - playing OR paused.+ /// stop() drops the engine to idle while keeping _currentItemId, so this is+ /// false for a stopped session even though [hasBook] stays true.+ bool get hasActiveSession =>+ _currentItemId != null &&+ (_player?.processingState ?? ProcessingState.idle) != ProcessingState.idle;bool get isPlaying => _player?.playing ?? false;/// True while [playItem] is setting up a new audio source.bool _isLoadingNewItem = false;diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dartindex 0c207b77..9654ab55 100644--- a/lib/services/player_settings.dart+++ b/lib/services/player_settings.dart@@ -168,6 +168,19 @@ class PlayerSettings {}static Future<void> setPodcastQueueMode(String value) => _set('podcastQueueMode', value, notify: true);+ /// Per-show podcast auto-advance direction: 'oldest_first' (default) or+ /// 'newest_first'. Stored under a raw (un-scoped) key because the advance+ /// logic in _lp_absorbing reads it straight from SharedPreferences.+ static Future<String> getPodcastAdvanceDir(String showId) async {+ final prefs = await SharedPreferences.getInstance();+ return prefs.getString('podcast_advance_dir_$showId') ?? 'oldest_first';+ }+ static Future<void> setPodcastAdvanceDir(String showId, String value) async {+ final prefs = await SharedPreferences.getInstance();+ await prefs.setString('podcast_advance_dir_$showId', value);+ _notify();+ }+/// Active playlist ID for playlist queue mode. Null when no playlist is selected.static Future<String?> getQueuePlaylistId() async {final s = await ScopedPrefs.getString('queuePlaylistId');diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dartindex 18ae91e8..0be784e8 100644--- a/lib/widgets/episode_list_sheet.dart+++ b/lib/widgets/episode_list_sheet.dart@@ -58,8 +58,6 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {bool _subscribed = false;bool _newestFirst = true;bool _hideFinished = false;- String _podcastAdvanceDir = 'oldest_first'; // 'oldest_first' or 'newest_first'- bool _podcastAutoAdvanceOn = false;bool _selectMode = false;final Set<String> _selectedEpisodeIds = {};bool _isBatchUpdating = false;@@ -96,7 +94,6 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {super.initState();_loadSortOrder();_loadHideFinished();- _loadAutoAdvanceDir();_loadEpisodes();_loadAutoDownloadState();}@@ -174,22 +171,6 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {if (saved != null && mounted) setState(() => _hideFinished = saved);}- void _loadAutoAdvanceDir() async {- final prefs = await SharedPreferences.getInstance();- final saved = prefs.getString('podcast_advance_dir_$_itemId');- if (saved != null && mounted) setState(() => _podcastAdvanceDir = saved);- final mode = await PlayerSettings.getPodcastQueueMode();- if (mounted) setState(() => _podcastAutoAdvanceOn = mode == 'auto_next');- }-- void _toggleAutoAdvanceDir() {- final newDir = _podcastAdvanceDir == 'oldest_first' ? 'newest_first' : 'oldest_first';- setState(() => _podcastAdvanceDir = newDir);- SharedPreferences.getInstance().then((prefs) {- prefs.setString('podcast_advance_dir_$_itemId', newDir);- });- }-void _toggleHideFinished() {setState(() => _hideFinished = !_hideFinished);SharedPreferences.getInstance().then((prefs) {@@ -476,44 +457,6 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {_hideFinished ? Icons.visibility_rounded : Icons.visibility_off_rounded,_hideFinished ? l.episodeListShowFinishedEpisodes : l.episodeListHideFinishedEpisodes,onTap: () { Navigator.pop(ctx); _toggleHideFinished(); }),- if (_podcastAutoAdvanceOn)- StatefulBuilder(builder: (ctx, setLocalState) {- final reversed = _podcastAdvanceDir == 'newest_first';- return Padding(- padding: const EdgeInsets.only(bottom: 6),- child: Container(- decoration: BoxDecoration(- color: cs.onSurface.withValues(alpha: 0.06),- borderRadius: BorderRadius.circular(14),- border: Border.all(color: cs.onSurface.withValues(alpha: 0.1)),- ),- padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),- child: Row(children: [- Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [- Text(l.reversePlayOrder, style: TextStyle(color: cs.onSurface, fontSize: 13, fontWeight: FontWeight.w600)),- const SizedBox(height: 2),- Text(- reversed ? l.episodeListPlaysNewerToOlder : l.episodeListPlaysOlderToNewer,- style: TextStyle(color: cs.onSurfaceVariant, fontSize: 11.5),- ),- ])),- SizedBox(- height: 28,- child: FittedBox(- fit: BoxFit.contain,- child: Switch(- value: reversed,- onChanged: (v) {- _toggleAutoAdvanceDir();- setLocalState(() {});- },- ),- ),- ),- ]),- ),- );- }),]),),);