A cross platform Audiobookshelf client for Android and iOS
Dart
Read ebooks offline, and download ebook-only books for offline reading
Barnabasecef6c2956b0
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arbindex 68cd223a..caef0c85 100644--- a/lib/l10n/app_en.arb+++ b/lib/l10n/app_en.arb@@ -3802,6 +3802,14 @@"libRemoveFoldersBody": "Removing a folder deletes its items from the library. This can't be undone.","readEbook": "Read",+ "ebookDownload": "Download",+ "ebookDownloaded": "Downloaded",+ "ebookSavedOffline": "Saved for offline reading",+ "ebookRemovedOffline": "Removed from offline",+ "ebookOfflineFailed": "Couldn't download the ebook",+ "ebookSaveToDevice": "Save to device",+ "ebookSaveToDeviceTitle": "Save to device?",+ "ebookSaveToDeviceBody": "This saves a copy of the ebook file somewhere on your device (you pick where). It won't make the book available offline in the reader - use Download for that.","readerFormatUnsupported": "This ebook format can't be opened in the reader yet","moreActions": "More","readerChapters": "Chapters",diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dartindex 0c8b1e03..1651f422 100644--- a/lib/l10n/app_localizations.dart+++ b/lib/l10n/app_localizations.dart@@ -11397,6 +11397,54 @@ abstract class AppLocalizations {/// **'Read'**String get readEbook;+ /// No description provided for @ebookDownload.+ ///+ /// In en, this message translates to:+ /// **'Download'**+ String get ebookDownload;++ /// No description provided for @ebookDownloaded.+ ///+ /// In en, this message translates to:+ /// **'Downloaded'**+ String get ebookDownloaded;++ /// No description provided for @ebookSavedOffline.+ ///+ /// In en, this message translates to:+ /// **'Saved for offline reading'**+ String get ebookSavedOffline;++ /// No description provided for @ebookRemovedOffline.+ ///+ /// In en, this message translates to:+ /// **'Removed from offline'**+ String get ebookRemovedOffline;++ /// No description provided for @ebookOfflineFailed.+ ///+ /// In en, this message translates to:+ /// **'Couldn\'t download the ebook'**+ String get ebookOfflineFailed;++ /// No description provided for @ebookSaveToDevice.+ ///+ /// In en, this message translates to:+ /// **'Save to device'**+ String get ebookSaveToDevice;++ /// No description provided for @ebookSaveToDeviceTitle.+ ///+ /// In en, this message translates to:+ /// **'Save to device?'**+ String get ebookSaveToDeviceTitle;++ /// No description provided for @ebookSaveToDeviceBody.+ ///+ /// In en, this message translates to:+ /// **'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.'**+ String get ebookSaveToDeviceBody;+/// No description provided for @readerFormatUnsupported.////// In en, this message translates to:diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dartindex ed4686d0..5e025033 100644--- a/lib/l10n/app_localizations_de.dart+++ b/lib/l10n/app_localizations_de.dart@@ -6570,6 +6570,31 @@ class AppLocalizationsDe extends AppLocalizations {@overrideString get readEbook => 'Read';+ @override+ String get ebookDownload => 'Download';++ @override+ String get ebookDownloaded => 'Downloaded';++ @override+ String get ebookSavedOffline => 'Saved for offline reading';++ @override+ String get ebookRemovedOffline => 'Removed from offline';++ @override+ String get ebookOfflineFailed => 'Couldn\'t download the ebook';++ @override+ String get ebookSaveToDevice => 'Save to device';++ @override+ String get ebookSaveToDeviceTitle => 'Save to device?';++ @override+ String get ebookSaveToDeviceBody =>+ 'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.';+@overrideString get readerFormatUnsupported =>'This ebook format can\'t be opened in the reader yet';diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dartindex 8319c076..f602cd23 100644--- a/lib/l10n/app_localizations_el.dart+++ b/lib/l10n/app_localizations_el.dart@@ -6503,6 +6503,31 @@ class AppLocalizationsEl extends AppLocalizations {@overrideString get readEbook => 'Read';+ @override+ String get ebookDownload => 'Download';++ @override+ String get ebookDownloaded => 'Downloaded';++ @override+ String get ebookSavedOffline => 'Saved for offline reading';++ @override+ String get ebookRemovedOffline => 'Removed from offline';++ @override+ String get ebookOfflineFailed => 'Couldn\'t download the ebook';++ @override+ String get ebookSaveToDevice => 'Save to device';++ @override+ String get ebookSaveToDeviceTitle => 'Save to device?';++ @override+ String get ebookSaveToDeviceBody =>+ 'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.';+@overrideString get readerFormatUnsupported =>'This ebook format can\'t be opened in the reader yet';diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dartindex ffd88818..70c35276 100644--- a/lib/l10n/app_localizations_en.dart+++ b/lib/l10n/app_localizations_en.dart@@ -6503,6 +6503,31 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get readEbook => 'Read';+ @override+ String get ebookDownload => 'Download';++ @override+ String get ebookDownloaded => 'Downloaded';++ @override+ String get ebookSavedOffline => 'Saved for offline reading';++ @override+ String get ebookRemovedOffline => 'Removed from offline';++ @override+ String get ebookOfflineFailed => 'Couldn\'t download the ebook';++ @override+ String get ebookSaveToDevice => 'Save to device';++ @override+ String get ebookSaveToDeviceTitle => 'Save to device?';++ @override+ String get ebookSaveToDeviceBody =>+ 'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.';+@overrideString get readerFormatUnsupported =>'This ebook format can\'t be opened in the reader yet';diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dartindex ca667827..e3615700 100644--- a/lib/l10n/app_localizations_es.dart+++ b/lib/l10n/app_localizations_es.dart@@ -6503,6 +6503,31 @@ class AppLocalizationsEs extends AppLocalizations {@overrideString get readEbook => 'Read';+ @override+ String get ebookDownload => 'Download';++ @override+ String get ebookDownloaded => 'Downloaded';++ @override+ String get ebookSavedOffline => 'Saved for offline reading';++ @override+ String get ebookRemovedOffline => 'Removed from offline';++ @override+ String get ebookOfflineFailed => 'Couldn\'t download the ebook';++ @override+ String get ebookSaveToDevice => 'Save to device';++ @override+ String get ebookSaveToDeviceTitle => 'Save to device?';++ @override+ String get ebookSaveToDeviceBody =>+ 'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.';+@overrideString get readerFormatUnsupported =>'This ebook format can\'t be opened in the reader yet';diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dartindex 778c47d5..37d3dd85 100644--- a/lib/l10n/app_localizations_fr.dart+++ b/lib/l10n/app_localizations_fr.dart@@ -6505,6 +6505,31 @@ class AppLocalizationsFr extends AppLocalizations {@overrideString get readEbook => 'Read';+ @override+ String get ebookDownload => 'Download';++ @override+ String get ebookDownloaded => 'Downloaded';++ @override+ String get ebookSavedOffline => 'Saved for offline reading';++ @override+ String get ebookRemovedOffline => 'Removed from offline';++ @override+ String get ebookOfflineFailed => 'Couldn\'t download the ebook';++ @override+ String get ebookSaveToDevice => 'Save to device';++ @override+ String get ebookSaveToDeviceTitle => 'Save to device?';++ @override+ String get ebookSaveToDeviceBody =>+ 'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.';+@overrideString get readerFormatUnsupported =>'This ebook format can\'t be opened in the reader yet';diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dartindex df3e8537..3061e983 100644--- a/lib/l10n/app_localizations_it.dart+++ b/lib/l10n/app_localizations_it.dart@@ -6503,6 +6503,31 @@ class AppLocalizationsIt extends AppLocalizations {@overrideString get readEbook => 'Read';+ @override+ String get ebookDownload => 'Download';++ @override+ String get ebookDownloaded => 'Downloaded';++ @override+ String get ebookSavedOffline => 'Saved for offline reading';++ @override+ String get ebookRemovedOffline => 'Removed from offline';++ @override+ String get ebookOfflineFailed => 'Couldn\'t download the ebook';++ @override+ String get ebookSaveToDevice => 'Save to device';++ @override+ String get ebookSaveToDeviceTitle => 'Save to device?';++ @override+ String get ebookSaveToDeviceBody =>+ 'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.';+@overrideString get readerFormatUnsupported =>'This ebook format can\'t be opened in the reader yet';diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dartindex 931866d2..8a585fab 100644--- a/lib/l10n/app_localizations_ja.dart+++ b/lib/l10n/app_localizations_ja.dart@@ -6503,6 +6503,31 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get readEbook => 'Read';+ @override+ String get ebookDownload => 'Download';++ @override+ String get ebookDownloaded => 'Downloaded';++ @override+ String get ebookSavedOffline => 'Saved for offline reading';++ @override+ String get ebookRemovedOffline => 'Removed from offline';++ @override+ String get ebookOfflineFailed => 'Couldn\'t download the ebook';++ @override+ String get ebookSaveToDevice => 'Save to device';++ @override+ String get ebookSaveToDeviceTitle => 'Save to device?';++ @override+ String get ebookSaveToDeviceBody =>+ 'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.';+@overrideString get readerFormatUnsupported =>'This ebook format can\'t be opened in the reader yet';diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dartindex 783fc577..9d87217e 100644--- a/lib/l10n/app_localizations_no.dart+++ b/lib/l10n/app_localizations_no.dart@@ -6503,6 +6503,31 @@ class AppLocalizationsNo extends AppLocalizations {@overrideString get readEbook => 'Read';+ @override+ String get ebookDownload => 'Download';++ @override+ String get ebookDownloaded => 'Downloaded';++ @override+ String get ebookSavedOffline => 'Saved for offline reading';++ @override+ String get ebookRemovedOffline => 'Removed from offline';++ @override+ String get ebookOfflineFailed => 'Couldn\'t download the ebook';++ @override+ String get ebookSaveToDevice => 'Save to device';++ @override+ String get ebookSaveToDeviceTitle => 'Save to device?';++ @override+ String get ebookSaveToDeviceBody =>+ 'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.';+@overrideString get readerFormatUnsupported =>'This ebook format can\'t be opened in the reader yet';diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dartindex 9b56acdd..02d0f651 100644--- a/lib/l10n/app_localizations_pt.dart+++ b/lib/l10n/app_localizations_pt.dart@@ -6503,6 +6503,31 @@ class AppLocalizationsPt extends AppLocalizations {@overrideString get readEbook => 'Read';+ @override+ String get ebookDownload => 'Download';++ @override+ String get ebookDownloaded => 'Downloaded';++ @override+ String get ebookSavedOffline => 'Saved for offline reading';++ @override+ String get ebookRemovedOffline => 'Removed from offline';++ @override+ String get ebookOfflineFailed => 'Couldn\'t download the ebook';++ @override+ String get ebookSaveToDevice => 'Save to device';++ @override+ String get ebookSaveToDeviceTitle => 'Save to device?';++ @override+ String get ebookSaveToDeviceBody =>+ 'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.';+@overrideString get readerFormatUnsupported =>'This ebook format can\'t be opened in the reader yet';diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dartindex 3a12fd4e..69d460d1 100644--- a/lib/l10n/app_localizations_ro.dart+++ b/lib/l10n/app_localizations_ro.dart@@ -6503,6 +6503,31 @@ class AppLocalizationsRo extends AppLocalizations {@overrideString get readEbook => 'Read';+ @override+ String get ebookDownload => 'Download';++ @override+ String get ebookDownloaded => 'Downloaded';++ @override+ String get ebookSavedOffline => 'Saved for offline reading';++ @override+ String get ebookRemovedOffline => 'Removed from offline';++ @override+ String get ebookOfflineFailed => 'Couldn\'t download the ebook';++ @override+ String get ebookSaveToDevice => 'Save to device';++ @override+ String get ebookSaveToDeviceTitle => 'Save to device?';++ @override+ String get ebookSaveToDeviceBody =>+ 'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.';+@overrideString get readerFormatUnsupported =>'This ebook format can\'t be opened in the reader yet';diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dartindex abf52a86..d154fdb9 100644--- a/lib/l10n/app_localizations_ru.dart+++ b/lib/l10n/app_localizations_ru.dart@@ -6506,6 +6506,31 @@ class AppLocalizationsRu extends AppLocalizations {@overrideString get readEbook => 'Read';+ @override+ String get ebookDownload => 'Download';++ @override+ String get ebookDownloaded => 'Downloaded';++ @override+ String get ebookSavedOffline => 'Saved for offline reading';++ @override+ String get ebookRemovedOffline => 'Removed from offline';++ @override+ String get ebookOfflineFailed => 'Couldn\'t download the ebook';++ @override+ String get ebookSaveToDevice => 'Save to device';++ @override+ String get ebookSaveToDeviceTitle => 'Save to device?';++ @override+ String get ebookSaveToDeviceBody =>+ 'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.';+@overrideString get readerFormatUnsupported =>'This ebook format can\'t be opened in the reader yet';diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dartindex 93a81019..d4220ddf 100644--- a/lib/l10n/app_localizations_zh.dart+++ b/lib/l10n/app_localizations_zh.dart@@ -6426,6 +6426,31 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get readEbook => 'Read';+ @override+ String get ebookDownload => 'Download';++ @override+ String get ebookDownloaded => 'Downloaded';++ @override+ String get ebookSavedOffline => 'Saved for offline reading';++ @override+ String get ebookRemovedOffline => 'Removed from offline';++ @override+ String get ebookOfflineFailed => 'Couldn\'t download the ebook';++ @override+ String get ebookSaveToDevice => 'Save to device';++ @override+ String get ebookSaveToDeviceTitle => 'Save to device?';++ @override+ String get ebookSaveToDeviceBody =>+ 'This saves a copy of the ebook file somewhere on your device (you pick where). It won\'t make the book available offline in the reader - use Download for that.';+@overrideString get readerFormatUnsupported =>'This ebook format can\'t be opened in the reader yet';diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dartindex 86e39590..32ee3690 100644--- a/lib/screens/library_screen.dart+++ b/lib/screens/library_screen.dart@@ -161,6 +161,9 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMibool _isLoadingPage = false;bool _hasMore = true;+ // Tracks the offline state so the grid reloads when it flips (offline shows+ // only downloads; back online shows the full library again).+ bool _wasOffline = false;int _page = 0;int _totalItems = 0;int? _randomSeed;@@ -222,6 +225,7 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi@overridevoid initState() {super.initState();+ _wasOffline = context.read<LibraryProvider>().isOffline;// Reveal driver is fed by NotificationListener at the screen level —// works across multiple per-tab scroll controllers in the IndexedStack// without needing to re-attach on every tab switch.@@ -1652,7 +1656,17 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi// Watch LibraryProvider so this screen rebuilds when the active library// or its data changes; the actual lib object is consumed inside// _buildHeaderSliver via context.watch.- context.watch<LibraryProvider>();+ final libWatch = context.watch<LibraryProvider>();+ // Reload the grid when the offline state flips so it swaps between the full+ // library and the downloads-only offline view.+ if (libWatch.isOffline != _wasOffline) {+ _wasOffline = libWatch.isOffline;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || _isScoped) return;+ setState(() { _items.clear(); _page = 0; _hasMore = true; _isLoadingPage = false; });+ _loadPage();+ });+ }final hasTabs = _tabController != null && !_isInSearchMode;return Scaffold(diff --git a/lib/services/download_service.dart b/lib/services/download_service.dartindex 681e846f..b0e7991f 100644--- a/lib/services/download_service.dart+++ b/lib/services/download_service.dart@@ -12,6 +12,7 @@ import '../l10n/app_localizations.dart';import '../main.dart' show rootNavigatorKey;import 'api_service.dart';import 'audio_player_service.dart';+import 'ebook_cache.dart';import 'offline_source.dart';enum DownloadStatus { none, downloading, downloaded, error }@@ -485,6 +486,49 @@ class DownloadService extends ChangeNotifier {bool isDownloaded(String itemId) =>_downloads[itemId]?.status == DownloadStatus.downloaded;+ /// Registers an ebook-only book as a completed download so it shows in the+ /// offline library and its detail sheet loads offline. There's no audio, so+ /// localPaths is empty - the book opens in the reader, never the player. The+ /// ebook bytes live in the reader's persistent cache (fetchEbookToCache).+ /// Fetches a full copy of the item so the offline sheet has the cover,+ /// description, and ebookFile - not just the title.+ Future<void> registerEbookDownload({+ required ApiService api,+ required String itemId,+ Map<String, dynamic>? item,+ String? libraryId,+ }) async {+ Map<String, dynamic>? fullItem;+ try {+ fullItem = await api.getLibraryItem(itemId);+ } catch (_) {}+ final stored = fullItem ?? item ?? {'id': itemId};+ final media = stored['media'] as Map<String, dynamic>?;+ final metadata = media?['metadata'] as Map<String, dynamic>?;+ final title = metadata?['title'] as String?;+ final author = metadata?['authorName'] as String?;++ final localCoverPath = await _cacheCover(api, itemId, api.getCoverUrl(itemId, width: 800));+ final sessionJson = jsonEncode({+ 'libraryItem': stored,+ 'mediaMetadata': metadata,+ 'duration': 0,+ 'chapters': const <dynamic>[],+ });+ _downloads[itemId] = DownloadInfo(+ itemId: itemId,+ status: DownloadStatus.downloaded,+ localPaths: const [],+ sessionData: sessionJson,+ title: title,+ author: author,+ localCoverPath: localCoverPath,+ libraryId: libraryId ?? stored['libraryId'] as String?,+ );+ await _save();+ notifyListeners();+ }+bool isDownloading(String itemId) =>_downloads[itemId]?.status == DownloadStatus.downloading;@@ -1221,6 +1265,18 @@ class DownloadService extends ChangeNotifier {TaskStatus.canceled,};+ /// Best-effort download of a book's ebook into the persistent reader cache so+ /// it reads offline. Swallows errors - the audio download is what matters.+ Future<void> _cacheEbookForOffline(+ ApiService api, String itemId, Map<String, dynamic> ebookFile, String title) async {+ try {+ await fetchEbookToCache(api, itemId, ebookFile, title);+ debugPrint('[Download] cached ebook for offline: $itemId');+ } catch (e) {+ debugPrint('[Download] ebook offline cache failed for $itemId: $e');+ }+ }+/// Resolve a book/episode to durable per-file download tasks and enqueue them./// Returns once the tasks are handed to `background_downloader`; progress and/// completion are driven asynchronously by [_onTaskUpdate] / [_finalizeSuccess]@@ -1278,6 +1334,15 @@ class DownloadService extends ChangeNotifier {final files = await _resolveDurableFiles(api, apiItemId, episodeId, audioTracks);+ // Pull the companion ebook into the offline cache too, so a downloaded+ // book is fully readable offline. Fire-and-forget - never blocks or fails+ // the audio download.+ final ebookFile = ((sessionData['libraryItem'] as Map<String, dynamic>?)?['media']+ as Map<String, dynamic>?)?['ebookFile'] as Map<String, dynamic>?;+ if (ebookFile != null) {+ unawaited(_cacheEbookForOffline(api, apiItemId, ebookFile, title));+ }+// Per-book destination. Android downloads to internal storage first - for// both the internal default AND SAF custom folders. SAF books are then// moved into the user's chosen folder under "Author/Title" on completion@@ -1910,6 +1975,9 @@ class DownloadService extends ChangeNotifier {debugPrint('[Download] cover cleanup failed: $e');}+ // Drop the offline ebook copy too, if any.+ await deleteCachedEbook(itemId);+_downloads.remove(itemId);await _save();notifyListeners();diff --git a/lib/services/ebook_cache.dart b/lib/services/ebook_cache.dartindex a6c72f3c..9e179963 100644--- a/lib/services/ebook_cache.dart+++ b/lib/services/ebook_cache.dart@@ -3,35 +3,57 @@ import 'package:http/http.dart' as http;import 'package:path_provider/path_provider.dart';import 'api_service.dart';-/// Downloads an Audiobookshelf ebook file to a temp cache and returns it,-/// reusing the cached copy when present. Follows redirects manually so the auth-/// headers survive the hop. Throws with a message on failure.+/// File extension (with leading dot) for an ABS ebookFile, or '' if unknown.+String ebookExtFromFile(Map<String, dynamic> ebookFile) {+ final name = (ebookFile['metadata'] as Map<String, dynamic>?)?['filename'] as String?+ ?? ebookFile['name'] as String?+ ?? '';+ return name.contains('.') ? name.substring(name.lastIndexOf('.')) : '';+}++Future<Directory> _ebookCacheDir() async {+ final base = await getApplicationSupportDirectory();+ final dir = Directory('${base.path}/ebook_cache');+ if (!dir.existsSync()) dir.createSync(recursive: true);+ return dir;+}++/// Persistent cache path for an item's ebook, keyed by itemId so it's stable+/// across sessions. Lives in app support (not temp, not iCloud-backed docs) so+/// once an ebook is here it stays available offline.+Future<File> ebookCacheFileFor(String itemId, Map<String, dynamic> ebookFile) async {+ final dir = await _ebookCacheDir();+ return File('${dir.path}/$itemId${ebookExtFromFile(ebookFile)}');+}++/// True if the item's ebook is already cached on disk (readable offline).+Future<bool> isEbookCached(String itemId, Map<String, dynamic> ebookFile) async {+ final f = await ebookCacheFileFor(itemId, ebookFile);+ return f.existsSync() && await f.length() > 0;+}++/// Returns the cached ebook, downloading it if not already present. The download+/// is atomic (written to a .part file then renamed) so an interrupted transfer+/// never leaves a half-written file that looks complete. Once fetched the ebook+/// stays available offline.Future<File> fetchEbookToCache(ApiService api,String itemId,Map<String, dynamic> ebookFile,String title,) async {+ final cachedFile = await ebookCacheFileFor(itemId, ebookFile);+ if (cachedFile.existsSync() && await cachedFile.length() > 0) return cachedFile;+final ino = ebookFile['ino'] as String?;if (ino == null) throw Exception('No ebook file found');- final ebookName = (ebookFile['metadata'] as Map<String, dynamic>?)?['filename'] as String?- ?? ebookFile['name'] as String?- ?? 'book';- final ext = ebookName.contains('.')- ? ebookName.substring(ebookName.lastIndexOf('.'))- : '';- final safeTitle = title.replaceAll(RegExp(r'[^\w\s-]'), '').trim();-- final cacheDir = await getTemporaryDirectory();- final cachedFile = File('${cacheDir.path}/ereader_$safeTitle$ext');- if (cachedFile.existsSync() && await cachedFile.length() > 0) return cachedFile;-final cleanBase = api.baseUrl.endsWith('/')? api.baseUrl.substring(0, api.baseUrl.length - 1): api.baseUrl;final url = '$cleanBase/api/items/$itemId/file/$ino';+ final partFile = File('${cachedFile.path}.part');final request = http.Request('GET', Uri.parse(url));request.followRedirects = false;api.mediaHeaders.forEach((k, v) => request.headers[k] = v);@@ -54,14 +76,34 @@ Future<File> fetchEbookToCache(}final ct = response.headers['content-type'] ?? '';if (ct.contains('text/html')) throw Exception('Server returned an error page');- final sink = cachedFile.openWrite();+ final sink = partFile.openWrite();try {await response.stream.pipe(sink);} finally {await sink.close();}+ if (cachedFile.existsSync()) await cachedFile.delete();+ await partFile.rename(cachedFile.path);} finally {client.close();+ if (partFile.existsSync()) {+ try { await partFile.delete(); } catch (_) {}+ }}return cachedFile;}++/// Removes any cached ebook for [itemId] (used when a download is removed).+Future<void> deleteCachedEbook(String itemId) async {+ try {+ final dir = await _ebookCacheDir();+ if (!dir.existsSync()) return;+ for (final f in dir.listSync()) {+ if (f is! File) continue;+ final name = f.uri.pathSegments.last;+ if (name == itemId || name.startsWith('$itemId.')) {+ try { await f.delete(); } catch (_) {}+ }+ }+ } catch (_) {}+}diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex a0d104b2..9b06f800 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -25,6 +25,7 @@ import 'card_buttons.dart';import '../services/api_service.dart';import '../services/bookmark_service.dart';import '../services/download_service.dart';+import '../services/ebook_cache.dart';import '../services/progress_sync_service.dart';import '../services/metadata_override_service.dart';import '../services/scoped_prefs.dart';@@ -100,6 +101,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {bool _hasLocalOverride = false;bool _showGoodreads = false;bool _ebookSaved = false;+ bool _ebookOfflineDownloading = false;bool _authorsExpanded = false;bool _narratorsExpanded = false;bool _squareCovers = false;@@ -269,6 +271,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {}void _deriveCoverScheme() {+ try {final url = _coverUrl;if (url == null) {debugPrint('[BookDetail] _deriveCoverScheme skipped (no cover url)');@@ -308,6 +311,9 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {);});});+ } catch (e) {+ debugPrint('[BookDetail] _deriveCoverScheme failed (non-fatal): $e');+ }}String? get _coverUrl {@@ -507,12 +513,12 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {style: FilledButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16))),))else if (isEbookOnly && ebookFile != null)- // Ebook-only but not an EPUB (PDF/comic/mobi) - can't read in-app, so- // the primary action downloads the file instead.+ // Ebook-only but not readable in-app (CBR) - can't open it, so the+ // primary action exports the file to the device instead.SizedBox(height: 52, child: FilledButton.icon(onPressed: () => _saveEbook(context, auth, ebookFile, title),icon: Icon(_ebookSaved ? Icons.download_done_rounded : Icons.save_alt_rounded, size: 24),- label: Text(_ebookSaved ? l.downloadEbookAgain : l.downloadEbook,+ label: Text(l.ebookSaveToDevice,style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.onPrimary)),style: FilledButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16))),))@@ -616,22 +622,60 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {)),if (ebookFile != null && canReadEbook(ebookFile)) ...[const SizedBox(width: 8),- Expanded(child: GestureDetector(- onTap: () => _openEbookReader(context, auth, ebookFile, title),- child: Container(- height: 36,- decoration: BoxDecoration(- color: cs.onSurface.withValues(alpha: 0.06),- borderRadius: BorderRadius.circular(14),- border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),- ),- child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [- Icon(Icons.menu_book_rounded, size: 16, color: cs.onSurfaceVariant),- const SizedBox(width: 6),- Text(l.readEbook, style: TextStyle(color: cs.onSurfaceVariant, fontSize: 12, fontWeight: FontWeight.w500)),- ]),- ),- )),+ // For ebook-only books the big button above is already "Read", so this+ // slot is the offline download (matching the audiobook download+ // button's Saved/green styling). For audiobooks with a companion ebook+ // it stays "Read" - the audio download already pulls the ebook along.+ Expanded(child: isEbookOnly+ ? ListenableBuilder(+ listenable: DownloadService(),+ builder: (_, __) {+ final saved = DownloadService().isDownloaded(widget.itemId);+ final dlGreen = Theme.of(context).brightness == Brightness.dark+ ? Colors.greenAccent : Colors.green.shade700;+ return GestureDetector(+ onTap: _ebookOfflineDownloading+ ? null+ : (saved+ ? () => _removeEbookOffline(context)+ : () => _downloadEbookOffline(context, auth, ebookFile, title)),+ child: Container(+ height: 36,+ decoration: BoxDecoration(+ color: saved ? dlGreen.withValues(alpha: 0.08) : cs.onSurface.withValues(alpha: 0.06),+ borderRadius: BorderRadius.circular(14),+ border: Border.all(color: saved ? dlGreen.withValues(alpha: 0.2) : cs.onSurface.withValues(alpha: 0.08)),+ ),+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [+ if (_ebookOfflineDownloading)+ SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: cs.onSurfaceVariant))+ else+ Icon(saved ? Icons.download_done_rounded : Icons.download_rounded,+ size: 16, color: saved ? dlGreen : cs.onSurfaceVariant),+ const SizedBox(width: 6),+ Text(saved ? l.saved : l.ebookDownload,+ style: TextStyle(color: saved ? dlGreen : cs.onSurfaceVariant, fontSize: 12, fontWeight: FontWeight.w500)),+ ]),+ ),+ );+ },+ )+ : GestureDetector(+ onTap: () => _openEbookReader(context, auth, ebookFile, title),+ child: Container(+ height: 36,+ decoration: BoxDecoration(+ color: cs.onSurface.withValues(alpha: 0.06),+ borderRadius: BorderRadius.circular(14),+ border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),+ ),+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [+ Icon(Icons.menu_book_rounded, size: 16, color: cs.onSurfaceVariant),+ const SizedBox(width: 6),+ Text(l.readEbook, style: TextStyle(color: cs.onSurfaceVariant, fontSize: 12, fontWeight: FontWeight.w500)),+ ]),+ ),+ )),],]),// More button below primary row@@ -891,7 +935,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {}if (ebookFile != null) {add(_ebookSaved ? Icons.download_done_rounded : Icons.save_alt_rounded,- _ebookSaved ? l.downloadEbookAgain : l.downloadEbook, () => _saveEbook(context, auth, ebookFile, title));+ l.ebookSaveToDevice, () => _saveEbook(context, auth, ebookFile, title));}if (ebookFile != null && auth.ereaderDevices.isNotEmpty) {add(Icons.send_to_mobile_rounded, l.sendToEreader, () => _sendToEreader(context, auth));@@ -1486,13 +1530,65 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {openEbookReader(context, itemId: widget.itemId, title: title, ebookFile: ebookFile);}+ /// Caches the ebook for offline reading and registers it as a download so it+ /// shows in the offline library and its detail sheet loads offline. Distinct+ /// from "Save to device", which exports a copy elsewhere.+ Future<void> _downloadEbookOffline(+ BuildContext context, AuthProvider auth, Map<String, dynamic> ebookFile, String title) async {+ if (_ebookOfflineDownloading) return;+ final l = AppLocalizations.of(context)!;+ final api = auth.apiService;+ if (api == null) return;+ setState(() => _ebookOfflineDownloading = true);+ try {+ await fetchEbookToCache(api, widget.itemId, ebookFile, title);+ await DownloadService().registerEbookDownload(+ api: api,+ itemId: widget.itemId,+ item: _item,+ libraryId: _item?['libraryId'] as String?,+ );+ if (mounted) {+ setState(() => _ebookOfflineDownloading = false);+ showOverlayToast(context, l.ebookSavedOffline, icon: Icons.download_done_rounded);+ }+ } catch (_) {+ if (mounted) {+ setState(() => _ebookOfflineDownloading = false);+ showOverlayToast(context, l.ebookOfflineFailed, icon: Icons.error_outline_rounded);+ }+ }+ }++ Future<void> _removeEbookOffline(BuildContext context) async {+ final l = AppLocalizations.of(context)!;+ await DownloadService().deleteDownload(widget.itemId);+ if (mounted) showOverlayToast(context, l.ebookRemovedOffline, icon: Icons.delete_outline_rounded);+ }+bool _ebookSaving = false;Future<void> _saveEbook(BuildContext context, AuthProvider auth, Map<String, dynamic> ebookFile, String bookTitle) async {if (_ebookSaving) return;- setState(() => _ebookSaving = true);final l = AppLocalizations.of(context)!;+ // Clarify this exports a copy elsewhere on the device and is NOT the same as+ // the offline Download, which is a common point of confusion.+ final confirmed = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ title: Text(l.ebookSaveToDeviceTitle),+ content: Text(l.ebookSaveToDeviceBody),+ actions: [+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),+ FilledButton(onPressed: () => Navigator.pop(ctx, true), child: Text(l.ebookSaveToDevice)),+ ],+ ),+ );+ if (confirmed != true) return;++ setState(() => _ebookSaving = true);+try {final api = auth.apiService;if (api == null) return;diff --git a/lib/widgets/ebook_reader_view.dart b/lib/widgets/ebook_reader_view.dartindex 5c7824d1..bce49f32 100644--- a/lib/widgets/ebook_reader_view.dart+++ b/lib/widgets/ebook_reader_view.dart@@ -4,14 +4,13 @@ import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_epub_viewer/flutter_epub_viewer.dart';import 'package:url_launcher/url_launcher.dart';-import 'package:path_provider/path_provider.dart';-import 'package:http/http.dart' as http;import 'package:provider/provider.dart';import '../l10n/app_localizations.dart';import '../providers/auth_provider.dart';import '../providers/library_provider.dart';import '../services/audio_player_service.dart';import '../services/ebook_annotation_service.dart';+import '../services/ebook_cache.dart';import '../services/reader_font_service.dart';import '../services/scoped_prefs.dart';import 'overlay_toast.dart';@@ -504,77 +503,11 @@ class EbookReaderViewState extends State<EbookReaderView> {setState(() { _error = 'Not connected to server'; _loading = false; });return;}-- final ino = widget.ebookFile['ino'] as String?;- if (ino == null) {- setState(() { _error = 'No ebook file found'; _loading = false; });- return;- }-- final ebookName = widget.ebookFile['metadata']?['filename'] as String?- ?? widget.ebookFile['name'] as String?- ?? 'book.epub';- final ext = ebookName.contains('.')- ? ebookName.substring(ebookName.lastIndexOf('.'))- : '.epub';- final safeTitle = widget.title.replaceAll(RegExp(r'[^\w\s-]'), '').trim();-- final cacheDir = await getTemporaryDirectory();- final cachedFile = File('${cacheDir.path}/ereader_$safeTitle$ext');-- 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 request = http.Request('GET', Uri.parse(url));- request.followRedirects = false;- api.mediaHeaders.forEach((k, v) => request.headers[k] = v);- final client = http.Client();- try {- var response = await client.send(request);-- // Follow redirects preserving auth headers- var redirects = 0;- while ([301, 302, 303, 307, 308].contains(response.statusCode) && redirects < 5) {- final location = response.headers['location'];- if (location == null) break;- final redirectUrl = Uri.parse(url).resolve(location);- final rReq = http.Request('GET', redirectUrl);- api.mediaHeaders.forEach((k, v) => rReq.headers[k] = v);- rReq.followRedirects = false;- response = await client.send(rReq);- redirects++;- }-- if (response.statusCode != 200) {- setState(() { _error = 'Failed to download ebook (${response.statusCode})'; _loading = false; });- return;- }-- final ct = response.headers['content-type'] ?? '';- if (ct.contains('text/html')) {- setState(() { _error = 'Server returned an error page'; _loading = false; });- return;- }-- final sink = cachedFile.openWrite();- try {- await response.stream.pipe(sink);- } finally {- await sink.close();- }- } finally {- client.close();- }- }-+ // Shared persistent cache - reuses a downloaded/previously-opened copy so+ // the book reads offline.+ final file = await fetchEbookToCache(api, widget.itemId, widget.ebookFile, widget.title);if (mounted) {- setState(() {- _cachedFile = cachedFile;- _loading = false;- });+ setState(() { _cachedFile = file; _loading = false; });}} catch (e) {debugPrint('[EbookReader] Error: $e');