A cross platform Audiobookshelf client for Android and iOS
Dart
Fix some issues with recent additions
Barnabas005cf092b01f
diff --git a/lib/providers/_lp_absorbing.dart b/lib/providers/_lp_absorbing.dartindex 73015d1f..7c73a049 100644--- a/lib/providers/_lp_absorbing.dart+++ b/lib/providers/_lp_absorbing.dart@@ -527,7 +527,9 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {}void markFinishedLocally(String itemId,- {bool skipRefresh = false, bool skipAutoAdvance = false}) {+ {bool skipRefresh = false,+ bool skipAutoAdvance = false,+ bool fromRemote = false}) {_resetItems.remove(itemId);final existing = _progressMap[itemId] ?? {};if (itemId.length > 36 && existing['isFinished'] != true) {@@ -577,7 +579,9 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {_checkRollingDownloads(itemId);unawaited(_catchUpQueueAutoDownloads());- if (DownloadService().isDownloaded(itemId)) {+ // The delete-absorbed-downloads setting promises that finishing an item+ // on the web or another device never deletes the download on this one.+ if (!fromRemote && DownloadService().isDownloaded(itemId)) {PlayerSettings.getRollingDownloadDeleteFinished().then((delete) {if (!delete) return;DownloadService().deleteDownload(itemId, skipStopCheck: true);diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dartindex f86530e0..a6101828 100644--- a/lib/providers/_lp_core.dart+++ b/lib/providers/_lp_core.dart@@ -18,6 +18,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {_checkRollingDownloads(playingKey);unawaited(_checkQueueAutoDownloads(playingKey));}+ unawaited(_catchUpListRollingDownloads(onlyListId: seriesOrShowId));}Future<void> disableRollingDownload(String seriesOrShowId) async {@@ -146,7 +147,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {ProgressSyncService().flushOfflineListeningTime(api: _api!);LocalSessionService().flushPending(api: _api!);}- if (_selectedLibraryId == null) {+ if (_selectedLibraryId == null || _librariesFromCache) {(this as LibraryProvider).loadLibraries();} else {(this as LibraryProvider).refresh();@@ -247,7 +248,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {ProgressSyncService().flushOfflineListeningTime(api: _api!);LocalSessionService().flushPending(api: _api!);}- if (_selectedLibraryId == null) {+ if (_selectedLibraryId == null || _librariesFromCache) {(this as LibraryProvider).loadLibraries();} else {(this as LibraryProvider).refresh();@@ -1226,7 +1227,8 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {: player.currentItemId;if (key == playingKey && player.hasBook) {if (mp['isFinished'] == true && !_resetItems.contains(key)) {- (this as _AbsorbingMixin).markFinishedLocally(key, skipAutoAdvance: true);+ (this as _AbsorbingMixin)+ .markFinishedLocally(key, skipAutoAdvance: true, fromRemote: true);} else if (mp['isFinished'] != true) {_progressMap[key] = mp;_localProgressOverrides.remove(key);@@ -2230,6 +2232,8 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {_checkRollingDownloads(latestBookKey);}}++ await _catchUpListRollingDownloads();}void _checkRollingDownloads(String playingKey) async {@@ -2259,7 +2263,10 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {final activeShowId = activeKey != null && activeKey.length > 36? activeKey.substring(0, 36): null;- final activeQueueOwnsWindow = activeQueueMode != 'off' &&+ // Only an auto_next queue follows this same show; playlist and+ // collection queues plan their own list's window instead, so they+ // must not suppress the show's rolling download.+ final activeQueueOwnsWindow = activeQueueMode == 'auto_next' &&resolveQueueAutoDownloadEnabled(queueMode: activeQueueMode,globalEnabled: globalQueueAutoDownload,@@ -2304,7 +2311,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {}}}- final activeQueueOwnsWindow = activeQueueMode != 'off' &&+ final activeQueueOwnsWindow = activeQueueMode == 'auto_next' &&resolveQueueAutoDownloadEnabled(queueMode: activeQueueMode,globalEnabled: globalQueueAutoDownload,@@ -2369,8 +2376,13 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {return episodeId == null ? itemId : '$itemId-$episodeId';}+ // Plans anchored to live playback abort when the user moves on; plans+ // from catch-up or an idle toggle have no playback to go stale against.+ final anchoredToPlayback = playingNow() == playingKey;bool isStale() =>- _api == null || isOffline || playingNow() != playingKey;+ _api == null ||+ isOffline ||+ (anchoredToPlayback && playingNow() != playingKey);Future<bool> settingsStillMatch() async =>!isStale() && await PlayerSettings.getRollingDownloadCount() == count;@@ -2404,12 +2416,75 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {count: count,api: api,isStale: isStale,- settingsStillMatch: settingsStillMatch,+ settingsStillMatch: () async =>+ await settingsStillMatch() &&+ _rollingDownloadSeries.contains(source.id),logLabel: '${source.kind}=${source.id}',);}}+ /// Plan list windows without a playback anchor: on launch/reconnect and+ /// when a list's toggle is turned on while idle. Anchors at the member+ /// with the most recent unfinished progress, or the first unfinished+ /// member of a list that was never started. A list whose member is+ /// currently playing is skipped - the playback-anchored check owns it.+ Future<void> _catchUpListRollingDownloads({String? onlyListId}) async {+ if (_api == null || isOffline || _rollingDownloadSeries.isEmpty) return;+ final count = await PlayerSettings.getRollingDownloadCount();+ if (count <= 0) return;+ final self = this as LibraryProvider;++ final player = AudioPlayerService();+ final playingItemId = player.currentItemId;+ final playingKey = playingItemId == null+ ? null+ : player.currentEpisodeId == null+ ? playingItemId+ : '$playingItemId-${player.currentEpisodeId}';++ final anchors = <String>{};+ void collectAnchor(String? id, List<Map<String, dynamic>> items) {+ if (id == null || !_rollingDownloadSeries.contains(id)) return;+ if (onlyListId != null && id != onlyListId) return;+ String? latestKey;+ num latestUpdate = -1;+ String? firstUnfinishedKey;+ for (final item in items) {+ final key = self._playlistItemKey(item);+ if (key.isEmpty) continue;+ if (key == playingKey) return;+ final progress = _progressMap[key];+ if (progress?['isFinished'] == true) continue;+ firstUnfinishedKey ??= key;+ final lastUpdate = progress?['lastUpdate'] as num? ?? 0;+ if (progress != null && lastUpdate > latestUpdate) {+ latestUpdate = lastUpdate;+ latestKey = key;+ }+ }+ final anchor = latestKey ?? firstUnfinishedKey;+ if (anchor != null) anchors.add(anchor);+ }++ for (final raw in _playlists) {+ if (raw is! Map<String, dynamic>) continue;+ collectAnchor(+ raw['id'] as String?,+ (raw['items'] as List<dynamic>? ?? const [])+ .whereType<Map<String, dynamic>>()+ .toList());+ }+ for (final raw in _collections) {+ if (raw is! Map<String, dynamic>) continue;+ collectAnchor(raw['id'] as String?, self._collectionItems(raw));+ }++ for (final anchor in anchors) {+ await _checkListRollingDownloads(anchor, count);+ }+ }+Future<String?> _queueAutoDownloadSourceId(String playingKey,String queueMode,diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dartindex 2dac94a2..08298210 100644--- a/lib/providers/_lp_state.dart+++ b/lib/providers/_lp_state.dart@@ -5,6 +5,7 @@ mixin _StateMixin on ChangeNotifier {ApiService? get _api => _auth?.apiService;List<dynamic> _libraries = [];+ bool _librariesFromCache = false;String? _selectedLibraryId;List<dynamic> _personalizedSections = [];List<dynamic> _series = [];diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex 72e2e881..6d217a46 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -145,6 +145,7 @@ class LibraryProvider extends ChangeNotifierif (isNewUser || isFreshLogin) {_libraries = [];+ _librariesFromCache = false;_selectedLibraryId = null;_personalizedSections = [];_series = [];@@ -255,6 +256,7 @@ class LibraryProvider extends ChangeNotifier_lastAuthKey = null;_lastUseLocalServer = null;_libraries = [];+ _librariesFromCache = false;_personalizedSections = [];_series = [];_progressMap = {};@@ -294,18 +296,22 @@ class LibraryProvider extends ChangeNotifiernotifyListeners();try {- _libraries = await _api!.getLibraries();- debugPrint(- '[Library] loadLibraries: got ${_libraries.length} libraries');- await LibraryCache.save(_libraries);+ final fetched = await _api!.getLibraries();+ debugPrint('[Library] loadLibraries: got ${fetched.length} libraries');- if (_libraries.isNotEmpty) {+ if (fetched.isNotEmpty) {+ _libraries = fetched;+ _librariesFromCache = false;+ await LibraryCache.save(fetched);await _restoreSelectedLibrary();await _loadSectionPrefs();await loadPersonalizedView(force: true);} else {- _selectedLibraryId = null;+ // getLibraries swallows network/auth failures and returns an empty+ // list, so empty is indistinguishable from a failed fetch. Keep the+ // current list, cache, and selection instead of wiping them.+ await _restoreCachedLibraries();}} catch (e) {if (_isLikelyNetworkError(e)) {@@ -328,6 +334,7 @@ class LibraryProvider extends ChangeNotifierfinal cached = await LibraryCache.load();if (cached.isEmpty) return;_libraries = cached;+ _librariesFromCache = true;await _restoreSelectedLibrary();debugPrint('[Library] Restored ${_libraries.length} cached libraries for offline use');diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dartindex 10f87c92..28bb78e0 100644--- a/lib/screens/library_screen.dart+++ b/lib/screens/library_screen.dart@@ -1214,9 +1214,14 @@ class LibraryScreenState extends State<LibraryScreen>void _loadOfflinePage(LibraryProvider lib) {final l = AppLocalizations.of(context)!;final isPodcast = lib.isPodcastLibrary;- final downloads = DownloadService().downloadedItems- .where((dl) => (dl.itemId.length > 36) == isPodcast)- .toList();+ final selectedId = lib.selectedLibraryId;+ final downloads = DownloadService().downloadedItems.where((dl) {+ final libraryId = dl.libraryId;+ if (libraryId != null && libraryId.isNotEmpty && selectedId != null) {+ return libraryId == selectedId;+ }+ return (dl.itemId.length > 36) == isPodcast;+ }).toList();final items = <Map<String, dynamic>>[];for (final dl in downloads) {diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex 41568378..e8c0cd44 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -3089,11 +3089,12 @@ class AudioPlayerService extends ChangeNotifier {final wasPlaying = _player!.playing;final currentAbsolutePos = position; // use absolute position getterfinal currentSpeed = _player!.speed;- final reportingCutoverAt = DateTime.now();- final finalStreamingSeconds = reportingCutoverAt- .difference(_lastServerSync)- .inSeconds- .clamp(0, 300);+ // Paused means the pause sync already reported the tail and the span+ // since then is idle time, not listening (same phantom-time hazard the+ // resume path defends against by resetting _lastServerSync).+ final finalStreamingSeconds = !wasPlaying+ ? 0+ : DateTime.now().difference(_lastServerSync).inSeconds.clamp(0, 300);debugPrint('[Player] Hot-swapping to local files at ${currentAbsolutePos.inSeconds}s',diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dartindex 3edd930c..c339ebc6 100644--- a/lib/services/player_settings.dart+++ b/lib/services/player_settings.dart@@ -4,6 +4,14 @@ import 'package:shared_preferences/shared_preferences.dart';import 'scoped_prefs.dart';import '../widgets/card_button_config.dart';+typedef QueueModeSnapshot = ({+ String bookMode,+ String podcastMode,+ String? playlistId,+ String? collectionId,+ String? collectionName,+});+// ─── Auto-rewind settings ───class AutoRewindSettings {@@ -405,6 +413,54 @@ class PlayerSettings {return true;});+ /// Snapshot of the queue-mode settings, taken before a play activates a+ /// playlist/collection queue so a failed play can put them back.+ static Future<QueueModeSnapshot> queueModeSnapshot() async => (+ bookMode: await getBookQueueMode(),+ podcastMode: await getPodcastQueueMode(),+ playlistId: await ScopedPrefs.getString('queuePlaylistId'),+ collectionId: await ScopedPrefs.getString('queueCollectionId'),+ collectionName: await ScopedPrefs.getString('queueCollectionName'),+ );++ /// Restore a [queueModeSnapshot] if the given playlist queue is still the+ /// active one - same guard as [clearQueueModePlaylistIfActive], so a mode+ /// the user changed again in the meantime is left alone.+ static Future<bool> restoreQueueModeIfPlaylistActive(+ String playlistId, QueueModeSnapshot snapshot) =>+ _serializeQueueModeMutation(() async {+ if (await getBookQueueMode() != 'playlist' ||+ await getPodcastQueueMode() != 'playlist' ||+ await getQueuePlaylistId() != playlistId) {+ return false;+ }+ await _applyQueueModeSnapshot(snapshot);+ return true;+ });++ static Future<bool> restoreQueueModeIfCollectionActive(+ String collectionId, QueueModeSnapshot snapshot) =>+ _serializeQueueModeMutation(() async {+ if (await getBookQueueMode() != 'collection' ||+ await getQueueCollectionId() != collectionId) {+ return false;+ }+ await _applyQueueModeSnapshot(snapshot);+ return true;+ });++ static Future<void> _applyQueueModeSnapshot(QueueModeSnapshot s) async {+ Future<void> put(String key, String? value) => value == null+ ? ScopedPrefs.remove(key)+ : ScopedPrefs.setString(key, value);+ await put('bookQueueMode', s.bookMode);+ await put('podcastQueueMode', s.podcastMode);+ await put('queuePlaylistId', s.playlistId);+ await put('queueCollectionId', s.collectionId);+ await put('queueCollectionName', s.collectionName);+ _notify();+ }+/// One-time migration from the old boolean auto-play settings to queueMode.static Future<void> migrateQueueMode() async {if (await ScopedPrefs.containsKey('queueMode')) return;diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex dd4ec2e8..37dae184 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -2097,13 +2097,14 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {}}- Future<void> _clearActivatedQueueSource() async {+ Future<void> _restoreActivatedQueueSource(QueueModeSnapshot backup) async {final playlistId = widget.sourcePlaylistId;final collectionId = widget.sourceCollectionId;if (playlistId != null && playlistId.isNotEmpty) {- await PlayerSettings.clearQueueModePlaylistIfActive(playlistId);+ await PlayerSettings.restoreQueueModeIfPlaylistActive(playlistId, backup);} else if (collectionId != null && collectionId.isNotEmpty) {- await PlayerSettings.clearQueueModeCollectionIfActive(collectionId);+ await PlayerSettings.restoreQueueModeIfCollectionActive(+ collectionId, backup);}}@@ -2128,6 +2129,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {}final api = auth.apiService;if (api == null) return;+ final queueModeBackup = await PlayerSettings.queueModeSnapshot();await _activateQueueSource();// Pop sheets and switch tab BEFORE starting playback. Otherwise the@@ -2138,7 +2140,7 @@ 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());+ unawaited(_restoreActivatedQueueSource(queueModeBackup));final ctx = rootNavigatorKey.currentContext;if (ctx != null) showErrorToast(ctx, error);} else {diff --git a/lib/widgets/episode_detail_sheet.dart b/lib/widgets/episode_detail_sheet.dartindex c89ce8ce..3561fe8a 100644--- a/lib/widgets/episode_detail_sheet.dart+++ b/lib/widgets/episode_detail_sheet.dart@@ -137,10 +137,10 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {}}- Future<void> _clearActivatedQueueSource() async {+ Future<void> _restoreActivatedQueueSource(QueueModeSnapshot backup) async {final playlistId = widget.sourcePlaylistId;if (playlistId != null && playlistId.isNotEmpty) {- await PlayerSettings.clearQueueModePlaylistIfActive(playlistId);+ await PlayerSettings.restoreQueueModeIfPlaylistActive(playlistId, backup);}}@@ -166,9 +166,10 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {final rootNav = Navigator.of(context, rootNavigator: true);final rootContext = rootNav.context;final lib = context.read<LibraryProvider>();+ final queueModeBackup = await PlayerSettings.queueModeSnapshot();await _activateQueueSource();if (!rootNav.mounted) {- await _clearActivatedQueueSource();+ await _restoreActivatedQueueSource(queueModeBackup);return;}debugPrint('[PodcastPlay] Popping stacked sheets before playItem (item=$_itemId episode=$_episodeId)');@@ -187,7 +188,7 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {);debugPrint('[PodcastPlay] playItem returned in ${DateTime.now().difference(t0).inMilliseconds}ms (error=${error ?? 'none'})');if (error != null) {- unawaited(_clearActivatedQueueSource());+ unawaited(_restoreActivatedQueueSource(queueModeBackup));if (rootContext.mounted) showErrorToast(rootContext, error);} else {unawaited(lib.syncQueueAutoDownloads());diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dartindex f137cd95..4f127712 100644--- a/lib/widgets/episode_list_sheet.dart+++ b/lib/widgets/episode_list_sheet.dart@@ -269,10 +269,11 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {}}- Future<void> _clearActivatedQueueSource(String episodeId) async {+ Future<void> _restoreActivatedQueueSource(+ String episodeId, QueueModeSnapshot backup) async {final playlistId = _playlistSourceForEpisode(episodeId);if (playlistId != null && playlistId.isNotEmpty) {- await PlayerSettings.clearQueueModePlaylistIfActive(playlistId);+ await PlayerSettings.restoreQueueModeIfPlaylistActive(playlistId, backup);}}@@ -363,6 +364,7 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {}final lib = context.read<LibraryProvider>();+ final queueModeBackup = await PlayerSettings.queueModeSnapshot();await _activateQueueSource(episodeId);final player = AudioPlayerService();final error = await player.playItem(@@ -384,7 +386,7 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {if (error == null) {unawaited(lib.syncQueueAutoDownloads());} else {- unawaited(_clearActivatedQueueSource(episodeId));+ unawaited(_restoreActivatedQueueSource(episodeId, queueModeBackup));}if (mounted) {if (error != null) showErrorToast(context, error);