Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add "When finished" setting with overlay and auto-remove options

Nathan Poulsoneb9e21735809
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index a6e958e1..be425025 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -1263,6 +1263,9 @@ class LibraryProvider extends ChangeNotifier {
if (_selectedLibraryId != null && !isOffline) {
loadPersonalizedView(force: true);
}
+ PlayerSettings.getWhenFinished().then((mode) {
+ if (mode == 'auto_remove') removeFromAbsorbing(itemId);
+ });
});
return; // skip the default refresh below — handled above
}
@@ -1271,6 +1274,9 @@ class LibraryProvider extends ChangeNotifier {
// Brief delay so the server has time to populate continue-series
Future.delayed(const Duration(milliseconds: 500), () {
loadPersonalizedView(force: true);
+ PlayerSettings.getWhenFinished().then((mode) {
+ if (mode == 'auto_remove') removeFromAbsorbing(itemId);
+ });
});
}
}
diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart
index dac11e65..2b5c4ce5 100644
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@ -40,6 +40,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
int _shakeAddMinutes = 5;
bool _autoPlayNextBook = false;
bool _autoPlayNextPodcast = false;
+ String _whenFinished = 'overlay';
bool _hideEbookOnly = false;
bool _showGoodreadsButton = false;
bool _loggingEnabled = false;
@@ -71,6 +72,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
final shakeMins = await PlayerSettings.getShakeAddMinutes();
final autoPlayBook = await PlayerSettings.getAutoPlayNextBook();
final autoPlayPod = await PlayerSettings.getAutoPlayNextPodcast();
+ final whenFinished = await PlayerSettings.getWhenFinished();
final hideEbook = await PlayerSettings.getHideEbookOnly();
final showGoodreads = await PlayerSettings.getShowGoodreadsButton();
final logging = await PlayerSettings.getLoggingEnabled();
@@ -95,6 +97,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
_shakeAddMinutes = shakeMins;
_autoPlayNextBook = autoPlayBook;
_autoPlayNextPodcast = autoPlayPod;
+ _whenFinished = whenFinished;
_hideEbookOnly = hideEbook;
_showGoodreadsButton = showGoodreads;
_loggingEnabled = logging;
@@ -607,6 +610,29 @@ class _SettingsScreenState extends State<SettingsScreen> {
} : null,
),
const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text('When finished', style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ const SizedBox(height: 4),
+ Text('What happens to the absorbing card when a book or episode finishes',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ const SizedBox(height: 8),
+ SizedBox(width: double.infinity, child: SegmentedButton<String>(
+ segments: const [
+ ButtonSegment(value: 'overlay', icon: Icon(Icons.layers_rounded), label: Text('Show Overlay')),
+ ButtonSegment(value: 'auto_remove', icon: Icon(Icons.auto_delete_rounded), label: Text('Auto-remove')),
+ ],
+ selected: {_whenFinished},
+ onSelectionChanged: _loaded ? (s) {
+ setState(() => _whenFinished = s.first);
+ PlayerSettings.setWhenFinished(s.first);
+ } : null,
+ style: const ButtonStyle(visualDensity: VisualDensity.compact),
+ )),
+ ]),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
// ── Auto-Rewind ──
SwitchListTile(
title: const Text('Auto-rewind on resume'),
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index e93ead50..a46a77c8 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -95,6 +95,9 @@ class PlayerSettings {
static Future<bool> getAutoPlayNextPodcast() => _get('autoPlayNextPodcast', false);
static Future<void> setAutoPlayNextPodcast(bool value) => _set('autoPlayNextPodcast', value);
+ static Future<String> getWhenFinished() => _get('whenFinished', 'overlay');
+ static Future<void> setWhenFinished(String value) => _set('whenFinished', value);
+
// ── Player UI settings (notify listeners on change) ──
static Future<bool> getShowBookSlider() => _get('showBookSlider', false);
@@ -1169,6 +1172,17 @@ class AudioPlayerService extends ChangeNotifier {
_playbackSessionId = sessionData['id'] as String?;
debugPrint('[Player] Got server session for local playback: $_playbackSessionId');
+ // Pick up chapters from session (e.g. podcast episodes with embedded chapters)
+ if (chapters.isEmpty) {
+ final sessionChapters = sessionData['chapters'] as List<dynamic>? ?? [];
+ if (sessionChapters.isNotEmpty) {
+ chapters = sessionChapters;
+ _chapters = sessionChapters;
+ _handler?.updateChaptersQueue(sessionChapters);
+ debugPrint('[Player] Loaded ${sessionChapters.length} chapters from session');
+ }
+ }
+
// Compare server position vs local — always use whichever is further ahead.
// You can't un-listen to a book, so the furthest position is the most recent.
// (Session updatedAt is unreliable — it reflects session creation time, not
@@ -1212,13 +1226,23 @@ class AudioPlayerService extends ChangeNotifier {
return false;
}
- // Get cached session data for track durations
+ // Get cached session data for track durations (and chapters if needed)
final cachedJson = _downloadService.getCachedSessionData(itemId);
List<dynamic>? audioTracks;
if (cachedJson != null) {
try {
final session = jsonDecode(cachedJson) as Map<String, dynamic>;
audioTracks = session['audioTracks'] as List<dynamic>?;
+ // Pick up chapters from cached session when not already loaded
+ if (chapters.isEmpty) {
+ final cachedChapters = session['chapters'] as List<dynamic>? ?? [];
+ if (cachedChapters.isNotEmpty) {
+ chapters = cachedChapters;
+ _chapters = cachedChapters;
+ _handler?.updateChaptersQueue(cachedChapters);
+ debugPrint('[Player] Loaded ${cachedChapters.length} chapters from cached session');
+ }
+ }
} catch (_) {}
}
@@ -1300,6 +1324,17 @@ class AudioPlayerService extends ChangeNotifier {
return false;
}
+ // Pick up chapters from session (e.g. podcast episodes with embedded chapters)
+ if (chapters.isEmpty) {
+ final sessionChapters = sessionData['chapters'] as List<dynamic>? ?? [];
+ if (sessionChapters.isNotEmpty) {
+ chapters = sessionChapters;
+ _chapters = sessionChapters;
+ _handler?.updateChaptersQueue(sessionChapters);
+ debugPrint('[Player] Loaded ${sessionChapters.length} chapters from session');
+ }
+ }
+
// Update totalDuration from session if it was unknown (e.g. podcast episodes
// where the embedded recentEpisode didn't include a duration field)
if (totalDuration <= 0) {
diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dart
index e2cd03c1..f5b212a7 100644
--- a/lib/widgets/absorbing_card.dart
+++ b/lib/widgets/absorbing_card.dart
@@ -43,6 +43,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
ui.Image? _blurredCover; // Precached blurred background
String? _blurredCoverUrl; // URL the blur was built from
List<String> _buttonOrder = PlayerSettings.defaultButtonOrder;
+ bool _autoRemoveFinished = false;
@override
bool get wantKeepAlive => true;
@@ -56,7 +57,11 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
List<dynamic> get _chapters {
// Prefer fetched chapters (from full item), fall back to inline data
if (_fetchedChapters != null && _fetchedChapters!.isNotEmpty) return _fetchedChapters!;
- return _media['chapters'] as List<dynamic>? ?? [];
+ final inline = _media['chapters'] as List<dynamic>? ?? [];
+ if (inline.isNotEmpty) return inline;
+ // For active podcast episodes, chapters come from the playback session
+ if (_isActive && widget.player.chapters.isNotEmpty) return widget.player.chapters;
+ return [];
}
bool get _isActive {
if (widget.player.currentItemId != _itemId) return false;
@@ -113,6 +118,13 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
DownloadService().addListener(_onDownloadChanged);
PlayerSettings.settingsChanged.addListener(_reloadButtonOrder);
_reloadButtonOrder();
+ _loadWhenFinished();
+ }
+
+ void _loadWhenFinished() {
+ PlayerSettings.getWhenFinished().then((mode) {
+ if (mounted) setState(() => _autoRemoveFinished = mode == 'auto_remove');
+ });
}
void _reloadButtonOrder() {
@@ -452,7 +464,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
shadows: [Shadow(color: isDark ? Colors.black.withValues(alpha: 0.6) : Colors.white.withValues(alpha: 0.6), blurRadius: 4)],
)),
const Spacer(),
- if (totalChapters > 0 && !_isPodcastEpisode)
+ if (totalChapters > 0 && (!_isPodcastEpisode || _chapters.isNotEmpty))
Text('Ch ${(chapterIdx + 1).clamp(1, totalChapters)} / $totalChapters',
style: tt.labelMedium?.copyWith(
color: isDark ? Colors.white.withValues(alpha: 0.85) : Colors.black.withValues(alpha: 0.75),
@@ -465,7 +477,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
// ── Book progress bar ──
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
- child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: progress, staticDuration: _effectiveDuration, chapters: _chapters, showBookBar: !_isPodcastEpisode && !lib.isPodcastLibrary, showChapterBar: false, itemId: _itemId),
+ child: CardDualProgressBar(player: widget.player, accent: accent, isActive: _isActive, staticProgress: progress, staticDuration: _effectiveDuration, chapters: _chapters, showBookBar: (!_isPodcastEpisode || _chapters.isNotEmpty) && (!lib.isPodcastLibrary || _chapters.isNotEmpty), showChapterBar: false, itemId: _itemId),
),
const SizedBox(height: 10),
// ── Cover with title/author/chapter overlaid + download badge ──
@@ -566,7 +578,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
),
],
// Finished overlay
- if (isFinished) ...[
+ if (isFinished && !_autoRemoveFinished) ...[
Positioned.fill(
child: Container(
color: Colors.black.withValues(alpha: 0.78),
@@ -657,7 +669,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 && _chapters.isEmpty) ? 0.0 : progress, staticDuration: (_isPodcastEpisode && _chapters.isEmpty) ? widget.player.totalDuration : _effectiveDuration, chapters: _chapters, showBookBar: false, showChapterBar: true, chapterName: (_isPodcastEpisode && _chapters.isEmpty) ? (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(