A cross platform Audiobookshelf client for Android and iOS
Dart
Add full-page download manager with covers, file sizes, and batch delete
Nathan Poulson320b08b0ef33
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.ktindex 03c00ab5..0c609909 100644--- a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt+++ b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt@@ -8,6 +8,8 @@ import android.media.audiofx.Equalizerimport android.media.audiofx.LoudnessEnhancerimport android.media.audiofx.Virtualizerimport android.os.Build+import android.os.Environment+import android.os.StatFsimport android.util.Logimport com.ryanheise.audioservice.AudioServiceActivityimport io.flutter.embedding.engine.FlutterEngine@@ -67,6 +69,23 @@ class MainActivity : AudioServiceActivity() {}Log.d(TAG, "EQ method channel registered")+ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.absorb.storage")+ .setMethodCallHandler { call, result ->+ when (call.method) {+ "getDeviceStorage" -> {+ try {+ val stat = StatFs(Environment.getDataDirectory().path)+ result.success(mapOf(+ "totalBytes" to stat.totalBytes,+ "availableBytes" to stat.availableBytes+ ))+ } catch (e: Exception) {+ result.error("STORAGE_ERROR", e.message, null)+ }+ }+ else -> result.notImplemented()+ }+ }}private fun handleInit(result: MethodChannel.Result) {diff --git a/lib/screens/downloads_screen.dart b/lib/screens/downloads_screen.dartnew file mode 100644index 00000000..4f2ac94b--- /dev/null+++ b/lib/screens/downloads_screen.dart@@ -0,0 +1,458 @@+import 'dart:io';+import 'package:cached_network_image/cached_network_image.dart';+import 'package:flutter/material.dart';+import 'package:provider/provider.dart';+import '../providers/library_provider.dart';+import '../services/download_service.dart';+import '../widgets/absorb_page_header.dart';++class DownloadsScreen extends StatefulWidget {+ const DownloadsScreen({super.key});+ @override+ State<DownloadsScreen> createState() => _DownloadsScreenState();+}++class _DownloadsScreenState extends State<DownloadsScreen> {+ bool _loading = true;+ List<DownloadInfo> _items = [];+ Map<String, int> _fileSizes = {};+ bool _selecting = false;+ final Set<String> _selected = {};++ @override+ void initState() {+ super.initState();+ _load();+ }++ Future<void> _load() async {+ final items = DownloadService().downloadedItems;+ final sizes = <String, int>{};+ for (final item in items) {+ sizes[item.itemId] = DownloadService().getItemFileSize(item.itemId);+ }+ if (mounted) {+ setState(() {+ _items = items;+ _fileSizes = sizes;+ _loading = false;+ });+ }+ }++ void _toggleSelect(String itemId) {+ setState(() {+ if (_selected.contains(itemId)) {+ _selected.remove(itemId);+ if (_selected.isEmpty) _selecting = false;+ } else {+ _selected.add(itemId);+ }+ });+ }++ void _enterSelection(String itemId) {+ setState(() {+ _selecting = true;+ _selected.add(itemId);+ });+ }++ void _exitSelection() {+ setState(() {+ _selecting = false;+ _selected.clear();+ });+ }++ Future<void> _deleteSelected() async {+ if (_selected.isEmpty) return;++ final count = _selected.length;+ final confirmed = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ icon: const Icon(Icons.delete_outline_rounded),+ title: Text('Delete $count download${count == 1 ? '' : 's'}?'),+ content: const Text('Downloaded files will be removed from this device.'),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(ctx, false),+ child: const Text('Cancel'),+ ),+ FilledButton(+ onPressed: () => Navigator.pop(ctx, true),+ child: const Text('Delete'),+ ),+ ],+ ),+ );++ if (confirmed != true || !mounted) return;++ for (final itemId in _selected.toList()) {+ await DownloadService().deleteDownload(itemId);+ }++ _exitSelection();+ await _load();++ if (mounted) {+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(+ content: Text('Deleted $count download${count == 1 ? '' : 's'}'),+ behavior: SnackBarBehavior.floating,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ ));+ }+ }++ Future<void> _deleteSingle(DownloadInfo info) async {+ final confirmed = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ icon: const Icon(Icons.delete_outline_rounded),+ title: const Text('Remove download?'),+ content: Text('Delete "${info.title}" from this device?'),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(ctx, false),+ child: const Text('Cancel'),+ ),+ FilledButton(+ onPressed: () => Navigator.pop(ctx, true),+ child: const Text('Delete'),+ ),+ ],+ ),+ );+ if (confirmed != true || !mounted) return;+ await DownloadService().deleteDownload(info.itemId);+ await _load();+ if (mounted) {+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(+ content: Text('"${info.title}" removed'),+ behavior: SnackBarBehavior.floating,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ ));+ }+ }++ static String _formatBytes(int bytes) {+ if (bytes < 1024) return '$bytes B';+ if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';+ if (bytes < 1024 * 1024 * 1024) {+ return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';+ }+ return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(2)} GB';+ }++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;++ return Scaffold(+ backgroundColor: Theme.of(context).scaffoldBackgroundColor,+ body: SafeArea(+ child: _loading+ ? const Center(child: CircularProgressIndicator())+ : Column(+ children: [+ // Header+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 12, 8, 0),+ child: Row(children: [+ const Expanded(+ child: AbsorbPageHeader(+ title: 'Downloads',+ padding: EdgeInsets.zero,+ ),+ ),+ if (_selecting)+ IconButton(+ icon: Icon(Icons.close_rounded,+ color: cs.onSurfaceVariant),+ tooltip: 'Cancel selection',+ onPressed: _exitSelection,+ )+ else ...[+ if (_items.isNotEmpty)+ IconButton(+ icon: Icon(Icons.checklist_rounded,+ color: cs.onSurfaceVariant),+ tooltip: 'Select',+ onPressed: () =>+ setState(() => _selecting = true),+ ),+ IconButton(+ icon: Icon(Icons.close_rounded,+ color: cs.onSurfaceVariant),+ onPressed: () => Navigator.pop(context),+ ),+ ],+ ]),+ ),+ const SizedBox(height: 12),++ // Content+ if (_items.isEmpty)+ Expanded(+ child: Center(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(Icons.download_done_rounded,+ size: 48,+ color: cs.onSurfaceVariant+ .withValues(alpha: 0.4)),+ const SizedBox(height: 12),+ Text('No downloads',+ style: tt.bodyLarge?.copyWith(+ color: cs.onSurfaceVariant)),+ ],+ ),+ ),+ )+ else+ Expanded(+ child: ListenableBuilder(+ listenable: DownloadService(),+ builder: (ctx, _) {+ final items = DownloadService().downloadedItems;+ return ListView.builder(+ padding:+ const EdgeInsets.fromLTRB(16, 0, 16, 24),+ itemCount: items.length,+ itemBuilder: (ctx, index) {+ final info = items[index];+ return _DownloadCard(+ info: info,+ fileSize:+ _fileSizes[info.itemId] ?? 0,+ cs: cs,+ tt: tt,+ selecting: _selecting,+ isSelected:+ _selected.contains(info.itemId),+ onToggle: () =>+ _toggleSelect(info.itemId),+ onLongPress: () =>+ _enterSelection(info.itemId),+ onDelete: () => _deleteSingle(info),+ formatBytes: _formatBytes,+ mediaHeaders: context+ .read<LibraryProvider>()+ .mediaHeaders,+ );+ },+ );+ },+ ),+ ),++ // Bottom delete bar+ if (_selecting && _selected.isNotEmpty)+ Container(+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 12),+ decoration: BoxDecoration(+ color: cs.surfaceContainerHigh,+ border: Border(+ top: BorderSide(+ color: cs.outlineVariant+ .withValues(alpha: 0.3),+ ),+ ),+ ),+ child: SafeArea(+ top: false,+ child: Row(children: [+ Text(+ '${_selected.length} selected',+ style: tt.bodyMedium+ ?.copyWith(color: cs.onSurface),+ ),+ const Spacer(),+ FilledButton.tonalIcon(+ icon: const Icon(+ Icons.delete_outline_rounded,+ size: 18),+ label: const Text('Delete'),+ style: FilledButton.styleFrom(+ backgroundColor: cs.errorContainer,+ foregroundColor: cs.onErrorContainer,+ ),+ onPressed: _deleteSelected,+ ),+ ]),+ ),+ ),+ ],+ ),+ ),+ );+ }+}++class _DownloadCard extends StatelessWidget {+ final DownloadInfo info;+ final int fileSize;+ final ColorScheme cs;+ final TextTheme tt;+ final bool selecting;+ final bool isSelected;+ final VoidCallback onToggle;+ final VoidCallback onLongPress;+ final VoidCallback onDelete;+ final String Function(int) formatBytes;+ final Map<String, String> mediaHeaders;++ const _DownloadCard({+ required this.info,+ required this.fileSize,+ required this.cs,+ required this.tt,+ required this.selecting,+ required this.isSelected,+ required this.onToggle,+ required this.onLongPress,+ required this.onDelete,+ required this.formatBytes,+ required this.mediaHeaders,+ });++ @override+ Widget build(BuildContext context) {+ return Padding(+ padding: const EdgeInsets.only(bottom: 8),+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: selecting ? onToggle : null,+ onLongPress: !selecting ? onLongPress : null,+ child: Card(+ elevation: 0,+ color: cs.surfaceContainerHigh,+ shape:+ RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),+ child: Padding(+ padding: const EdgeInsets.all(12),+ child: Row(+ children: [+ if (selecting)+ Padding(+ padding: const EdgeInsets.only(right: 10),+ child: Icon(+ isSelected+ ? Icons.check_circle_rounded+ : Icons.circle_outlined,+ size: 22,+ color: isSelected+ ? cs.primary+ : cs.onSurfaceVariant.withValues(alpha: 0.5),+ ),+ ),+ // Cover art+ ClipRRect(+ borderRadius: BorderRadius.circular(8),+ child: SizedBox(+ width: 48,+ height: 48,+ child: _buildCover(),+ ),+ ),+ const SizedBox(width: 12),+ // Title, author, size+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ info.title ?? 'Unknown',+ style: tt.titleSmall+ ?.copyWith(fontWeight: FontWeight.w600),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ if (info.author != null && info.author!.isNotEmpty)+ Padding(+ padding: const EdgeInsets.only(top: 2),+ child: Text(+ info.author!,+ style: tt.bodySmall+ ?.copyWith(color: cs.onSurfaceVariant),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ if (fileSize > 0)+ Padding(+ padding: const EdgeInsets.only(top: 2),+ child: Text(+ formatBytes(fileSize),+ style: tt.labelSmall?.copyWith(+ color:+ cs.onSurfaceVariant.withValues(alpha: 0.7),+ ),+ ),+ ),+ ],+ ),+ ),+ if (!selecting)+ IconButton(+ icon: Icon(Icons.delete_outline_rounded,+ color: cs.error, size: 22),+ tooltip: 'Delete',+ onPressed: onDelete,+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }++ Widget _buildCover() {+ // Try local cover first (offline-safe)+ if (info.localCoverPath != null && info.localCoverPath!.isNotEmpty) {+ final file = File(info.localCoverPath!);+ if (file.existsSync()) {+ return Image.file(file,+ fit: BoxFit.cover,+ errorBuilder: (_, __, ___) => _coverPlaceholder());+ }+ }++ // Try coverUrl via CachedNetworkImage+ if (info.coverUrl != null && info.coverUrl!.isNotEmpty) {+ if (info.coverUrl!.startsWith('/')) {+ final file = File(info.coverUrl!);+ if (file.existsSync()) {+ return Image.file(file,+ fit: BoxFit.cover,+ errorBuilder: (_, __, ___) => _coverPlaceholder());+ }+ return _coverPlaceholder();+ }+ return CachedNetworkImage(+ imageUrl: info.coverUrl!,+ fit: BoxFit.cover,+ httpHeaders: mediaHeaders,+ placeholder: (_, __) => _coverPlaceholder(),+ errorWidget: (_, __, ___) => _coverPlaceholder(),+ );+ }++ return _coverPlaceholder();+ }++ Widget _coverPlaceholder() {+ return Container(+ color: cs.surfaceContainerHighest,+ child: Center(+ child: Icon(Icons.headphones_rounded,+ size: 24, color: cs.onSurfaceVariant.withValues(alpha: 0.4)),+ ),+ );+ }+}diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dartindex a4dea751..865a4753 100644--- a/lib/screens/settings_screen.dart+++ b/lib/screens/settings_screen.dart@@ -18,6 +18,7 @@ import '../services/log_service.dart';import '../screens/login_screen.dart';import '../screens/app_shell.dart';import '../screens/admin_screen.dart';+import '../screens/downloads_screen.dart';import '../screens/bookmarks_screen.dart';import '../main.dart' show themeNotifier, parseThemeMode;import '../widgets/absorb_page_header.dart';@@ -58,6 +59,8 @@ class _SettingsScreenState extends State<SettingsScreen> {bool _loaded = false;String _downloadLocationLabel = 'App Internal Storage (Default)';int _totalDownloadSizeBytes = 0;+ int _deviceTotalBytes = 0;+ int _deviceAvailableBytes = 0;AutoSleepSettings _autoSleepSettings = const AutoSleepSettings();String _appVersion = '';String? _expandedSection;@@ -96,6 +99,7 @@ class _SettingsScreenState extends State<SettingsScreen> {final dlLabel = await DownloadService().downloadLocationLabel;final dlSize = await DownloadService().totalDownloadSize;+ final deviceStorage = await DownloadService.getDeviceStorage();final autoSleep = await AutoSleepSettings.load();final pkgInfo = await PackageInfo.fromPlatform();if (mounted) setState(() {@@ -125,6 +129,10 @@ class _SettingsScreenState extends State<SettingsScreen> {_themeMode = theme;_downloadLocationLabel = dlLabel;_totalDownloadSizeBytes = dlSize;+ if (deviceStorage != null) {+ _deviceTotalBytes = deviceStorage['totalBytes']!;+ _deviceAvailableBytes = deviceStorage['availableBytes']!;+ }_autoSleepSettings = autoSleep;_appVersion = pkgInfo.version;_loaded = true;@@ -1125,14 +1133,17 @@ class _SettingsScreenState extends State<SettingsScreen> {trailing: const Icon(Icons.chevron_right),onTap: () => _pickDownloadLocation(context, cs, tt),),- if (_totalDownloadSizeBytes > 0) ...[+ if (_totalDownloadSizeBytes > 0 || _deviceTotalBytes > 0) ...[const Divider(height: 1, indent: 16, endIndent: 16),ListTile(leading: Icon(Icons.data_usage_rounded, color: cs.onSurfaceVariant),title: const Text('Storage used'),subtitle: Text(- _formatBytes(_totalDownloadSizeBytes),+ '${_totalDownloadSizeBytes > 0 ? '${_formatBytes(_totalDownloadSizeBytes)} used by downloads' : ''}'+ '${_totalDownloadSizeBytes > 0 && _deviceTotalBytes > 0 ? '\n' : ''}'+ '${_deviceTotalBytes > 0 ? '${_formatBytes(_deviceAvailableBytes)} free of ${_formatBytes(_deviceTotalBytes)}' : ''}',style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ isThreeLine: _totalDownloadSizeBytes > 0 && _deviceTotalBytes > 0,),],const Divider(height: 1, indent: 16, endIndent: 16),@@ -1140,7 +1151,8 @@ class _SettingsScreenState extends State<SettingsScreen> {leading: Icon(Icons.storage_rounded, color: cs.primary),title: const Text('Manage downloads'),trailing: const Icon(Icons.chevron_right),- onTap: () => _showDownloadManager(context, cs, tt),+ onTap: () => Navigator.push(context,+ MaterialPageRoute(builder: (_) => const DownloadsScreen())),),],),@@ -1810,107 +1822,6 @@ class _SettingsScreenState extends State<SettingsScreen> {);}- void _showDownloadManager(BuildContext context, ColorScheme cs, TextTheme tt) {- showModalBottomSheet(- context: context,- backgroundColor: Colors.transparent,- isScrollControlled: true,- builder: (ctx) => DraggableScrollableSheet(- initialChildSize: 0.5,- minChildSize: 0.05,- maxChildSize: 0.85,- expand: false,- builder: (ctx, scrollController) => Container(- decoration: BoxDecoration(- color: cs.surface,- borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),- ),- child: ListenableBuilder(- listenable: DownloadService(),- builder: (ctx, _) {- final items = DownloadService().downloadedItems;- return Column(- children: [- Padding(- padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),- child: Column(- mainAxisSize: MainAxisSize.min,- children: [- Container(width: 40, height: 4,- decoration: BoxDecoration(- color: cs.onSurfaceVariant.withValues(alpha: 0.3),- borderRadius: BorderRadius.circular(2))),- const SizedBox(height: 16),- Text('Downloads',- style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),- const SizedBox(height: 12),- ],- ),- ),- if (items.isEmpty)- Padding(- padding: const EdgeInsets.all(24),- child: Text('No downloads',- style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),- )- else- Expanded(- child: ListView.builder(- controller: scrollController,- padding: EdgeInsets.only(bottom: 32 + MediaQuery.of(ctx).viewPadding.bottom),- itemCount: items.length,- itemBuilder: (ctx, index) {- final info = items[index];- return ListTile(- leading: Icon(Icons.headphones_rounded, color: cs.primary),- title: Text(info.title ?? 'Unknown',- maxLines: 1, overflow: TextOverflow.ellipsis),- subtitle: Text(info.author ?? '',- maxLines: 1, overflow: TextOverflow.ellipsis,- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),- trailing: IconButton(- icon: Icon(Icons.delete_outline, color: cs.error),- onPressed: () {- showDialog(- context: ctx,- builder: (d) => AlertDialog(- title: const Text('Remove download?'),- content: Text('Delete "${info.title}" from device?'),- actions: [- TextButton(- onPressed: () => Navigator.pop(d),- child: const Text('Cancel')),- FilledButton(- onPressed: () {- DownloadService().deleteDownload(info.itemId);- Navigator.pop(d);- ScaffoldMessenger.of(ctx)- ..clearSnackBars()- ..showSnackBar(SnackBar(- content: Text('"${info.title}" removed'),- duration: const Duration(seconds: 2),- behavior: SnackBarBehavior.floating,- ));- },- child: const Text('Remove')),- ],- ),- );- },- ),- );- },- ),- ),- ],- );- },- ),- ),- ),- );- }-void _backupSettings(BuildContext context, ColorScheme cs, TextTheme tt) {showDialog(context: context,diff --git a/lib/services/download_service.dart b/lib/services/download_service.dartindex d44c84b0..d80db9d6 100644--- a/lib/services/download_service.dart+++ b/lib/services/download_service.dart@@ -2,6 +2,7 @@ import 'dart:async';import 'dart:convert';import 'dart:io';import 'package:flutter/material.dart';+import 'package:flutter/services.dart';import 'package:path_provider/path_provider.dart';import 'package:shared_preferences/shared_preferences.dart';import 'package:connectivity_plus/connectivity_plus.dart';@@ -197,6 +198,40 @@ class DownloadService extends ChangeNotifier {return total;}+ /// Calculate total file size for a single download item.+ int getItemFileSize(String itemId) {+ final info = _downloads[itemId];+ if (info == null || info.status != DownloadStatus.downloaded) return 0;+ int total = 0;+ for (final path in info.localPaths) {+ try {+ final file = File(path);+ if (file.existsSync()) {+ total += file.lengthSync();+ }+ } catch (_) {}+ }+ return total;+ }++ static const _storageChannel = MethodChannel('com.absorb.storage');++ /// Get device storage info: {totalBytes, availableBytes}. Returns null on failure.+ static Future<Map<String, int>?> getDeviceStorage() async {+ try {+ final result = await _storageChannel.invokeMethod('getDeviceStorage');+ if (result is Map) {+ return {+ 'totalBytes': (result['totalBytes'] as num).toInt(),+ 'availableBytes': (result['availableBytes'] as num).toInt(),+ };+ }+ } catch (e) {+ debugPrint('[Download] getDeviceStorage error: $e');+ }+ return null;+ }+DownloadInfo getInfo(String itemId) =>_downloads[itemId] ?? DownloadInfo(itemId: itemId);