A cross platform Audiobookshelf client for Android and iOS
Dart
Refresh covers in AA/CarPlay/in-app on re-download or server change
Barnabas8bd31cd5fb10
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt b/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.ktindex 843c3df1..74208d87 100644--- a/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt+++ b/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt@@ -40,14 +40,17 @@ class CoverContentProvider : ContentProvider() {override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {val itemId = extractItemId(uri) ?: return nullval context = context ?: return null+ val ts = uri.getQueryParameter("ts")invalidateStaleCacheIfNeeded(context, itemId, uri)val coverFile = findCoverFile(context, itemId)if (coverFile != null) {+ Log.d(TAG, "openFile $itemId ts=$ts served=${coverFile.path} mtime=${coverFile.lastModified()}")return ParcelFileDescriptor.open(coverFile, ParcelFileDescriptor.MODE_READ_ONLY)}// Not available locally — try fetching from the server and cachingval cached = fetchAndCache(context, itemId) ?: return null+ Log.d(TAG, "openFile $itemId ts=$ts fetched=${cached.path} mtime=${cached.lastModified()}")return ParcelFileDescriptor.open(cached, ParcelFileDescriptor.MODE_READ_ONLY)}@@ -215,9 +218,13 @@ class CoverContentProvider : ContentProvider() {) {val tsParam = uri.getQueryParameter("ts")?.toLongOrNull() ?: returnval cacheFile = File(context.cacheDir, "aa_covers/$itemId.jpg")- if (cacheFile.exists() && cacheFile.lastModified() < tsParam) {- Log.d(TAG, "Invalidating stale cover cache for $itemId (file=${cacheFile.lastModified()} < ts=$tsParam)")- cacheFile.delete()+ if (cacheFile.exists()) {+ if (cacheFile.lastModified() < tsParam) {+ Log.d(TAG, "Invalidating stale aa_covers for $itemId (file=${cacheFile.lastModified()} < ts=$tsParam)")+ cacheFile.delete()+ } else {+ Log.d(TAG, "aa_covers fresh for $itemId (file=${cacheFile.lastModified()} >= ts=$tsParam)")+ }}}diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dartindex 87f1c853..8381c39e 100644--- a/lib/providers/_lp_state.dart+++ b/lib/providers/_lp_state.dart@@ -320,11 +320,16 @@ mixin _StateMixin on ChangeNotifier {if (_api != null && !isOffline) {final ts = _itemUpdatedAt[apiItemId];- return _api!.getCoverUrl(apiItemId, width: width, updatedAt: ts);+ final url = _api!.getCoverUrl(apiItemId, width: width, updatedAt: ts);+ debugPrint('[Cover] network $apiItemId ts=$ts -> $url');+ return url;}final dl = DownloadService().getInfo(itemId);if (dl.localCoverPath != null) {+ final f = File(dl.localCoverPath!);+ final mtime = f.existsSync() ? f.lastModifiedSync().millisecondsSinceEpoch : -1;+ debugPrint('[Cover] local $itemId path=${dl.localCoverPath} mtime=$mtime');return dl.localCoverPath;}diff --git a/lib/services/android_auto_service.dart b/lib/services/android_auto_service.dartindex a54a47aa..2b88df94 100644--- a/lib/services/android_auto_service.dart+++ b/lib/services/android_auto_service.dart@@ -1,6 +1,6 @@import 'dart:async';import 'dart:convert';-import 'dart:io' show Platform;+import 'dart:io' show File, Platform;import 'package:audio_service/audio_service.dart';import 'package:flutter/foundation.dart';@@ -203,7 +203,29 @@ class AutoLibraryEntry {class AndroidAutoService {static final AndroidAutoService _instance = AndroidAutoService._();factory AndroidAutoService() => _instance;- AndroidAutoService._();+ AndroidAutoService._() {+ DownloadService().addListener(_onDownloadsChanged);+ }++ Timer? _downloadsRefreshDebounce;+ void _onDownloadsChanged() {+ // Coalesce bursts (multiple state ticks during a download).+ _downloadsRefreshDebounce?.cancel();+ _downloadsRefreshDebounce = Timer(const Duration(milliseconds: 500), () async {+ await _refreshDownloaded();+ _childrenCache.remove(AutoMediaIds.downloads);+ _childrenCache.remove(AutoMediaIds.root);+ if (Platform.isAndroid) {+ try {+ // ignore: deprecated_member_use+ await AudioServiceBackground.notifyChildrenChanged(AutoMediaIds.downloads);+ } catch (_) {}+ }+ try {+ onServerDataChanged?.call();+ } catch (_) {}+ });+ }// ── Cached data ──List<AutoBookEntry> _continueListening = [];@@ -376,10 +398,11 @@ class AndroidAutoService {/// Must match the authority registered in AndroidManifest.xml.static const _coverAuthority = 'com.barnabas.absorb.covers';- // Per-item updatedAt; appended to cover URIs so AA/CarPlay see a new URL- // when a cover changes and refetch instead of serving the cached bitmap.+ // Per-item updatedAt for cover ?ts= cache busting on AA/CarPlay.static final Map<String, int> _itemUpdatedAt = {};+ static int? coverTsFor(String itemId) => _itemUpdatedAt[itemId];+/// Build a content:// URI for a locally cached cover image./// Android Auto requires content:// URIs, file:// won't work.static String localCoverUri(String itemId) {@@ -388,15 +411,11 @@ class AndroidAutoService {return ts != null ? '$base?ts=$ts' : base;}- /// Record a fresh server-side updatedAt for an item. Called from the socket- /// `item_updated` handler so AA/CarPlay reload covers when they change.static void notifyItemUpdated(String itemId, int updatedAt) {final prev = _itemUpdatedAt[itemId];if (prev == updatedAt) return;_itemUpdatedAt[itemId] = updatedAt;- // The cached MediaItem lists embed the old cover URI, so any list could- // be stale. Clear them; AA will reload on the next browse and pick up the- // new ts-suffixed URI.+ // Children cache holds old cover URIs._instance._childrenCache.clear();try {onServerDataChanged?.call();@@ -438,16 +457,24 @@ class AndroidAutoService {episodeId = dl.itemId.substring(37);}- // Use show ID for podcast episode covers so the CoverContentProvider- // can fall back to /api/items/<showId>/cover on the server.+ // Podcast episode covers use the show ID so the provider can fall back+ // to /api/items/<showId>/cover.final coverKey = isEpisode ? showId! : dl.itemId;- // iOS CarPlay can't load Android content:// URIs - use the local- // cover file directly. Android Auto requires content:// (file://- // doesn't work for it). Falls back to the content URI on iOS too if- // there's no local file path so behavior degrades gracefully.+ if (dl.localCoverPath != null && dl.localCoverPath!.isNotEmpty) {+ try {+ final f = File(dl.localCoverPath!);+ if (f.existsSync()) {+ final ms = f.lastModifiedSync().millisecondsSinceEpoch;+ final prev = _itemUpdatedAt[coverKey];+ if (prev == null || ms > prev) _itemUpdatedAt[coverKey] = ms;+ }+ } catch (_) {}+ }String coverUrl;if (Platform.isIOS && dl.localCoverPath != null && dl.localCoverPath!.isNotEmpty) {coverUrl = Uri.file(dl.localCoverPath!).toString();+ final ts = _itemUpdatedAt[coverKey];+ if (ts != null) coverUrl = '$coverUrl?ts=$ts';} else {coverUrl = localCoverUri(coverKey);}@@ -714,6 +741,9 @@ class AndroidAutoService {final id = item['id'] as String?;if (id == null) return null;+ final updatedAt = (item['updatedAt'] as num?)?.toInt();+ if (updatedAt != null) _itemUpdatedAt[id] = updatedAt;+final media = item['media'] as Map<String, dynamic>?;final metadata = media?['metadata'] as Map<String, dynamic>? ?? {};final title = metadata['title'] as String? ?? 'Unknown';@@ -1229,7 +1259,7 @@ class AndroidAutoService {Future<String?> getCoverHttpUrl(String itemId) async {final api = await getApi();if (api == null) return null;- return api.getCoverUrl(itemId);+ return api.getCoverUrl(itemId, updatedAt: _itemUpdatedAt[itemId]);}/// Fetch books for a library, returning raw entries.@@ -1367,10 +1397,12 @@ class AndroidAutoService {if (item is! Map<String, dynamic>) continue;final id = item['id'] as String?;if (id == null) continue;+ final updatedAt = (item['updatedAt'] as num?)?.toInt();+ if (updatedAt != null) _itemUpdatedAt[id] = updatedAt;final media = item['media'] as Map<String, dynamic>?;final metadata = media?['metadata'] as Map<String, dynamic>? ?? {};final title = metadata['title'] as String? ?? 'Unknown';- allShows.add((id: id, title: title, coverUrl: api.getCoverUrl(id)));+ allShows.add((id: id, title: title, coverUrl: api.getCoverUrl(id, updatedAt: updatedAt)));}final total = (result['total'] as num?)?.toInt() ?? 0;if (allShows.length >= total || results.length < pageSize) break;@@ -1390,6 +1422,8 @@ class AndroidAutoService {try {final fullItem = await api.getLibraryItem(showId);if (fullItem == null) return [];+ final showUpdatedAt = (fullItem['updatedAt'] as num?)?.toInt();+ if (showUpdatedAt != null) _itemUpdatedAt[showId] = showUpdatedAt;final media = fullItem['media'] as Map<String, dynamic>?;final metadata = media?['metadata'] as Map<String, dynamic>? ?? {};final showTitle = metadata['title'] as String? ?? 'Podcast';@@ -1410,7 +1444,7 @@ class AndroidAutoService {title: ep['title'] as String? ?? 'Episode',author: showTitle,duration: (ep['duration'] as num?)?.toDouble() ?? 0,- coverUrl: api.getCoverUrl(showId),+ coverUrl: api.getCoverUrl(showId, updatedAt: showUpdatedAt),chapters: ep['chapters'] as List<dynamic>? ?? [],episodeId: epId,showId: showId,diff --git a/lib/services/carplay_service.dart b/lib/services/carplay_service.dartindex 9ccc8c93..574bcf46 100644--- a/lib/services/carplay_service.dart+++ b/lib/services/carplay_service.dart@@ -444,15 +444,13 @@ class CarPlayService {/// drills into the show's episodes.CPListItem _playableListItem(AutoBookEntry entry, ApiService? api) {final coverItemId = entry.showId ?? entry.id;- // Prefer the entry's own coverUrl when it's a local file:// path so- // downloaded books still show artwork in the CarPlay browse list when- // the server is unreachable. AndroidAutoService.refresh() populates- // file:// for downloads on iOS; the server URL from api.getCoverUrl is- // only useful when we can actually reach the server.+ // Downloaded books: file:// URL (already mtime-busted in _refreshDownloaded).+ // Streaming: ?ts= the server updatedAt so iOS refetches after a cover change.final entryUrl = entry.coverUrl;+ final ts = AndroidAutoService.coverTsFor(coverItemId);final coverUrl = (entryUrl != null && entryUrl.startsWith('file://'))? entryUrl- : api?.getCoverUrl(coverItemId);+ : api?.getCoverUrl(coverItemId, updatedAt: ts);final isPodcastShow = entry.mediaType == 'podcast' &&entry.episodeId == null &&diff --git a/lib/services/download_service.dart b/lib/services/download_service.dartindex 22b64204..aaf9c464 100644--- a/lib/services/download_service.dart+++ b/lib/services/download_service.dart@@ -678,9 +678,12 @@ class DownloadService extends ChangeNotifier {if (!dir.existsSync()) dir.createSync(recursive: true);final coverFile = File('${dir.path}/cover.jpg');await coverFile.writeAsBytes(resp.bodyBytes);+ final evicted = PaintingBinding.instance.imageCache+ .evict(FileImage(coverFile));localCoverPath = coverFile.path;needsUpdate = true;- debugPrint('[Download] Cached cover for ${info.itemId}');+ debugPrint('[Download] Cached cover for ${info.itemId} '+ '(${resp.bodyBytes.length} bytes, evict=$evicted)');}} catch (e) {debugPrint('[Download] Cover cache failed for ${info.itemId}: $e');@@ -1208,12 +1211,20 @@ class DownloadService extends ChangeNotifier {}} catch (_) {}- // Clean up cached cover image (stored separately in internal storage)try {final internalBase = await _internalBasePath;final coverDir = Directory('$internalBase/$itemId');+ final coverFile = File('$internalBase/$itemId/cover.jpg');+ // FileImage caches by path; evict so a re-download at the same path renders fresh.+ if (coverFile.existsSync()) {+ final evicted = PaintingBinding.instance.imageCache+ .evict(FileImage(coverFile));+ debugPrint('[Download] evict cover ${coverFile.path} -> $evicted');+ }if (coverDir.existsSync()) coverDir.deleteSync(recursive: true);- } catch (_) {}+ } catch (e) {+ debugPrint('[Download] cover cleanup failed: $e');+ }_downloads.remove(itemId);await _save();