Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Make the sleep timer rewind stick, stop paused books jumping back to an older spot, show podcast playlists again, keep playing when the files run past the last chapter, say when a download has to stream, show downloaded books on Home and stop logins from spinning forever

Barnabas3824040bd841
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index 4af30ec7..d16bf6d4 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -1763,6 +1763,14 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
// the paused player back and then syncs that old spot up over the
// real one. The position saved here carries its own timestamp.
unawaited(() async {
+ // This phone's own sync coming back can only be behind where it
+ // is now (GH #440), whatever the clocks say.
+ final from = mp['fromSession'];
+ if (from != null && from == player.playbackSessionId) {
+ debugPrint('[Sync] Ignoring remote position for paused player: '
+ "it is this phone's own sync ($from)");
+ return;
+ }
final savedAt =
await ProgressSyncService().getSavedTimestamp(key);
if (newUpd <= savedAt) {
@@ -1963,6 +1971,10 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
}
}
}
+ // Playlists and collections load straight away: they came last, and a
+ // podcast-only step below that threw skipped them (GH #413).
+ loadPlaylists();
+ loadCollections();
_narratedToContinueListening();
await (this as _AbsorbingMixin)._updateAbsorbingCache();
@@ -1976,9 +1988,6 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
if (isPodcastLibrary) {
_hydrateRssFeedFieldsDeferred();
}
-
- loadPlaylists();
- loadCollections();
} catch (e) {
if (_isLikelyNetworkError(e)) {
_goOffline();
@@ -2200,31 +2209,41 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
Future<void> loadPlaylists({bool force = false}) async {
if (_api == null || _selectedLibraryId == null || isOffline) return;
+ final libId = _selectedLibraryId!;
+ // A load already running for another library (a switch mid-load) would
+ // hand this one that library's playlists.
final existing = _playlistsInFlight;
- if (existing != null) {
+ if (existing != null && _playlistsInFlightFor == libId) {
await existing;
return;
}
- final inFlight = _doLoadPlaylists();
+ final inFlight = _doLoadPlaylists(libId);
_playlistsInFlight = inFlight;
+ _playlistsInFlightFor = libId;
try {
await inFlight;
} finally {
if (identical(_playlistsInFlight, inFlight)) {
_playlistsInFlight = null;
+ _playlistsInFlightFor = null;
}
}
}
- Future<void> _doLoadPlaylists() async {
+ Future<void> _doLoadPlaylists([String? forLibrary]) async {
+ final libId = forLibrary ?? _selectedLibraryId;
+ if (_api == null || libId == null) return;
_isLoadingPlaylists = true;
try {
// Keep whatever we already had when the request fails, rather than
// blanking the shelves over one bad response.
- final loaded = await _api!.getLibraryPlaylists(_selectedLibraryId!);
- if (loaded != null) _playlists = loaded;
- } catch (_) {}
+ final loaded = await _api!.getLibraryPlaylists(libId);
+ if (loaded != null && _selectedLibraryId == libId) _playlists = loaded;
+ debugPrint('[Library] playlists for $libId: ${loaded?.length ?? 'failed'}');
+ } catch (e) {
+ debugPrint('[Library] playlists for $libId failed: $e');
+ }
_isLoadingPlaylists = false;
notifyListeners();
unawaited(_catchUpQueueAutoDownloads());
@@ -2313,28 +2332,33 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
Future<void> loadCollections({bool force = false}) async {
if (_api == null || _selectedLibraryId == null || isOffline) return;
+ final libId = _selectedLibraryId!;
final existing = _collectionsInFlight;
- if (existing != null) {
+ if (existing != null && _collectionsInFlightFor == libId) {
await existing;
return;
}
- final inFlight = _doLoadCollections();
+ final inFlight = _doLoadCollections(libId);
_collectionsInFlight = inFlight;
+ _collectionsInFlightFor = libId;
try {
await inFlight;
} finally {
if (identical(_collectionsInFlight, inFlight)) {
_collectionsInFlight = null;
+ _collectionsInFlightFor = null;
}
}
}
- Future<void> _doLoadCollections() async {
+ Future<void> _doLoadCollections([String? forLibrary]) async {
+ final libId = forLibrary ?? _selectedLibraryId;
+ if (_api == null || libId == null) return;
_isLoadingCollections = true;
try {
- final loaded = await _api!.getLibraryCollections(_selectedLibraryId!);
- if (loaded != null) _collections = loaded;
+ final loaded = await _api!.getLibraryCollections(libId);
+ if (loaded != null && _selectedLibraryId == libId) _collections = loaded;
} catch (_) {}
_isLoadingCollections = false;
notifyListeners();
diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dart
index 256f009d..b028c794 100644
--- a/lib/providers/_lp_state.dart
+++ b/lib/providers/_lp_state.dart
@@ -56,10 +56,12 @@ mixin _StateMixin on ChangeNotifier {
List<dynamic> _playlists = [];
bool _isLoadingPlaylists = false;
Future<void>? _playlistsInFlight;
+ String? _playlistsInFlightFor;
List<dynamic> _collections = [];
bool _isLoadingCollections = false;
Future<void>? _collectionsInFlight;
+ String? _collectionsInFlightFor;
List<String> _sectionOrder = [];
Set<String> _hiddenSectionIds = {};
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index f7f8f57c..39b837de 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -509,6 +509,10 @@ class LibraryProvider extends ChangeNotifier
await _rememberBookLibrary(libraryId);
await _loadSectionPrefs();
notifyListeners();
+ // The shelves can come from the cache without a fetch, and playlists
+ // and collections were just cleared, so they load either way.
+ unawaited(loadPlaylists());
+ unawaited(loadCollections());
await loadPersonalizedView();
AndroidAutoService().refresh(force: true);
CarPlayService().refreshTemplates();
diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart
index f6b329e4..a8fdf106 100644
--- a/lib/screens/home_screen.dart
+++ b/lib/screens/home_screen.dart
@@ -15,6 +15,7 @@ import '../services/ebook_cache.dart';
import '../services/narrated_books.dart';
import '../services/narration_service.dart';
import '../widgets/ebook_router.dart';
+import '../widgets/cover_badges.dart';
import '../widgets/overlay_toast.dart';
import '../widgets/narration_download_dialog.dart';
import '../widgets/desktop_batch_actions.dart';
@@ -1159,6 +1160,13 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {
Positioned.fill(
child: _buildCoverImage(coverUrl, cs, lib.mediaHeaders),
),
+ if (DownloadService().isDownloaded(playbackDownloadKey(itemId, episodeId)))
+ const Positioned(
+ left: 0,
+ right: 0,
+ bottom: 0,
+ child: CoverStateBadges(isDownloaded: true, isFinished: false),
+ ),
if (isCurrentItem && player.isPlaying)
Positioned(
right: 6, bottom: 6,
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 1991a8ac..7d48c046 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -1011,12 +1011,17 @@ class ApiService {
if (!kIsWeb) 'User-Agent': userAgent,
},
body: jsonEncode({'username': username, 'password': password}),
- );
+ // A server that takes the connection and then never answers (a proxy
+ // up with the server behind it down) left the sign-in spinning forever.
+ ).timeout(const Duration(seconds: 20));
if (response.statusCode == 200) {
return (jsonDecode(response.body) as Map<String, dynamic>, 200);
}
return (null, response.statusCode);
+ } on TimeoutException {
+ debugPrint('[API] login to $url got no answer in 20s');
+ return (null, 0);
} catch (e) {
return (null, 0);
}
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index dd38cbb7..9caa9750 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -35,6 +35,7 @@ import '../utils/episode_key.dart';
import '../utils/duration_format.dart';
import '../l10n/app_localizations.dart';
import '../main.dart' show rootNavigatorKey;
+import '../widgets/overlay_toast.dart' show showNavigatorOverlayToast;
export 'player_settings.dart';
String playbackDownloadKey(String itemId, String? episodeId) =>
@@ -1489,6 +1490,14 @@ class AudioPlayerService extends ChangeNotifier {
ApiService? get currentApi => _api;
String? _playbackSessionId;
+ /// The server session this phone is playing on, so its own syncs echoed
+ /// back over the socket can be told apart from another device's.
+ String? get playbackSessionId => _playbackSessionId;
+
+ // A source swap started by pausing. A seek waits for it: the swap reloads
+ // at the spot it saw, so a seek that landed first was undone (GH #433).
+ Future<void>? _pauseSwap;
+
/// Phase 1.7: latest streaming URLs (with auth token already in the
/// query string) and custom HTTP headers needed by reverse proxies like
/// Cloudflare Access. Stashed to the iOS app group on each player update
@@ -2853,8 +2862,21 @@ class AudioPlayerService extends ChangeNotifier {
}
/// Seek to an absolute book position, handling multi-file offset conversion.
+ // A seek that lands at the very end of a file never answers on Android,
+ // and everything waiting on it hung with it (GH #428).
+ static const _seekCap = Duration(seconds: 6);
+ void _seekTimedOut() => debugPrint('[Player] Seek got no answer in ${_seekCap.inSeconds}s - carrying on');
+
Future<void> _seekAbsolute(double absoluteSeconds) async {
if (_player == null) return;
+ final swap = _pauseSwap;
+ if (swap != null) {
+ _pauseSwap = null;
+ try {
+ await swap;
+ } catch (_) {}
+ if (_player == null) return;
+ }
_lastSeekTargetSec = absoluteSeconds;
_lastSeekAt = DateTime.now();
@@ -2896,9 +2918,9 @@ class AudioPlayerService extends ChangeNotifier {
if (_trackStartOffsets.length <= 1) {
// Single file — seek directly
- await _player!.seek(
- Duration(milliseconds: (absoluteSeconds * 1000).round()),
- );
+ await _player!
+ .seek(Duration(milliseconds: (absoluteSeconds * 1000).round()))
+ .timeout(_seekCap, onTimeout: _seekTimedOut);
notifyListeners();
return;
}
@@ -2915,10 +2937,9 @@ class AudioPlayerService extends ChangeNotifier {
);
// Update index BEFORE seeking so positionStream events use the right offset
_currentTrackIndex = i;
- await _player!.seek(
- Duration(milliseconds: (localOffset * 1000).round()),
- index: i,
- );
+ await _player!
+ .seek(Duration(milliseconds: (localOffset * 1000).round()), index: i)
+ .timeout(_seekCap, onTimeout: _seekTimedOut);
notifyListeners();
return;
}
@@ -3184,6 +3205,9 @@ class AudioPlayerService extends ChangeNotifier {
// prompts rewind like a manual pause, gated by activationDelay.
await service._player?.pause();
service._lastPauseTime = DateTime.now();
+ // Keep the spot on this phone, though: without it a server copy
+ // up to a sync behind could be taken for newer (GH #440).
+ unawaited(service._saveProgressLocal(service.position));
// Android reports a permanent focus loss (another app or the
// car's own source took the audio for good) as `unknown`; calls
// and nav prompts come as transient `pause`/`duck`. Only a
@@ -4599,7 +4623,17 @@ class AudioPlayerService extends ChangeNotifier {
forceTranscode: true,
generation: gen,
);
- if (fallbackResult == null) return null;
+ if (fallbackResult == null) {
+ // Streaming uses data the download was meant to save, so say so.
+ final l = _l10n();
+ showNavigatorOverlayToast(
+ rootNavigatorKey.currentState,
+ l?.playerDownloadStreamingInstead ??
+ "This download couldn't be played, so it's streaming from the server. Downloading it again may fix it.",
+ icon: Icons.cloud_download_outlined,
+ );
+ return null;
+ }
debugPrint(
'[Player] Transcoded fallback after local failure did not start: $fallbackResult',
);
@@ -6387,7 +6421,16 @@ class AudioPlayerService extends ChangeNotifier {
// ─── Completion detection (fallback) ───────────────────
// processingStateStream is the primary signal; this is a safety net.
- if (_totalDuration > 0 && posSec >= _totalDuration - 1.0) {
+ // Files that run longer than the server indexed them (changed on
+ // disk after a scan) play on: ending the book at the indexed length
+ // tore the player down mid-audio and left it stuck (GH #428).
+ if (_totalDuration > 0 && posSec >= _totalDuration - 1.0 && !_engineAtEnd()) {
+ if (_overrunLoggedFor != _currentItemId) {
+ _overrunLoggedFor = _currentItemId;
+ debugPrint('[Player] Audio runs past the indexed length '
+ '(${_totalDuration.toStringAsFixed(0)}s) - playing on until the files end');
+ }
+ } else if (_totalDuration > 0 && posSec >= _totalDuration - 1.0) {
if (_preloadedNextBook != null && _isBackgrounded && Platform.isIOS) {
debugPrint(
'[PreBuffer] Position-fallback near end with pre-buffer loaded — firing auto-queue advance',
@@ -6666,6 +6709,19 @@ class AudioPlayerService extends ChangeNotifier {
bool _isCompletingBook = false;
+ String? _overrunLoggedFor;
+
+ /// Whether the player itself is at the end of the last file, rather than
+ /// only past the length the server indexed.
+ bool _engineAtEnd() {
+ final p = _player;
+ if (p == null) return true;
+ if (_trackStartOffsets.length > 1 && _currentTrackIndex < _trackStartOffsets.length - 2) return false;
+ final d = p.duration;
+ if (d == null || d <= Duration.zero) return true;
+ return p.position >= d - const Duration(seconds: 2);
+ }
+
Future<void> _onPlaybackComplete({bool userRequested = false}) async {
// Alpha: captures completion path choice for GH #186 (book restart bug).
// Re-entry attempts are logged too so we can see if completion fires
@@ -6775,7 +6831,9 @@ class AudioPlayerService extends ChangeNotifier {
// automaticallyWaitsToMinimizeStalling=false this gives gapless
// background auto-advance. GH #244.
if (Platform.isAndroid) {
- await _player?.stop();
+ await _player?.stop().timeout(const Duration(seconds: 5), onTimeout: () {
+ debugPrint('[Complete] player stop took over 5s - carrying on');
+ });
} else {
await _player?.pause();
}
@@ -6836,11 +6894,17 @@ class AudioPlayerService extends ChangeNotifier {
// any auto-advance begins a new session (awaited to avoid racing it).
if (_localSessionMode) {
_logEvent(PlaybackEventType.sessionEnd, detail: 'local book finished');
+ // Capped: a dozing phone on a slow tunnel left the book half finished
+ // with the controls gone (GH #428).
bool pushed = false;
if (_api != null) {
- pushed = await LocalSessionService().pushActive(api: _api!);
+ pushed = await LocalSessionService()
+ .pushActive(api: _api!)
+ .timeout(const Duration(seconds: 8), onTimeout: () => false);
}
- await LocalSessionService().finalizeActive(pushed: pushed);
+ await LocalSessionService()
+ .finalizeActive(pushed: pushed)
+ .timeout(const Duration(seconds: 8), onTimeout: () {});
}
// Notify LibraryProvider before clearing state so it can update isFinished locally.
@@ -7839,9 +7903,11 @@ class AudioPlayerService extends ChangeNotifier {
// A finished download goes first - once on the files the session's URLs
// no longer matter.
if (_pendingLocalSwapKey != null) {
- unawaited(_applyPendingLocalSwap(resumeAfter: false));
+ final swap = _pauseSwap = _applyPendingLocalSwap(resumeAfter: false);
+ unawaited(swap);
} else if (_pendingSessionUpgrade != null) {
- unawaited(_applyPendingSessionUpgrade(resumeAfter: false));
+ final swap = _pauseSwap = _applyPendingSessionUpgrade(resumeAfter: false);
+ unawaited(swap);
}
// After 10 min paused, close the server session so we don't inflate
@@ -7921,6 +7987,19 @@ class AudioPlayerService extends ChangeNotifier {
logAs: PlaybackEventType.autoRewind,
logDetail: '$amount (sleep timer)',
);
+ // Pausing for sleep already saved and sent the spot from before the
+ // rewind, so a restart or another device went back there (GH #433).
+ debugPrint('[SleepTimer] Saving the rewound spot: ${(target.inMilliseconds / 1000.0).toStringAsFixed(1)}s');
+ await _saveProgressLocal(target);
+ final manualOffline =
+ (_prefs ?? await SharedPreferences.getInstance()).getBool('manual_offline_mode') ?? false;
+ if (manualOffline || _isOfflineMode) return;
+ if (_playbackSessionId != null) {
+ await _syncToServer(target, timeListenedOverride: 0);
+ } else if (_currentItemId != null && _api != null) {
+ final syncKey = _currentEpisodeId != null ? '$_currentItemId-$_currentEpisodeId' : _currentItemId!;
+ _progressSync.syncToServer(api: _api!, itemId: syncKey);
+ }
}
Future<void> skipForward([int seconds = 30]) async {
diff --git a/lib/services/socket_service.dart b/lib/services/socket_service.dart
index 9377a214..e7e2951e 100644
--- a/lib/services/socket_service.dart
+++ b/lib/services/socket_service.dart
@@ -389,7 +389,7 @@ class SocketService {
if (data is Map<String, dynamic>) {
final patch = data['data'] as Map<String, dynamic>?;
if (patch != null) {
- onProgressUpdated?.call(patch);
+ onProgressUpdated?.call(_withSession(patch, data));
}
}
});
@@ -523,6 +523,14 @@ class SocketService {
}
/// Disconnect and tear down the socket, clearing all callbacks.
+ /// The progress row with the server session that sent it, when there was
+ /// one, so this phone can tell its own syncs echoed back from another
+ /// device's.
+ static Map<String, dynamic> _withSession(Map<String, dynamic> patch, Map<String, dynamic> event) {
+ final session = event['sessionId'];
+ return session is String ? {...patch, 'fromSession': session} : patch;
+ }
+
void disconnect() {
_socket?.dispose();
_socket = null;
@@ -596,7 +604,7 @@ class SocketService {
_socket!.on('user_item_progress_updated', (data) {
if (data is Map<String, dynamic>) {
final patch = data['data'] as Map<String, dynamic>?;
- if (patch != null) onProgressUpdated?.call(patch);
+ if (patch != null) onProgressUpdated?.call(_withSession(patch, data));
}
});