A cross platform Audiobookshelf client for Android and iOS
Dart
Fix Android Auto covers, release notifications, and user-switch staleness
Nathan Poulsonb7403b46a179
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt b/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.ktindex 30578939..618f0ff6 100644--- a/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt+++ b/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt@@ -7,31 +7,28 @@ import android.database.MatrixCursorimport android.net.Uriimport android.os.ParcelFileDescriptorimport android.provider.OpenableColumns+import android.util.Logimport java.io.File+import java.net.HttpURLConnection+import java.net.URL/**- * ContentProvider that serves locally-cached cover images to Android Auto.+ * ContentProvider that serves cover images to Android Auto.*- * Android Auto cannot load file:// URIs directly — it requires content:// URIs.- * This provider maps:+ * Android Auto cannot load HTTP or file:// URIs directly — it requires+ * content:// URIs. This provider maps:* content://com.barnabas.absorb.covers/cover/<itemId>- * to the cover.jpg file in the item's download directory.*- * Place this file at:- * android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt- *- * Register in AndroidManifest.xml inside the <application> tag:- *- * <provider- * android:name=".CoverContentProvider"- * android:authorities="com.barnabas.absorb.covers"- * android:exported="true"- * android:grantUriPermissions="true" />+ * Lookup order:+ * 1. Locally downloaded cover (item's download directory)+ * 2. Cached cover fetched from the ABS server (cacheDir/aa_covers/)+ * 3. Fetch from server on-demand → cache → serve*/class CoverContentProvider : ContentProvider() {companion object {const val AUTHORITY = "com.barnabas.absorb.covers"+ private const val TAG = "CoverProvider"fun buildCoverUri(itemId: String): Uri {return Uri.parse("content://$AUTHORITY/cover/$itemId")@@ -43,22 +40,19 @@ class CoverContentProvider : ContentProvider() {override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor? {val itemId = extractItemId(uri) ?: return nullval context = context ?: return null- val coverFile = findCoverFile(context, itemId) ?: return null- return ParcelFileDescriptor.open(coverFile, ParcelFileDescriptor.MODE_READ_ONLY)+ val coverFile = findCoverFile(context, itemId)+ if (coverFile != null) {+ return ParcelFileDescriptor.open(coverFile, ParcelFileDescriptor.MODE_READ_ONLY)+ }++ // Not available locally — try fetching from the server and caching+ val cached = fetchAndCache(context, itemId) ?: return null+ return ParcelFileDescriptor.open(cached, ParcelFileDescriptor.MODE_READ_ONLY)}- /**- * Return MIME type for the URI. Android Auto's image loader checks this- * to determine if it can handle the content:// URI as an image.- */override fun getType(uri: Uri): String = "image/jpeg"- /**- * Return supported stream MIME types. Android Auto may call this to verify- * the provider can serve image data before attempting to load it.- */override fun getStreamTypes(uri: Uri, mimeTypeFilter: String): Array<String>? {- // Match any image filter (e.g. "image/*", "*/*", "image/jpeg")if (mimeTypeFilter == "*/*" ||mimeTypeFilter == "image/*" ||mimeTypeFilter == "image/jpeg") {@@ -67,10 +61,6 @@ class CoverContentProvider : ContentProvider() {return null}- /**- * Implement query to return file metadata. Some Android Auto implementations- * query the provider for display name and size before loading the image.- */override fun query(uri: Uri,projection: Array<out String>?,@@ -80,7 +70,9 @@ class CoverContentProvider : ContentProvider() {): Cursor? {val itemId = extractItemId(uri) ?: return nullval context = context ?: return null- val coverFile = findCoverFile(context, itemId) ?: return null+ val coverFile = findCoverFile(context, itemId)+ ?: fetchAndCache(context, itemId)+ ?: return nullval cols = projection ?: arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE)val cursor = MatrixCursor(cols.map { it }.toTypedArray())@@ -95,6 +87,58 @@ class CoverContentProvider : ContentProvider() {return cursor}+ // ── Server fetch + cache ──++ private fun fetchAndCache(context: android.content.Context, itemId: String): File? {+ try {+ val prefs = context.getSharedPreferences(+ "FlutterSharedPreferences", android.content.Context.MODE_PRIVATE+ )+ val serverUrl = prefs.getString("flutter.server_url", null)+ val token = prefs.getString("flutter.token", null)+ if (serverUrl.isNullOrEmpty() || token.isNullOrEmpty()) {+ Log.w(TAG, "No server_url or token in prefs — cannot fetch cover")+ return null+ }++ val cleanUrl = serverUrl.trimEnd('/')+ val fetchUrl = "$cleanUrl/api/items/$itemId/cover?width=400&token=$token"++ val cacheDir = File(context.cacheDir, "aa_covers")+ if (!cacheDir.exists()) cacheDir.mkdirs()+ val cacheFile = File(cacheDir, "$itemId.jpg")++ val connection = URL(fetchUrl).openConnection() as HttpURLConnection+ connection.connectTimeout = 5000+ connection.readTimeout = 5000+ connection.instanceFollowRedirects = true++ try {+ if (connection.responseCode != 200) {+ Log.w(TAG, "Cover fetch failed: HTTP ${connection.responseCode} for $itemId")+ return null+ }+ connection.inputStream.use { input ->+ cacheFile.outputStream().use { output ->+ input.copyTo(output)+ }+ }+ } finally {+ connection.disconnect()+ }++ if (cacheFile.exists() && cacheFile.length() > 0) {+ Log.d(TAG, "Cached cover for $itemId (${cacheFile.length()} bytes)")+ return cacheFile+ }+ cacheFile.delete()+ return null+ } catch (e: Exception) {+ Log.e(TAG, "Error fetching cover for $itemId", e)+ return null+ }+ }+// ── Helpers ──private fun extractItemId(uri: Uri): String? {@@ -131,6 +175,10 @@ class CoverContentProvider : ContentProvider() {if (file.exists() && file.canRead()) return file}+ // Check the server-fetch cache+ val cacheFile = File(context.cacheDir, "aa_covers/$itemId.jpg")+ if (cacheFile.exists() && cacheFile.length() > 0) return cacheFile+return null}diff --git a/android/app/src/main/res/raw/keep.xml b/android/app/src/main/res/raw/keep.xmlnew file mode 100644index 00000000..ac43412c--- /dev/null+++ b/android/app/src/main/res/raw/keep.xml@@ -0,0 +1,3 @@+<?xml version="1.0" encoding="utf-8"?>+<resources xmlns:tools="http://schemas.android.com/tools"+ tools:keep="@drawable/ic_speed_*" />diff --git a/lib/main.dart b/lib/main.dartindex 64adabef..35451ad7 100644--- a/lib/main.dart+++ b/lib/main.dart@@ -280,16 +280,18 @@ class _AuthGateState extends State<AuthGate> {}Future<void> _initServices() async {+ // Register the audio handler FIRST so Android Auto's MediaBrowserService+ // can connect immediately on cold start (app force-closed → AA launches it).try {- await Permission.notification.request();+ await AudioPlayerService.init();} catch (e) {- debugPrint('Permission request failed: $e');+ debugPrint('AudioService init failed: $e');}try {- await AudioPlayerService.init();+ await Permission.notification.request();} catch (e) {- debugPrint('AudioService init failed: $e');+ debugPrint('Permission request failed: $e');}// Initialize Chromecastdiff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dartindex ecb00f34..e7acec74 100644--- a/lib/providers/auth_provider.dart+++ b/lib/providers/auth_provider.dart@@ -2,6 +2,7 @@ import 'dart:convert';import 'package:flutter/material.dart';import 'package:shared_preferences/shared_preferences.dart';import '../services/api_service.dart';+import '../services/android_auto_service.dart';import '../services/audio_player_service.dart';import '../services/user_account_service.dart';@@ -269,6 +270,9 @@ class AuthProvider extends ChangeNotifier {}} catch (_) {}+ // Clear Android Auto browse tree cache so it doesn't show stale data+ AndroidAutoService().clearCache();+_token = null;_serverUrl = null;_username = null;@@ -303,6 +307,9 @@ class AuthProvider extends ChangeNotifier {}} catch (_) {}+ // Clear Android Auto browse tree cache so it refreshes for the new user+ AndroidAutoService().clearCache();+// Set the new account as active in the account serviceUserAccountService().switchTo(account.serverUrl, account.username);diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex 4da5cf45..55ce18d9 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -299,16 +299,19 @@ class LibraryProvider extends ChangeNotifier {void updateAuth(AuthProvider auth) {final wasAuthenticated = _auth?.isAuthenticated ?? false;- final previousUserId = _auth?.userId;_auth = auth;if (auth.isAuthenticated) {- final isNewUser = previousUserId != null && previousUserId != auth.userId;final isFreshLogin = !wasAuthenticated;- // Build a key to detect duplicate calls from ProxyProvider re-triggering+ // Build a key to detect duplicate calls from ProxyProvider re-triggering.+ // Use the stored string key (not the object reference) to detect user+ // switches — _auth is the same AuthProvider instance, so comparing+ // _auth?.userId would always equal auth.userId.final authKey = '${auth.userId}@${auth.serverUrl}';- final isDuplicate = authKey == _lastAuthKey && !isNewUser && !isFreshLogin;+ final isNewUser = _lastAuthKey != null && authKey != _lastAuthKey;+ final isDuplicate = !isNewUser && !isFreshLogin;+ debugPrint('[Library] updateAuth: key=$authKey lastKey=$_lastAuthKey isNewUser=$isNewUser isFreshLogin=$isFreshLogin isDuplicate=$isDuplicate');_lastAuthKey = authKey;if (isDuplicate) return; // Skip redundant update@@ -341,11 +344,13 @@ class LibraryProvider extends ChangeNotifier {ChromecastService.setOnBookFinishedCallback(markFinishedLocally);restoreOfflineMode().then((_) {+ debugPrint('[Library] restoreOfflineMode done, serverReachable=${auth.serverReachable} api=${_api != null} offline=$isOffline');_startConnectivityMonitoring();_loadManualAbsorbing();// If server was unreachable on startup, force offline mode and pingif (!auth.serverReachable) {+ debugPrint('[Library] Server not reachable — going offline');_networkOffline = true;_buildOfflineSections();_isLoading = false;@@ -359,7 +364,10 @@ class LibraryProvider extends ChangeNotifier {ProgressSyncService().flushPendingSync(api: _api!);DownloadService().enrichMetadata(_api!);}+ debugPrint('[Library] Calling loadLibraries()');loadLibraries();+ }).catchError((e) {+ debugPrint('[Library] restoreOfflineMode error: $e');});} else {_lastAuthKey = null;diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dartindex 42a9f78c..f6983399 100644--- a/lib/screens/home_screen.dart+++ b/lib/screens/home_screen.dart@@ -226,7 +226,15 @@ class _HomeScreenState extends State<HomeScreen> {final lib = context.watch<LibraryProvider>();final allLibraries = lib.libraries;final libraryName = lib.selectedLibrary?['name'] as String? ?? 'Library';- if (!lib.isLoading) _refreshFilteredCache(lib);+ if (lib.isLoading) {+ // Reset cache so stale data isn't shown after a user switch+ // (where the new user may have the same number of sections).+ _cachedSections = null;+ _cachedClItems = null;+ _lastSectionsLength = -1;+ } else {+ _refreshFilteredCache(lib);+ }return Scaffold(body: Container(diff --git a/lib/services/android_auto_service.dart b/lib/services/android_auto_service.dartindex 978c46fc..fb4c6676 100644--- a/lib/services/android_auto_service.dart+++ b/lib/services/android_auto_service.dart@@ -1,7 +1,7 @@import 'dart:async';import 'dart:convert';import 'package:audio_service/audio_service.dart';-import 'package:connectivity_plus/connectivity_plus.dart';+import 'package:flutter/foundation.dart';import 'package:shared_preferences/shared_preferences.dart';import 'api_service.dart';@@ -157,6 +157,19 @@ class AndroidAutoService {DateTime? _lastRefresh;bool _isRefreshing = false;+ /// Clear all cached browse-tree data and force a fresh server fetch+ /// on the next access. Call when the user switches accounts or logs out.+ void clearCache() {+ _continueListening = [];+ _downloaded = [];+ _recentlyAdded = [];+ _libraries = [];+ _lastRefresh = null;+ _downloadsReady = false;+ _isRefreshing = false;+ debugPrint('[AndroidAuto] Cache cleared (user switch/logout)');+ }+// ── API helpers ──Future<ApiService?> getApi() async {@@ -239,12 +252,11 @@ class AndroidAutoService {/// Build a content:// URI for a locally cached cover image./// Android Auto requires content:// URIs — file:// won't work.- static String _localCoverUri(String itemId) =>+ static String localCoverUri(String itemId) =>'content://$_coverAuthority/cover/$itemId';Future<void> _refreshDownloaded() async {final ds = DownloadService();- final api = await getApi();final items = ds.downloadedItems;final entries = <AutoBookEntry>[];@@ -261,19 +273,10 @@ class AndroidAutoService {final localPos = await ProgressSyncService().getSavedPosition(dl.itemId);- // Use HTTP cover URLs when online (more reliable in AA browse list),- // fall back to local content:// URIs when offline.- String? coverUrl;- final connectivity = await Connectivity().checkConnectivity();- final isOnline = !connectivity.contains(ConnectivityResult.none);- if (isOnline && api != null) {- coverUrl = api.getCoverUrl(dl.itemId, width: 400);- } else {- final localCover = await ds.getLocalCoverPath(dl.itemId);- if (localCover != null) {- coverUrl = _localCoverUri(dl.itemId);- }- }+ // Always use content:// URIs — Android Auto on real car head units+ // cannot load HTTP URLs. The CoverContentProvider serves local+ // downloads directly and fetches/caches from the server on demand.+ final coverUrl = localCoverUri(dl.itemId);entries.add(AutoBookEntry(id: dl.itemId,@@ -284,7 +287,7 @@ class AndroidAutoService {chapters: chapters,currentTime: localPos > 0 ? localPos : null,));- debugPrint('[AndroidAuto] Download entry: ${dl.title} cover=${coverUrl ?? "null"}');+ debugPrint('[AndroidAuto] Download entry: ${dl.title} cover=$coverUrl');}_downloaded = entries;@@ -390,7 +393,7 @@ class AndroidAutoService {title: title,author: author,duration: duration,- coverUrl: api.getCoverUrl(id, width: 400),+ coverUrl: localCoverUri(id),chapters: chapters,currentTime: currentTime,);@@ -413,7 +416,7 @@ class AndroidAutoService {title: title,author: author,duration: duration,- coverUrl: api.getCoverUrl(id, width: 400),+ coverUrl: localCoverUri(id),chapters: chapters,);}diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex a8a0122e..3928564e 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -214,6 +214,7 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {_player.playbackEventStream.map(_transformEvent).pipe(playbackState);}+// OnePlus/Oppo/Realme (ColorOS) renders notification media buttons in// reverse order. Flip the controls so they end up visually correct.// Only on API < 33 — on 33+ the system media player renders from@@ -588,8 +589,35 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {// Try to find in cached entries firstvar entry = _autoService.findEntry(absId);- // If not in cache (e.g. from series/author drilldown or search),- // fetch the item details from server+ // If not in AA cache, check if the item is downloaded locally.+ // This handles cold-start scenarios where the AA browse tree hasn't+ // been populated yet but the user taps a downloaded book.+ if (entry == null) {+ final ds = DownloadService();+ if (ds.isDownloaded(absId)) {+ debugPrint('[Handler] Book not in AA cache but downloaded locally: $absId');+ final dl = ds.getInfo(absId);+ double duration = 0;+ List<dynamic> chapters = [];+ if (dl.sessionData != null) {+ try {+ final session = jsonDecode(dl.sessionData!) as Map<String, dynamic>;+ duration = (session['duration'] as num?)?.toDouble() ?? 0;+ chapters = session['chapters'] as List<dynamic>? ?? [];+ } catch (_) {}+ }+ entry = AutoBookEntry(+ id: absId,+ title: dl.title ?? 'Unknown',+ author: dl.author ?? '',+ duration: duration,+ coverUrl: AndroidAutoService.localCoverUri(absId),+ chapters: chapters,+ );+ }+ }++ // If still not found, fetch the item details from serverif (entry == null) {debugPrint('[Handler] Book not cached, fetching from server: $absId');try {@@ -602,7 +630,7 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {title: metadata['title'] as String? ?? 'Unknown',author: metadata['authorName'] as String? ?? '',duration: (media?['duration'] as num?)?.toDouble() ?? 0,- coverUrl: api.getCoverUrl(absId, width: 400),+ coverUrl: AndroidAutoService.localCoverUri(absId),chapters: media?['chapters'] as List<dynamic>? ?? [],);}