Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Fix podcast download crash on large libraries, add stacked series covers

Nathan Poulson49bea23a5833
diff --git a/lib/services/download_service.dart b/lib/services/download_service.dart
index a80feb68..ed1fc8d9 100644
--- a/lib/services/download_service.dart
+++ b/lib/services/download_service.dart
@@ -87,7 +87,7 @@ class DownloadInfo {
?.map((e) => e as String)
.toList() ??
[],
- sessionData: json['sessionData'] as String?,
+ sessionData: _stripLibraryItem(json['sessionData'] as String?),
title: title,
author: author,
coverUrl: coverUrl,
@@ -115,6 +115,20 @@ class _QueuedDownload {
});
}
+/// Strip the bulky `libraryItem` from persisted session data.
+/// For podcasts this contains ALL episodes and can be hundreds of KB.
+String? _stripLibraryItem(String? sessionJson) {
+ if (sessionJson == null) return null;
+ try {
+ final session = jsonDecode(sessionJson) as Map<String, dynamic>;
+ if (session.containsKey('libraryItem')) {
+ session.remove('libraryItem');
+ return jsonEncode(session);
+ }
+ } catch (_) {}
+ return sessionJson;
+}
+
/// Sanitize a string for use as a filesystem directory/file name.
String _sanitizePath(String name) {
// Replace filesystem-illegal characters with underscore
@@ -319,7 +333,15 @@ class DownloadService extends ChangeNotifier {
if (entry.value.status != DownloadStatus.downloaded) continue;
bool allExist = true;
for (final path in entry.value.localPaths) {
- if (!await File(path).exists()) {
+ try {
+ final exists = await File(path).exists()
+ .timeout(const Duration(seconds: 3));
+ if (!exists) {
+ allExist = false;
+ break;
+ }
+ } catch (_) {
+ // Timeout or permission error — treat as missing
allExist = false;
break;
}
@@ -793,15 +815,23 @@ class DownloadService extends ChangeNotifier {
final sessionId = sessionData['id'] as String?;
if (sessionId != null) {
try {
- await api.closePlaybackSession(sessionId);
+ await api.closePlaybackSession(sessionId)
+ .timeout(const Duration(seconds: 10));
} catch (_) {}
}
+ // Strip large nested objects from session data before persisting.
+ // libraryItem contains the full item (with ALL episodes for podcasts)
+ // and can be hundreds of KB - storing one per downloaded episode
+ // bloats SharedPreferences and can cause ANR/OOM.
+ final slimSession = Map<String, dynamic>.from(sessionData);
+ slimSession.remove('libraryItem');
+
_downloads[itemId] = DownloadInfo(
itemId: itemId,
status: DownloadStatus.downloaded,
localPaths: completedPaths,
- sessionData: jsonEncode(sessionData),
+ sessionData: jsonEncode(slimSession),
title: title,
author: author,
coverUrl: coverUrl,
@@ -879,6 +909,7 @@ class DownloadService extends ChangeNotifier {
_activeDownloadIds.remove(itemId);
_downloadSlots.remove(itemId);
+ try { _httpClients[itemId]?.close(); } catch (_) {}
_httpClients.remove(itemId);
_cancelledIds.remove(itemId);
diff --git a/lib/widgets/library_grid_tiles.dart b/lib/widgets/library_grid_tiles.dart
index d924eb97..a0b27283 100644
--- a/lib/widgets/library_grid_tiles.dart
+++ b/lib/widgets/library_grid_tiles.dart
@@ -198,6 +198,191 @@ class _GridBookTileState extends State<GridBookTile> {
}
}
+// ═══════════════════════════════════════════════════════════════
+// Stacked cover art for series tiles
+// Shows up to 3 covers offset behind each other.
+// ═══════════════════════════════════════════════════════════════
+class _StackedCovers extends StatelessWidget {
+ final List<String?> coverUrls;
+ final int numBooks;
+ final Map<String, String> mediaHeaders;
+ final ColorScheme cs;
+ final double seriesProgress;
+ final int booksFinished;
+
+ const _StackedCovers({
+ required this.coverUrls,
+ required this.numBooks,
+ required this.mediaHeaders,
+ required this.cs,
+ this.seriesProgress = 0,
+ this.booksFinished = 0,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final count = coverUrls.length.clamp(1, 4);
+
+ const inset = 5.0;
+ final totalOffset = count > 1 ? inset * (count - 1) : 0.0;
+
+ return AspectRatio(
+ aspectRatio: 1,
+ child: Stack(
+ children: [
+ // Back covers (furthest back first so front paints on top)
+ for (int i = count - 1; i > 0; i--)
+ Positioned(
+ top: (totalOffset - i * inset),
+ right: (totalOffset - i * inset),
+ left: i * inset,
+ bottom: i * inset,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(10),
+ boxShadow: [
+ BoxShadow(
+ color: Colors.black.withValues(alpha: 0.15),
+ blurRadius: 2,
+ offset: const Offset(-1, 1),
+ ),
+ ],
+ ),
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: _coverImage(coverUrls[i]),
+ ),
+ ),
+ ),
+ // Front cover (bottom-left)
+ Positioned(
+ top: totalOffset,
+ right: totalOffset,
+ left: 0,
+ bottom: 0,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(10),
+ boxShadow: count > 1
+ ? [
+ BoxShadow(
+ color: Colors.black.withValues(alpha: 0.2),
+ blurRadius: 3,
+ offset: const Offset(-1, 1),
+ ),
+ ]
+ : [],
+ ),
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ _coverImage(coverUrls.isNotEmpty ? coverUrls[0] : null),
+ // Series progress bar
+ if (seriesProgress > 0 && booksFinished < numBooks)
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: 0,
+ child: LinearProgressIndicator(
+ value: seriesProgress.clamp(0.0, 1.0),
+ minHeight: 3,
+ backgroundColor: Colors.black38,
+ valueColor: AlwaysStoppedAnimation(cs.primary),
+ ),
+ ),
+ // Finished banner
+ if (booksFinished > 0 && booksFinished >= numBooks)
+ 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.7),
+ Colors.black.withValues(alpha: 0.0),
+ ],
+ ),
+ ),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Icon(Icons.check_circle_rounded, size: 10,
+ color: Colors.greenAccent),
+ const SizedBox(width: 3),
+ Text('Finished',
+ style: TextStyle(fontSize: 9, fontWeight: FontWeight.w600,
+ color: Colors.white.withValues(alpha: 0.9))),
+ ],
+ ),
+ ),
+ ),
+ // Book count badge
+ Positioned(
+ top: 6,
+ right: 6,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3),
+ decoration: BoxDecoration(
+ color: cs.primaryContainer,
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.auto_stories_rounded, size: 11, color: cs.onPrimaryContainer),
+ const SizedBox(width: 3),
+ Text(booksFinished > 0 && booksFinished < numBooks
+ ? '$booksFinished/$numBooks'
+ : '$numBooks',
+ style: TextStyle(fontSize: 10, fontWeight: FontWeight.w700,
+ color: cs.onPrimaryContainer)),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _coverImage(String? url) {
+ if (url == null) return _placeholder();
+ if (url.startsWith('/')) {
+ return Image.file(File(url), fit: BoxFit.cover,
+ errorBuilder: (_, __, ___) => _placeholder());
+ }
+ return CachedNetworkImage(
+ imageUrl: url,
+ fit: BoxFit.cover,
+ httpHeaders: mediaHeaders,
+ placeholder: (_, __) => _placeholder(),
+ errorWidget: (_, __, ___) => _placeholder(),
+ );
+ }
+
+ Widget _placeholder() {
+ return Container(
+ color: cs.surfaceContainerHighest,
+ child: Center(
+ child: Icon(Icons.auto_stories_rounded,
+ size: 24, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
+ ),
+ );
+ }
+}
+
// ═══════════════════════════════════════════════════════════════
// Grid series tile (collapsed series in browse grid)
// ═══════════════════════════════════════════════════════════════
@@ -212,7 +397,6 @@ class GridSeriesTile extends StatelessWidget {
final lib = context.watch<LibraryProvider>();
final auth = context.read<AuthProvider>();
- final itemId = item['id'] as String? ?? '';
final collapsedSeries = item['collapsedSeries'] as Map<String, dynamic>? ?? {};
final seriesName = collapsedSeries['name'] as String? ?? 'Unknown Series';
final seriesId = collapsedSeries['id'] as String? ?? '';
@@ -220,7 +404,29 @@ class GridSeriesTile extends StatelessWidget {
final media = item['media'] as Map<String, dynamic>? ?? {};
final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
final author = metadata['authorName'] as String? ?? '';
- final coverUrl = lib.getCoverUrl(itemId);
+
+ // Gather up to 4 cover URLs from libraryItemIds
+ final itemIds = (collapsedSeries['libraryItemIds'] as List<dynamic>?)
+ ?.map((e) => e as String)
+ .toList() ?? [item['id'] as String? ?? ''];
+ final coverUrls = itemIds
+ .take(4)
+ .map((id) => lib.getCoverUrl(id))
+ .toList();
+
+ // Calculate series progress
+ double totalProgress = 0;
+ int finished = 0;
+ for (final id in itemIds) {
+ final pd = lib.getProgressData(id);
+ if (pd?['isFinished'] == true) {
+ finished++;
+ totalProgress += 1.0;
+ } else {
+ totalProgress += lib.getProgress(id);
+ }
+ }
+ final seriesProgress = itemIds.isNotEmpty ? totalProgress / itemIds.length : 0.0;
return GestureDetector(
onTap: () {
@@ -238,55 +444,15 @@ class GridSeriesTile extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- AspectRatio(
- aspectRatio: 1,
- child: ClipRRect(
- borderRadius: BorderRadius.circular(10),
- child: Stack(
- fit: StackFit.expand,
- children: [
- // Cover image (first book in series)
- 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),
-
- // Book count badge — top-right
- Positioned(
- top: 6,
- right: 6,
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3),
- decoration: BoxDecoration(
- color: cs.primaryContainer,
- borderRadius: BorderRadius.circular(10),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(Icons.auto_stories_rounded, size: 11, color: cs.onPrimaryContainer),
- const SizedBox(width: 3),
- Text('$numBooks',
- style: TextStyle(fontSize: 10, fontWeight: FontWeight.w700,
- color: cs.onPrimaryContainer)),
- ],
- ),
- ),
- ),
- ],
- ),
- ),
+ _StackedCovers(
+ coverUrls: coverUrls,
+ numBooks: numBooks,
+ mediaHeaders: lib.mediaHeaders,
+ cs: cs,
+ seriesProgress: seriesProgress,
+ booksFinished: finished,
),
const SizedBox(height: 5),
- // Series name
Text(
seriesName,
maxLines: 1,
@@ -297,7 +463,6 @@ class GridSeriesTile extends StatelessWidget {
fontSize: 11,
),
),
- // Author
if (author.isNotEmpty)
Text(
author,
@@ -312,16 +477,6 @@ class GridSeriesTile extends StatelessWidget {
),
);
}
-
- Widget _placeholder(ColorScheme cs) {
- return Container(
- color: cs.surfaceContainerHighest,
- child: Center(
- child: Icon(Icons.auto_stories_rounded,
- size: 24, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
- ),
- );
- }
}
// ═══════════════════════════════════════════════════════════════
@@ -345,18 +500,40 @@ class GridSeriesTileDirect extends StatelessWidget {
final books = series['books'] as List<dynamic>? ?? [];
final numBooks = books.length;
- // Get cover from first book in series
- String? coverUrl;
+ // Get author from first book
String author = '';
if (books.isNotEmpty) {
final firstBook = books.first as Map<String, dynamic>? ?? {};
- final bookId = firstBook['id'] as String? ?? '';
- if (bookId.isNotEmpty) coverUrl = lib.getCoverUrl(bookId);
final media = firstBook['media'] as Map<String, dynamic>? ?? {};
final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
author = metadata['authorName'] as String? ?? '';
}
+ // Gather up to 4 cover URLs from books
+ final coverUrls = books
+ .take(4)
+ .map((b) {
+ final bookId = (b as Map<String, dynamic>)['id'] as String? ?? '';
+ return bookId.isNotEmpty ? lib.getCoverUrl(bookId) : null;
+ })
+ .toList();
+
+ // Calculate series progress
+ double totalProgress = 0;
+ int finished = 0;
+ for (final b in books) {
+ final bookId = (b as Map<String, dynamic>)['id'] as String? ?? '';
+ if (bookId.isEmpty) continue;
+ final pd = lib.getProgressData(bookId);
+ if (pd?['isFinished'] == true) {
+ finished++;
+ totalProgress += 1.0;
+ } else {
+ totalProgress += lib.getProgress(bookId);
+ }
+ }
+ final seriesProgress = books.isNotEmpty ? totalProgress / books.length : 0.0;
+
return GestureDetector(
onTap: () {
if (seriesId.isNotEmpty) {
@@ -373,49 +550,13 @@ class GridSeriesTileDirect extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- AspectRatio(
- aspectRatio: 1,
- child: ClipRRect(
- borderRadius: BorderRadius.circular(10),
- child: Stack(
- fit: StackFit.expand,
- children: [
- 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),
- Positioned(
- top: 6,
- right: 6,
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3),
- decoration: BoxDecoration(
- color: cs.primaryContainer,
- borderRadius: BorderRadius.circular(10),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(Icons.auto_stories_rounded, size: 11, color: cs.onPrimaryContainer),
- const SizedBox(width: 3),
- Text('$numBooks',
- style: TextStyle(fontSize: 10, fontWeight: FontWeight.w700,
- color: cs.onPrimaryContainer)),
- ],
- ),
- ),
- ),
- ],
- ),
- ),
+ _StackedCovers(
+ coverUrls: coverUrls,
+ numBooks: numBooks,
+ mediaHeaders: lib.mediaHeaders,
+ cs: cs,
+ seriesProgress: seriesProgress,
+ booksFinished: finished,
),
const SizedBox(height: 5),
Text(
@@ -442,16 +583,6 @@ class GridSeriesTileDirect extends StatelessWidget {
),
);
}
-
- Widget _placeholder(ColorScheme cs) {
- return Container(
- color: cs.surfaceContainerHighest,
- child: Center(
- child: Icon(Icons.auto_stories_rounded,
- size: 24, color: cs.onSurfaceVariant.withValues(alpha: 0.3)),
- ),
- );
- }
}
// ═══════════════════════════════════════════════════════════════
diff --git a/pubspec.yaml b/pubspec.yaml
index cd56d7b4..8c5dd4ce 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,7 +1,7 @@
name: absorb
description: A Material 3 Audiobookshelf client.
publish_to: 'none'
-version: 1.8.12+42
+version: 1.8.13+43
environment:
sdk: '>=3.1.0 <4.0.0'