A cross platform Audiobookshelf client for Android and iOS
Dart
Fix audio loss after notification interruptions, cover caching, and next-in-series ordering
Nathan Poulson8c5c98e9c0c6
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex 5e62e00b..935b51fa 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -652,20 +652,36 @@ class LibraryProvider extends ChangeNotifier {Set<String> _manualAbsorbAdds = {};Set<String> _manualAbsorbRemoves = {};- // Persisted set of all book IDs ever shown on the absorbing page- Set<String> _absorbingBookIds = {};+ // Persisted ordered list of all book IDs on the absorbing page+ List<String> _absorbingBookIds = [];// Cached item data for books that may no longer be in server sectionsMap<String, Map<String, dynamic>> _absorbingItemCache = {};+ // Track last finished item so we can insert next-in-series after it+ String? _lastFinishedItemId;Set<String> get manualAbsorbAdds => _manualAbsorbAdds;Set<String> get manualAbsorbRemoves => _manualAbsorbRemoves;- Set<String> get absorbingBookIds => _absorbingBookIds;+ List<String> get absorbingBookIds => _absorbingBookIds;++ /// Add a key to _absorbingBookIds if not already present.+ /// If [afterKey] is provided and exists, insert right after it.+ void _absorbingIdsAdd(String key, {String? afterKey}) {+ if (_absorbingBookIds.contains(key)) return;+ if (afterKey != null) {+ final idx = _absorbingBookIds.indexOf(afterKey);+ if (idx >= 0) {+ _absorbingBookIds.insert(idx + 1, key);+ return;+ }+ }+ _absorbingIdsAdd(key);+ }Map<String, Map<String, dynamic>> get absorbingItemCache => _absorbingItemCache;Future<void> _loadManualAbsorbing() async {_manualAbsorbAdds = (await ScopedPrefs.getStringList('absorbing_manual_adds')).toSet();_manualAbsorbRemoves = (await ScopedPrefs.getStringList('absorbing_manual_removes')).toSet();- _absorbingBookIds = (await ScopedPrefs.getStringList('absorbing_seen_ids')).toSet();+ _absorbingBookIds = (await ScopedPrefs.getStringList('absorbing_seen_ids')).toList();final cacheList = await ScopedPrefs.getStringList('absorbing_item_cache_v2');_absorbingItemCache = {};for (final s in cacheList) {@@ -704,6 +720,8 @@ class LibraryProvider extends ChangeNotifier {final id = section['id'] as String? ?? '';if (id == 'continue-listening' || id == 'continue-series' ||id == 'downloaded-books') {+ // For continue-series items, insert right after the finished book+ final insertAfter = id == 'continue-series' ? _lastFinishedItemId : null;for (final e in (section['entities'] as List<dynamic>? ?? [])) {if (e is Map<String, dynamic>) {final itemId = e['id'] as String?;@@ -717,7 +735,7 @@ class LibraryProvider extends ChangeNotifier {allowedKeys.add(key);showEntities[itemId] = e;if (!_manualAbsorbRemoves.contains(key)) {- _absorbingBookIds.add(key);+ _absorbingIdsAdd(key, afterKey: insertAfter);_absorbingItemCache[key] = {...e, '_absorbingKey': key};}}@@ -725,7 +743,7 @@ class LibraryProvider extends ChangeNotifier {// Book — use plain itemIdallowedKeys.add(itemId);if (!_manualAbsorbRemoves.contains(itemId)) {- _absorbingBookIds.add(itemId);+ _absorbingIdsAdd(itemId, afterKey: insertAfter);_absorbingItemCache[itemId] = e;}}@@ -784,7 +802,7 @@ class LibraryProvider extends ChangeNotifier {'title': 'Episode',};syntheticEntry['_absorbingKey'] = key;- _absorbingBookIds.add(key);+ _absorbingIdsAdd(key);_absorbingItemCache[key] = syntheticEntry;allowedKeys.add(key);}@@ -833,7 +851,7 @@ class LibraryProvider extends ChangeNotifier {_absorbingItemCache.remove(old);}for (final entry in migrateAdd.entries) {- _absorbingBookIds.add(entry.key);+ _absorbingIdsAdd(entry.key);_absorbingItemCache[entry.key] = entry.value;}@@ -886,7 +904,7 @@ class LibraryProvider extends ChangeNotifier {Future<void> addToAbsorbing(String itemId) async {_manualAbsorbAdds.add(itemId);_manualAbsorbRemoves.remove(itemId);- _absorbingBookIds.add(itemId);+ _absorbingIdsAdd(itemId);await _saveManualAbsorbing();notifyListeners();}@@ -897,7 +915,7 @@ class LibraryProvider extends ChangeNotifier {void unblockFromAbsorbing(String key) {bool changed = _manualAbsorbRemoves.remove(key);if (!_absorbingBookIds.contains(key)) {- _absorbingBookIds.add(key);+ _absorbingIdsAdd(key);changed = true;// Populate the cache from current sections if availablefinal isCompound = key.contains('-');@@ -931,12 +949,18 @@ class LibraryProvider extends ChangeNotifier {/// Mark an item as finished locally so the overlay appears immediately,/// before the next server refresh confirms isFinished.+ /// Then refresh sections so next-in-series appears without navigating away.void markFinishedLocally(String itemId) {if (_resetItems.contains(itemId)) return;final existing = _progressMap[itemId] ?? {};_progressMap[itemId] = {...existing, 'isFinished': true};_localProgressOverrides[itemId] = 1.0;+ _lastFinishedItemId = itemId;notifyListeners();+ // Refresh sections so continue-series items appear immediately+ if (_api != null && _selectedLibraryId != null && !isOffline) {+ loadPersonalizedView();+ }}/// Check if a book/episode is on the absorbing page (persisted local list, not removed).diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex ab7c59f4..4c0cea3d 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -680,7 +680,9 @@ class AudioPlayerService extends ChangeNotifier {androidNotificationChannelId: 'com.audiobookshelf.app.channel.audio',androidNotificationChannelName: 'Absorb',androidNotificationOngoing: true,- androidStopForegroundOnPause: true,+ // Keep foreground service alive when paused — prevents Android from+ // killing audio after notification interruptions on locked screen.+ androidStopForegroundOnPause: false,androidNotificationIcon: 'drawable/ic_notification',androidBrowsableRootExtras: {AndroidContentStyle.supportedKey: true,@@ -715,7 +717,12 @@ class AudioPlayerService extends ChangeNotifier {if (event.begin) {if (service.isPlaying) {debugPrint('[AudioSession] Interrupted (${event.type}) — pausing');- await service.pause();+ // Pause the underlying player directly — NOT service.pause() —+ // to keep the interruption lightweight. service.pause() saves progress,+ // syncs to server, clears _wasPlayingBeforeInterrupt, and sets+ // _lastPauseTime (triggering auto-rewind on resume). For transient+ // notification interruptions we just need to duck the audio briefly.+ await service._player?.pause();service._wasPlayingBeforeInterrupt = true;}} else {diff --git a/lib/services/download_service.dart b/lib/services/download_service.dartindex 0da53a42..3cd7fa36 100644--- a/lib/services/download_service.dart+++ b/lib/services/download_service.dart@@ -137,6 +137,14 @@ class DownloadService extends ChangeNotifier {return '${appDir.path}/downloads';}+ /// Always returns the internal app directory for cover caching.+ /// Covers are stored here even when audio uses a custom external path,+ /// because external storage may have permission restrictions.+ Future<String> get _internalBasePath async {+ final appDir = await getApplicationDocumentsDirectory();+ return '${appDir.path}/downloads';+ }+/// Set a custom download location. Pass null to revert to default.Future<void> setCustomDownloadPath(String? path) async {_customDownloadPath = path;@@ -281,31 +289,39 @@ class DownloadService extends ChangeNotifier {}}- // Cache cover locally if not already cached+ // Cache cover in internal storage if not already cachedif (localCoverPath == null || !File(localCoverPath).existsSync()) {- final basePath = await downloadBasePath;- final existingCover = File('$basePath/${info.itemId}/cover.jpg');+ final internalBase = await _internalBasePath;+ final existingCover = File('$internalBase/${info.itemId}/cover.jpg');if (existingCover.existsSync()) {// Already on disk from a previous download, just not trackedlocalCoverPath = existingCover.path;needsUpdate = true;} else {- // Try to download from server- final url = coverUrl ?? api.getCoverUrl(apiItemId);- try {- final resp = await http.get(Uri.parse(url), headers: api.mediaHeaders)- .timeout(const Duration(seconds: 10));- if (resp.statusCode == 200 && resp.bodyBytes.isNotEmpty) {- final dir = Directory('$basePath/${info.itemId}');- if (!dir.existsSync()) dir.createSync(recursive: true);- final coverFile = File('${dir.path}/cover.jpg');- await coverFile.writeAsBytes(resp.bodyBytes);- localCoverPath = coverFile.path;- needsUpdate = true;- debugPrint('[Download] Cached cover for ${info.itemId}');+ // Also check the custom download path (old downloads may have cover there)+ final basePath = await downloadBasePath;+ final oldCover = File('$basePath/${info.itemId}/cover.jpg');+ if (oldCover.existsSync()) {+ localCoverPath = oldCover.path;+ needsUpdate = true;+ } else {+ // Download from server into internal storage+ final url = coverUrl ?? api.getCoverUrl(apiItemId);+ try {+ final resp = await http.get(Uri.parse(url), headers: api.mediaHeaders)+ .timeout(const Duration(seconds: 10));+ if (resp.statusCode == 200 && resp.bodyBytes.isNotEmpty) {+ final dir = Directory('$internalBase/${info.itemId}');+ if (!dir.existsSync()) dir.createSync(recursive: true);+ final coverFile = File('${dir.path}/cover.jpg');+ await coverFile.writeAsBytes(resp.bodyBytes);+ localCoverPath = coverFile.path;+ needsUpdate = true;+ debugPrint('[Download] Cached cover for ${info.itemId}');+ }+ } catch (e) {+ debugPrint('[Download] Cover cache failed for ${info.itemId}: $e');}- } catch (e) {- debugPrint('[Download] Cover cache failed for ${info.itemId}: $e');}}}@@ -352,7 +368,7 @@ class DownloadService extends ChangeNotifier {}/// Get the local cover file path for a downloaded item.- /// Checks the persisted path first, then probes disk for cover.jpg.+ /// Checks the persisted path first, then probes internal and download dirs.Future<String?> getLocalCoverPath(String itemId) async {final info = _downloads[itemId];if (info == null || info.status != DownloadStatus.downloaded) return null;@@ -362,10 +378,17 @@ class DownloadService extends ChangeNotifier {return info.localCoverPath;}- // Probe disk (handles old downloads before cover caching was added)+ // Check internal storage (where covers are now cached)+ final internalBase = await _internalBasePath;+ final internalCover = File('$internalBase/$itemId/cover.jpg');+ if (internalCover.existsSync()) return internalCover.path;++ // Check custom download path (old downloads may have cover there)final basePath = await downloadBasePath;- final coverFile = File('$basePath/$itemId/cover.jpg');- if (coverFile.existsSync()) return coverFile.path;+ if (basePath != internalBase) {+ final customCover = File('$basePath/$itemId/cover.jpg');+ if (customCover.existsSync()) return customCover.path;+ }return null;}@@ -487,14 +510,18 @@ class DownloadService extends ChangeNotifier {bookDir.createSync(recursive: true);}- // Cache the cover image locally for offline use (Android Auto, etc.)+ // Cache the cover image in internal storage for offline use (lockscreen, Android Auto).+ // Always use internal path — custom external paths may lack write permission.String? localCoverPath;if (coverUrl != null && coverUrl.isNotEmpty) {try {final coverResp = await http.get(Uri.parse(coverUrl), headers: api.mediaHeaders).timeout(const Duration(seconds: 10));if (coverResp.statusCode == 200 && coverResp.bodyBytes.isNotEmpty) {- final coverFile = File('${bookDir.path}/cover.jpg');+ final internalBase = await _internalBasePath;+ final coverDir = Directory('$internalBase/$itemId');+ if (!coverDir.existsSync()) coverDir.createSync(recursive: true);+ final coverFile = File('${coverDir.path}/cover.jpg');await coverFile.writeAsBytes(coverResp.bodyBytes);localCoverPath = coverFile.path;debugPrint('[Download] Cached cover image: $localCoverPath');diff --git a/pubspec.yaml b/pubspec.yamlindex dbbe6049..a0c49bd6 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -1,7 +1,7 @@name: absorbdescription: A Material 3 Audiobookshelf client for Android.publish_to: 'none'-version: 1.7.16+34+version: 1.7.17+34environment:sdk: '>=3.1.0 <4.0.0'