Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Give BookOrbit its own Continue Reading shelf, hide Find in ebook on its EPUB3 books, and drop the Listen button now that new EPUB3s are recognized in a second or two instead of half a minute

Barnabasfafb8bf2d36c
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index 9d5ca205..b09d82ce 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -2610,7 +2610,14 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
result.add(allSections.remove(id)!);
}
}
+ // An order saved before Continue Reading existed (BookOrbit had none)
+ // gets it next to Continue Listening rather than at the bottom.
+ final reading = allSections.remove('continue-reading');
result.addAll(allSections.values);
+ if (reading != null) {
+ final listening = result.indexWhere((s) => s['id'] == 'continue-listening');
+ result.insert(listening + 1, reading);
+ }
return result;
}
diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dart
index 4abde298..256f009d 100644
--- a/lib/providers/_lp_state.dart
+++ b/lib/providers/_lp_state.dart
@@ -48,6 +48,7 @@ mixin _StateMixin on ChangeNotifier {
Timer? _progressRefreshDebounce;
static const _progressDrivenShelfIds = <String>[
'continue-listening',
+ 'continue-reading',
'continue-series',
'listen-again',
];
diff --git a/lib/services/bookorbit_api_service.dart b/lib/services/bookorbit_api_service.dart
index bc7a8c07..5397d3c2 100644
--- a/lib/services/bookorbit_api_service.dart
+++ b/lib/services/bookorbit_api_service.dart
@@ -1528,14 +1528,50 @@ class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {
}
}
- await add('continue-listening', () async {
+ // BookOrbit's dashboard keeps listening and reading apart, and so do the
+ // shelves here, the way Audiobookshelf has them. A narrated EPUB is
+ // listened to, so it goes with the audiobooks; a book only the
+ // library's own in-progress query found goes by whether it has audio.
+ List<Map<String, dynamic>>? inProgress;
+ var listenIds = <String>{}, readIds = <String>{};
+ Future<List<Map<String, dynamic>>> progressCards() async {
+ final had = inProgress;
+ if (had != null) return had;
final listening = await _shelfCards('continue-listening', 50);
final reading = await _shelfCards('continue-reading', 50);
+ listenIds = {for (final c in listening) '${c['id']}'};
+ readIds = {for (final c in reading) '${c['id']}'};
final seen = <String>{};
final merged = [...listening, ...reading].where((c) => seen.add('${c['id']}')).toList();
- final cards = (await _inProgressHere(merged, libId)).take(limit).toList();
+ return inProgress = await _inProgressHere(merged, libId);
+ }
+
+ Map media(Map<String, dynamic> c) => _cardItem(c, libraryId: libId)['media'] as Map? ?? const {};
+ bool hasAudio(Map m) => m['narration'] != null || ((m['duration'] as num?) ?? 0) > 0;
+ bool listened(Map<String, dynamic> c) {
+ final id = '${c['id']}';
+ final m = media(c);
+ if (listenIds.contains(id) || m['narration'] != null) return true;
+ return !readIds.contains(id) && hasAudio(m);
+ }
+
+ bool read(Map<String, dynamic> c) {
+ final id = '${c['id']}';
+ final m = media(c);
+ if (m['narration'] != null) return false;
+ if (readIds.contains(id)) return true;
+ return !listenIds.contains(id) && !hasAudio(m);
+ }
+
+ await add('continue-listening', () async {
+ final cards = (await progressCards()).where(listened).take(limit).toList();
return shelf('continue-listening', 'Continue Listening', cards);
});
+ await add('continue-reading', () async {
+ final cards = (await progressCards()).where(read).take(limit).toList();
+ debugPrint('[BookOrbit] Continue Reading: ${cards.length} of ${readIds.length} reading cards');
+ return shelf('continue-reading', 'Continue Reading', cards);
+ });
await add('continue-series', () async {
final cards = await _hasOneLibrary()
? await _shelfCards('up-next-in-series', limit)
@@ -3977,6 +4013,11 @@ class BookOrbitApiService extends ApiService implements BookOrbitTokenSource {
/// Public for the reader's read along: the same narration the player is
/// streaming, so its timings line up exactly.
+ /// Whether [bookId] is known here to be a book whose audio is its EPUB's
+ /// narration, from a narration already looked up (playing it, or opening
+ /// it in the reader). No request.
+ bool knownNarrated(String bookId) => _narrations.containsKey(_key(bookId));
+
Future<MediaOverlay?> narrationFor(String bookId) async {
try {
return (await _narration(bookId))?.overlay;
diff --git a/lib/services/media_overlay.dart b/lib/services/media_overlay.dart
index d2631b71..281beacb 100644
--- a/lib/services/media_overlay.dart
+++ b/lib/services/media_overlay.dart
@@ -391,8 +391,13 @@ class MediaOverlay {
fromFiles((name) async => _text(archive, name));
/// The same, with the EPUB's files read through [load] (a local zip, or
- /// range requests to one on the server).
- static Future<MediaOverlay?> fromFiles(Future<String?> Function(String name) load) async {
+ /// range requests to one on the server). [onNarrated] hears as soon as the
+ /// package shows the book reads itself aloud, with the length it states,
+ /// before the timing files are read.
+ static Future<MediaOverlay?> fromFiles(
+ Future<String?> Function(String name) load, {
+ void Function(double? duration)? onNarrated,
+ }) async {
final container = await load('META-INF/container.xml');
if (container == null) return null;
final rootfile = _rootfileTag.firstMatch(container);
@@ -416,8 +421,27 @@ class MediaOverlay {
final types = {for (final v in byId.values) v.href: v.type};
final overlayIds = {for (final v in byId.values) if (v.overlay != null) v.overlay!};
if (overlayIds.isEmpty) return null;
+ onNarrated?.call(_packageDuration(opf));
final labels = await _navLabels(load, byId.values.where((v) => v.props.split(' ').contains('nav')).map((v) => v.href));
+ // On a server each timing file is a request of its own, so they come a
+ // few at a time; one after another took half a minute on a big book.
+ final smilPaths = <String>[];
+ for (final m in _itemrefTag.allMatches(opf)) {
+ final ref = _attrs(m.group(0)!)['idref'];
+ final overlayId = ref == null ? null : byId[ref]?.overlay;
+ final path = overlayId == null ? null : byId[overlayId]?.href;
+ if (path != null && !smilPaths.contains(path)) smilPaths.add(path);
+ }
+ final smils = <String, String?>{};
+ for (var i = 0; i < smilPaths.length; i += 8) {
+ final batch = smilPaths.sublist(i, min(i + 8, smilPaths.length));
+ final got = await Future.wait(batch.map(load));
+ for (var j = 0; j < batch.length; j++) {
+ smils[batch[j]] = got[j];
+ }
+ }
+
final raw = <_RawClip>[];
final sectionInfo = <int, ({String href, String? label})>{};
final spine = <String>[];
@@ -430,7 +454,7 @@ class MediaOverlay {
final overlayId = item?.overlay;
if (item == null || overlayId == null) continue;
final smilPath = byId[overlayId]?.href;
- final smil = smilPath == null ? null : await load(smilPath);
+ final smil = smilPath == null ? null : smils[smilPath];
if (smil == null) continue;
sectionInfo[spineIndex] = (href: item.href, label: labels[item.href]);
for (final par in _parBlock.allMatches(smil)) {
@@ -456,6 +480,19 @@ class MediaOverlay {
return _build(raw, mediaTypes: types, sectionInfo: sectionInfo)?.withContents(spine, labels);
}
+ /// The narration's whole length as the package states it: the
+ /// `media:duration` meta that refines nothing. Null when it isn't given.
+ static double? _packageDuration(String opf) {
+ for (final m in _metaTag.allMatches(opf)) {
+ final a = _attrs(m.group(1)!);
+ if (a['property'] != 'media:duration' || a.containsKey('refines')) continue;
+ return parseClock(m.group(2)!.trim());
+ }
+ return null;
+ }
+
+ static final _metaTag = RegExp(r'<(?:\w+:)?meta\b([^>]*)>([^<]*)</(?:\w+:)?meta>', caseSensitive: false);
+
/// [withContents] from BookOrbit's book info: its spine and table of
/// contents, the first entry in each file.
MediaOverlay withBookOrbitContents(Map<String, dynamic> info) {
diff --git a/lib/services/narration_service.dart b/lib/services/narration_service.dart
index f088600b..8a5bb407 100644
--- a/lib/services/narration_service.dart
+++ b/lib/services/narration_service.dart
@@ -81,11 +81,6 @@ void _copyWithout(({String from, String to, List<String> skip}) job) {
}
}
-/// Downloading the narration was called off.
-class NarrationCancelled implements Exception {
- const NarrationCancelled();
-}
-
/// Narrated EPUBs (EPUB 3 media overlays): the narration as the book's
/// audio, and the sentence timings read along follows.
///
@@ -93,8 +88,8 @@ class NarrationCancelled implements Exception {
/// Audiobookshelf server treats them as plain ebooks, so there it all
/// happens on the phone: the EPUB is looked into with range requests (its
/// index and timings), the reader gets a copy without the audio, and the
-/// narration plays once downloaded, fetched as just the audio files out of
-/// the EPUB.
+/// narration plays once downloaded: the whole EPUB comes down as a normal
+/// background download and its audio files are taken out of it here.
class NarrationService {
NarrationService._();
static final NarrationService instance = NarrationService._();
@@ -251,10 +246,49 @@ class NarrationService {
/// Looks into an Audiobookshelf book's EPUB on the server (its index and
/// timings only) to see whether it reads itself aloud. Remembered, so it is
/// asked once per book.
- Future<MediaOverlay?> probe(ApiService api, Map<String, dynamic> item) async {
+ ///
+ /// [onNarrated] hears as soon as the EPUB's package shows narration, with
+ /// the length it states, while the timings are still coming. One look per
+ /// book at a time: a second caller waits on the first.
+ Future<MediaOverlay?> probe(
+ ApiService api,
+ Map<String, dynamic> item, {
+ void Function(double? duration)? onNarrated,
+ }) {
final itemId = item['id'] as String?;
+ if (itemId == null) return Future.value(null);
+ if (onNarrated != null) {
+ if (_seenNarrated.containsKey(itemId)) {
+ onNarrated(_seenNarrated[itemId]);
+ } else {
+ (_onNarrated[itemId] ??= []).add(onNarrated);
+ }
+ }
+ final running = _probing[itemId];
+ if (running != null) {
+ debugPrint('[Narration] $itemId is already being looked into - waiting on that look');
+ return running;
+ }
+ final look = () async {
+ try {
+ return await _probe(api, item, itemId);
+ } finally {
+ _probing.remove(itemId);
+ _onNarrated.remove(itemId);
+ _seenNarrated.remove(itemId);
+ }
+ }();
+ _probing[itemId] = look;
+ return look;
+ }
+
+ final Map<String, Future<MediaOverlay?>> _probing = {};
+ final Map<String, List<void Function(double? duration)>> _onNarrated = {};
+ final Map<String, double?> _seenNarrated = {};
+
+ Future<MediaOverlay?> _probe(ApiService api, Map<String, dynamic> item, String itemId) async {
final ebookFile = resolveEbookFile(item);
- if (itemId == null || ebookFile == null || api.isBookOrbit) return null;
+ if (ebookFile == null || api.isBookOrbit) return null;
if (ebookExtFromFile(ebookFile) != '.epub') return null;
if (await knownNarrated(itemId) == false) return null;
final local = await localOverlay(itemId);
@@ -265,6 +299,14 @@ class NarrationService {
final o = await MediaOverlay.fromFiles((name) async {
final e = zip.entry(name);
return e == null ? null : utf8.decode(await zip.read(e), allowMalformed: true);
+ }, onNarrated: (duration) {
+ debugPrint('[Narration] $itemId: its package lists narration '
+ '(${duration == null ? 'no length given' : '${duration.toStringAsFixed(0)}s'}) after '
+ '${DateTime.now().difference(started).inMilliseconds}ms - reading the timings');
+ _seenNarrated[itemId] = duration;
+ for (final cb in _onNarrated.remove(itemId) ?? const <void Function(double?)>[]) {
+ cb(duration);
+ }
});
debugPrint('[Narration] looked into $itemId on the server in '
'${DateTime.now().difference(started).inMilliseconds}ms: '
@@ -420,33 +462,6 @@ class NarrationService {
return localOverlay(itemId);
}
- /// Puts an Audiobookshelf book's narration on the phone as its audio:
- /// just the audio files, fetched out of the EPUB on the server. Servers
- /// without range requests fall back to the whole EPUB. False when the EPUB
- /// has no narration.
- Future<bool> prepareLocal(
- ApiService api,
- Map<String, dynamic> item, {
- void Function(double progress)? onProgress,
- }) async {
- final itemId = item['id'] as String?;
- final ebookFile = resolveEbookFile(item);
- if (itemId == null || ebookFile == null) return false;
- final o = await probe(api, item);
- if (o != null) {
- try {
- await _fetchAudio(api, item, itemId, ebookFile, o, onProgress);
- return true;
- } on NarrationCancelled {
- rethrow;
- } catch (e) {
- debugPrint('[Narration] fetching the audio out of the EPUB failed ($e) - using the whole file');
- }
- }
- if (await knownNarrated(itemId) == false) return false;
- return _extractFromWholeEpub(api, item, itemId, ebookFile);
- }
-
List<String> _trackNames(List<Map<String, dynamic>> tracks) => [
for (final t in tracks)
((t['metadata'] as Map)['filename'] as String).replaceAll(RegExp(r'[\\/:*?"<>|]'), '_'),
@@ -487,73 +502,6 @@ class NarrationService {
);
}
- Future<void> _fetchAudio(
- ApiService api,
- Map<String, dynamic> item,
- String itemId,
- Map<String, dynamic> ebookFile,
- MediaOverlay o,
- void Function(double progress)? onProgress,
- ) async {
- final zip = await _remote(api, itemId, ebookFile);
- final names = _trackNames(o.audioTracks((t) => t.href));
- final dir = '${await DownloadService().downloadBasePath}/$itemId';
- Directory(dir).createSync(recursive: true);
- final entries = <RemoteZipEntry>[];
- for (final t in o.tracks) {
- final e = zip.entry(t.href);
- if (e == null) throw RemoteZipException('${t.href} is not in the EPUB');
- entries.add(e);
- }
- final total = entries.fold<int>(0, (s, e) => s + e.compressedSize);
- var before = 0;
- final paths = <String>[];
- final started = DateTime.now();
- for (var i = 0; i < entries.length; i++) {
- final out = File('$dir/${names[i]}');
- if (!(out.existsSync() && out.lengthSync() == entries[i].size)) {
- final base = before;
- await zip.download(entries[i], out,
- onBytes: (done) => onProgress?.call(total == 0 ? 0 : (base + done) / total));
- }
- before += entries[i].compressedSize;
- onProgress?.call(total == 0 ? 0 : before / total);
- paths.add(out.path);
- }
- debugPrint('[Narration] fetched ${paths.length} audio files ($total bytes) out of the EPUB for '
- '$itemId in ${DateTime.now().difference(started).inSeconds}s');
- await _keep(api, item, itemId, o, dir, paths);
- }
-
- Future<bool> _extractFromWholeEpub(
- ApiService api,
- Map<String, dynamic> item,
- String itemId,
- Map<String, dynamic> ebookFile,
- ) async {
- final metadata = (item['media'] as Map<String, dynamic>?)?['metadata'] as Map<String, dynamic>?;
- final title = metadata?['title'] as String? ?? '';
- final epub = await fetchEbookToCache(api, itemId, ebookFile, title);
- final o = await compute(_parseEpub, epub.path);
- if (o == null || o.isEmpty) {
- await _remember(itemId, null);
- return false;
- }
- final names = _trackNames(o.audioTracks((t) => t.href));
- final dir = '${await DownloadService().downloadBasePath}/$itemId';
- final started = DateTime.now();
- final paths = await compute(_extract, (
- epub: epub.path,
- dir: dir,
- hrefs: o.tracks.map((t) => t.href).toList(),
- names: names,
- ));
- debugPrint('[Narration] took ${paths.length} audio files out of the whole EPUB for $itemId '
- 'in ${DateTime.now().difference(started).inSeconds}s');
- await _keep(api, item, itemId, o, dir, paths);
- return true;
- }
-
/// A narrated EPUB downloaded whole to [epubPath]: its audio files are taken
/// out into [dir] and kept as the book's download, the reader gets a copy
/// without the audio when it has none yet, and the EPUB is deleted. False
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index 0c692556..30a69a2b 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -10,7 +10,6 @@ import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'overlay_toast.dart';
import 'narration_download_dialog.dart';
-import 'progress_dialog.dart';
import '../services/media_overlay.dart';
import '../services/narration_service.dart';
import '../services/read_listen_sync.dart';
@@ -247,9 +246,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
return _rawCoverScheme;
}
- // What this phone knows about the EPUB reading itself aloud: true, false
- // (checked, it doesn't), or null (not looked at yet).
- bool? _knownNarrated;
// An Audiobookshelf ebook-only book whose EPUB reads itself aloud: the
// sheet shows it as an audiobook, the way BookOrbit's arrive.
MediaOverlay? _localNarration;
@@ -286,22 +282,36 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
});
}
MediaOverlay? o;
- bool? known;
- try {
- o = await NarrationService.instance.probe(api, item);
- if (o != null) await NarrationService.instance.markAudiobook(widget.itemId, o);
- known = await NarrationService.instance.knownNarrated(widget.itemId);
- // Looked at before the list kept plain EPUBs too.
- if (o == null && known == false && !NarratedBooks.checked(widget.itemId)) {
- await NarratedBooks.set(widget.itemId, null);
+ // A look that fails (rather than finding no narration) gets one more go,
+ // so a hiccup doesn't leave a narrated EPUB showing as a plain ebook.
+ for (var attempt = 1; attempt <= 2 && mounted; attempt++) {
+ try {
+ o = await NarrationService.instance.probe(api, item, onNarrated: (duration) {
+ // The package says it reads itself aloud: that settles the buttons
+ // while the timings are still coming.
+ if (duration == null || duration <= 0 || !mounted) return;
+ debugPrint('[Narration] ${widget.itemId}: narrated by its package - showing it as an audiobook now');
+ unawaited(NarratedBooks.set(widget.itemId, duration).then((_) {
+ if (mounted && _lookingForNarration) setState(() => _lookingForNarration = false);
+ }));
+ });
+ if (o != null) await NarrationService.instance.markAudiobook(widget.itemId, o);
+ final known = await NarrationService.instance.knownNarrated(widget.itemId);
+ // Looked at before the list kept plain EPUBs too.
+ if (o == null && known == false && !NarratedBooks.checked(widget.itemId)) {
+ await NarratedBooks.set(widget.itemId, null);
+ }
+ if (o != null || known != null) break;
+ debugPrint('[Narration] ${widget.itemId}: the EPUB on the server could not be looked into '
+ '(try $attempt of 2)');
+ } catch (e) {
+ debugPrint('[Narration] ${widget.itemId}: looking for narration failed (try $attempt of 2): $e');
}
- } catch (e) {
- debugPrint('[Narration] ${widget.itemId}: looking for narration failed: $e');
+ if (attempt == 1) await Future.delayed(const Duration(seconds: 2));
}
if (!mounted) return;
setState(() {
_localNarration = o;
- _knownNarrated = known;
_lookingForNarration = false;
});
}
@@ -339,62 +349,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
),
);
- /// Puts the narration on the phone (just the audio, out of the EPUB on the
- /// server), with how far along it is. False when there is none.
- Future<bool> _prepareNarration() async {
- final l = AppLocalizations.of(context)!;
- final api = context.read<AuthProvider>().apiService;
- final item = _item;
- if (api == null || item == null) return false;
- debugPrint('[Narration] ${widget.itemId} can not stream - downloading the narration first');
- final label = ValueNotifier<String>(l.narrationPreparing);
- showProgressDialogListenable(context, label);
- var ok = false;
- try {
- ok = await NarrationService.instance.prepareLocal(api, item, onProgress: (p) {
- label.value = '${l.narrationPreparing} ${(p * 100).clamp(0, 100).toStringAsFixed(0)}%';
- });
- } catch (e) {
- debugPrint('[Narration] getting the narration failed: $e');
- }
- if (mounted) Navigator.of(context, rootNavigator: true).pop();
- Future.delayed(const Duration(milliseconds: 500), label.dispose);
- if (!mounted) return false;
- final o = ok ? await NarrationService.instance.localOverlay(widget.itemId) : null;
- final known = await NarrationService.instance.knownNarrated(widget.itemId);
- if (!mounted) return false;
- setState(() {
- _localNarration = o ?? _localNarration;
- _knownNarrated = known;
- });
- if (!ok) showOverlayToast(context, l.narrationNone, icon: Icons.headphones_rounded);
- return ok;
- }
-
- /// The Listen button on a big EPUB this phone couldn't look into (a server
- /// without range requests): fetch it whole, then play like Absorb.
- Future<void> _listenToNarration() async {
- if (!await _prepareNarration() || !mounted) return;
- final o = _localNarration;
- if (o == null) return;
- final shaped = NarrationService.instance.withNarration(_item!, o);
- final media = shaped['media'] as Map<String, dynamic>;
- final metadata = media['metadata'] as Map<String, dynamic>? ?? const {};
- setState(() {
- _item = shaped;
- _isAbsorbing = true;
- });
- await _startAbsorb(
- context,
- auth: context.read<AuthProvider>(),
- title: metadata['title'] as String? ?? '',
- author: metadata['authorName'] as String? ?? '',
- coverUrl: _coverUrl,
- duration: (media['duration'] as num?)?.toDouble() ?? 0,
- chapters: media['chapters'] as List<dynamic>? ?? const [],
- );
- }
-
@override void initState() {
super.initState();
// Quick-actions sheet seeds from the tile's item map so it paints instantly
@@ -409,9 +363,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
_loadItem();
_loadBookmarks();
_warmStats();
- NarrationService.instance.knownNarrated(widget.itemId).then((known) {
- if (known != null && mounted) setState(() => _knownNarrated = known);
- });
PlayerSettings.getSyncReadingListening().then((on) {
if (mounted && on != _autoSync) setState(() => _autoSync = on);
});
@@ -1329,37 +1280,6 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
);
},
),
- // A big EPUB this phone couldn't look into (a server without range
- // requests) may read itself aloud; tapping finds out. A checked one
- // shows as an audiobook instead.
- if (isEbookOnly &&
- !_lookingForNarration &&
- ebookFile != null &&
- ebookExtFromFile(ebookFile) == '.epub' &&
- !lib.isOffline &&
- _knownNarrated == null &&
- ((ebookFile['metadata'] as Map?)?['size'] as num? ?? 0) > 150 * 1024 * 1024) ...[
- const SizedBox(height: 8),
- SizedBox(
- height: 40,
- child: Material(
- color: accent.withValues(alpha: 0.14),
- borderRadius: BorderRadius.circular(14),
- clipBehavior: Clip.antiAlias,
- child: InkWell(
- onTap: _listenToNarration,
- child: Center(
- child: Row(mainAxisSize: MainAxisSize.min, children: [
- Icon(Icons.headphones_rounded, size: 18, color: accent),
- const SizedBox(width: 8),
- Text(l.narrationListen,
- style: tt.labelLarge?.copyWith(fontWeight: FontWeight.w600, color: accent)),
- ]),
- ),
- ),
- ),
- ),
- ],
// A companion ebook gets its own, smaller button under Absorb with the
// reading progress filled in the same way. Ebook-only books already
// have Read as the big button above.
diff --git a/lib/widgets/card_buttons.dart b/lib/widgets/card_buttons.dart
index 6e9a2740..7dcbaa98 100644
--- a/lib/widgets/card_buttons.dart
+++ b/lib/widgets/card_buttons.dart
@@ -1607,8 +1607,14 @@ class CardActionDelegate {
/// A book whose audio is its EPUB's narration: Read already opens on the
/// sentence being heard, so Find in ebook would be the same button twice.
- bool get _narratedEbook =>
- episodeId == null && (NarratedBooks.contains(itemId) || _media['narration'] != null);
+ bool get _narratedEbook {
+ if (episodeId != null) return false;
+ if (NarratedBooks.contains(itemId) || _media['narration'] != null) return true;
+ // A BookOrbit card's book can arrive without its files; the narration
+ // looked up when it played or opened says so either way.
+ final api = context.read<AuthProvider>().apiService;
+ return api is BookOrbitApiService && api.knownNarrated(itemId);
+ }
/// The saved button order, less what this book has no use for.
List<String> get _shownOrder =>