Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add cast completion handling, finished overlay improvements, and bigger device picker

Nathan Poulson171ea0a287b6
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index f28bcf00..5e62e00b 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -10,6 +10,7 @@ import '../services/api_service.dart';
import '../services/progress_sync_service.dart';
import '../services/download_service.dart';
import '../services/android_auto_service.dart';
+import '../services/chromecast_service.dart';
/// Holds library data and personalized home sections.
class LibraryProvider extends ChangeNotifier {
@@ -309,6 +310,7 @@ class LibraryProvider extends ChangeNotifier {
// Restore manual offline preference and start connectivity monitoring
// Must complete before loading libraries so offline state is correct
AudioPlayerService.setOnBookFinishedCallback(markFinishedLocally);
+ ChromecastService.setOnBookFinishedCallback(markFinishedLocally);
restoreOfflineMode().then((_) {
_startConnectivityMonitoring();
@@ -334,6 +336,7 @@ class LibraryProvider extends ChangeNotifier {
} else {
_lastAuthKey = null;
AudioPlayerService.setOnBookFinishedCallback(null);
+ ChromecastService.setOnBookFinishedCallback(null);
_libraries = [];
_personalizedSections = [];
_series = [];
diff --git a/lib/services/chromecast_service.dart b/lib/services/chromecast_service.dart
index 7f2a16f1..cbd265f3 100644
--- a/lib/services/chromecast_service.dart
+++ b/lib/services/chromecast_service.dart
@@ -39,10 +39,17 @@ class ChromecastService extends ChangeNotifier {
Duration get castPosition => _castPosition;
String? get connectedDeviceName => _connectedDeviceName;
+ /// Called when a book finishes during cast playback (before state is cleared).
+ static void Function(String itemId)? _onBookFinishedCallback;
+ static void setOnBookFinishedCallback(void Function(String itemId)? cb) {
+ _onBookFinishedCallback = cb;
+ }
+
StreamSubscription? _sessionSub, _mediaStatusSub, _positionSub;
Timer? _syncTimer;
final _progressSync = ProgressSyncService();
bool _initialized = false;
+ bool _isCompletingBook = false;
// ── Init ──
@@ -120,6 +127,7 @@ class ChromecastService extends ChangeNotifier {
void _listenToMediaStatus() {
_mediaStatusSub?.cancel();
_mediaStatusSub = GoogleCastRemoteMediaClient.instance.mediaStatusStream.listen((status) {
+ final prev = _playbackState;
if (status == null) {
_playbackState = CastPlaybackState.idle;
} else {
@@ -132,6 +140,17 @@ class ChromecastService extends ChangeNotifier {
default: _playbackState = CastPlaybackState.idle;
}
}
+
+ // Detect playback completion: was playing/buffering → now idle, position near end
+ if (_playbackState == CastPlaybackState.idle &&
+ (prev == CastPlaybackState.playing || prev == CastPlaybackState.buffering) &&
+ _castingItemId != null && _castingDuration > 0) {
+ final pos = _castPosition.inMilliseconds / 1000.0;
+ if (pos >= _castingDuration - 5) {
+ _onCastPlaybackComplete();
+ }
+ }
+
notifyListeners();
});
}
@@ -482,6 +501,61 @@ class ChromecastService extends ChangeNotifier {
notifyListeners();
}
+ // ── Completion ──
+
+ Future<void> _onCastPlaybackComplete() async {
+ if (_isCompletingBook) return;
+ _isCompletingBook = true;
+
+ final itemId = _castingItemId;
+ final episodeId = _castingEpisodeId;
+ final duration = _castingDuration;
+ debugPrint('[Cast] Book complete: $_castingTitle');
+
+ // Mark as finished on the server
+ if (itemId != null && _api != null) {
+ try {
+ if (episodeId != null) {
+ await _api!.updateEpisodeProgress(
+ itemId, episodeId,
+ currentTime: duration,
+ duration: duration,
+ isFinished: true,
+ );
+ } else {
+ await _api!.markFinished(itemId, duration);
+ }
+ debugPrint('[Cast] Marked as finished on server');
+ } catch (e) {
+ debugPrint('[Cast] Failed to mark finished: $e');
+ }
+ }
+
+ // Save locally as finished
+ if (itemId != null) {
+ final progressKey = episodeId != null ? '$itemId-$episodeId' : itemId;
+ await _progressSync.saveLocal(
+ itemId: progressKey,
+ currentTime: duration,
+ duration: duration,
+ speed: 1.0,
+ );
+ }
+
+ // Notify LibraryProvider (episodes don't mark the whole show as finished)
+ if (itemId != null && episodeId == null) {
+ _onBookFinishedCallback?.call(itemId);
+ }
+
+ // Clear casting state but keep connection
+ _syncTimer?.cancel();
+ _castingItemId = _castingEpisodeId = _castingTitle = _castingAuthor = _castingCoverUrl = null;
+ _castingDuration = 0;
+ _castingChapters = [];
+ _isCompletingBook = false;
+ notifyListeners();
+ }
+
// ── Sync ──
Future<void> _saveProgressLocal() async {
diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dart
index 54dd5ad7..7f48b0b9 100644
--- a/lib/widgets/absorbing_card.dart
+++ b/lib/widgets/absorbing_card.dart
@@ -535,7 +535,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
),
],
// Finished overlay
- if (isFinished && !isCastingThis) ...[
+ if (isFinished) ...[
Positioned.fill(
child: Container(
color: Colors.black.withValues(alpha: 0.78),
@@ -570,6 +570,26 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
),
),
const SizedBox(height: 8),
+ if (isDownloaded)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: SizedBox(
+ width: double.infinity,
+ child: GestureDetector(
+ onTap: () => _deleteDownload(dlKey),
+ child: Container(
+ padding: const EdgeInsets.symmetric(vertical: 9),
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(11),
+ border: Border.all(color: Colors.white.withValues(alpha: 0.18)),
+ ),
+ child: const Text('Delete Download',
+ textAlign: TextAlign.center,
+ style: TextStyle(color: Colors.white70, fontSize: 12, fontWeight: FontWeight.w500)),
+ ),
+ ),
+ ),
+ ),
SizedBox(
width: double.infinity,
child: GestureDetector(
@@ -580,7 +600,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
borderRadius: BorderRadius.circular(11),
border: Border.all(color: Colors.white.withValues(alpha: 0.18)),
),
- child: const Text('Remove',
+ child: const Text('Remove from Absorbing',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white70, fontSize: 12, fontWeight: FontWeight.w500)),
),
@@ -825,6 +845,10 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli
if (mounted) setState(() => _isStarting = false);
}
+ void _deleteDownload(String dlKey) {
+ DownloadService().deleteDownload(dlKey);
+ }
+
Future<void> _removeFromAbsorbing() async {
if (widget.player.currentItemId == _itemId) {
await widget.player.pause();
diff --git a/lib/widgets/chromecast_button.dart b/lib/widgets/chromecast_button.dart
index 4bbb5a1b..7b6d5b94 100644
--- a/lib/widgets/chromecast_button.dart
+++ b/lib/widgets/chromecast_button.dart
@@ -36,7 +36,7 @@ void showCastDevicePicker(
Text('Cast to Device', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: cs.onSurface)),
const SizedBox(height: 16),
SizedBox(
- height: 200,
+ height: 400,
child: StreamBuilder<List<GoogleCastDevice>>(
stream: cast.devicesStream,
builder: (_, snap) {