Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Section detail sheets, grid toggles, cover color extraction, JWT notification fix

Nathan Poulson13482f7a6a6e
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 618f0ff6..78828bfc 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/CoverContentProvider.kt
@@ -95,48 +95,112 @@ class CoverContentProvider : ContentProvider() {
"FlutterSharedPreferences", android.content.Context.MODE_PRIVATE
)
val serverUrl = prefs.getString("flutter.server_url", null)
- val token = prefs.getString("flutter.token", null)
+ var token = prefs.getString("flutter.token", null)
if (serverUrl.isNullOrEmpty() || token.isNullOrEmpty()) {
- Log.w(TAG, "No server_url or token in prefs — cannot fetch cover")
+ 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
+ var result = fetchCover(cleanUrl, itemId, token, cacheFile)
+ if (result == 401) {
+ // Access token expired - try refreshing via the refresh token
+ val newToken = refreshAccessToken(cleanUrl, prefs)
+ if (newToken != null) {
+ token = newToken
+ result = fetchCover(cleanUrl, itemId, token, cacheFile)
+ }
+ }
+
+ if (result == 200 && 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
+ }
+ }
+
+ private fun fetchCover(serverUrl: String, itemId: String, token: String, outFile: File): Int {
+ val fetchUrl = "$serverUrl/api/items/$itemId/cover?width=400&token=$token"
+ val connection = URL(fetchUrl).openConnection() as HttpURLConnection
+ connection.connectTimeout = 5000
+ connection.readTimeout = 5000
+ connection.instanceFollowRedirects = true
+ try {
+ val code = connection.responseCode
+ if (code != 200) {
+ Log.w(TAG, "Cover fetch failed: HTTP $code for $itemId")
+ return code
+ }
+ connection.inputStream.use { input ->
+ outFile.outputStream().use { output ->
+ input.copyTo(output)
+ }
+ }
+ return 200
+ } finally {
+ connection.disconnect()
+ }
+ }
+
+ private fun refreshAccessToken(
+ serverUrl: String,
+ prefs: android.content.SharedPreferences
+ ): String? {
+ val refreshToken = prefs.getString("flutter.refresh_token", null)
+ if (refreshToken.isNullOrEmpty()) {
+ Log.w(TAG, "No refresh token available")
+ return null
+ }
+ try {
+ val connection = URL("$serverUrl/api/authorize").openConnection() as HttpURLConnection
+ connection.requestMethod = "POST"
connection.connectTimeout = 5000
connection.readTimeout = 5000
- connection.instanceFollowRedirects = true
-
+ connection.setRequestProperty("Authorization", "Bearer $refreshToken")
+ connection.setRequestProperty("x-return-tokens", "true")
try {
if (connection.responseCode != 200) {
- Log.w(TAG, "Cover fetch failed: HTTP ${connection.responseCode} for $itemId")
+ Log.w(TAG, "Token refresh failed: HTTP ${connection.responseCode}")
return null
}
- connection.inputStream.use { input ->
- cacheFile.outputStream().use { output ->
- input.copyTo(output)
+ val body = connection.inputStream.bufferedReader().readText()
+ // Simple JSON parsing - extract accessToken and refreshToken
+ val newAccess = extractJsonString(body, "accessToken")
+ val newRefresh = extractJsonString(body, "refreshToken")
+ if (newAccess != null) {
+ prefs.edit()
+ .putString("flutter.token", newAccess)
+ .apply()
+ if (newRefresh != null) {
+ prefs.edit()
+ .putString("flutter.refresh_token", newRefresh)
+ .apply()
}
+ Log.d(TAG, "Token refreshed successfully from CoverContentProvider")
+ return newAccess
}
} 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
+ Log.e(TAG, "Token refresh error", e)
}
+ return null
+ }
+
+ private fun extractJsonString(json: String, key: String): String? {
+ val pattern = "\"$key\"\\s*:\\s*\"([^\"]+)\""
+ val match = Regex(pattern).find(json)
+ return match?.groupValues?.get(1)
}
// ── Helpers ──
diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist
index d478b5cd..acccc024 100644
--- a/ios/Runner/Info.plist
+++ b/ios/Runner/Info.plist
@@ -95,5 +95,7 @@
<string>Absorb may use the microphone for audio features.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Absorb needs access to your photo library to save or select images.</string>
+ <key>ITSAppUsesNonExemptEncryption</key>
+ <false/>
</dict>
</plist>
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index c5e763de..6c3b36ad 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -379,6 +379,84 @@ class LibraryProvider extends ChangeNotifier {
_isLoading = false;
}
+ /// Re-inject the downloaded-books section when downloads change.
+ void _onDownloadsChanged() {
+ if (isOffline || _personalizedSections.isEmpty) return;
+ // Remove existing downloaded-books section and re-inject
+ _personalizedSections.removeWhere(
+ (s) => (s as Map)['id'] == 'downloaded-books');
+ _injectDownloadedSection();
+ notifyListeners();
+ }
+
+ /// Inject a "Downloads" section into the online personalized view so users
+ /// can see their downloaded items alongside server sections.
+ void _injectDownloadedSection() {
+ final isPodcast = isPodcastLibrary;
+ final allDownloads = DownloadService().downloadedItems;
+ final downloads = allDownloads
+ .where((dl) => (dl.itemId.length > 36) == isPodcast)
+ .toList();
+ if (downloads.isEmpty) return;
+
+ final entities = <Map<String, dynamic>>[];
+ for (final dl in downloads) {
+ double duration = 0;
+ List<dynamic> chapters = [];
+ String? episodeTitle;
+ 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>? ?? [];
+ episodeTitle = session['episodeTitle'] as String? ??
+ session['displayTitle'] as String?;
+ } catch (_) {}
+ }
+
+ final isCompound = dl.itemId.length > 36;
+ if (isCompound) {
+ final showId = dl.itemId.substring(0, 36);
+ final episodeId = dl.itemId.substring(37);
+ entities.add({
+ 'id': showId,
+ '_absorbingKey': dl.itemId,
+ 'recentEpisode': {
+ 'id': episodeId,
+ 'title': episodeTitle ?? dl.title ?? 'Episode',
+ },
+ 'media': {
+ 'metadata': {
+ 'title': dl.title ?? 'Unknown Title',
+ 'authorName': dl.author ?? '',
+ },
+ 'duration': duration,
+ 'chapters': chapters,
+ },
+ });
+ } else {
+ entities.add({
+ 'id': dl.itemId,
+ 'media': {
+ 'metadata': {
+ 'title': dl.title ?? 'Unknown Title',
+ 'authorName': dl.author ?? '',
+ },
+ 'duration': duration,
+ 'chapters': chapters,
+ },
+ });
+ }
+ }
+
+ _personalizedSections.add({
+ 'id': 'downloaded-books',
+ 'label': isPodcast ? 'Downloaded Episodes' : 'Downloaded Books',
+ 'type': isPodcast ? 'podcast' : 'book',
+ 'entities': entities,
+ });
+ }
+
// User's media progress, keyed by libraryItemId
Map<String, Map<String, dynamic>> _progressMap = {};
@@ -530,11 +608,17 @@ class LibraryProvider extends ChangeNotifier {
}
StreamSubscription? _connectivitySub;
+ bool _listeningToDownloads = false;
/// Called by ProxyProvider when auth changes.
String? _lastAuthKey; // Guard against redundant updateAuth from ProxyProvider
void updateAuth(AuthProvider auth) {
+ // Listen to download changes so the Downloads shelf appears/updates live.
+ if (!_listeningToDownloads) {
+ _listeningToDownloads = true;
+ DownloadService().addListener(_onDownloadsChanged);
+ }
final wasAuthenticated = _auth?.isAuthenticated ?? false;
_auth = auth;
@@ -1183,6 +1267,9 @@ class LibraryProvider extends ChangeNotifier {
}
await _updateAbsorbingCache();
+ // Inject a "Downloads" section from locally downloaded items.
+ _injectDownloadedSection();
+
// For podcast libraries, defer RSS-heavy fields until after first paint.
if (isPodcastLibrary) {
_hydrateRssFeedFieldsDeferred();
diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dart
index e822ac63..22c42a98 100644
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@ -9,6 +9,7 @@ import '../services/chromecast_service.dart';
import '../services/sleep_timer_service.dart';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
+import 'package:palette_generator/palette_generator.dart';
import '../main.dart' show snappyTransitionsNotifier, coverSchemeNotifier;
import '../l10n/app_localizations.dart';
import '../services/android_auto_service.dart';
@@ -199,10 +200,9 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
void _onLibraryChanged() {
if (!mounted) return;
- // Once absorbing list loads, derive cover scheme if we haven't yet
- if (coverSchemeNotifier.value == null) {
- _deriveCoverScheme();
- }
+ // Re-derive cover scheme whenever absorbing list changes so the app
+ // theme always reflects the current [0] book.
+ _deriveCoverScheme();
}
/// Attempt to derive cover scheme. Returns true if successful.
@@ -222,7 +222,7 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
if (itemId == null) {
return false;
}
- if (itemId == _lastCoverItemId && coverSchemeNotifier.value != null) return true;
+ if (itemId == _lastCoverItemId) return true;
final lib = context.read<LibraryProvider>();
final coverUrl = lib.getCoverUrl(itemId, width: 400);
@@ -239,12 +239,23 @@ class _AppShellState extends State<AppShell> with WidgetsBindingObserver, Ticker
}
final brightness = Theme.of(context).brightness;
- ColorScheme.fromImageProvider(provider: provider, brightness: brightness)
- .then((scheme) {
+ debugPrint('[CoverScheme] Extracting from $coverUrl for item $itemId');
+ PaletteGenerator.fromImageProvider(provider, maximumColorCount: 16)
+ .then((palette) {
+ final seedColor = palette.vibrantColor?.color
+ ?? palette.dominantColor?.color
+ ?? palette.colors.firstOrNull;
+ if (seedColor == null) {
+ debugPrint('[CoverScheme] No colors extracted');
+ _lastCoverItemId = null;
+ return;
+ }
+ debugPrint('[CoverScheme] Extracted seed: $seedColor (vibrant=${palette.vibrantColor?.color}, dominant=${palette.dominantColor?.color})');
+ final scheme = ColorScheme.fromSeed(seedColor: seedColor, brightness: brightness);
coverSchemeNotifier.value = scheme;
- PlayerSettings.setCoverSeedColor(scheme.primary.toARGB32());
- }).catchError((_) {
- // Image load failed - allow retry
+ PlayerSettings.setCoverSeedColor(seedColor.toARGB32());
+ }).catchError((e) {
+ debugPrint('[CoverScheme] Extraction failed: $e');
_lastCoverItemId = null;
});
return true; // cover URL found, image load in progress
diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart
index 5c90cabc..0a23361a 100644
--- a/lib/screens/home_screen.dart
+++ b/lib/screens/home_screen.dart
@@ -16,6 +16,7 @@ import '../main.dart' show oledNotifier;
import '../widgets/home_customize_sheet.dart';
import '../widgets/playlist_detail_sheet.dart';
import '../widgets/collection_detail_sheet.dart';
+import '../widgets/section_detail_sheet.dart';
import 'app_shell.dart';
class HomeScreen extends StatefulWidget {
@@ -496,22 +497,35 @@ class _HomeScreenState extends State<HomeScreen> {
if (clItems.isEmpty) return <Widget>[];
return <Widget>[
SliverToBoxAdapter(
- child: Padding(
- padding: const EdgeInsets.fromLTRB(20, 24, 20, 0),
- child: Row(children: [
- Icon(Icons.play_circle_outline_rounded,
- size: 16, color: cs.primary.withValues(alpha: 0.7)),
- const SizedBox(width: 8),
- Text('Continue Listening',
- style: tt.titleSmall?.copyWith(
- fontWeight: FontWeight.w500,
- color: cs.onSurface.withValues(alpha: 0.8),
- letterSpacing: 0.3,
- )),
- const SizedBox(width: 12),
- Expanded(child: Container(height: 0.5,
- color: cs.outlineVariant.withValues(alpha: 0.2))),
- ]),
+ child: GestureDetector(
+ onTap: () => SectionDetailSheet.show(
+ context,
+ title: 'Continue Listening',
+ icon: Icons.play_circle_outline_rounded,
+ entities: clItems,
+ coverAspectRatio: _rectangleCovers ? 2 / 3 : 1.0,
+ ),
+ behavior: HitTestBehavior.opaque,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(20, 24, 20, 0),
+ child: Row(children: [
+ Icon(Icons.play_circle_outline_rounded,
+ size: 16, color: cs.primary.withValues(alpha: 0.7)),
+ const SizedBox(width: 8),
+ Text('Continue Listening',
+ style: tt.titleSmall?.copyWith(
+ fontWeight: FontWeight.w500,
+ color: cs.onSurface.withValues(alpha: 0.8),
+ letterSpacing: 0.3,
+ )),
+ const SizedBox(width: 4),
+ Icon(Icons.chevron_right_rounded, size: 16,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.4)),
+ const SizedBox(width: 12),
+ Expanded(child: Container(height: 0.5,
+ color: cs.outlineVariant.withValues(alpha: 0.2))),
+ ]),
+ ),
),
),
SliverToBoxAdapter(
@@ -560,6 +574,14 @@ class _HomeScreenState extends State<HomeScreen> {
sectionIcon = Icons.collections_bookmark_rounded;
} else {
sectionIcon = _sectionIcons[id] ?? Icons.album_outlined;
+ final sectionLabel = label as String;
+ titleTap = () => SectionDetailSheet.show(
+ context,
+ title: sectionLabel,
+ icon: sectionIcon,
+ entities: entities,
+ coverAspectRatio: _rectangleCovers ? 2 / 3 : 1.0,
+ );
}
return <Widget>[
diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dart
index 2b187f00..5907578b 100644
--- a/lib/screens/library_screen.dart
+++ b/lib/screens/library_screen.dart
@@ -139,6 +139,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
final newTab = _tabController!.index;
if (newTab == _currentTab) return;
setState(() => _currentTab = newTab);
+ PlayerSettings.setLibraryTab(newTab);
// Lazy load data for the tab
if (newTab == 1 && _seriesItems.isEmpty && !_isLoadingSeriesPage) {
_loadSeriesPage();
@@ -233,6 +234,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
PlayerSettings.getAuthorSortAsc(),
PlayerSettings.getPodcastSort(),
PlayerSettings.getPodcastSortAsc(),
+ PlayerSettings.getLibraryTab(),
]);
if (!mounted) return;
final sortName = results[0] as String;
@@ -245,6 +247,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
final authorSortAsc = results[7] as bool;
final podcastSortName = results[8] as String;
final podcastSortAsc = results[9] as bool;
+ final savedTab = results[10] as int;
final isPodcast = context.read<LibraryProvider>().isPodcastLibrary;
setState(() {
// Book library sort/filter
@@ -282,7 +285,18 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi
_filter = LibraryFilter.none;
_genreFilter = null;
}
+ // Restore last active tab (only for book libraries with tabs)
+ if (!isPodcast && savedTab > 0 && savedTab < 3) {
+ _currentTab = savedTab;
+ _tabController?.animateTo(savedTab);
+ }
});
+ // Lazy load data for the restored tab
+ if (!isPodcast && savedTab == 1 && _seriesItems.isEmpty && !_isLoadingSeriesPage) {
+ _loadSeriesPage();
+ } else if (!isPodcast && savedTab == 2 && !_authorsLoaded && !_isLoadingAuthors) {
+ _loadAuthors();
+ }
}
void _onSettingsChanged() {
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 1109eabe..2cbdc66a 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -265,6 +265,9 @@ class PlayerSettings {
static Future<String> getLibraryGenreFilter() => _get('libraryGenreFilter', '');
static Future<void> setLibraryGenreFilter(String? value) => _set('libraryGenreFilter', value ?? '');
+ static Future<int> getLibraryTab() => _get('libraryTab', 0);
+ static Future<void> setLibraryTab(int value) => _set('libraryTab', value);
+
// ── Podcast library sort persistence ──
static Future<String> getPodcastSort() => _get('podcastSort', 'recentlyAdded');
@@ -641,6 +644,12 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
}
/// Called when the user swipes the app away from recents.
+ ///
+ /// Only pause instead of stopping - the 10-minute pause timeout already
+ /// handles cleanup (server session + audio focus). Calling stop() here
+ /// deactivates the MediaSession, and on some devices (Android 16+) the
+ /// system never re-routes BT media buttons to a reactivated session,
+ /// leaving earbud controls permanently broken until reboot.
@override
Future<void> onTaskRemoved() async {
debugPrint('[Handler] onTaskRemoved - app swiped away');
@@ -648,11 +657,11 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
if (ChromecastService().isCasting) return;
if (_service != null) {
await _service!.pause();
- await _service!.stop();
} else {
- await _player.stop();
+ await _player.pause();
}
- await super.onTaskRemoved();
+ // Don't call super.onTaskRemoved() - it calls stop() which deactivates
+ // the MediaSession and breaks BT media button routing on restart.
}
@override
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index 83e67bcc..bcc00014 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -8,6 +8,7 @@ import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'overlay_toast.dart';
import 'package:cached_network_image/cached_network_image.dart';
+import 'package:palette_generator/palette_generator.dart';
import 'package:path_provider/path_provider.dart';
import 'package:file_picker/file_picker.dart';
import 'package:http/http.dart' as http;
@@ -195,9 +196,15 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
final lib = context.read<LibraryProvider>();
provider = CachedNetworkImageProvider(url, headers: lib.mediaHeaders);
}
- ColorScheme.fromImageProvider(provider: provider, brightness: brightness)
- .then((s) { if (mounted) setState(() => _coverScheme = s); })
- .catchError((_) {});
+ PaletteGenerator.fromImageProvider(provider, maximumColorCount: 16)
+ .then((palette) {
+ final seedColor = palette.vibrantColor?.color
+ ?? palette.dominantColor?.color
+ ?? palette.colors.firstOrNull;
+ if (seedColor == null || !mounted) return;
+ setState(() => _coverScheme = ColorScheme.fromSeed(
+ seedColor: seedColor, brightness: brightness));
+ }).catchError((_) {});
}
String? get _coverUrl {
@@ -215,13 +222,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
return auth.apiService?.getCoverUrl(widget.itemId, width: 4000);
}
- /// Low-res cover for the blurred background - saves GPU work.
- String? get _blurCoverUrl {
- final localCover = _item?['_localCoverUrl'] as String?;
- if (localCover != null && localCover.isNotEmpty) return localCover;
- final auth = context.read<AuthProvider>();
- return auth.apiService?.getCoverUrl(widget.itemId, width: 200);
- }
@override Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
@@ -230,28 +230,16 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(color: Theme.of(context).scaffoldBackgroundColor, borderRadius: const BorderRadius.vertical(top: Radius.circular(24))),
child: Stack(children: [
- // Blurred cover + gradient scrim as a single cached layer to avoid
- // expensive re-compositing of ImageFilter.blur during sheet drag.
- RepaintBoundary(
- child: Stack(children: [
- if (_blurCoverUrl != null)
- Positioned.fill(
- child: CachedNetworkImage(
- imageUrl: _blurCoverUrl!, fit: BoxFit.cover,
- httpHeaders: context.read<LibraryProvider>().mediaHeaders,
- imageBuilder: (_, p) => ImageFiltered(
- imageFilter: ui.ImageFilter.blur(sigmaX: 25, sigmaY: 25, tileMode: TileMode.decal),
- child: Image(image: p, fit: BoxFit.cover)),
- placeholder: (_, __) => const SizedBox(),
- errorWidget: (_, __, ___) => const SizedBox(),
- ),
- ),
- Positioned.fill(child: DecoratedBox(decoration: BoxDecoration(gradient: LinearGradient(
- begin: Alignment.topCenter, end: Alignment.bottomCenter,
- colors: [Theme.of(context).scaffoldBackgroundColor.withValues(alpha: 0.6), Theme.of(context).scaffoldBackgroundColor.withValues(alpha: 0.85), Theme.of(context).scaffoldBackgroundColor],
- )))),
- ]),
- ),
+ // Cover-derived color gradient background - lighter than blurred image.
+ Positioned.fill(child: DecoratedBox(decoration: BoxDecoration(gradient: LinearGradient(
+ begin: Alignment.topCenter, end: Alignment.bottomCenter,
+ stops: const [0.0, 0.4, 1.0],
+ colors: [
+ (_coverScheme?.primaryContainer ?? Theme.of(context).scaffoldBackgroundColor).withValues(alpha: 0.5),
+ Theme.of(context).scaffoldBackgroundColor.withValues(alpha: 0.85),
+ Theme.of(context).scaffoldBackgroundColor,
+ ],
+ )))),
_isLoading || (_item != null && _coverUrl != null && _coverScheme == null)
? Center(child: CircularProgressIndicator(strokeWidth: 2, color: cs.onSurface.withValues(alpha: 0.24)))
: _item == null
diff --git a/lib/widgets/collection_detail_sheet.dart b/lib/widgets/collection_detail_sheet.dart
index a0e9f144..934b5050 100644
--- a/lib/widgets/collection_detail_sheet.dart
+++ b/lib/widgets/collection_detail_sheet.dart
@@ -40,6 +40,7 @@ class CollectionDetailSheet extends StatefulWidget {
class _CollectionDetailSheetState extends State<CollectionDetailSheet> {
bool _reordering = false;
+ bool _gridView = false;
List<Map<String, dynamic>>? _reorderItems;
Future<void> _removeItem(LibraryProvider lib, String libraryItemId) async {
@@ -158,6 +159,13 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {
Text('${books.length} book${books.length == 1 ? '' : 's'}',
style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),
),
+ const SizedBox(width: 12),
+ GestureDetector(
+ onTap: () => setState(() => _gridView = !_gridView),
+ child: Icon(
+ _gridView ? Icons.view_list_rounded : Icons.grid_view_rounded,
+ size: 20, color: cs.onSurfaceVariant),
+ ),
if (isRoot && books.length > 1) ...[
const SizedBox(width: 12),
GestureDetector(
@@ -186,7 +194,9 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {
Expanded(
child: _reordering
? _buildReorderList(cs, tt, lib)
- : _buildItemList(cs, tt, lib, books, isRoot: isRoot),
+ : _gridView
+ ? _buildGrid(cs, tt, lib, books)
+ : _buildItemList(cs, tt, lib, books, isRoot: isRoot),
),
]);
}
@@ -450,6 +460,126 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {
);
}
+ Widget _buildGrid(ColorScheme cs, TextTheme tt, LibraryProvider lib, List<dynamic> books) {
+ final isDark = Theme.of(context).brightness == Brightness.dark;
+ final doneColor = isDark ? Colors.greenAccent[400]! : Colors.green.shade700;
+
+ return GridView.builder(
+ controller: widget.scrollController,
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4)
+ .copyWith(bottom: 40),
+ gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: 3,
+ mainAxisSpacing: 12,
+ crossAxisSpacing: 12,
+ childAspectRatio: 0.62,
+ ),
+ itemCount: books.length,
+ itemBuilder: (context, index) {
+ final book = books[index] as Map<String, dynamic>;
+ final itemId = book['id'] as String? ?? '';
+ final media = book['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final author = metadata['authorName'] as String? ?? '';
+ final coverUrl = lib.getCoverUrl(itemId);
+ final isExplicit = PlayerSettings.showExplicitBadge && metadata['explicit'] == true;
+ final progress = lib.getProgress(itemId);
+ final isFinished = lib.getProgressData(itemId)?['isFinished'] == true;
+ final isDownloaded = DownloadService().isDownloaded(itemId);
+
+ return GestureDetector(
+ onTap: () => showBookDetailSheet(context, itemId),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ AspectRatio(
+ aspectRatio: 1,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: Stack(children: [
+ Positioned.fill(
+ child: coverUrl != null
+ ? (coverUrl.startsWith('/')
+ ? Image.file(File(coverUrl), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _placeholder(cs))
+ : CachedNetworkImage(
+ imageUrl: coverUrl, fit: BoxFit.cover,
+ httpHeaders: lib.mediaHeaders,
+ placeholder: (_, __) => _placeholder(cs),
+ errorWidget: (_, __, ___) => _placeholder(cs),
+ ))
+ : _placeholder(cs),
+ ),
+ if (isExplicit)
+ Positioned(
+ top: 4, right: 4,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
+ decoration: BoxDecoration(
+ color: Colors.red.withValues(alpha: 0.85),
+ borderRadius: BorderRadius.circular(4),
+ ),
+ child: const Text('E', style: TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.w800)),
+ ),
+ ),
+ if (progress > 0 && !isFinished)
+ Positioned(
+ left: 0, right: 0, bottom: 0,
+ child: LinearProgressIndicator(
+ value: progress.clamp(0.0, 1.0),
+ minHeight: 3,
+ backgroundColor: Colors.black38,
+ valueColor: AlwaysStoppedAnimation(cs.primary),
+ ),
+ ),
+ if (isFinished || isDownloaded)
+ Positioned(
+ left: 0, right: 0, bottom: 0,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.bottomCenter,
+ end: Alignment.topCenter,
+ colors: [
+ Colors.black.withValues(alpha: 0.85),
+ Colors.black.withValues(alpha: 0.0),
+ ],
+ ),
+ ),
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ if (isFinished)
+ Row(mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.check_circle_rounded, size: 10, color: doneColor),
+ const SizedBox(width: 3),
+ Text('Done', style: TextStyle(fontSize: 9, fontWeight: FontWeight.w600, color: doneColor)),
+ ]),
+ if (isDownloaded)
+ Row(mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.download_done_rounded, size: 10, color: cs.primary),
+ const SizedBox(width: 3),
+ Text('Saved', style: TextStyle(fontSize: 9, fontWeight: FontWeight.w600, color: cs.primary)),
+ ]),
+ ]),
+ ),
+ ),
+ ]),
+ ),
+ ),
+ const SizedBox(height: 6),
+ Text(title, maxLines: 2, overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(fontWeight: FontWeight.w600, color: cs.onSurface)),
+ if (author.isNotEmpty)
+ Text(author, maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(fontSize: 10, color: cs.onSurfaceVariant)),
+ ],
+ ),
+ );
+ },
+ );
+ }
+
Widget _placeholder(ColorScheme cs) {
return Container(
color: cs.surfaceContainerHigh,
diff --git a/lib/widgets/playlist_detail_sheet.dart b/lib/widgets/playlist_detail_sheet.dart
index 7d63fb43..37830ebc 100644
--- a/lib/widgets/playlist_detail_sheet.dart
+++ b/lib/widgets/playlist_detail_sheet.dart
@@ -41,6 +41,7 @@ class PlaylistDetailSheet extends StatefulWidget {
class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {
bool _reordering = false;
+ bool _gridView = false;
List<Map<String, dynamic>>? _reorderItems;
bool _selectMode = false;
final Set<String> _selectedKeys = {}; // "libraryItemId" or "libraryItemId-episodeId"
@@ -294,6 +295,13 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {
Text('${items.length} item${items.length == 1 ? '' : 's'}',
style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant),
),
+ const SizedBox(width: 8),
+ GestureDetector(
+ onTap: () => setState(() => _gridView = !_gridView),
+ child: Icon(
+ _gridView ? Icons.view_list_rounded : Icons.grid_view_rounded,
+ size: 20, color: cs.onSurfaceVariant),
+ ),
if (items.length > 1) ...[
const SizedBox(width: 8),
GestureDetector(
@@ -320,7 +328,9 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {
? _buildReorderList(cs, tt, lib)
: _selectMode
? _buildSelectList(cs, tt, lib, items)
- : _buildItemList(cs, tt, lib, items),
+ : _gridView
+ ? _buildGrid(cs, tt, lib, items)
+ : _buildItemList(cs, tt, lib, items),
),
// Batch action bar
if (_selectMode && _selectedKeys.isNotEmpty)
@@ -712,6 +722,151 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {
);
}
+ Widget _buildGrid(ColorScheme cs, TextTheme tt, LibraryProvider lib, List<dynamic> items) {
+ final isDark = Theme.of(context).brightness == Brightness.dark;
+ final doneColor = isDark ? Colors.greenAccent[400]! : Colors.green.shade700;
+
+ return GridView.builder(
+ controller: widget.scrollController,
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4)
+ .copyWith(bottom: 40),
+ gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: 3,
+ mainAxisSpacing: 12,
+ crossAxisSpacing: 12,
+ childAspectRatio: 0.62,
+ ),
+ itemCount: items.length,
+ itemBuilder: (context, index) {
+ final item = items[index] as Map<String, dynamic>;
+ final libraryItemId = item['libraryItemId'] as String? ?? '';
+ final episodeId = item['episodeId'] as String?;
+ final libraryItem = item['libraryItem'] as Map<String, dynamic>?;
+ if (libraryItem == null) return const SizedBox.shrink();
+
+ final media = libraryItem['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final author = metadata['authorName'] as String? ?? '';
+ final coverUrl = lib.getCoverUrl(libraryItemId);
+ final isExplicit = PlayerSettings.showExplicitBadge && metadata['explicit'] == true;
+ final progressKey = episodeId != null ? '$libraryItemId-$episodeId' : libraryItemId;
+ final progress = lib.getProgress(progressKey);
+ final isFinished = lib.getProgressData(progressKey)?['isFinished'] == true;
+ final isDownloaded = DownloadService().isDownloaded(libraryItemId);
+
+ String? episodeTitle;
+ if (episodeId != null) {
+ final episodes = media['episodes'] as List<dynamic>? ?? [];
+ episodeTitle = episodes.cast<Map<String, dynamic>>().where(
+ (e) => e['id'] == episodeId,
+ ).firstOrNull?['title'] as String?;
+ }
+
+ return GestureDetector(
+ onTap: () {
+ if (episodeId != null) {
+ final episodes = media['episodes'] as List<dynamic>? ?? [];
+ final ep = episodes.cast<Map<String, dynamic>>().where(
+ (e) => e['id'] == episodeId,
+ ).firstOrNull;
+ if (ep != null) {
+ EpisodeDetailSheet.show(context, libraryItem, ep);
+ }
+ } else {
+ showBookDetailSheet(context, libraryItemId);
+ }
+ },
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ AspectRatio(
+ aspectRatio: 1,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: Stack(children: [
+ Positioned.fill(
+ child: coverUrl != null
+ ? (coverUrl.startsWith('/')
+ ? Image.file(File(coverUrl), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _placeholder(cs))
+ : CachedNetworkImage(
+ imageUrl: coverUrl, fit: BoxFit.cover,
+ httpHeaders: lib.mediaHeaders,
+ placeholder: (_, __) => _placeholder(cs),
+ errorWidget: (_, __, ___) => _placeholder(cs),
+ ))
+ : _placeholder(cs),
+ ),
+ if (isExplicit)
+ Positioned(
+ top: 4, right: 4,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
+ decoration: BoxDecoration(
+ color: Colors.red.withValues(alpha: 0.85),
+ borderRadius: BorderRadius.circular(4),
+ ),
+ child: const Text('E', style: TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.w800)),
+ ),
+ ),
+ if (progress > 0 && !isFinished)
+ Positioned(
+ left: 0, right: 0, bottom: 0,
+ child: LinearProgressIndicator(
+ value: progress.clamp(0.0, 1.0),
+ minHeight: 3,
+ backgroundColor: Colors.black38,
+ valueColor: AlwaysStoppedAnimation(cs.primary),
+ ),
+ ),
+ if (isFinished || isDownloaded)
+ Positioned(
+ left: 0, right: 0, bottom: 0,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.bottomCenter,
+ end: Alignment.topCenter,
+ colors: [
+ Colors.black.withValues(alpha: 0.85),
+ Colors.black.withValues(alpha: 0.0),
+ ],
+ ),
+ ),
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ if (isFinished)
+ Row(mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.check_circle_rounded, size: 10, color: doneColor),
+ const SizedBox(width: 3),
+ Text('Done', style: TextStyle(fontSize: 9, fontWeight: FontWeight.w600, color: doneColor)),
+ ]),
+ if (isDownloaded)
+ Row(mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.download_done_rounded, size: 10, color: cs.primary),
+ const SizedBox(width: 3),
+ Text('Saved', style: TextStyle(fontSize: 9, fontWeight: FontWeight.w600, color: cs.primary)),
+ ]),
+ ]),
+ ),
+ ),
+ ]),
+ ),
+ ),
+ const SizedBox(height: 6),
+ Text(episodeTitle ?? title, maxLines: 2, overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(fontWeight: FontWeight.w600, color: cs.onSurface)),
+ if ((episodeTitle != null ? title : author).isNotEmpty)
+ Text(episodeTitle != null ? title : author, maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(fontSize: 10, color: cs.onSurfaceVariant)),
+ ],
+ ),
+ );
+ },
+ );
+ }
+
Widget _placeholder(ColorScheme cs) {
return Container(
color: cs.surfaceContainerHigh,
diff --git a/lib/widgets/section_detail_sheet.dart b/lib/widgets/section_detail_sheet.dart
new file mode 100644
index 00000000..ba2e3fae
--- /dev/null
+++ b/lib/widgets/section_detail_sheet.dart
@@ -0,0 +1,374 @@
+import 'dart:io';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:provider/provider.dart';
+import 'package:cached_network_image/cached_network_image.dart';
+import '../providers/library_provider.dart';
+import '../services/audio_player_service.dart';
+import '../services/download_service.dart';
+import 'book_detail_sheet.dart';
+import 'overlay_toast.dart';
+import 'stackable_sheet.dart';
+
+/// Generic detail sheet for any home screen section (Continue Listening,
+/// Recently Added, Downloads, etc.). Shows items in a list or 3-column grid
+/// with progress bars, saved/done badges, and explicit badges.
+class SectionDetailSheet extends StatefulWidget {
+ final String title;
+ final IconData icon;
+ final List<dynamic> entities;
+ final double coverAspectRatio;
+ final ScrollController? scrollController;
+
+ const SectionDetailSheet({
+ super.key,
+ required this.title,
+ required this.icon,
+ required this.entities,
+ this.coverAspectRatio = 1.0,
+ this.scrollController,
+ });
+
+ static void show(BuildContext context, {
+ required String title,
+ required IconData icon,
+ required List<dynamic> entities,
+ double coverAspectRatio = 1.0,
+ }) {
+ showStackableSheet(
+ context: context,
+ useSafeArea: true,
+ showHandle: true,
+ maxChildSize: 0.95,
+ builder: (context, scrollController) => SectionDetailSheet(
+ title: title,
+ icon: icon,
+ entities: entities,
+ coverAspectRatio: coverAspectRatio,
+ scrollController: scrollController,
+ ),
+ );
+ }
+
+ @override
+ State<SectionDetailSheet> createState() => _SectionDetailSheetState();
+}
+
+class _SectionDetailSheetState extends State<SectionDetailSheet> {
+ bool _gridView = false;
+
+ @override
+ Widget build(BuildContext context) {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final lib = context.watch<LibraryProvider>();
+
+ return Column(children: [
+ // Header
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
+ child: Row(children: [
+ Icon(widget.icon, size: 20, color: cs.primary),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(widget.title,
+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600),
+ maxLines: 1, overflow: TextOverflow.ellipsis),
+ ),
+ Text('${widget.entities.length}',
+ style: tt.labelMedium?.copyWith(color: cs.onSurfaceVariant)),
+ const SizedBox(width: 12),
+ GestureDetector(
+ onTap: () => setState(() => _gridView = !_gridView),
+ child: Icon(
+ _gridView ? Icons.view_list_rounded : Icons.grid_view_rounded,
+ size: 20, color: cs.onSurfaceVariant,
+ ),
+ ),
+ ]),
+ ),
+ const SizedBox(height: 4),
+ Expanded(
+ child: _gridView
+ ? _buildGrid(cs, tt, lib)
+ : _buildList(cs, tt, lib),
+ ),
+ ]);
+ }
+
+ Widget _buildList(ColorScheme cs, TextTheme tt, LibraryProvider lib) {
+ final isDark = Theme.of(context).brightness == Brightness.dark;
+ final doneColor = isDark ? Colors.greenAccent[400]! : Colors.green.shade700;
+
+ return ListView.builder(
+ controller: widget.scrollController,
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4)
+ .copyWith(bottom: 40),
+ itemCount: widget.entities.length,
+ itemBuilder: (context, index) {
+ final item = widget.entities[index] as Map<String, dynamic>;
+ final itemId = item['id'] as String? ?? '';
+ final media = item['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final author = metadata['authorName'] as String? ?? '';
+ final coverUrl = lib.getCoverUrl(itemId);
+ final isExplicit = PlayerSettings.showExplicitBadge &&
+ metadata['explicit'] == true;
+ final progress = lib.getProgress(itemId);
+ final isFinished =
+ lib.getProgressData(itemId)?['isFinished'] == true;
+ final isDownloaded = DownloadService().isDownloaded(itemId);
+ final isOnAbsorbing = lib.isOnAbsorbingList(itemId);
+
+ final card = Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Card(
+ elevation: 0,
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(14)),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: () => showBookDetailSheet(context, itemId),
+ borderRadius: BorderRadius.circular(14),
+ child: SizedBox(
+ height: 112,
+ child: Row(children: [
+ AspectRatio(
+ aspectRatio: widget.coverAspectRatio,
+ child: Stack(children: [
+ Positioned.fill(child: _cover(coverUrl, lib, cs)),
+ if (isExplicit) _explicitBadge(),
+ if (progress > 0 && !isFinished) _progressBar(cs, progress),
+ if (isFinished || isDownloaded)
+ _badges(cs, doneColor, isFinished, isDownloaded),
+ ]),
+ ),
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 14, vertical: 10),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Text(title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: cs.onSurface)),
+ const SizedBox(height: 4),
+ Text(author,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ ),
+ ),
+ ),
+ ]),
+ ),
+ ),
+ ),
+ );
+
+ return Dismissible(
+ key: ValueKey('absorb-$itemId'),
+ direction: isOnAbsorbing
+ ? DismissDirection.none
+ : DismissDirection.startToEnd,
+ confirmDismiss: (_) async {
+ await lib.addToAbsorbingQueue(itemId);
+ lib.absorbingItemCache[itemId] = Map<String, dynamic>.from(item);
+ HapticFeedback.mediumImpact();
+ if (context.mounted) {
+ showOverlayToast(context, 'Added "$title" to Absorbing',
+ icon: Icons.add_circle_outline_rounded);
+ }
+ return false;
+ },
+ background: Container(
+ alignment: Alignment.centerLeft,
+ padding: const EdgeInsets.only(left: 20),
+ decoration: BoxDecoration(
+ color: cs.primary.withValues(alpha: 0.15),
+ borderRadius: BorderRadius.circular(14),
+ ),
+ child: Icon(Icons.add_circle_outline_rounded, color: cs.primary),
+ ),
+ child: card,
+ );
+ },
+ );
+ }
+
+ Widget _buildGrid(ColorScheme cs, TextTheme tt, LibraryProvider lib) {
+ final isDark = Theme.of(context).brightness == Brightness.dark;
+ final doneColor = isDark ? Colors.greenAccent[400]! : Colors.green.shade700;
+ final isRect = widget.coverAspectRatio < 1.0;
+ // Text area is ~50px; cover uses aspect ratio to determine height
+ final childAspectRatio = isRect ? 0.45 : 0.62;
+
+ return GridView.builder(
+ controller: widget.scrollController,
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4)
+ .copyWith(bottom: 40),
+ gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: 3,
+ mainAxisSpacing: 12,
+ crossAxisSpacing: 12,
+ childAspectRatio: childAspectRatio,
+ ),
+ itemCount: widget.entities.length,
+ itemBuilder: (context, index) {
+ final item = widget.entities[index] as Map<String, dynamic>;
+ final itemId = item['id'] as String? ?? '';
+ final media = item['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final title = metadata['title'] as String? ?? 'Unknown';
+ final author = metadata['authorName'] as String? ?? '';
+ final coverUrl = lib.getCoverUrl(itemId);
+ final isExplicit = PlayerSettings.showExplicitBadge &&
+ metadata['explicit'] == true;
+ final progress = lib.getProgress(itemId);
+ final isFinished =
+ lib.getProgressData(itemId)?['isFinished'] == true;
+ final isDownloaded = DownloadService().isDownloaded(itemId);
+
+ return GestureDetector(
+ onTap: () => showBookDetailSheet(context, itemId),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ AspectRatio(
+ aspectRatio: widget.coverAspectRatio,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: Stack(children: [
+ Positioned.fill(child: _cover(coverUrl, lib, cs)),
+ if (isExplicit) _explicitBadge(),
+ if (progress > 0 && !isFinished)
+ _progressBar(cs, progress),
+ if (isFinished || isDownloaded)
+ _badges(cs, doneColor, isFinished, isDownloaded),
+ ]),
+ ),
+ ),
+ const SizedBox(height: 6),
+ Text(title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.onSurface)),
+ if (author.isNotEmpty)
+ Text(author,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(
+ fontSize: 10, color: cs.onSurfaceVariant)),
+ ],
+ ),
+ );
+ },
+ );
+ }
+
+ // ── Shared widgets ──
+
+ Widget _cover(String? coverUrl, LibraryProvider lib, ColorScheme cs) {
+ if (coverUrl == null) return _placeholder(cs);
+ if (coverUrl.startsWith('/')) {
+ return Image.file(File(coverUrl), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _placeholder(cs));
+ }
+ return CachedNetworkImage(
+ imageUrl: coverUrl, fit: BoxFit.cover,
+ httpHeaders: lib.mediaHeaders,
+ placeholder: (_, __) => _placeholder(cs),
+ errorWidget: (_, __, ___) => _placeholder(cs),
+ );
+ }
+
+ Widget _placeholder(ColorScheme cs) => Container(
+ color: cs.surfaceContainerHighest,
+ child: Icon(Icons.book_rounded, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ );
+
+ Widget _explicitBadge() => Positioned(
+ top: 4, right: 4,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
+ decoration: BoxDecoration(
+ color: Colors.red.withValues(alpha: 0.85),
+ borderRadius: BorderRadius.circular(4),
+ ),
+ child: const Text('E',
+ style: TextStyle(
+ color: Colors.white,
+ fontSize: 9,
+ fontWeight: FontWeight.w800)),
+ ),
+ );
+
+ Widget _progressBar(ColorScheme cs, double progress) => Positioned(
+ left: 0, right: 0, bottom: 0,
+ child: LinearProgressIndicator(
+ value: progress.clamp(0.0, 1.0),
+ minHeight: 3,
+ backgroundColor: Colors.black38,
+ valueColor: AlwaysStoppedAnimation(cs.primary),
+ ),
+ );
+
+ Widget _badges(ColorScheme cs, Color doneColor, bool isFinished,
+ bool isDownloaded) =>
+ Positioned(
+ left: 0, right: 0, bottom: 0,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.bottomCenter,
+ end: Alignment.topCenter,
+ colors: [
+ Colors.black.withValues(alpha: 0.85),
+ Colors.black.withValues(alpha: 0.0),
+ ],
+ ),
+ ),
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ if (isFinished)
+ Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.check_circle_rounded,
+ size: 10, color: doneColor),
+ const SizedBox(width: 3),
+ Text('Done',
+ style: TextStyle(
+ fontSize: 9,
+ fontWeight: FontWeight.w600,
+ color: doneColor)),
+ ]),
+ if (isDownloaded)
+ Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.download_done_rounded,
+ size: 10, color: cs.primary),
+ const SizedBox(width: 3),
+ Text('Saved',
+ style: TextStyle(
+ fontSize: 9,
+ fontWeight: FontWeight.w600,
+ color: cs.primary)),
+ ]),
+ ]),
+ ),
+ );
+}
diff --git a/pubspec.lock b/pubspec.lock
index 2ad6c5e4..a53cf918 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -620,6 +620,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.2.1"
+ palette_generator:
+ dependency: "direct main"
+ description:
+ name: palette_generator
+ sha256: "4420f7ccc3f0a4a906144e73f8b6267cd940b64f57a7262e95cb8cec3a8ae0ed"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.3.3+7"
path:
dependency: transitive
description:
diff --git a/pubspec.yaml b/pubspec.yaml
index 15cd865c..7958386f 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,11 +1,12 @@
name: absorb
description: An Audiobookshelf Client
publish_to: 'none'
-version: 1.8.41+63
+version: 1.8.42+64
# v1.8.41: JWT auth (accessToken + refreshToken), MANAGE_EXTERNAL_STORAGE removed from playstore flavor
# Build scripts (run from Git Bash):
# . ./build_bundle.sh - Play Store AAB (no MANAGE_EXTERNAL_STORAGE)
# . ./build_github.sh - GitHub APK (full permissions, includes update checker)
+# flutter run --flavor github = . ./run.sh
environment:
sdk: '>=3.1.0 <4.0.0'
@@ -85,6 +86,7 @@ dependencies:
webview_flutter: ^4.13.1
flutter_markdown_plus: ^1.0.7
wakelock_plus: ^1.3.3
+ palette_generator: ^0.3.3+7
dev_dependencies:
flutter_test:
diff --git a/run.sh b/run.sh
new file mode 100644
index 00000000..c86799d6
--- /dev/null
+++ b/run.sh
@@ -0,0 +1,2 @@
+#!/bin/bash
+flutter run --flavor github --dart-define=GITHUB_BUILD=true "$@"