A cross platform Audiobookshelf client for Android and iOS
Dart
Fix ebook downloads, audio interruption handling, and card ordering
Nathan Poulson04d6db17ed7b
diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dartindex 4f4ca2be..4a89848a 100644--- a/lib/screens/absorbing_screen.dart+++ b/lib/screens/absorbing_screen.dart@@ -83,6 +83,9 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {? '${_player.currentItemId!}-${_player.currentEpisodeId!}': _player.currentItemId!;lib.unblockFromAbsorbing(playingKey);+ // Persist so this item stays at front even if the app is killed+ _lastFinishedId = playingKey;+ ScopedPrefs.setString('absorbing_last_finished', playingKey);// Suppress the list reorder if we're not already at page 0, so the// animation slides the current view to the front instead of jumping.final currentPage = _pageController.hasClientsdiff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex 0d91317f..9fbcfd9c 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -702,6 +702,7 @@ class AudioPlayerService extends ChangeNotifier {static Future<void> _configureAudioSession() async {final session = await AudioSession.instance;await session.configure(const AudioSessionConfiguration.speech());+ await session.setActive(true);_interruptSub?.cancel();_interruptSub = session.interruptionEventStream.listen((event) async {@@ -710,8 +711,8 @@ class AudioPlayerService extends ChangeNotifier {if (event.begin) {if (service.isPlaying) {debugPrint('[AudioSession] Interrupted (${event.type}) — pausing');- service._wasPlayingBeforeInterrupt = true;await service.pause();+ service._wasPlayingBeforeInterrupt = true;}} else {if (service._wasPlayingBeforeInterrupt) {@@ -1468,6 +1469,8 @@ class AudioPlayerService extends ChangeNotifier {}}_lastPauseTime = null;+ // Re-activate audio session (needed after stop() releases it)+ try { (await AudioSession.instance).setActive(true); } catch (_) {}_player?.play();_logEvent(PlaybackEventType.play);// Check auto sleep on every resume — catches window entry between pauses@@ -1621,6 +1624,8 @@ class AudioPlayerService extends ChangeNotifier {if (SleepTimerService().isActive) {SleepTimerService().cancel();}+ // Release audio focus so other apps can use it+ try { (await AudioSession.instance).setActive(false); } catch (_) {}}/// Stop playback without saving progress — used by reset progress.diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex f79f54fe..9fd89d11 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -8,6 +8,7 @@ import 'package:cached_network_image/cached_network_image.dart';import 'package:path_provider/path_provider.dart';import 'package:file_picker/file_picker.dart';import 'package:http/http.dart' as http;+import 'package:shared_preferences/shared_preferences.dart';import 'package:url_launcher/url_launcher.dart';import '../providers/auth_provider.dart';import '../providers/library_provider.dart';@@ -49,11 +50,17 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {bool _isAbsorbing = false;bool _hasLocalOverride = false;bool _showGoodreads = false;+ bool _ebookSaved = false;@override void initState() {super.initState();_loadItem();PlayerSettings.getShowGoodreadsButton().then((v) { if (mounted) setState(() => _showGoodreads = v); });+ SharedPreferences.getInstance().then((p) {+ if (mounted && (p.getStringList('saved_ebooks') ?? []).contains(widget.itemId)) {+ setState(() => _ebookSaved = true);+ }+ });}Future<void> _loadItem() async {@@ -275,10 +282,10 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [_ebookSaving? SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: cs.onSurfaceVariant))- : Icon(Icons.save_alt_rounded, size: 16, color: cs.onSurfaceVariant),+ : Icon(_ebookSaved ? Icons.download_done_rounded : Icons.save_alt_rounded, size: 16, color: cs.onSurfaceVariant),const SizedBox(width: 6),Text(- _ebookSaving ? 'Saving…' : 'Download eBook',+ _ebookSaving ? 'Saving…' : _ebookSaved ? 'Download eBook Again' : 'Download eBook',style: TextStyle(color: cs.onSurfaceVariant, fontSize: 12, fontWeight: FontWeight.w500),),]),@@ -333,10 +340,10 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [_ebookSaving? SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: cs.onSurfaceVariant))- : Icon(Icons.save_alt_rounded, size: 16, color: cs.onSurfaceVariant),+ : Icon(_ebookSaved ? Icons.download_done_rounded : Icons.save_alt_rounded, size: 16, color: cs.onSurfaceVariant),const SizedBox(width: 6),Text(- _ebookSaving ? 'Saving…' : 'Download eBook',+ _ebookSaving ? 'Saving…' : _ebookSaved ? 'Download eBook Again' : 'Download eBook',style: TextStyle(color: cs.onSurfaceVariant, fontSize: 12, fontWeight: FontWeight.w500),),]),@@ -512,30 +519,38 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {// Download to cache first (reuse if already cached)final cacheDir = await getTemporaryDirectory();final cachedFile = File('${cacheDir.path}/$safeTitle$ext');- late final List<int> bytes;- if (cachedFile.existsSync()) {- bytes = await cachedFile.readAsBytes();- } else {+ if (!cachedFile.existsSync()) {final cleanBase = api.baseUrl.endsWith('/') ? api.baseUrl.substring(0, api.baseUrl.length - 1) : api.baseUrl;final url = '$cleanBase/api/items/${widget.itemId}/file/$ino';- final response = await http.get(- Uri.parse(url),- headers: {'Authorization': 'Bearer ${api.token}'},- ).timeout(const Duration(seconds: 60));-- if (response.statusCode == 200) {- bytes = response.bodyBytes;- await cachedFile.writeAsBytes(bytes);- } else {- if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text('Failed to download ebook (${response.statusCode})')));++ // Use streamed download to avoid loading entire file into memory+ // and to prevent timeout-based truncation of large files+ final request = http.Request('GET', Uri.parse(url));+ request.headers['Authorization'] = 'Bearer ${api.token}';+ final client = http.Client();+ try {+ final response = await client.send(request);+ if (response.statusCode != 200) {+ if (mounted) {+ ScaffoldMessenger.of(context).showSnackBar(+ SnackBar(content: Text('Failed to download ebook (${response.statusCode})')));+ }+ return;}- return;+ final sink = cachedFile.openWrite();+ try {+ await response.stream.pipe(sink);+ } finally {+ await sink.close();+ }+ } finally {+ client.close();}}+ final bytes = await cachedFile.readAsBytes();+// Open system save dialog so user can choose the locationfinal savedPath = await FilePicker.platform.saveFile(dialogTitle: 'Save eBook',@@ -545,6 +560,15 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {if (savedPath == null) return; // user cancelled+ // Track that this ebook has been saved+ final prefs = await SharedPreferences.getInstance();+ final saved = prefs.getStringList('saved_ebooks') ?? [];+ if (!saved.contains(widget.itemId)) {+ saved.add(widget.itemId);+ await prefs.setStringList('saved_ebooks', saved);+ }+ if (mounted) setState(() => _ebookSaved = true);+if (mounted) {ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Saved: $safeTitle$ext'),diff --git a/pubspec.yaml b/pubspec.yamlindex d3980c34..45f2d006 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -1,7 +1,7 @@name: absorbdescription: A Material 3 Audiobookshelf client for Android.publish_to: 'none'-version: 1.7.8+34+version: 1.7.14+34environment:sdk: '>=3.1.0 <4.0.0'