A cross platform Audiobookshelf client for Android and iOS
Dart
Make queue downloads follow each show and improve queue controls
Barnabasa5f700485414
diff --git a/lib/providers/_lp_absorbing.dart b/lib/providers/_lp_absorbing.dartindex ceefe9f1..8170d0d5 100644--- a/lib/providers/_lp_absorbing.dart+++ b/lib/providers/_lp_absorbing.dart@@ -1,6 +1,8 @@part of 'library_provider.dart';mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {+ int _staleSourceCleanupGeneration = 0;+bool _dedupeAbsorbingIds() {final seen = <String>{};final deduped = <String>[];@@ -1099,7 +1101,7 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {String _playlistItemKey(Map<String, dynamic> item) {final lid = item['libraryItemId'] as String? ?? '';final eid = item['episodeId'] as String?;- return eid != null ? '$lid-$eid' : lid;+ return queueItemKey(libraryItemId: lid, episodeId: eid);}/// Index of the first playlist item that isn't marked finished. Returns -1@@ -1197,25 +1199,40 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {return _playPlaylistItem(item);}- /// Returns true if [libraryItemId] (+ optional [episodeId]) appears in the- /// active queue playlist's items. Used to decide whether playing a given- /// item should keep playlist mode active or kick the user out of it.- Future<bool> isInActiveQueuePlaylist(String libraryItemId,- {String? episodeId}) async {- final playlistId = await PlayerSettings.getQueuePlaylistId();- if (playlistId == null) return false;+ Future<bool?> _isInQueuePlaylist(+ String playlistId,+ String libraryItemId, {+ String? episodeId,+ }) async {final pl = await _getPlaylistById(playlistId);- if (pl == null) return false;- final items = (pl['items'] as List<dynamic>?) ?? const [];+ if (pl == null) return null;+ final items = pl['items'];+ if (items is! List) return null;final target =episodeId != null ? '$libraryItemId-$episodeId' : libraryItemId;for (final m in items) {- if (m is! Map<String, dynamic>) continue;- if (_playlistItemKey(m) == target) return true;+ if (m is! Map<String, dynamic>) return null;+ final key = _playlistItemKey(m);+ if (key.isEmpty) return null;+ if (key == target) return true;}return false;}+ /// Returns true if [libraryItemId] (+ optional [episodeId]) appears in the+ /// active queue playlist's items.+ Future<bool> isInActiveQueuePlaylist(String libraryItemId,+ {String? episodeId}) async {+ final playlistId = await PlayerSettings.getQueuePlaylistId();+ if (playlistId == null) return false;+ final membership = await _isInQueuePlaylist(+ playlistId,+ libraryItemId,+ episodeId: episodeId,+ );+ return membership ?? false;+ }+Future<void> _advanceInPlaylist(String finishedKey) async {final playlistId = await PlayerSettings.getQueuePlaylistId();if (playlistId == null) {@@ -1225,7 +1242,7 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {final pl = await _getPlaylistById(playlistId);if (pl == null) {debugPrint('[AutoAdvance] Playlist $playlistId missing; exiting playlist queue mode');- await PlayerSettings.clearQueueModePlaylist();+ await PlayerSettings.clearQueueModePlaylistIfActive(playlistId);return;}final items = (pl['items'] as List<dynamic>?) ?? const [];@@ -1531,18 +1548,116 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {return _playPlaylistItem(items[idx]);}+ Future<bool?> _isInQueueCollection(+ String collectionId,+ String libraryItemId, {+ String? episodeId,+ }) async {+ final c = await _getCollectionById(collectionId);+ if (c == null) return null;+ final books = c['books'];+ if (books is! List) return null;+ final target =+ episodeId != null ? '$libraryItemId-$episodeId' : libraryItemId;+ for (final book in books) {+ if (book is! Map<String, dynamic>) return null;+ final id = book['id'] as String? ?? '';+ if (id.isEmpty) return null;+ if (id == target) return true;+ }+ return false;+ }+Future<bool> isInActiveQueueCollection(String libraryItemId,{String? episodeId}) async {final collectionId = await PlayerSettings.getQueueCollectionId();if (collectionId == null) return false;- final c = await _getCollectionById(collectionId);- if (c == null) return false;- final items = _collectionItems(c);- final target = episodeId != null ? '$libraryItemId-$episodeId' : libraryItemId;- for (final m in items) {- if (_playlistItemKey(m) == target) return true;+ final membership = await _isInQueueCollection(+ collectionId,+ libraryItemId,+ episodeId: episodeId,+ );+ return membership ?? false;+ }++ Future<void> _clearStaleSourceQueueModeForCurrentPlayback() async {+ final cleanupGeneration = ++_staleSourceCleanupGeneration;+ final player = AudioPlayerService();+ final libraryItemId = player.currentItemId;+ if (libraryItemId == null) return;+ final episodeId = player.currentEpisodeId;++ bool playerStillMatches() =>+ cleanupGeneration == _staleSourceCleanupGeneration &&+ player.currentItemId == libraryItemId &&+ player.currentEpisodeId == episodeId;++ final bookMode = await PlayerSettings.getBookQueueMode();+ if (!playerStillMatches()) return;+ final podcastMode = await PlayerSettings.getPodcastQueueMode();+ if (!playerStillMatches()) return;+ final activeMode = episodeId == null ? bookMode : podcastMode;++ if (activeMode == 'playlist') {+ if (bookMode != 'playlist' || podcastMode != 'playlist') return;+ final playlistId = await PlayerSettings.getQueuePlaylistId();+ if (playlistId == null || !playerStillMatches()) return;+ final membership = await _isInQueuePlaylist(+ playlistId,+ libraryItemId,+ episodeId: episodeId,+ );+ if (membership != false || !playerStillMatches()) return;++ final latestBookMode = await PlayerSettings.getBookQueueMode();+ if (!playerStillMatches()) return;+ final latestPodcastMode = await PlayerSettings.getPodcastQueueMode();+ if (!playerStillMatches()) return;+ final latestPlaylistId = await PlayerSettings.getQueuePlaylistId();+ if (!playerStillMatches() ||+ latestBookMode != bookMode ||+ latestPodcastMode != podcastMode ||+ latestPlaylistId != playlistId) {+ return;+ }++ final cleared =+ await PlayerSettings.clearQueueModePlaylistIfActive(playlistId);+ if (!cleared) return;+ if (!playerStillMatches()) return;+ debugPrint(+ '[Queue] Cleared playlist mode because $libraryItemId is outside $playlistId',+ );+ unawaited(_catchUpQueueAutoDownloads());+ return;}- return false;++ if (activeMode != 'collection' || episodeId != null) return;+ final collectionId = await PlayerSettings.getQueueCollectionId();+ if (collectionId == null || !playerStillMatches()) return;+ final membership = await _isInQueueCollection(+ collectionId,+ libraryItemId,+ );+ if (membership != false || !playerStillMatches()) return;++ final latestBookMode = await PlayerSettings.getBookQueueMode();+ if (!playerStillMatches()) return;+ final latestCollectionId = await PlayerSettings.getQueueCollectionId();+ if (!playerStillMatches() ||+ latestBookMode != bookMode ||+ latestCollectionId != collectionId) {+ return;+ }++ final cleared =+ await PlayerSettings.clearQueueModeCollectionIfActive(collectionId);+ if (!cleared) return;+ if (!playerStillMatches()) return;+ debugPrint(+ '[Queue] Cleared collection mode because $libraryItemId is outside $collectionId',+ );+ unawaited(_catchUpQueueAutoDownloads());}Future<void> _advanceInCollection(String finishedKey) async {@@ -1550,7 +1665,7 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {if (collectionId == null) return;final c = await _getCollectionById(collectionId);if (c == null) {- await PlayerSettings.clearQueueModeCollection();+ await PlayerSettings.clearQueueModeCollectionIfActive(collectionId);return;}final items = _collectionItems(c);diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dartindex 428a30a3..cccddde5 100644--- a/lib/providers/_lp_core.dart+++ b/lib/providers/_lp_core.dart@@ -10,8 +10,14 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {_rollingDownloadSeries.add(seriesOrShowId);await _saveRollingDownloadSeries();notifyListeners();- final playingKey = AudioPlayerService().currentItemId;- if (playingKey != null) _checkRollingDownloads(playingKey);+ final player = AudioPlayerService();+ final itemId = player.currentItemId;+ if (itemId != null) {+ final episodeId = player.currentEpisodeId;+ final playingKey = episodeId == null ? itemId : '$itemId-$episodeId';+ _checkRollingDownloads(playingKey);+ unawaited(_checkQueueAutoDownloads(playingKey));+ }}Future<void> disableRollingDownload(String seriesOrShowId) async {@@ -2242,7 +2248,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {: activeKey.length > 36? await PlayerSettings.getPodcastQueueMode(): await PlayerSettings.getBookQueueMode();- final activeQueueOwnsWindow = activeQueueMode != 'off' &&+ final globalQueueAutoDownload =await PlayerSettings.getQueueAutoDownload();if (_rollingDownloadSeries.isEmpty && !autoSeriesDefault) return;final count = await PlayerSettings.getRollingDownloadCount();@@ -2252,16 +2258,19 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {final activeShowId = activeKey != null && activeKey.length > 36? activeKey.substring(0, 36): null;+ final activeQueueOwnsWindow = activeQueueMode != 'off' &&+ resolveQueueAutoDownloadEnabled(+ queueMode: activeQueueMode,+ globalEnabled: globalQueueAutoDownload,+ activeSourceId: activeShowId,+ activeSourceEnabled: activeShowId != null &&+ _rollingDownloadSeries.contains(activeShowId),+ );if (activeQueueOwnsWindow && activeShowId == showId) return;if (_rollingDownloadSeries.contains(showId)) {_rollingDownloadPodcast(playingKey, count);}} else {- if (activeQueueOwnsWindow &&- activeKey == playingKey &&- !autoSeriesDefault) {- return;- }var data = _itemDataWithSeries(playingKey);var (seriesId, _) = data != null ? _StateMixin._extractSeries(data) : (null, null);if (seriesId == null) {@@ -2277,26 +2286,59 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {await _saveRollingDownloadSeries();notifyListeners();}- if (activeQueueOwnsWindow && activeKey != null && activeKey.length <= 36) {- if (activeKey == playingKey) return;- var activeData = _itemDataWithSeries(activeKey);- var (activeSeriesId, _) = activeData != null- ? _StateMixin._extractSeries(activeData)- : (null, null);- if (activeSeriesId == null) {- activeData = await api.getLibraryItem(activeKey);- if (activeData != null) {- (activeSeriesId, _) = _StateMixin._extractSeries(activeData);+ String? activeSeriesId;+ if (activeKey != null && activeKey.length <= 36) {+ if (activeKey == playingKey) {+ activeSeriesId = seriesId;+ } else {+ var activeData = _itemDataWithSeries(activeKey);+ (activeSeriesId, _) = activeData != null+ ? _StateMixin._extractSeries(activeData)+ : (null, null);+ if (activeSeriesId == null) {+ activeData = await api.getLibraryItem(activeKey);+ if (activeData != null) {+ (activeSeriesId, _) = _StateMixin._extractSeries(activeData);+ }}}- if (activeSeriesId == seriesId) return;}+ final activeQueueOwnsWindow = activeQueueMode != 'off' &&+ resolveQueueAutoDownloadEnabled(+ queueMode: activeQueueMode,+ globalEnabled: globalQueueAutoDownload,+ activeSourceId: activeSeriesId,+ activeSourceEnabled: activeSeriesId != null &&+ _rollingDownloadSeries.contains(activeSeriesId),+ );+ if (activeQueueOwnsWindow && activeSeriesId == seriesId) return;if (_rollingDownloadSeries.contains(seriesId)) {_rollingDownloadBook(playingKey, count);}}}+ Future<String?> _queueAutoDownloadSourceId(+ String playingKey,+ String queueMode,+ ApiService api,+ ) async {+ if (queueMode != 'auto_next') return null;+ if (playingKey.length > 36) return playingKey.substring(0, 36);++ var data = _itemDataWithSeries(playingKey);+ var (seriesId, _) = data != null+ ? _StateMixin._extractSeries(data)+ : (null, null);+ if (seriesId == null) {+ data = await api.getLibraryItem(playingKey);+ if (data != null) {+ (seriesId, _) = _StateMixin._extractSeries(data);+ }+ }+ return seriesId;+ }+Future<void> _checkQueueAutoDownloads(String playingKey) async {try {final self = this as LibraryProvider;@@ -2338,7 +2380,18 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {: null;if (isStale()) return;- final enabled = await PlayerSettings.getQueueAutoDownload();+ final autoDownloadSourceId =+ await _queueAutoDownloadSourceId(playingKey, queueMode, api);+ if (isStale()) return;+ final globalAutoDownload =+ await PlayerSettings.getQueueAutoDownload();+ final enabled = resolveQueueAutoDownloadEnabled(+ queueMode: queueMode,+ globalEnabled: globalAutoDownload,+ activeSourceId: autoDownloadSourceId,+ activeSourceEnabled: autoDownloadSourceId != null &&+ _rollingDownloadSeries.contains(autoDownloadSourceId),+ );if (!enabled || isStale()) return;final count = await PlayerSettings.getRollingDownloadCount();if (count <= 0 || isStale()) return;@@ -2371,7 +2424,16 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {isStale()) {return false;}- if (!await PlayerSettings.getQueueAutoDownload() || isStale()) {+ final currentGlobalAutoDownload =+ await PlayerSettings.getQueueAutoDownload();+ if (isStale() ||+ !resolveQueueAutoDownloadEnabled(+ queueMode: queueMode,+ globalEnabled: currentGlobalAutoDownload,+ activeSourceId: autoDownloadSourceId,+ activeSourceEnabled: autoDownloadSourceId != null &&+ _rollingDownloadSeries.contains(autoDownloadSourceId),+ )) {return false;}if (await PlayerSettings.getRollingDownloadCount() != count ||@@ -2414,9 +2476,10 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {String keyOf(Map<String, dynamic> item) {final libraryItemId = item['libraryItemId'] as String? ?? '';final episodeId = item['episodeId'] as String?;- return episodeId == null- ? libraryItemId- : '$libraryItemId-$episodeId';+ return queueItemKey(+ libraryItemId: libraryItemId,+ episodeId: episodeId,+ );}final pendingItems = queueItemsNeedingDownload(items: items.where((item) => keyOf(item).isNotEmpty),diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex 169a643d..72e2e881 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -85,6 +85,7 @@ class LibraryProvider extends ChangeNotifierAudioPlayerService.setOnPlaybackStateChangedCallback((playing) {if (playing) {onPlaybackStarted();+ unawaited(_clearStaleSourceQueueModeForCurrentPlayback());} else {onPlaybackStopped();}diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dartindex b565238d..676489a0 100644--- a/lib/screens/absorbing_screen.dart+++ b/lib/screens/absorbing_screen.dart@@ -7,6 +7,7 @@ import '../providers/library_provider.dart';import '../services/audio_player_service.dart';import '../services/chromecast_service.dart';import '../services/download_service.dart';+import '../services/queue_download_policy.dart';import '../services/scoped_prefs.dart';import '../widgets/absorb_page_header.dart';import '../main.dart' show flatNotifier, gradientIntensityNotifier, rootNavigatorKey;@@ -947,11 +948,12 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {expand: false,initialChildSize: needsMoreRoom ? 0.9 : 0.7,minChildSize: needsMoreRoom ? 0.85 : 0.5,- maxChildSize: 0.95,- builder: (_, __) => _ReorderAbsorbingSheet(+ maxChildSize: 1.0,+ builder: (_, scrollController) => _ReorderAbsorbingSheet(keys: keys,books: books,lib: lib,+ scrollController: scrollController,absorbingKeyFn: _absorbingKey,queueMode: _queueMode,isMerged: _mergeLibraries,@@ -1058,6 +1060,7 @@ class _ReorderAbsorbingSheet extends StatefulWidget {final List<String> keys;final List<Map<String, dynamic>> books;final LibraryProvider lib;+ final ScrollController scrollController;final String Function(Map<String, dynamic>) absorbingKeyFn;final String queueMode;final bool isMerged;@@ -1069,6 +1072,7 @@ class _ReorderAbsorbingSheet extends StatefulWidget {required this.keys,required this.books,required this.lib,+ required this.scrollController,required this.absorbingKeyFn,required this.queueMode,required this.isMerged,@@ -1104,17 +1108,6 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {PlayerSettings.getShowUpNextLabel().then((v) {if (mounted) setState(() => _showUpNext = v);});- Future.wait([- PlayerSettings.getQueueAutoDownload(),- PlayerSettings.getRollingDownloadCount(),- ]).then((values) {- if (!mounted) return;- setState(() {- _queueAutoDownload = values[0] as bool;- _rollingDownloadCount = values[1] as int;- _queueDownloadSettingsLoaded = true;- });- });final showId = _currentPodcastShowId;if (showId != null) {PlayerSettings.getPodcastAdvanceDir(showId).then((v) {@@ -1148,6 +1141,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {if (!mounted || nextKey == _currentItemId) return;setState(() {_currentItemId = nextKey;+ _queueDownloadSettingsLoaded = false;_seriesBooks = null;_seriesId = null;_seriesName = null;@@ -1180,6 +1174,47 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {_currentPodcastShowId != null ||(_currentItemId == null && widget.isPodcast);+ String? get _activeAutoDownloadSourceId {+ if (_queueMode != 'auto_next') return null;+ return _currentPodcastShowId ?? _seriesId;+ }++ Future<void> _refreshQueueDownloadSettings() async {+ final queueMode = _queueMode;+ final sourceId = _activeAutoDownloadSourceId;+ final globalEnabled = await PlayerSettings.getQueueAutoDownload();+ final count = await PlayerSettings.getRollingDownloadCount();+ if (!mounted ||+ queueMode != _queueMode ||+ sourceId != _activeAutoDownloadSourceId) return;+ setState(() {+ _queueAutoDownload = resolveQueueAutoDownloadEnabled(+ queueMode: queueMode,+ globalEnabled: globalEnabled,+ activeSourceId: sourceId,+ activeSourceEnabled:+ sourceId != null && widget.lib.isRollingDownloadEnabled(sourceId),+ );+ _rollingDownloadCount = count;+ _queueDownloadSettingsLoaded = true;+ });+ }++ Future<void> _setQueueAutoDownload(bool value) async {+ final sourceId = _activeAutoDownloadSourceId;+ setState(() => _queueAutoDownload = value);+ if (_queueMode == 'auto_next' && sourceId != null) {+ if (value) {+ await widget.lib.enableRollingDownload(sourceId);+ } else {+ await widget.lib.disableRollingDownload(sourceId);+ }+ } else {+ await PlayerSettings.setQueueAutoDownload(value);+ }+ unawaited(widget.lib.syncQueueAutoDownloads());+ }+// 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// the list paints without a flash while the API call completes.@@ -1216,6 +1251,8 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {} else if (_queueMode == 'collection') {await _loadCollectionContent(generation);}+ if (!mounted || generation != _modeContentGeneration) return;+ await _refreshQueueDownloadSettings();}Future<void> _loadShowEpisodes(int generation) async {@@ -1372,6 +1409,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {setState(() {_queueMode = mode;_activeQueueSourceId = sourceId;+ _queueDownloadSettingsLoaded = false;if (modeChanged || mode == 'playlist') {_playlistItems = null;_playlistId = null;@@ -1402,7 +1440,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {child: Column(children: [// HandleCenter(child: Container(- margin: const EdgeInsets.only(top: 10),+ margin: const EdgeInsets.only(top: 8),width: 32, height: 4,decoration: BoxDecoration(color: cs.onSurface.withValues(alpha: 0.2),@@ -1411,7 +1449,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {)),// HeaderPadding(- padding: const EdgeInsets.fromLTRB(16, 12, 8, 8),+ padding: const EdgeInsets.fromLTRB(16, 8, 8, 4),child: Row(children: [Expanded(child: Text(l.absorbingManageQueue,style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600))),@@ -1426,7 +1464,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {),// Queue mode togglePadding(- padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 6),child: SegmentedButton<String>(segments: [ButtonSegment(value: 'off', icon: const Icon(Icons.stop_rounded, size: 16), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeOff, maxLines: 1))),@@ -1468,48 +1506,39 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {),],)),+ if (_queueAutoDownload)+ Tooltip(+ message: l.keepNext,+ child: DropdownButtonHideUnderline(+ child: DropdownButton<int>(+ value: _rollingDownloadCount,+ isDense: true,+ items: const [2, 3, 4, 5]+ .map((count) => DropdownMenuItem(+ value: count,+ child: Text('$count'),+ ))+ .toList(),+ onChanged: _queueDownloadSettingsLoaded+ ? (value) async {+ if (value == null) return;+ setState(() => _rollingDownloadCount = value);+ await PlayerSettings.setRollingDownloadCount(value);+ unawaited(widget.lib.syncQueueAutoDownloads());+ }+ : null,+ ),+ ),+ ),+ const SizedBox(width: 4),Switch(value: _queueAutoDownload,onChanged: _queueDownloadSettingsLoaded- ? (value) async {- setState(() => _queueAutoDownload = value);- await PlayerSettings.setQueueAutoDownload(value);- unawaited(widget.lib.syncQueueAutoDownloads());- }+ ? _setQueueAutoDownload: null,materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,),]),- if (_queueAutoDownload)- Padding(- padding: const EdgeInsets.only(top: 4, bottom: 4),- child: Row(children: [- Text(l.keepNext,- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),- const SizedBox(width: 12),- Expanded(child: SegmentedButton<int>(- showSelectedIcon: false,- 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: (values) async {- if (values.isEmpty) return;- final value = values.first;- setState(() => _rollingDownloadCount = value);- await PlayerSettings.setRollingDownloadCount(value);- unawaited(widget.lib.syncQueueAutoDownloads());- },- style: const ButtonStyle(- visualDensity: VisualDensity.compact,- tapTargetSize: MaterialTapTargetSize.shrinkWrap,- ),- )),- ]),- ),]),),if (_queueMode != 'off')@@ -1700,6 +1729,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {);}return ListView.builder(+ controller: widget.scrollController,padding: EdgeInsets.only(bottom: bottomInset + 16),itemCount: books.length,itemBuilder: (context, i) {@@ -1732,6 +1762,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {return newestFirst ? bt.compareTo(at) : at.compareTo(bt);});return ListView.builder(+ controller: widget.scrollController,padding: EdgeInsets.only(bottom: bottomInset + 16),itemCount: sorted.length,itemBuilder: (context, i) {@@ -1771,6 +1802,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {return seqOf(a).compareTo(seqOf(b));});return ListView.builder(+ controller: widget.scrollController,padding: EdgeInsets.only(bottom: bottomInset + 16),itemCount: books.length,itemBuilder: (context, i) {@@ -1796,6 +1828,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {);}return ListView.builder(+ controller: widget.scrollController,padding: EdgeInsets.only(bottom: bottomInset + 16),itemCount: items.length,itemBuilder: (context, i) {@@ -1975,6 +2008,7 @@ class _ReorderAbsorbingSheetState extends State<_ReorderAbsorbingSheet> {Widget _buildManualList(ColorScheme cs, TextTheme tt, AppLocalizations l, double bottomInset) {return ReorderableListView.builder(+ scrollController: widget.scrollController,buildDefaultDragHandles: false,onReorderStart: (_) => HapticFeedback.mediumImpact(),padding: EdgeInsets.only(bottom: bottomInset + 16),diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex e8e5ac82..41568378 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -3067,9 +3067,10 @@ class AudioPlayerService extends ChangeNotifier {}}- // Auto-navigate to Absorbing tab when an episode starts playing- if (result == null && episodeId != null) {- _onEpisodePlayStartedCallback?.call();+ if (result == null && playbackGeneration == _playbackGeneration) {+ _onPlaybackStateChangedCallback?.call(true);+ // Auto-navigate to Absorbing tab when an episode starts playing.+ if (episodeId != null) _onEpisodePlayStartedCallback?.call();}return result;}diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dartindex efe101ea..3edd930c 100644--- a/lib/services/player_settings.dart+++ b/lib/services/player_settings.dart@@ -55,6 +55,19 @@ class PlayerSettings {/// Notifier that fires when any player setting changes./// Widgets can listen to this instead of polling SharedPreferences.static final ChangeNotifier settingsChanged = ChangeNotifier();+ static Future<void> _queueModeMutation = Future.value();++ static Future<T> _serializeQueueModeMutation<T>(+ Future<T> Function() mutation,+ ) {+ final result = _queueModeMutation.then((_) => mutation());+ _queueModeMutation = result.then<void>(+ (_) {},+ onError: (Object _, StackTrace __) {},+ );+ return result;+ }+static void _notify() {// ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_membersettingsChanged.notifyListeners();@@ -252,7 +265,10 @@ class PlayerSettings {final value = await ScopedPrefs.getString('bookQueueMode');return value ?? await getQueueMode();}- static Future<void> setBookQueueMode(String value) => _set('bookQueueMode', value, notify: true);+ static Future<void> setBookQueueMode(String value) =>+ _serializeQueueModeMutation(+ () => _set('bookQueueMode', value, notify: true),+ );static Future<bool> getShowUpNextLabel() => _get('showUpNextLabel', true);static Future<void> setShowUpNextLabel(bool value) =>@@ -262,7 +278,10 @@ class PlayerSettings {final value = await ScopedPrefs.getString('podcastQueueMode');return value ?? await getQueueMode();}- static Future<void> setPodcastQueueMode(String value) => _set('podcastQueueMode', value, notify: true);+ static Future<void> setPodcastQueueMode(String value) =>+ _serializeQueueModeMutation(+ () => _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@@ -295,32 +314,49 @@ class PlayerSettings {final s = await ScopedPrefs.getString('queuePlaylistId');return (s == null || s.isEmpty) ? null : s;}- static Future<void> setQueuePlaylistId(String? id) async {- if (id == null || id.isEmpty) {- await ScopedPrefs.remove('queuePlaylistId');- } else {- await ScopedPrefs.setString('queuePlaylistId', id);- }- _notify();- }+ static Future<void> setQueuePlaylistId(String? id) =>+ _serializeQueueModeMutation(() async {+ if (id == null || id.isEmpty) {+ await ScopedPrefs.remove('queuePlaylistId');+ } else {+ await ScopedPrefs.setString('queuePlaylistId', id);+ }+ _notify();+ });/// Enter playlist queue mode atomically: both book and podcast modes flip to/// 'playlist' and the active playlist is set. Playlists can mix book and/// podcast items, so the two modes always agree when in playlist mode.- static Future<void> setQueueModePlaylist(String playlistId) async {- await ScopedPrefs.setString('bookQueueMode', 'playlist');- await ScopedPrefs.setString('podcastQueueMode', 'playlist');- await ScopedPrefs.setString('queuePlaylistId', playlistId);- _notify();- }+ static Future<void> setQueueModePlaylist(String playlistId) =>+ _serializeQueueModeMutation(() async {+ await ScopedPrefs.setString('bookQueueMode', 'playlist');+ await ScopedPrefs.setString('podcastQueueMode', 'playlist');+ await ScopedPrefs.setString('queuePlaylistId', playlistId);+ _notify();+ });/// Exit playlist queue mode: both modes back to 'off' and active playlist cleared.- static Future<void> clearQueueModePlaylist() async {- await ScopedPrefs.setString('bookQueueMode', 'off');- await ScopedPrefs.setString('podcastQueueMode', 'off');- await ScopedPrefs.remove('queuePlaylistId');- _notify();- }+ static Future<void> clearQueueModePlaylist() =>+ _serializeQueueModeMutation(() async {+ await ScopedPrefs.setString('bookQueueMode', 'off');+ await ScopedPrefs.setString('podcastQueueMode', 'off');+ await ScopedPrefs.remove('queuePlaylistId');+ _notify();+ });++ static Future<bool> clearQueueModePlaylistIfActive(String playlistId) =>+ _serializeQueueModeMutation(() async {+ if (await getBookQueueMode() != 'playlist' ||+ await getPodcastQueueMode() != 'playlist' ||+ await getQueuePlaylistId() != playlistId) {+ return false;+ }+ await ScopedPrefs.setString('bookQueueMode', 'off');+ await ScopedPrefs.setString('podcastQueueMode', 'off');+ await ScopedPrefs.remove('queuePlaylistId');+ _notify();+ return true;+ });// ── Collection queue mode (books only) ──// Mirrors playlist queue mode but plays through a collection's books. Drives@@ -335,24 +371,39 @@ class PlayerSettings {static Future<String?> getQueueCollectionName() =>ScopedPrefs.getString('queueCollectionName');- static Future<void> setQueueModeCollection(String collectionId, String name) async {- await ScopedPrefs.setString('bookQueueMode', 'collection');- await ScopedPrefs.setString('queueCollectionId', collectionId);- await ScopedPrefs.setString('queueCollectionName', name);- // Collection mode replaces any active playlist queue.- await ScopedPrefs.remove('queuePlaylistId');- if ((await ScopedPrefs.getString('podcastQueueMode')) == 'playlist') {- await ScopedPrefs.setString('podcastQueueMode', 'off');- }- _notify();- }-- static Future<void> clearQueueModeCollection() async {- await ScopedPrefs.setString('bookQueueMode', 'off');- await ScopedPrefs.remove('queueCollectionId');- await ScopedPrefs.remove('queueCollectionName');- _notify();- }+ static Future<void> setQueueModeCollection(String collectionId, String name) =>+ _serializeQueueModeMutation(() async {+ await ScopedPrefs.setString('bookQueueMode', 'collection');+ await ScopedPrefs.setString('queueCollectionId', collectionId);+ await ScopedPrefs.setString('queueCollectionName', name);+ // Collection mode replaces any active playlist queue.+ await ScopedPrefs.remove('queuePlaylistId');+ if ((await ScopedPrefs.getString('podcastQueueMode')) == 'playlist') {+ await ScopedPrefs.setString('podcastQueueMode', 'off');+ }+ _notify();+ });++ static Future<void> clearQueueModeCollection() =>+ _serializeQueueModeMutation(() async {+ await ScopedPrefs.setString('bookQueueMode', 'off');+ await ScopedPrefs.remove('queueCollectionId');+ await ScopedPrefs.remove('queueCollectionName');+ _notify();+ });++ static Future<bool> clearQueueModeCollectionIfActive(String collectionId) =>+ _serializeQueueModeMutation(() async {+ if (await getBookQueueMode() != 'collection' ||+ await getQueueCollectionId() != collectionId) {+ return false;+ }+ await ScopedPrefs.setString('bookQueueMode', 'off');+ await ScopedPrefs.remove('queueCollectionId');+ await ScopedPrefs.remove('queueCollectionName');+ _notify();+ return true;+ });/// One-time migration from the old boolean auto-play settings to queueMode.static Future<void> migrateQueueMode() async {diff --git a/lib/services/queue_download_policy.dart b/lib/services/queue_download_policy.dartindex add9494f..5ab48b9e 100644--- a/lib/services/queue_download_policy.dart+++ b/lib/services/queue_download_policy.dart@@ -1,3 +1,19 @@+bool resolveQueueAutoDownloadEnabled({+ required String queueMode,+ required bool globalEnabled,+ required String? activeSourceId,+ required bool activeSourceEnabled,+}) {+ if (queueMode == 'auto_next' && activeSourceId != null) {+ return activeSourceEnabled;+ }+ return globalEnabled;+}++String queueItemKey({required String libraryItemId, String? episodeId}) {+ return episodeId == null ? libraryItemId : '$libraryItemId-$episodeId';+}+List<T> queueTailFrom<T>({required List<T> items,required String currentKey,diff --git a/lib/widgets/book_card.dart b/lib/widgets/book_card.dartindex bda00ef4..e14aabeb 100644--- a/lib/widgets/book_card.dart+++ b/lib/widgets/book_card.dart@@ -16,6 +16,10 @@ class BookCard extends StatelessWidget {final bool showProgress;final bool isWide;final double coverAspectRatio;+ final String? sourcePlaylistId;+ final String? sourcePlaylistEpisodeId;+ final String? sourceCollectionId;+ final String? sourceCollectionName;const BookCard({super.key,@@ -23,6 +27,10 @@ class BookCard extends StatelessWidget {this.showProgress = false,this.isWide = false,this.coverAspectRatio = 1.0,+ this.sourcePlaylistId,+ this.sourcePlaylistEpisodeId,+ this.sourceCollectionId,+ this.sourceCollectionName,});@override@@ -66,12 +74,28 @@ class BookCard extends StatelessWidget {if (lib.isPodcastLibrary) {final episode = item['recentEpisode'] as Map<String, dynamic>?;if (episode != null) {- EpisodeDetailSheet.show(context, item, episode);+ EpisodeDetailSheet.show(+ context,+ item,+ episode,+ sourcePlaylistId: sourcePlaylistId,+ );} else {- EpisodeListSheet.show(context, item);+ EpisodeListSheet.show(+ context,+ item,+ sourcePlaylistId: sourcePlaylistId,+ sourcePlaylistEpisodeId: sourcePlaylistEpisodeId,+ );}} else {- showBookDetailSheet(context, itemId);+ showBookDetailSheet(+ context,+ itemId,+ sourcePlaylistId: sourcePlaylistId,+ sourceCollectionId: sourceCollectionId,+ sourceCollectionName: sourceCollectionName,+ );}}@@ -84,13 +108,25 @@ class BookCard extends StatelessWidget {// Episode card -> episode quick sheet; show cover -> keep current behaviour.final episode = item['recentEpisode'] as Map<String, dynamic>?;if (episode != null) {- EpisodeDetailSheet.showQuick(context, item, episode);+ EpisodeDetailSheet.showQuick(+ context,+ item,+ episode,+ sourcePlaylistId: sourcePlaylistId,+ );} else {_navigateToDetail(context);}return;}- showQuickActionsSheet(context, itemId, initialItem: item);+ showQuickActionsSheet(+ context,+ itemId,+ initialItem: item,+ sourcePlaylistId: sourcePlaylistId,+ sourceCollectionId: sourceCollectionId,+ sourceCollectionName: sourceCollectionName,+ );}/// Wide "continue listening" card with square cover + text side-by-side.diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex 0875610b..dd4ec2e8 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -50,20 +50,39 @@ import '../utils/duration_format.dart';// ─── BOOK DETAIL BOTTOM SHEET ───────────────────────────────-void showBookDetailSheet(BuildContext context, String itemId) {+void showBookDetailSheet(+ BuildContext context,+ String itemId, {+ String? sourcePlaylistId,+ String? sourceCollectionId,+ String? sourceCollectionName,+}) {showStackableSheet(context: context,useSafeArea: true,initialChildSize: 0.85,maxChildSize: 0.95,- builder: (ctx, sc) => _BookDetailSheetContent(itemId: itemId, scrollController: sc),+ builder: (ctx, sc) => _BookDetailSheetContent(+ itemId: itemId,+ scrollController: sc,+ sourcePlaylistId: sourcePlaylistId,+ sourceCollectionId: sourceCollectionId,+ sourceCollectionName: sourceCollectionName,+ ),);}/// Long-press shortcut: a compact sheet with Absorb + Download up top and the/// full set of book actions as pills, skipping the trip into the detail sheet./// Pass [initialItem] (the tile's library-item map) so it renders instantly.-void showQuickActionsSheet(BuildContext context, String itemId, {Map<String, dynamic>? initialItem}) {+void showQuickActionsSheet(+ BuildContext context,+ String itemId, {+ Map<String, dynamic>? initialItem,+ String? sourcePlaylistId,+ String? sourceCollectionId,+ String? sourceCollectionName,+}) {showStackableSheet(context: context,useSafeArea: true,@@ -74,6 +93,9 @@ void showQuickActionsSheet(BuildContext context, String itemId, {Map<String, dynscrollController: sc,quick: true,initialItem: initialItem,+ sourcePlaylistId: sourcePlaylistId,+ sourceCollectionId: sourceCollectionId,+ sourceCollectionName: sourceCollectionName,),);}@@ -142,11 +164,17 @@ class _BookDetailSheetContent extends StatefulWidget {final ScrollController scrollController;final bool quick;final Map<String, dynamic>? initialItem;+ final String? sourcePlaylistId;+ final String? sourceCollectionId;+ final String? sourceCollectionName;const _BookDetailSheetContent({required this.itemId,required this.scrollController,this.quick = false,this.initialItem,+ this.sourcePlaylistId,+ this.sourceCollectionId,+ this.sourceCollectionName,});@override State<_BookDetailSheetContent> createState() => _BookDetailSheetContentState();}@@ -633,7 +661,13 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {return FilledButton.icon(onPressed: showAbsorbingState- ? () {+ ? () async {+ if (isCurrentPlaying) {+ final lib = context.read<LibraryProvider>();+ await _activateQueueSource();+ unawaited(lib.syncQueueAutoDownloads());+ }+ if (!context.mounted) return;Navigator.of(context).popUntil((route) => route.isFirst);AppShell.goToAbsorbingGlobal();}@@ -1110,7 +1144,15 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {add(Icons.open_in_full_rounded, l.bookDetailsLabel, () {final rc = rootNavigatorKey.currentContext;Navigator.of(context).pop();- if (rc != null) showBookDetailSheet(rc, widget.itemId);+ if (rc != null) {+ showBookDetailSheet(+ rc,+ widget.itemId,+ sourcePlaylistId: widget.sourcePlaylistId,+ sourceCollectionId: widget.sourceCollectionId,+ sourceCollectionName: widget.sourceCollectionName,+ );+ }});}// The full item (with ebookFile) loads after the sheet is already open,@@ -1154,7 +1196,13 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {final showAbsorbingState = _isAbsorbing || isCurrentPlaying;return GestureDetector(onTap: showAbsorbingState- ? () {+ ? () async {+ if (isCurrentPlaying) {+ final lib = context.read<LibraryProvider>();+ await _activateQueueSource();+ unawaited(lib.syncQueueAutoDownloads());+ }+ if (!context.mounted) return;Navigator.of(context).popUntil((route) => route.isFirst);AppShell.goToAbsorbingGlobal();}@@ -2036,6 +2084,29 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {if (mounted) setState(() {});}+ Future<void> _activateQueueSource() async {+ final playlistId = widget.sourcePlaylistId;+ final collectionId = widget.sourceCollectionId;+ if (playlistId != null && playlistId.isNotEmpty) {+ await PlayerSettings.setQueueModePlaylist(playlistId);+ } else if (collectionId != null && collectionId.isNotEmpty) {+ await PlayerSettings.setQueueModeCollection(+ collectionId,+ widget.sourceCollectionName ?? '',+ );+ }+ }++ Future<void> _clearActivatedQueueSource() async {+ final playlistId = widget.sourcePlaylistId;+ final collectionId = widget.sourceCollectionId;+ if (playlistId != null && playlistId.isNotEmpty) {+ await PlayerSettings.clearQueueModePlaylistIfActive(playlistId);+ } else if (collectionId != null && collectionId.isNotEmpty) {+ await PlayerSettings.clearQueueModeCollectionIfActive(collectionId);+ }+ }+Future<void> _startAbsorb(BuildContext context, {required AuthProvider auth, required String title, required String author, required String? coverUrl, required double duration, required List<dynamic> chapters}) async {// Discard, not stop: we're about to start playback ourselves, so briefly// resuming the previous book would just be an audible blip.@@ -2043,9 +2114,12 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {final player = AudioPlayerService();// Grab the root navigator before we pop the sheetfinal rootNav = Navigator.of(context, rootNavigator: true);+ final lib = context.read<LibraryProvider>();if (player.currentItemId == widget.itemId) {- if (!player.isPlaying) player.play();+ await _activateQueueSource();+ if (!player.isPlaying) await player.play();+ unawaited(lib.syncQueueAutoDownloads());rootNav.popUntil((route) => route.isFirst);Future.delayed(const Duration(milliseconds: 100), () {AppShell.goToAbsorbingGlobal();@@ -2054,8 +2128,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {}final api = auth.apiService;if (api == null) return;-- final lib = context.mounted ? context.read<LibraryProvider>() : null;+ await _activateQueueSource();// Pop sheets and switch tab BEFORE starting playback. Otherwise the// auto-expand triggered by playItem pushes the expanded player on top@@ -2065,11 +2138,14 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {final error = await player.playItem(api: api, itemId: widget.itemId, title: title, author: author, coverUrl: coverUrl, totalDuration: duration, chapters: chapters, libraryId: _item?['libraryId'] as String?);if (error != null) {+ unawaited(_clearActivatedQueueSource());final ctx = rootNavigatorKey.currentContext;if (ctx != null) showErrorToast(ctx, error);+ } else {+ unawaited(lib.syncQueueAutoDownloads());}- lib?.refreshLocalProgress();- lib?.refresh();+ lib.refreshLocalProgress();+ lib.refresh();}Future<void> _markFinished(BuildContext context, AuthProvider auth, double duration) async {diff --git a/lib/widgets/collection_detail_sheet.dart b/lib/widgets/collection_detail_sheet.dartindex 51614d4d..4b04c274 100644--- a/lib/widgets/collection_detail_sheet.dart+++ b/lib/widgets/collection_detail_sheet.dart@@ -289,8 +289,16 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {child: _editing? _buildEditList(cs, tt, lib, l): _gridView- ? _buildGrid(cs, tt, lib, books, l)- : _buildItemList(cs, tt, lib, books, l, canEditCollection: canEditCollection),+ ? _buildGrid(cs, tt, lib, books, name, l)+ : _buildItemList(+ cs,+ tt,+ lib,+ books,+ name,+ l,+ canEditCollection: canEditCollection,+ ),),if (_editing && canDeleteCollection)Container(@@ -346,7 +354,13 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {AppShell.goToAbsorbingGlobal();await PlayerSettings.setQueueModeCollection(id, name);final started = await lib.playCollectionFromStart(id);- if (started) unawaited(lib.syncQueueAutoDownloads());+ if (started) {+ unawaited(lib.syncQueueAutoDownloads());+ } else {+ unawaited(+ PlayerSettings.clearQueueModeCollectionIfActive(id),+ );+ }}: null,icon: Icon(allFinished@@ -409,7 +423,15 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {);}- Widget _buildItemList(ColorScheme cs, TextTheme tt, LibraryProvider lib, List<dynamic> books, AppLocalizations l, {required bool canEditCollection}) {+ Widget _buildItemList(+ ColorScheme cs,+ TextTheme tt,+ LibraryProvider lib,+ List<dynamic> books,+ String collectionName,+ AppLocalizations l, {+ required bool canEditCollection,+ }) {return ListView.builder(controller: widget.scrollController,padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4).copyWith(bottom: 40),@@ -435,7 +457,12 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),clipBehavior: Clip.antiAlias,child: InkWell(- onTap: () => showBookDetailSheet(context, itemId),+ onTap: () => showBookDetailSheet(+ context,+ itemId,+ sourceCollectionId: widget.collectionId,+ sourceCollectionName: collectionName,+ ),borderRadius: BorderRadius.circular(14),child: SizedBox(height: 112,@@ -574,7 +601,14 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {);}- Widget _buildGrid(ColorScheme cs, TextTheme tt, LibraryProvider lib, List<dynamic> books, AppLocalizations l) {+ Widget _buildGrid(+ ColorScheme cs,+ TextTheme tt,+ LibraryProvider lib,+ List<dynamic> books,+ String collectionName,+ AppLocalizations l,+ ) {return GridView.builder(controller: widget.scrollController,padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4)@@ -600,7 +634,12 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {final isDownloaded = DownloadService().isDownloaded(itemId);return GestureDetector(- onTap: () => showBookDetailSheet(context, itemId),+ onTap: () => showBookDetailSheet(+ context,+ itemId,+ sourceCollectionId: widget.collectionId,+ sourceCollectionName: collectionName,+ ),child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [diff --git a/lib/widgets/episode_detail_sheet.dart b/lib/widgets/episode_detail_sheet.dartindex 512fe316..c89ce8ce 100644--- a/lib/widgets/episode_detail_sheet.dart+++ b/lib/widgets/episode_detail_sheet.dart@@ -1,3 +1,4 @@+import 'dart:async';import 'dart:ui';import 'package:flutter/material.dart';import 'package:provider/provider.dart';@@ -26,21 +27,33 @@ class EpisodeDetailSheet extends StatefulWidget {final Map<String, dynamic> podcastItem;final Map<String, dynamic> episode;final ScrollController? scrollController;+ final String? sourcePlaylistId;/// Compact long-press layout: header + Play + Download + the action grid,/// skipping the description / chapters / all-episodes sections.final bool quick;- const EpisodeDetailSheet({super.key, required this.podcastItem, required this.episode})+ const EpisodeDetailSheet({+ super.key,+ required this.podcastItem,+ required this.episode,+ this.sourcePlaylistId,+ }): scrollController = null, quick = false;const EpisodeDetailSheet._({required this.podcastItem,required this.episode,required this.scrollController,+ this.sourcePlaylistId,this.quick = false,}) : super(key: null);- static void show(BuildContext context, Map<String, dynamic> podcastItem, Map<String, dynamic> episode) {+ static void show(+ BuildContext context,+ Map<String, dynamic> podcastItem,+ Map<String, dynamic> episode, {+ String? sourcePlaylistId,+ }) {final itemKey = podcastItem['id'] ?? identityHashCode(podcastItem);final episodeKey = episode['id'] ?? identityHashCode(episode);final openKey = '$itemKey::$episodeKey';@@ -55,12 +68,18 @@ class EpisodeDetailSheet extends StatefulWidget {podcastItem: podcastItem,episode: episode,scrollController: scrollController,+ sourcePlaylistId: sourcePlaylistId,),).whenComplete(() => _openEpisodeKeys.remove(openKey));}/// Long-press shortcut: a compact quick-actions sheet for one episode.- static void showQuick(BuildContext context, Map<String, dynamic> podcastItem, Map<String, dynamic> episode) {+ static void showQuick(+ BuildContext context,+ Map<String, dynamic> podcastItem,+ Map<String, dynamic> episode, {+ String? sourcePlaylistId,+ }) {showStackableSheet(context: context,useSafeArea: true,@@ -70,6 +89,7 @@ class EpisodeDetailSheet extends StatefulWidget {podcastItem: podcastItem,episode: episode,scrollController: scrollController,+ sourcePlaylistId: sourcePlaylistId,quick: true,),);@@ -110,6 +130,20 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {String get _rawDescription => widget.episode['description'] as String? ?? '';+ Future<void> _activateQueueSource() async {+ final playlistId = widget.sourcePlaylistId;+ if (playlistId != null && playlistId.isNotEmpty) {+ await PlayerSettings.setQueueModePlaylist(playlistId);+ }+ }++ Future<void> _clearActivatedQueueSource() async {+ final playlistId = widget.sourcePlaylistId;+ if (playlistId != null && playlistId.isNotEmpty) {+ await PlayerSettings.clearQueueModePlaylistIfActive(playlistId);+ }+ }+Future<void> _play() async {final auth = context.read<AuthProvider>();final api = auth.apiService;@@ -131,6 +165,12 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {// collapsed after tab transition races with sheet pop animations.final rootNav = Navigator.of(context, rootNavigator: true);final rootContext = rootNav.context;+ final lib = context.read<LibraryProvider>();+ await _activateQueueSource();+ if (!rootNav.mounted) {+ await _clearActivatedQueueSource();+ return;+ }debugPrint('[PodcastPlay] Popping stacked sheets before playItem (item=$_itemId episode=$_episodeId)');rootNav.popUntil((route) => route.isFirst);debugPrint('[PodcastPlay] Sheets popped, calling playItem');@@ -146,8 +186,11 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {libraryId: widget.podcastItem['libraryId'] as String?,);debugPrint('[PodcastPlay] playItem returned in ${DateTime.now().difference(t0).inMilliseconds}ms (error=${error ?? 'none'})');- if (error != null && rootContext.mounted) {- showErrorToast(rootContext, error);+ if (error != null) {+ unawaited(_clearActivatedQueueSource());+ if (rootContext.mounted) showErrorToast(rootContext, error);+ } else {+ unawaited(lib.syncQueueAutoDownloads());}}@@ -386,7 +429,12 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {const SizedBox(height: 16),GestureDetector(onTap: () {- EpisodeListSheet.show(context, widget.podcastItem);+ EpisodeListSheet.show(+ context,+ widget.podcastItem,+ sourcePlaylistId: widget.sourcePlaylistId,+ sourcePlaylistEpisodeId: _episodeId,+ );},child: Container(padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),@@ -693,7 +741,14 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {onTap: () {final rc = rootNavigatorKey.currentContext;Navigator.of(context).pop();- if (rc != null) EpisodeDetailSheet.show(rc, widget.podcastItem, widget.episode);+ if (rc != null) {+ EpisodeDetailSheet.show(+ rc,+ widget.podcastItem,+ widget.episode,+ sourcePlaylistId: widget.sourcePlaylistId,+ );+ }}),];}diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dartindex 2b9e3ff5..f137cd95 100644--- a/lib/widgets/episode_list_sheet.dart+++ b/lib/widgets/episode_list_sheet.dart@@ -27,17 +27,31 @@ export 'episode_detail_sheet.dart';class EpisodeListSheet extends StatefulWidget {final Map<String, dynamic> podcastItem;final ScrollController? scrollController;+ final String? sourcePlaylistId;+ final String? sourcePlaylistEpisodeId;- const EpisodeListSheet({super.key, required this.podcastItem})+ const EpisodeListSheet({+ super.key,+ required this.podcastItem,+ this.sourcePlaylistId,+ this.sourcePlaylistEpisodeId,+ }): scrollController = null;const EpisodeListSheet._({required this.podcastItem,required this.scrollController,+ this.sourcePlaylistId,+ this.sourcePlaylistEpisodeId,}) : super(key: null);/// Show the episode list as a modal bottom sheet.- static void show(BuildContext context, Map<String, dynamic> podcastItem) {+ static void show(+ BuildContext context,+ Map<String, dynamic> podcastItem, {+ String? sourcePlaylistId,+ String? sourcePlaylistEpisodeId,+ }) {showStackableSheet(context: context,useSafeArea: true,@@ -46,6 +60,8 @@ class EpisodeListSheet extends StatefulWidget {builder: (_, scrollController) => EpisodeListSheet._(podcastItem: podcastItem,scrollController: scrollController,+ sourcePlaylistId: sourcePlaylistId,+ sourcePlaylistEpisodeId: sourcePlaylistEpisodeId,),);}@@ -241,6 +257,25 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {});}+ String? _playlistSourceForEpisode(String episodeId) {+ if (widget.sourcePlaylistEpisodeId != episodeId) return null;+ return widget.sourcePlaylistId;+ }++ Future<void> _activateQueueSource(String episodeId) async {+ final playlistId = _playlistSourceForEpisode(episodeId);+ if (playlistId != null && playlistId.isNotEmpty) {+ await PlayerSettings.setQueueModePlaylist(playlistId);+ }+ }++ Future<void> _clearActivatedQueueSource(String episodeId) async {+ final playlistId = _playlistSourceForEpisode(episodeId);+ if (playlistId != null && playlistId.isNotEmpty) {+ await PlayerSettings.clearQueueModePlaylistIfActive(playlistId);+ }+ }+Future<void> _batchMarkFinished(bool finished) async {if (_selectedEpisodeIds.isEmpty) return;final auth = context.read<AuthProvider>();@@ -327,6 +362,8 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {return;}+ final lib = context.read<LibraryProvider>();+ await _activateQueueSource(episodeId);final player = AudioPlayerService();final error = await player.playItem(api: api,@@ -344,6 +381,11 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {// is fine: the player resolves it from the session/server.libraryId: _podcastItem['libraryId'] as String?,);+ if (error == null) {+ unawaited(lib.syncQueueAutoDownloads());+ } else {+ unawaited(_clearActivatedQueueSource(episodeId));+ }if (mounted) {if (error != null) showErrorToast(context, error);Navigator.of(context, rootNavigator: true).popUntil((route) => route.isFirst);@@ -881,6 +923,8 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {podcastTitle: _title,onPlay: () => _playEpisode(ep),onDownload: () => _downloadEpisode(ep),+ sourcePlaylistId:+ _playlistSourceForEpisode(epId),),);},diff --git a/lib/widgets/episode_row.dart b/lib/widgets/episode_row.dartindex 1293403d..2ee9c4e4 100644--- a/lib/widgets/episode_row.dart+++ b/lib/widgets/episode_row.dart@@ -12,6 +12,7 @@ class EpisodeRow extends StatefulWidget {final String podcastTitle;final VoidCallback onPlay;final VoidCallback onDownload;+ final String? sourcePlaylistId;const EpisodeRow({super.key,@@ -21,6 +22,7 @@ class EpisodeRow extends StatefulWidget {required this.podcastTitle,required this.onPlay,required this.onDownload,+ this.sourcePlaylistId,});@override@@ -83,9 +85,19 @@ class _EpisodeRowState extends State<EpisodeRow> {return InkWell(onTap: () {- EpisodeDetailSheet.show(context, widget.podcastItem, ep);+ EpisodeDetailSheet.show(+ context,+ widget.podcastItem,+ ep,+ sourcePlaylistId: widget.sourcePlaylistId,+ );},- onLongPress: () => EpisodeDetailSheet.showQuick(context, widget.podcastItem, ep),+ onLongPress: () => EpisodeDetailSheet.showQuick(+ context,+ widget.podcastItem,+ ep,+ sourcePlaylistId: widget.sourcePlaylistId,+ ),child: Padding(padding: const EdgeInsets.fromLTRB(20, 10, 12, 10),child: Column(diff --git a/lib/widgets/home_section.dart b/lib/widgets/home_section.dartindex bc22acab..c7e85ee4 100644--- a/lib/widgets/home_section.dart+++ b/lib/widgets/home_section.dart@@ -37,9 +37,19 @@ class HomeSection extends StatelessWidget {final isContinueListening = sectionId == 'continue-listening';final isPlaylistSection = sectionType == 'playlist';+ final isCollectionSection = sectionType == 'collection';final isAuthorSection = sectionType == 'author' || sectionType == 'authors';final isSeriesSection = sectionType == 'series';final isEpisodeSection = sectionType == 'episode';+ final sourcePlaylistId = isPlaylistSection+ ? _sourceIdFromSectionId('playlist')+ : null;+ final sourceCollectionId = isCollectionSection+ ? _sourceIdFromSectionId('collection')+ : null;+ final sourceCollectionName = sourceCollectionId == null+ ? null+ : _collectionNameFromTitle(title);// Check if any entities have recentEpisode (podcast episode sections)final hasEpisodeEntities = !isEpisodeSection && entities.isNotEmpty &&@@ -102,12 +112,14 @@ class HomeSection extends StatelessWidget {itemCount: entities.length,itemBuilder: (context, index) {var entity = entities[index];+ String? sourcePlaylistEpisodeId;// Playlist items nest actual item under 'libraryItem'if (isPlaylistSection && entity is Map<String, dynamic>) {final inner = entity['libraryItem'] as Map<String, dynamic>?;if (inner != null) {final episodeId = entity['episodeId'] as String?;+ sourcePlaylistEpisodeId = episodeId;final episode = entity['episode'] as Map<String, dynamic>?;entity = Map<String, dynamic>.from(inner);if (episodeId != null && episode != null) {@@ -134,7 +146,10 @@ class HomeSection extends StatelessWidget {if (isEpisodeSection && entity is Map<String, dynamic>) {return SizedBox(width: cardWidth,- child: _EpisodeCard(item: entity),+ child: _EpisodeCard(+ item: entity,+ sourcePlaylistId: sourcePlaylistId,+ ),);}@@ -144,7 +159,10 @@ class HomeSection extends StatelessWidget {entity['recentEpisode'] != null) {return SizedBox(width: cardWidth,- child: _EpisodeCard(item: entity),+ child: _EpisodeCard(+ item: entity,+ sourcePlaylistId: sourcePlaylistId,+ ),);}@@ -155,6 +173,10 @@ class HomeSection extends StatelessWidget {showProgress: isContinueListening,isWide: isContinueListening,coverAspectRatio: isContinueListening ? 1.0 : coverAspectRatio,+ sourcePlaylistId: sourcePlaylistId,+ sourcePlaylistEpisodeId: sourcePlaylistEpisodeId,+ sourceCollectionId: sourceCollectionId,+ sourceCollectionName: sourceCollectionName,),);},@@ -164,6 +186,18 @@ class HomeSection extends StatelessWidget {),);}++ String? _sourceIdFromSectionId(String type) {+ final prefix = '$type:';+ if (!sectionId.startsWith(prefix)) return null;+ final id = sectionId.substring(prefix.length);+ return id.isEmpty ? null : id;+ }++ String _collectionNameFromTitle(String value) {+ const prefix = 'Server Collection - ';+ return value.startsWith(prefix) ? value.substring(prefix.length) : value;+ }}/// A horizontal scrolling list with smooth snap-to-card behavior.@@ -250,8 +284,12 @@ class _SnapScrollListState extends State<_SnapScrollList> {/// Shows the show cover with the episode title overlaid at the bottom.class _EpisodeCard extends StatelessWidget {final Map<String, dynamic> item;+ final String? sourcePlaylistId;- const _EpisodeCard({required this.item});+ const _EpisodeCard({+ required this.item,+ this.sourcePlaylistId,+ });@overrideWidget build(BuildContext context) {@@ -277,14 +315,28 @@ class _EpisodeCard extends StatelessWidget {return GestureDetector(onTap: () {if (episode != null) {- EpisodeDetailSheet.show(context, item, episode);+ EpisodeDetailSheet.show(+ context,+ item,+ episode,+ sourcePlaylistId: sourcePlaylistId,+ );} else {- EpisodeListSheet.show(context, item);+ EpisodeListSheet.show(+ context,+ item,+ sourcePlaylistId: sourcePlaylistId,+ );}},// Long-press an episode card for its quick-actions sheet (shows stay as-is).onLongPress: episode == null ? null- : () => EpisodeDetailSheet.showQuick(context, item, episode),+ : () => EpisodeDetailSheet.showQuick(+ context,+ item,+ episode,+ sourcePlaylistId: sourcePlaylistId,+ ),child: Column(crossAxisAlignment: CrossAxisAlignment.start,mainAxisSize: MainAxisSize.min,@@ -403,4 +455,4 @@ class _EpisodeCard extends StatelessWidget {),);}-}\ No newline at end of file+}diff --git a/lib/widgets/playlist_detail_sheet.dart b/lib/widgets/playlist_detail_sheet.dartindex 5427a6d7..c8ed389f 100644--- a/lib/widgets/playlist_detail_sheet.dart+++ b/lib/widgets/playlist_detail_sheet.dart@@ -77,12 +77,26 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {if (episodeId != null) {final ep = _findEpisode(playlistItem, libraryItem, episodeId);if (ep != null) {- EpisodeDetailSheet.show(context, libraryItem, ep);+ EpisodeDetailSheet.show(+ context,+ libraryItem,+ ep,+ sourcePlaylistId: widget.playlistId,+ );} else {- EpisodeListSheet.show(context, libraryItem);+ EpisodeListSheet.show(+ context,+ libraryItem,+ sourcePlaylistId: widget.playlistId,+ sourcePlaylistEpisodeId: episodeId,+ );}} else {- showBookDetailSheet(context, libraryItemId);+ showBookDetailSheet(+ context,+ libraryItemId,+ sourcePlaylistId: widget.playlistId,+ );}}@@ -468,7 +482,13 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {AppShell.goToAbsorbingGlobal();await PlayerSettings.setQueueModePlaylist(playlistId);final started = await lib.playPlaylistFromStart(playlistId);- if (started) unawaited(lib.syncQueueAutoDownloads());+ if (started) {+ unawaited(lib.syncQueueAutoDownloads());+ } else {+ unawaited(+ PlayerSettings.clearQueueModePlaylistIfActive(playlistId),+ );+ }}: null,icon: Icon(allFinished@@ -580,7 +600,7 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {final progressKey = episodeId != null ? '$libraryItemId-$episodeId' : libraryItemId;final progress = lib.getProgress(progressKey);final isFinished = lib.getProgressData(progressKey)?['isFinished'] == true;- final isDownloaded = DownloadService().isDownloaded(libraryItemId);+ final isDownloaded = DownloadService().isDownloaded(progressKey);String? episodeTitle;if (episodeId != null) {@@ -723,7 +743,7 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {final progressKey = episodeId != null ? '$libraryItemId-$episodeId' : libraryItemId;final progress = lib.getProgress(progressKey);final isFinished = lib.getProgressData(progressKey)?['isFinished'] == true;- final isDownloaded = DownloadService().isDownloaded(libraryItemId);+ final isDownloaded = DownloadService().isDownloaded(progressKey);String? episodeTitle;if (episodeId != null) {