Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Keep an ebook you have opened on the phone after its audio download is gone, and list it offline and under Downloads

Barnabas853cd8cefe3b
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index 5ce3b16e..f2f4f94a 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -329,6 +329,7 @@
"downloadsDownloading": "Downloading",
"downloadsQueued": "Queued",
"downloadsCompleted": "Completed",
+ "downloadsEbooks": "Ebooks",
"downloadsWaiting": "Waiting...",
"downloadsCancel": "Cancel",
"downloadsDelete": "Delete",
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index 0fe45e35..3abfbb51 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -1456,6 +1456,12 @@ abstract class AppLocalizations {
/// **'Completed'**
String get downloadsCompleted;
+ /// No description provided for @downloadsEbooks.
+ ///
+ /// In en, this message translates to:
+ /// **'Ebooks'**
+ String get downloadsEbooks;
+
/// No description provided for @downloadsWaiting.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index 69bb53aa..83a9f0c6 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -744,6 +744,9 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get downloadsCompleted => 'Abgeschlossen';
+ @override
+ String get downloadsEbooks => 'Ebooks';
+
@override
String get downloadsWaiting => 'Warten...';
diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dart
index f8fd4b5e..d223272b 100644
--- a/lib/l10n/app_localizations_el.dart
+++ b/lib/l10n/app_localizations_el.dart
@@ -737,6 +737,9 @@ class AppLocalizationsEl extends AppLocalizations {
@override
String get downloadsCompleted => 'Completed';
+ @override
+ String get downloadsEbooks => 'Ebooks';
+
@override
String get downloadsWaiting => 'Waiting...';
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index 4b2b1378..0a22ad17 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -737,6 +737,9 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get downloadsCompleted => 'Completed';
+ @override
+ String get downloadsEbooks => 'Ebooks';
+
@override
String get downloadsWaiting => 'Waiting...';
diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart
index 112cc44b..0d43876b 100644
--- a/lib/l10n/app_localizations_es.dart
+++ b/lib/l10n/app_localizations_es.dart
@@ -739,6 +739,9 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get downloadsCompleted => 'Completed';
+ @override
+ String get downloadsEbooks => 'Ebooks';
+
@override
String get downloadsWaiting => 'Waiting...';
diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart
index 3037cdc6..d7a32f67 100644
--- a/lib/l10n/app_localizations_fr.dart
+++ b/lib/l10n/app_localizations_fr.dart
@@ -745,6 +745,9 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get downloadsCompleted => 'Terminé';
+ @override
+ String get downloadsEbooks => 'Ebooks';
+
@override
String get downloadsWaiting => 'En attente...';
diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart
index 7c26c95e..03c822ea 100644
--- a/lib/l10n/app_localizations_it.dart
+++ b/lib/l10n/app_localizations_it.dart
@@ -737,6 +737,9 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get downloadsCompleted => 'Completed';
+ @override
+ String get downloadsEbooks => 'Ebooks';
+
@override
String get downloadsWaiting => 'Waiting...';
diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart
index df187ac8..9210015a 100644
--- a/lib/l10n/app_localizations_ja.dart
+++ b/lib/l10n/app_localizations_ja.dart
@@ -737,6 +737,9 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get downloadsCompleted => 'Completed';
+ @override
+ String get downloadsEbooks => 'Ebooks';
+
@override
String get downloadsWaiting => 'Waiting...';
diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dart
index 9908a9d6..4adc3ab4 100644
--- a/lib/l10n/app_localizations_no.dart
+++ b/lib/l10n/app_localizations_no.dart
@@ -737,6 +737,9 @@ class AppLocalizationsNo extends AppLocalizations {
@override
String get downloadsCompleted => 'Completed';
+ @override
+ String get downloadsEbooks => 'Ebooks';
+
@override
String get downloadsWaiting => 'Waiting...';
diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart
index 189f0575..e4356f5f 100644
--- a/lib/l10n/app_localizations_pt.dart
+++ b/lib/l10n/app_localizations_pt.dart
@@ -737,6 +737,9 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get downloadsCompleted => 'Completed';
+ @override
+ String get downloadsEbooks => 'Ebooks';
+
@override
String get downloadsWaiting => 'Waiting...';
diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dart
index d7702aeb..d01674ca 100644
--- a/lib/l10n/app_localizations_ro.dart
+++ b/lib/l10n/app_localizations_ro.dart
@@ -737,6 +737,9 @@ class AppLocalizationsRo extends AppLocalizations {
@override
String get downloadsCompleted => 'Completed';
+ @override
+ String get downloadsEbooks => 'Ebooks';
+
@override
String get downloadsWaiting => 'Waiting...';
diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart
index 28f5e970..0b760248 100644
--- a/lib/l10n/app_localizations_ru.dart
+++ b/lib/l10n/app_localizations_ru.dart
@@ -738,6 +738,9 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get downloadsCompleted => 'Завершено';
+ @override
+ String get downloadsEbooks => 'Ebooks';
+
@override
String get downloadsWaiting => 'Подождите...';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index 7877e1b2..4ad1c0ef 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -727,6 +727,9 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get downloadsCompleted => '已完成';
+ @override
+ String get downloadsEbooks => 'Ebooks';
+
@override
String get downloadsWaiting => '等待中...';
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index 118fcfd7..50fa00d4 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -459,10 +459,23 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
}
return (dl.itemId.length > 36) == isPodcast;
}).toList();
+ final downloadedIds = downloads.map((d) => d.itemId).toSet();
+ final keptEbooks = isPodcast
+ ? const <DownloadInfo>[]
+ : DownloadService().keptEbooks.where((k) {
+ if (downloadedIds.contains(k.itemId)) return false;
+ final libraryId = k.libraryId;
+ if (libraryId != null &&
+ libraryId.isNotEmpty &&
+ _selectedLibraryId != null) {
+ return libraryId == _selectedLibraryId;
+ }
+ return true;
+ }).toList();
debugPrint(
'[Library] Building offline sections: ${downloads.length}/${allDownloads.length} downloads (${isPodcast ? "podcast" : "book"}) '
- 'library=$_selectedLibraryId of ${_libraries.length}');
- if (downloads.isEmpty) {
+ '+${keptEbooks.length} kept ebooks library=$_selectedLibraryId of ${_libraries.length}');
+ if (downloads.isEmpty && keptEbooks.isEmpty) {
_personalizedSections = [];
_errorMessage = null;
_isLoading = false;
@@ -476,6 +489,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
double duration = 0;
List<dynamic> chapters = [];
String? episodeTitle;
+ Map<String, dynamic>? ebookFile;
if (dl.sessionData != null) {
try {
final session = jsonDecode(dl.sessionData!) as Map<String, dynamic>;
@@ -483,6 +497,8 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
chapters = session['chapters'] as List<dynamic>? ?? [];
episodeTitle = session['episodeTitle'] as String? ??
session['displayTitle'] as String?;
+ ebookFile = resolveEbookFile(
+ session['libraryItem'] as Map<String, dynamic>?);
} catch (_) {}
}
@@ -519,6 +535,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
},
'duration': duration,
'chapters': chapters,
+ if (ebookFile != null) 'ebookFile': ebookFile,
},
};
}
@@ -534,6 +551,27 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
if (progress > 0 && !isFinished) continueEntities.add(entity);
downloadedEntities.add(entity);
}
+ for (final kept in keptEbooks) {
+ Map<String, dynamic>? item;
+ try {
+ item = (jsonDecode(kept.sessionData ?? '{}')
+ as Map<String, dynamic>)['libraryItem'] as Map<String, dynamic>?;
+ } catch (_) {}
+ final ebookFile = resolveEbookFile(item);
+ downloadedEntities.add({
+ 'id': kept.itemId,
+ if (kept.libraryId != null) 'libraryId': kept.libraryId,
+ 'media': {
+ 'metadata': {
+ 'title': kept.title ?? 'Unknown Title',
+ 'authorName': kept.author ?? '',
+ },
+ 'duration': 0,
+ 'chapters': const <dynamic>[],
+ if (ebookFile != null) 'ebookFile': ebookFile,
+ },
+ });
+ }
_personalizedSections = [
if (continueEntities.isNotEmpty)
@@ -583,6 +621,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
double duration = 0;
List<dynamic> chapters = [];
String? episodeTitle;
+ Map<String, dynamic>? ebookFile;
if (dl.sessionData != null) {
try {
final session = jsonDecode(dl.sessionData!) as Map<String, dynamic>;
@@ -590,6 +629,8 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
chapters = session['chapters'] as List<dynamic>? ?? [];
episodeTitle = session['episodeTitle'] as String? ??
session['displayTitle'] as String?;
+ ebookFile = resolveEbookFile(
+ session['libraryItem'] as Map<String, dynamic>?);
} catch (_) {}
}
@@ -625,6 +666,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
},
'duration': duration,
'chapters': chapters,
+ if (ebookFile != null) 'ebookFile': ebookFile,
},
});
}
diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dart
index 77f2423a..1469f635 100644
--- a/lib/providers/_lp_state.dart
+++ b/lib/providers/_lp_state.dart
@@ -398,6 +398,8 @@ mixin _StateMixin on ChangeNotifier {
if (dl.localCoverPath != null) {
return dl.localCoverPath;
}
+ final kept = DownloadService().keptEbook(itemId);
+ if (kept?.localCoverPath != null) return kept!.localCoverPath;
if (dl.status == DownloadStatus.none) {
final match = DownloadService()
diff --git a/lib/screens/downloads_screen.dart b/lib/screens/downloads_screen.dart
index 98c61409..dd8844df 100644
--- a/lib/screens/downloads_screen.dart
+++ b/lib/screens/downloads_screen.dart
@@ -7,6 +7,8 @@ import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
import '../services/download_service.dart';
+import '../services/ebook_cache.dart';
+import '../widgets/ebook_router.dart';
import '../services/signed_out_playback.dart';
import '../services/wording.dart';
import '../widgets/absorb_page_header.dart';
@@ -173,6 +175,51 @@ class _DownloadsScreenState extends State<DownloadsScreen> {
}
}
+ Future<void> _openEbook(DownloadInfo info) async {
+ final l = AppLocalizations.of(context)!;
+ final ebookFile = await cachedEbookFileFor(info.itemId);
+ if (!mounted) return;
+ if (ebookFile == null) {
+ showOverlayToast(context, l.findInEbookNoEbook,
+ icon: Icons.menu_book_outlined);
+ return;
+ }
+ await openEbookReader(
+ context,
+ itemId: info.itemId,
+ title: info.title ?? '',
+ ebookFile: ebookFile,
+ );
+ }
+
+ Future<void> _deleteEbook(DownloadInfo info) async {
+ final l = AppLocalizations.of(context)!;
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ icon: const Icon(Icons.delete_outline_rounded),
+ title: Text(l.downloadsDeleteCount(1)),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(ctx, false),
+ child: Text(l.cancel),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(ctx, true),
+ child: Text(l.delete),
+ ),
+ ],
+ ),
+ );
+ if (confirmed != true || !mounted) return;
+ await DownloadService().deleteKeptEbook(info.itemId);
+ await _load();
+ if (mounted) {
+ showOverlayToast(context, l.downloadsRemovedTitle(info.title ?? ''),
+ icon: Icons.delete_outline_rounded);
+ }
+ }
+
/// Plays straight from the download record, so it works offline and from
/// any library - the one way to reach a downloaded podcast when the app
/// started offline stuck in a book library.
@@ -328,7 +375,14 @@ class _DownloadsScreenState extends State<DownloadsScreen> {
final active = filterByLibrary(ds.activeDownloads);
final queued = filterByLibrary(ds.queuedDownloads);
final completed = filterByLibrary(ds.downloadedItems);
- final hasAny = active.isNotEmpty || queued.isNotEmpty || completed.isNotEmpty;
+ final downloadedIds = completed.map((d) => d.itemId).toSet();
+ final ebooks = filterByLibrary(ds.keptEbooks)
+ .where((e) => !downloadedIds.contains(e.itemId))
+ .toList();
+ final hasAny = active.isNotEmpty ||
+ queued.isNotEmpty ||
+ completed.isNotEmpty ||
+ ebooks.isNotEmpty;
if (!hasAny) {
return Center(
@@ -414,6 +468,33 @@ class _DownloadsScreenState extends State<DownloadsScreen> {
mediaHeaders: context.read<LibraryProvider>().mediaHeaders,
),
],
+ // Ebooks kept from the reader, no audio on the phone
+ if (ebooks.isNotEmpty) ...[
+ Padding(
+ padding: const EdgeInsets.only(left: 4, top: 4, bottom: 8),
+ child: Text(l.downloadsEbooks,
+ style: tt.labelMedium?.copyWith(
+ color: cs.onSurfaceVariant,
+ fontWeight: FontWeight.w600)),
+ ),
+ for (final info in ebooks)
+ _DownloadCard(
+ info: info,
+ fileSize: cachedEbookBytesSync(info.itemId),
+ cs: cs,
+ tt: tt,
+ selecting: false,
+ isSelected: false,
+ onToggle: () {},
+ onPlay: () => _openEbook(info),
+ onLongPress: () {},
+ onDelete: () => _deleteEbook(info),
+ formatBytes: _formatBytes,
+ mediaHeaders: context.read<LibraryProvider>().mediaHeaders,
+ playIcon: Icons.menu_book_rounded,
+ playTooltip: l.readEbook,
+ ),
+ ],
],
);
},
@@ -479,6 +560,8 @@ class _DownloadCard extends StatelessWidget {
final VoidCallback onDelete;
final String Function(int) formatBytes;
final Map<String, String> mediaHeaders;
+ final IconData playIcon;
+ final String? playTooltip;
const _DownloadCard({
required this.info,
@@ -493,6 +576,8 @@ class _DownloadCard extends StatelessWidget {
required this.onDelete,
required this.formatBytes,
required this.mediaHeaders,
+ this.playIcon = Icons.play_circle_outline_rounded,
+ this.playTooltip,
});
@override
@@ -575,9 +660,8 @@ class _DownloadCard extends StatelessWidget {
),
if (!selecting)
IconButton(
- icon: Icon(Icons.play_circle_outline_rounded,
- color: cs.primary, size: 26),
- tooltip: Wording.of(context).absorb,
+ icon: Icon(playIcon, color: cs.primary, size: 26),
+ tooltip: playTooltip ?? Wording.of(context).absorb,
onPressed: onPlay,
),
if (!selecting)
diff --git a/lib/services/download_service.dart b/lib/services/download_service.dart
index b2b081a4..beb4d653 100644
--- a/lib/services/download_service.dart
+++ b/lib/services/download_service.dart
@@ -537,6 +537,72 @@ class DownloadService extends ChangeNotifier {
DownloadInfo getInfo(String itemId) =>
_downloads[itemId] ?? DownloadInfo(itemId: itemId);
+ // Books whose ebook was opened in the reader. The cached copy stays listed
+ // and kept when there is no audio download to carry it. Never a download
+ // record: the player must not think the audio is on the phone.
+ final Map<String, DownloadInfo> _keptEbooks = {};
+
+ List<DownloadInfo> get keptEbooks => _keptEbooks.values.toList();
+
+ DownloadInfo? keptEbook(String itemId) => _keptEbooks[itemId];
+
+ Future<void> keepEbook({
+ required ApiService api,
+ required String itemId,
+ Map<String, dynamic>? item,
+ }) async {
+ if (_keptEbooks.containsKey(itemId)) return;
+ Map<String, dynamic>? full;
+ try {
+ full = await api.getLibraryItem(itemId);
+ } catch (_) {}
+ final stored = full ?? item;
+ if (stored == null) return;
+ final media = stored['media'] as Map<String, dynamic>?;
+ final metadata = media?['metadata'] as Map<String, dynamic>?;
+ String? coverPath;
+ try {
+ final resp = await http
+ .get(Uri.parse(_hiResCoverUrl(api.getCoverUrl(itemId, width: 800))),
+ headers: api.mediaHeaders)
+ .timeout(const Duration(seconds: 10));
+ if (resp.statusCode == 200 && resp.bodyBytes.isNotEmpty) {
+ final f = await ebookCoverCacheFile(itemId);
+ await f.writeAsBytes(resp.bodyBytes);
+ coverPath = f.path;
+ }
+ } catch (_) {}
+ _keptEbooks[itemId] = DownloadInfo(
+ itemId: itemId,
+ status: DownloadStatus.downloaded,
+ sessionData: jsonEncode({
+ 'libraryItem': stored,
+ 'mediaMetadata': metadata,
+ 'duration': 0,
+ 'chapters': const <dynamic>[],
+ }),
+ title: metadata?['title'] as String?,
+ author: metadata?['authorName'] as String?,
+ localCoverPath: coverPath,
+ libraryId: stored['libraryId'] as String?,
+ );
+ await _save();
+ notifyListeners();
+ debugPrint('[Download] ebook kept for offline: $itemId');
+ }
+
+ Future<void> deleteKeptEbook(String itemId) async {
+ if (_keptEbooks.remove(itemId) == null) return;
+ // A downloaded audiobook still reads from the same cached file.
+ if (_downloads.containsKey(itemId)) {
+ await deleteCachedEbookCover(itemId);
+ } else {
+ await deleteCachedEbook(itemId);
+ }
+ await _save();
+ notifyListeners();
+ }
+
bool isDownloaded(String itemId) =>
_downloads[itemId]?.status == DownloadStatus.downloaded;
@@ -650,6 +716,18 @@ class DownloadService extends ChangeNotifier {
if (prefs.getString('custom_download_path') != null) {
await prefs.remove('custom_download_path');
}
+ final keptJson = prefs.getString('kept_ebooks');
+ if (keptJson != null) {
+ try {
+ final map = jsonDecode(keptJson) as Map<String, dynamic>;
+ for (final entry in map.entries) {
+ _keptEbooks[entry.key] =
+ DownloadInfo.fromJson(entry.value as Map<String, dynamic>);
+ }
+ } catch (e) {
+ debugPrint('[Download] kept ebooks init error: $e');
+ }
+ }
final json = prefs.getString('downloads');
if (json != null) {
try {
@@ -1276,6 +1354,9 @@ class DownloadService extends ChangeNotifier {
}
}
await prefs.setString('downloads', jsonEncode(map));
+ await prefs.setString('kept_ebooks', jsonEncode({
+ for (final e in _keptEbooks.entries) e.key: e.value.toJson(),
+ }));
}
List<String>? getLocalPaths(String itemId) {
@@ -1508,6 +1589,13 @@ class DownloadService extends ChangeNotifier {
/// (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 {
+ // An ebook opened from a streamed book has a cached file and nothing
+ // that lists it. Give those a record once, so they show offline.
+ for (final id in await cachedEbookItemIds()) {
+ if (_downloads.containsKey(id) || _keptEbooks.containsKey(id)) continue;
+ if (!_ebookRecheckDone.add('kept:$id')) continue;
+ await keepEbook(api: api, itemId: id);
+ }
var changed = false;
for (final entry in _downloads.entries.toList()) {
final info = entry.value;
@@ -2770,8 +2858,8 @@ class DownloadService extends ChangeNotifier {
debugPrint('[Download] cover cleanup failed: $e');
}
- // Drop the offline ebook copy too, if any.
- await deleteCachedEbook(itemId);
+ // Drop the offline ebook copy too, unless the reader has a claim on it.
+ if (!_keptEbooks.containsKey(itemId)) await deleteCachedEbook(itemId);
_downloads.remove(itemId);
await _save();
diff --git a/lib/services/ebook_cache.dart b/lib/services/ebook_cache.dart
index cdf37b5f..d5c0416b 100644
--- a/lib/services/ebook_cache.dart
+++ b/lib/services/ebook_cache.dart
@@ -110,6 +110,38 @@ Future<Map<String, dynamic>?> cachedEbookFileFor(String itemId) async {
return null;
}
+/// Item ids that have an ebook file in the cache.
+Future<List<String>> cachedEbookItemIds() async {
+ final ids = <String>{};
+ try {
+ final dir = await _ebookCacheDir();
+ for (final f in dir.listSync()) {
+ if (f is! File) continue;
+ final name = f.uri.pathSegments.last;
+ final dot = name.lastIndexOf('.');
+ if (dot <= 0) continue;
+ final ext = name.substring(dot + 1).toLowerCase();
+ if (!allEbookFormats.contains(ext)) continue;
+ ids.add(name.substring(0, dot));
+ }
+ } catch (_) {}
+ return ids.toList();
+}
+
+/// Cover kept beside a cached ebook for the offline lists. Named so neither
+/// cachedEbookFileFor nor cachedEbookBytesSync can take it for the book.
+Future<File> ebookCoverCacheFile(String itemId) async {
+ final dir = await _ebookCacheDir();
+ return File('${dir.path}/cover_$itemId.jpg');
+}
+
+Future<void> deleteCachedEbookCover(String itemId) async {
+ try {
+ final f = await ebookCoverCacheFile(itemId);
+ if (f.existsSync()) await f.delete();
+ } catch (_) {}
+}
+
/// 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.
@@ -233,7 +265,9 @@ Future<void> deleteCachedEbook(String itemId) async {
for (final f in dir.listSync()) {
if (f is! File) continue;
final name = f.uri.pathSegments.last;
- if (name == itemId || name.startsWith('$itemId.')) {
+ if (name == itemId ||
+ name.startsWith('$itemId.') ||
+ name == 'cover_$itemId.jpg') {
try { await f.delete(); } catch (_) {}
}
}
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index a08ee65a..62a329b7 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -519,9 +519,11 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
// Offline fallback: build item from local download data
final dl = DownloadService().getInfo(widget.itemId);
- if (dl.sessionData != null) {
+ final sessionData =
+ dl.sessionData ?? DownloadService().keptEbook(widget.itemId)?.sessionData;
+ if (sessionData != null) {
try {
- final session = jsonDecode(dl.sessionData!) as Map<String, dynamic>;
+ final session = jsonDecode(sessionData) as Map<String, dynamic>;
// Prefer full libraryItem if it wasn't stripped
final localItem = session['libraryItem'] as Map<String, dynamic>?;
if (localItem != null && mounted) {
diff --git a/lib/widgets/ebook_reader_view.dart b/lib/widgets/ebook_reader_view.dart
index d35e368b..14d7cd50 100644
--- a/lib/widgets/ebook_reader_view.dart
+++ b/lib/widgets/ebook_reader_view.dart
@@ -860,6 +860,22 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs
if (savedProgress != null) _progress = savedProgress.clamp(0.0, 1.0);
}
+ /// The file is on the device now, but the offline lists only know records.
+ /// An ebook-only book becomes a download record; a book with audio gets a
+ /// kept ebook record, so the copy outlives the audio download.
+ Future<void> _rememberForOffline(ApiService api) async {
+ final downloads = DownloadService();
+ if (!downloads.isDownloaded(widget.itemId)) {
+ final registered = await downloads.registerEbookDownload(
+ api: api,
+ itemId: widget.itemId,
+ onlyIfNoAudio: true,
+ );
+ if (registered) return;
+ }
+ await downloads.keepEbook(api: api, itemId: widget.itemId);
+ }
+
Future<void> _downloadAndOpen() async {
try {
final auth = context.read<AuthProvider>();
@@ -874,16 +890,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs
debugPrint('[EbookReader] open item=${widget.itemId} ext=${ebookExtFromFile(widget.ebookFile)} '
'cached=${await isEbookCached(widget.itemId, widget.ebookFile)} playing=$playing');
final file = await fetchEbookToCache(api, widget.itemId, widget.ebookFile, widget.title);
- // The file is now on the device, but the offline library only lists
- // download records. An ebook-only book that has been read should be
- // there too, not just one saved from its detail sheet.
- if (!DownloadService().isDownloaded(widget.itemId)) {
- unawaited(DownloadService().registerEbookDownload(
- api: api,
- itemId: widget.itemId,
- onlyIfNoAudio: true,
- ));
- }
+ unawaited(_rememberForOffline(api));
final len = file.existsSync() ? await file.length() : 0;
final locations = await loadCachedLocations(file);
debugPrint('[EbookReader] file ready item=${widget.itemId} bytes=$len '