Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Fix Android Auto: sort series books by sequence, refresh covers on update

Barnabas749122f9759b
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt b/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt
index 78828bfc..843c3df1 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt
@@ -40,6 +40,7 @@ class CoverContentProvider : ContentProvider() {
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {
val itemId = extractItemId(uri) ?: return null
val context = context ?: return null
+ invalidateStaleCacheIfNeeded(context, itemId, uri)
val coverFile = findCoverFile(context, itemId)
if (coverFile != null) {
return ParcelFileDescriptor.open(coverFile, ParcelFileDescriptor.MODE_READ_ONLY)
@@ -70,6 +71,7 @@ class CoverContentProvider : ContentProvider() {
): Cursor? {
val itemId = extractItemId(uri) ?: return null
val context = context ?: return null
+ invalidateStaleCacheIfNeeded(context, itemId, uri)
val coverFile = findCoverFile(context, itemId)
?: fetchAndCache(context, itemId)
?: return null
@@ -203,6 +205,22 @@ class CoverContentProvider : ContentProvider() {
return match?.groupValues?.get(1)
}
+ // If the URI carries a `ts` query param newer than the aa_covers file's
+ // mtime, drop the file so the next lookup re-fetches from the server.
+ // Downloaded covers are owned by the download pipeline, not touched here.
+ private fun invalidateStaleCacheIfNeeded(
+ context: android.content.Context,
+ itemId: String,
+ uri: Uri
+ ) {
+ val tsParam = uri.getQueryParameter("ts")?.toLongOrNull() ?: return
+ val 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()
+ }
+ }
+
// ── Helpers ──
private fun extractItemId(uri: Uri): String? {
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index c67bf353..079f4461 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -964,7 +964,12 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
// Update cover cache buster timestamp
final id = data['id'] as String?;
final ts = data['updatedAt'] as num?;
- if (id != null && ts != null) _itemUpdatedAt[id] = ts.toInt();
+ if (id != null && ts != null) {
+ _itemUpdatedAt[id] = ts.toInt();
+ // Mirror into AA/CarPlay so the next browse-tree refresh hands out a
+ // ts-suffixed cover URI and the native cover cache can invalidate.
+ AndroidAutoService.notifyItemUpdated(id, ts.toInt());
+ }
if (id != null) {
final coverPath = (data['media'] as Map<String, dynamic>?)?['coverPath'] as String?;
registerHasCover(id, coverPath != null && coverPath.isNotEmpty);
diff --git a/lib/services/android_auto_service.dart b/lib/services/android_auto_service.dart
index f1f1e2ed..bd78de9d 100644
--- a/lib/services/android_auto_service.dart
+++ b/lib/services/android_auto_service.dart
@@ -349,10 +349,36 @@ 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.
+ static final Map<String, int> _itemUpdatedAt = {};
+
/// Build a content:// URI for a locally cached cover image.
- /// Android Auto requires content:// URIs — file:// won't work.
- static String localCoverUri(String itemId) =>
- 'content://$_coverAuthority/cover/$itemId';
+ /// Android Auto requires content:// URIs, file:// won't work.
+ static String localCoverUri(String itemId) {
+ final ts = _itemUpdatedAt[itemId];
+ final base = 'content://$_coverAuthority/cover/$itemId';
+ 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;
+ try {
+ onServerDataChanged?.call();
+ } catch (e) {
+ debugPrint('[AutoBrowse] notifyItemUpdated listener threw: $e');
+ }
+ if (Platform.isAndroid) {
+ try {
+ // ignore: deprecated_member_use
+ AudioServiceBackground.notifyChildrenChanged(AutoMediaIds.root);
+ } catch (_) {}
+ }
+ }
Future<void> _refreshDownloaded() async {
final ds = DownloadService();
@@ -978,8 +1004,7 @@ class AndroidAutoService {
try {
final results = await api.getBooksBySeries(libraryId, seriesId);
- return results
- .whereType<Map<String, dynamic>>()
+ return _sortBySeriesSequence(results, seriesId)
.map((item) => _libraryItemToEntry(item, api))
.whereType<AutoBookEntry>()
.map((e) => e.toMediaItem())
@@ -990,6 +1015,38 @@ class AndroidAutoService {
}
}
+ /// Sort raw library items by their sequence within the given series.
+ /// The server's `sort=media.metadata.series.sequence` param sorts as a
+ /// string, so "10" lands before "2". Books missing a sequence go last.
+ static final _leadingNumberRe = RegExp(r'^[\d.]+');
+ List<Map<String, dynamic>> _sortBySeriesSequence(
+ List<dynamic> results, String seriesId) {
+ final maps = results.whereType<Map<String, dynamic>>().toList();
+ double seqFor(Map<String, dynamic> item) {
+ final media = item['media'] as Map<String, dynamic>? ?? const {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? const {};
+ final raw = metadata['series'];
+ final seriesList = raw is List
+ ? raw.whereType<Map<String, dynamic>>()
+ : raw is Map<String, dynamic>
+ ? [raw]
+ : const <Map<String, dynamic>>[];
+ for (final s in seriesList) {
+ if (s['id'] != seriesId) continue;
+ final match = _leadingNumberRe
+ .firstMatch((s['sequence'] ?? '').toString().trim());
+ if (match != null) {
+ final parsed = double.tryParse(match.group(0)!);
+ if (parsed != null) return parsed;
+ }
+ }
+ return double.maxFinite;
+ }
+
+ maps.sort((a, b) => seqFor(a).compareTo(seqFor(b)));
+ return maps;
+ }
+
Future<List<MediaItem>> _fetchAuthorBooks(String authorId, String libraryId) async {
final api = await getApi();
if (api == null) return [];
@@ -1212,8 +1269,7 @@ class AndroidAutoService {
if (api == null) return [];
try {
final results = await api.getBooksBySeries(libraryId, seriesId);
- return results
- .whereType<Map<String, dynamic>>()
+ return _sortBySeriesSequence(results, seriesId)
.map((item) => _libraryItemToEntry(item, api))
.whereType<AutoBookEntry>()
.toList();