A cross platform Audiobookshelf client for Android and iOS
Dart
Download the companion ebook with the audiobook so Read works offline
Barnabasc85891a00034
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dartindex 605b73ea..9065681b 100644--- a/lib/providers/_lp_core.dart+++ b/lib/providers/_lp_core.dart@@ -1070,6 +1070,10 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {if (_rollingDownloadSeries.isNotEmpty) _catchUpRollingDownloads();unawaited(_catchUpQueueAutoDownloads());(this as LibraryProvider).catchUpSubscribedPodcasts();+ final ebookApi = _api;+ if (ebookApi != null) {+ unawaited(DownloadService().catchUpEbookCaches(ebookApi));+ }} else {debugPrint('[Library] Connectivity changed but server unreachable — starting ping timer');if (_networkOffline) {diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex af84406f..b37a906f 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -327,6 +327,10 @@ class LibraryProvider extends ChangeNotifier_catchUpRollingDownloads();unawaited(_catchUpQueueAutoDownloads());catchUpSubscribedPodcasts();+ final ebookApi = _api;+ if (ebookApi != null) {+ unawaited(DownloadService().catchUpEbookCaches(ebookApi));+ }}Future<void> _restoreCachedLibraries() async {diff --git a/lib/services/download_service.dart b/lib/services/download_service.dartindex 2d6d6659..c32e8eda 100644--- a/lib/services/download_service.dart+++ b/lib/services/download_service.dart@@ -409,6 +409,7 @@ class DownloadService extends ChangeNotifier {/// Calculate total size of all downloaded files.Future<int> get totalDownloadSize async {+ await hydrateEbookCacheDir();int total = 0;for (final info in _downloads.values) {if (info.status == DownloadStatus.downloaded) {@@ -421,6 +422,7 @@ class DownloadService extends ChangeNotifier {}} catch (_) {}}+ total += cachedEbookBytesSync(info.itemId);}}return total;@@ -440,7 +442,7 @@ class DownloadService extends ChangeNotifier {}} catch (_) {}}- return total;+ return total + cachedEbookBytesSync(itemId);}static const _storageChannel = MethodChannel('com.absorb.storage');@@ -1414,13 +1416,34 @@ class DownloadService extends ChangeNotifier {Future<void> _cacheEbookForOffline(ApiService api, String itemId, Map<String, dynamic> ebookFile, String title) async {try {- await fetchEbookToCache(api, itemId, ebookFile, title);+ final f = await fetchEbookToCache(api, itemId, ebookFile, title);+ await _excludeFromBackup(f.path);debugPrint('[Download] cached ebook for offline: $itemId');} catch (e) {debugPrint('[Download] ebook offline cache failed for $itemId: $e');}}+ /// Re-fetch any companion ebooks whose fire-and-forget download never landed+ /// (killed mid-transfer, offline at the time). Called when the app comes up+ /// with a working connection; cheap when everything is already cached.+ Future<void> catchUpEbookCaches(ApiService api) async {+ for (final info in _downloads.values.toList()) {+ if (info.status != DownloadStatus.downloaded) continue;+ if (info.sessionData == null) continue;+ try {+ final session = jsonDecode(info.sessionData!) as Map<String, dynamic>;+ final ebookFile =+ resolveEbookFile(session['libraryItem'] as Map<String, dynamic>?);+ if (ebookFile == null) continue;+ final apiItemId = session['libraryItemId'] as String? ?? info.itemId;+ if (await isEbookCached(apiItemId, ebookFile)) continue;+ await _cacheEbookForOffline(+ api, apiItemId, ebookFile, info.title ?? apiItemId);+ } catch (_) {}+ }+ }+/// 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]@@ -1509,8 +1532,27 @@ class DownloadService extends ChangeNotifier {final localCoverPath = await _cacheCover(api, itemId, coverUrl);- // Strip the bulky libraryItem before persisting the session for offline use.- final slimSession = Map<String, dynamic>.from(sessionData)..remove('libraryItem');+ // Keep a trimmed libraryItem in the persisted session: metadata, chapters+ // and the ebook info survive for offline Read, while the bulky episode+ // and audio file lists are dropped (mirrors _stripLibraryItem).+ // libraryFiles shrinks to just the resolved ebook entry, which covers+ // audiobooks-only libraries where every ebook is supplementary and+ // media.ebookFile is never set.+ final slimSession = Map<String, dynamic>.from(sessionData);+ final fullItem = sessionData['libraryItem'] as Map<String, dynamic>?;+ if (fullItem == null) {+ slimSession.remove('libraryItem');+ } else {+ final slimItem = Map<String, dynamic>.from(fullItem);+ final media = slimItem['media'] as Map<String, dynamic>?;+ if (media != null) {+ slimItem['media'] = Map<String, dynamic>.from(media)+ ..remove('episodes')+ ..remove('audioFiles');+ }+ slimItem['libraryFiles'] = [if (ebookFile != null) ebookFile];+ slimSession['libraryItem'] = slimItem;+ }final sessionId = sessionData['id'] as String?;if (sessionId != null) unawaited(api.closePlaybackSession(sessionId));@@ -2389,6 +2431,10 @@ class DownloadService extends ChangeNotifier {_activeDownloadIds.remove(itemId);}+ // Drop a companion ebook the fire-and-forget fetch may have already+ // landed, so a cancelled download doesn't orphan it.+ unawaited(deleteCachedEbook(itemId));+// Instant UI feedback (cleanup paths also notify)._downloads.remove(itemId);notifyListeners();diff --git a/lib/services/ebook_cache.dart b/lib/services/ebook_cache.dartindex c7569473..5b52de87 100644--- a/lib/services/ebook_cache.dart+++ b/lib/services/ebook_cache.dart@@ -49,13 +49,60 @@ Map<String, dynamic>? resolveEbookFile(Map<String, dynamic>? item) {return firstReadable ?? firstEbook;}+Directory? _ebookCacheDirHandle;+Future<Directory> _ebookCacheDir() async {final base = await getApplicationSupportDirectory();final dir = Directory('${base.path}/ebook_cache');if (!dir.existsSync()) dir.createSync(recursive: true);+ _ebookCacheDirHandle = dir;return dir;}+/// Warms the synchronous directory handle so [cachedEbookBytesSync] can see+/// cached ebooks from sync code (e.g. download size accounting).+Future<void> hydrateEbookCacheDir() => _ebookCacheDir();++/// Size in bytes of the cached ebook for [itemId], or 0 when there is none or+/// the directory handle hasn't been warmed yet.+int cachedEbookBytesSync(String itemId) {+ final dir = _ebookCacheDirHandle;+ if (dir == null || !dir.existsSync()) return 0;+ try {+ for (final f in dir.listSync()) {+ if (f is File && f.uri.pathSegments.last.startsWith('$itemId.')) {+ return f.lengthSync();+ }+ }+ } catch (_) {}+ return 0;+}++/// Synthesizes an ebookFile map from a cached file on disk, so a downloaded+/// book can open its ebook offline even when no ebook metadata survived (old+/// downloads persisted before the trimmed libraryItem was kept). The format+/// comes from the cached file's extension, which [ebookCacheFileFor] derived+/// from the real ebookFile at download time, so the reader routing (EPUB vs+/// PDF vs foliate) stays correct. Returns null when nothing is cached.+Future<Map<String, dynamic>?> cachedEbookFileFor(String itemId) async {+ try {+ final dir = await _ebookCacheDir();+ for (final f in dir.listSync()) {+ if (f is! File) continue;+ final name = f.uri.pathSegments.last;+ if (!name.startsWith('$itemId.')) continue;+ if (await f.length() <= 0) continue;+ final ext = name.substring(name.lastIndexOf('.') + 1).toLowerCase();+ if (!allEbookFormats.contains(ext)) continue;+ return {+ 'ebookFormat': ext,+ 'metadata': {'filename': name},+ };+ }+ } catch (_) {}+ return null;+}+/// 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.@@ -92,9 +139,13 @@ Future<File> fetchEbookToCache(final cleanBase = api.baseUrl.endsWith('/')? api.baseUrl.substring(0, api.baseUrl.length - 1): api.baseUrl;- final url = '$cleanBase/api/items/$itemId/file/$ino';+ // Auth travels both ways: the Authorization header (re-attached across the+ // manual redirect hops below) plus `?token=` in the URL, because some+ // reverse proxies strip the header - the same reason audio file downloads+ // use the token form (see ApiService.buildFileUrl).+ final url = '$cleanBase/api/items/$itemId/file/$ino?token=${api.token}';- debugPrint('[EbookCache] downloading item=$itemId url=$url');+ debugPrint('[EbookCache] downloading item=$itemId path=/api/items/$itemId/file/$ino');final startedAt = DateTime.now();final partFile = File('${cachedFile.path}.part');final request = http.Request('GET', Uri.parse(url));diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dartindex ee5f2989..2225d00a 100644--- a/lib/widgets/absorbing_card.dart+++ b/lib/widgets/absorbing_card.dart@@ -1138,6 +1138,11 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClivoid _openEbookReader() async {var ebookFile = _ebookFile;+ // A downloaded book's ebook may already sit in the reader cache - check+ // that before any network retry, so offline Read opens instantly instead+ // of waiting out a timeout. The reader opens from this same cached file+ // either way.+ ebookFile ??= await cachedEbookFileFor(_itemId);if (ebookFile == null) {// The initState fetch is one-shot and can fail silently (network blip),// so give it another chance before declaring there's no ebook.@@ -1146,7 +1151,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli}if (!mounted) return;if (ebookFile == null) {- showOverlayToast(context, 'No ebook file for this book', icon: Icons.menu_book_outlined);+ showOverlayToast(context, AppLocalizations.of(context)!.noEbookFileFound, icon: Icons.menu_book_outlined);return;}openEbookReader(context, itemId: _itemId, title: _title, ebookFile: ebookFile);diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex 62a20da8..6284baff 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -201,6 +201,10 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {bool _isUpdatingProgressDate = false;bool _speedAdjustedTime = true;double _savedSpeed = 1.0;+ // Ebook synthesized from the offline reader cache, for downloads whose+ // persisted metadata predates the trimmed-libraryItem fix. Read-only+ // surfaces fall back to it; Save/Send still need the server's file entry.+ Map<String, dynamic>? _cachedEbookFallback;ColorScheme? _rawCoverScheme;String? _coverSchemeUrl; // URL the current scheme was derived from@@ -245,6 +249,9 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {setState(() => _ebookSaved = true);}});+ cachedEbookFileFor(widget.itemId).then((f) {+ if (mounted && f != null) setState(() => _cachedEbookFallback = f);+ });}@override@@ -542,7 +549,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {final progressData = lib.getProgressData(widget.itemId);final isFinished = progressData?['isFinished'] == true;final currentTime = (progressData?['currentTime'] as num?)?.toDouble() ?? 0;- final ebookFile = resolveEbookFile(_item);+ final ebookFile = resolveEbookFile(_item) ?? _cachedEbookFallback;final isEbookOnly = PlayerSettings.isEbookOnly(_item!);// Preview only makes sense before the book has been started. The 60s@@ -999,7 +1006,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {final title = metadata['title'] as String? ?? l.unknown;final authorName = metadata['authorName'] as String? ?? '';final duration = (media['duration'] as num?)?.toDouble() ?? 0;- final ebookFile = resolveEbookFile(_item);+ final ebookFile = resolveEbookFile(_item) ?? _cachedEbookFallback;final isEbookOnly = PlayerSettings.isEbookOnly(_item!);final lib = context.watch<LibraryProvider>();@@ -1136,11 +1143,14 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {if (ebookFile != null && canReadEbook(ebookFile)) {add(Icons.menu_book_rounded, l.readEbook, () => _openEbookReader(context, auth, ebookFile, title));}- if (ebookFile != null) {+ // Save/Send push the file elsewhere, which needs the server's own file+ // entry (with ino) - the cache-synthesized fallback can't serve them.+ final serverEbookFile = resolveEbookFile(_item);+ if (serverEbookFile != null) {add(_ebookSaved ? Icons.download_done_rounded : Icons.save_alt_rounded,- l.ebookSaveToDevice, () => _saveEbook(context, auth, ebookFile, title));+ l.ebookSaveToDevice, () => _saveEbook(context, auth, serverEbookFile, title));}- if (ebookFile != null && auth.ereaderDevices.isNotEmpty) {+ if (serverEbookFile != null && auth.ereaderDevices.isNotEmpty) {add(Icons.send_to_mobile_rounded, l.sendToEreader, () => _sendToEreader(context, auth));}if (progress > 0 || isFinished) {diff --git a/lib/widgets/expanded_card.dart b/lib/widgets/expanded_card.dartindex a17956d0..d1c155b2 100644--- a/lib/widgets/expanded_card.dart+++ b/lib/widgets/expanded_card.dart@@ -1184,6 +1184,11 @@ class _ExpandedCardState extends State<ExpandedCard> {void _openReader() async {var ef = _ebookFile;+ // A downloaded book's ebook may already sit in the reader cache - check+ // that before any network retry, so offline Read opens instantly instead+ // of waiting out a timeout. The reader opens from this same cached file+ // either way.+ ef ??= await cachedEbookFileFor(_itemId);if (ef == null) {// The initState fetch is one-shot and can fail silently (network blip),// so give it another chance before declaring there's no ebook.@@ -1192,7 +1197,7 @@ class _ExpandedCardState extends State<ExpandedCard> {}if (!mounted) return;if (ef == null) {- showOverlayToast(context, 'No ebook file for this book', icon: Icons.menu_book_outlined);+ showOverlayToast(context, AppLocalizations.of(context)!.noEbookFileFound, icon: Icons.menu_book_outlined);return;}openEbookReader(context, itemId: _itemId, title: _title, ebookFile: ef);