A cross platform Audiobookshelf client for Android and iOS
Dart
Show local covers everywhere and pick fields when matching
Barnabas2478a9a844e3
diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dartindex 87f1c853..f6c5b402 100644--- a/lib/providers/_lp_state.dart+++ b/lib/providers/_lp_state.dart@@ -319,6 +319,11 @@ mixin _StateMixin on ChangeNotifier {if (_itemsWithoutCover.contains(apiItemId)) return null;if (_api != null && !isOffline) {+ // A local metadata override cover wins over the server cover so the+ // chosen art shows everywhere (grid, absorbing card), not just the+ // book sheet.+ final overrideCover = MetadataOverrideService().coverUrlFor(itemId);+ if (overrideCover != null && overrideCover.isNotEmpty) return overrideCover;final ts = _itemUpdatedAt[apiItemId];return _api!.getCoverUrl(apiItemId, width: width, updatedAt: ts);}diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex 28d537a4..7bcd1f60 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -14,6 +14,7 @@ import '../services/android_auto_service.dart';import '../services/carplay_service.dart';import '../services/chromecast_service.dart';import '../services/bookmark_service.dart';+import '../services/metadata_override_service.dart';import '../services/session_cache.dart';import '../services/socket_service.dart';import '../services/home_widget_service.dart';@@ -136,6 +137,10 @@ class LibraryProvider extends ChangeNotifiernotifyListeners();}+ // Refresh the local metadata cover overrides for this account so the+ // grid/card covers reflect them, then repaint once loaded.+ MetadataOverrideService().loadAll().then((_) => notifyListeners());+restoreOfflineMode().then((_) async {debugPrint('[Library] restoreOfflineMode done, serverReachable=${auth.serverReachable} api=${_api != null} offline=$isOffline');@@ -223,6 +228,11 @@ class LibraryProvider extends ChangeNotifier}}+ /// Repaint listeners after a local metadata cover override is saved or+ /// cleared, so the grid/absorbing card re-resolve [getCoverUrl] (the cache+ /// is already updated synchronously by MetadataOverrideService).+ void notifyCoverOverridesChanged() => notifyListeners();+Future<void> loadLibraries() async {if (_api == null) return;diff --git a/lib/services/metadata_override_service.dart b/lib/services/metadata_override_service.dartindex f3d0bf54..53cb3784 100644--- a/lib/services/metadata_override_service.dart+++ b/lib/services/metadata_override_service.dart@@ -1,6 +1,8 @@import 'dart:convert';import 'package:flutter/foundation.dart';+import 'package:shared_preferences/shared_preferences.dart';import 'scoped_prefs.dart';+import 'user_account_service.dart';/// Stores user-chosen metadata overrides locally per item./// These override server metadata that is empty or wrong, without@@ -13,6 +15,50 @@ class MetadataOverrideService {static const _prefix = 'metadata_override_';+ /// Synchronous cache of cover overrides, keyed by item id. Populated by+ /// [loadAll] on startup/account switch and kept in sync by save/delete.+ /// Lets [coverUrlFor] resolve a local cover without an async prefs read,+ /// so the library grid and absorbing card can apply the override too.+ final Map<String, String> _coverCache = {};++ /// Synchronous lookup of a local cover override for an item, or null.+ /// Handles composite keys (e.g. `<itemId><episodeId>`) by also checking+ /// the 36-char base item id the override is stored under.+ String? coverUrlFor(String itemId) {+ final direct = _coverCache[itemId];+ if (direct != null && direct.isNotEmpty) return direct;+ if (itemId.length > 36) {+ final base = _coverCache[itemId.substring(0, 36)];+ if (base != null && base.isNotEmpty) return base;+ }+ return null;+ }++ /// Load every stored override's cover into [_coverCache]. Call on startup+ /// and whenever the active account changes. Mirrors the bookmark service's+ /// scoped-key enumeration so it only reads the active user's overrides.+ Future<void> loadAll() async {+ final prefs = await SharedPreferences.getInstance();+ final scope = UserAccountService().activeScopeKey;+ final fullPrefix = scope.isEmpty ? _prefix : '$scope:$_prefix';+ _coverCache.clear();+ for (final key in prefs.getKeys()) {+ if (!key.startsWith(fullPrefix)) continue;+ final itemId = key.substring(fullPrefix.length);+ final raw = prefs.getString(key);+ if (raw == null) continue;+ try {+ final map = jsonDecode(raw) as Map<String, dynamic>;+ final cover = map['coverUrl'];+ if (cover != null && cover.toString().isNotEmpty) {+ _coverCache[itemId] = cover.toString();+ }+ } catch (_) {}+ }+ debugPrint(+ '[MetadataOverride] Loaded ${_coverCache.length} cover override(s) for scope "$scope"');+ }+/// Save a metadata override for an item. Only non-null fields are stored.Future<void> save(String itemId, Map<String, dynamic> override) async {// Merge with any existing override@@ -21,6 +67,13 @@ class MetadataOverrideService {// Remove null valuesmerged.removeWhere((_, v) => v == null);await ScopedPrefs.setString('$_prefix$itemId', jsonEncode(merged));+ // Keep the sync cover cache in step so grid/card covers update at once.+ final cover = merged['coverUrl'];+ if (cover != null && cover.toString().isNotEmpty) {+ _coverCache[itemId] = cover.toString();+ } else {+ _coverCache.remove(itemId);+ }debugPrint('[MetadataOverride] Saved override for $itemId: ${merged.keys.join(', ')}');}@@ -38,6 +91,7 @@ class MetadataOverrideService {/// Delete a metadata override for an item.Future<void> delete(String itemId) async {await ScopedPrefs.remove('$_prefix$itemId');+ _coverCache.remove(itemId);}/// Check if an item has a local override.diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex efd943ef..343d1299 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -686,6 +686,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {final continueSeriesId = lib.continueSeriesShelfMatch(bookSeriesIds);showModalBottomSheet(context: context,+ isScrollControlled: true,backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(24)),@@ -697,6 +698,9 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {child: Column(mainAxisSize: MainAxisSize.min, children: [Center(child: Container(width: 40, height: 4, margin: const EdgeInsets.only(bottom: 16),decoration: BoxDecoration(color: cs.onSurface.withValues(alpha: 0.24), borderRadius: BorderRadius.circular(2)))),+ Flexible(+ child: SingleChildScrollView(+ child: Column(mainAxisSize: MainAxisSize.min, children: [_moreItem(cs, lib.isOnAbsorbingList(widget.itemId)? Icons.remove_circle_outline_rounded : Icons.add_circle_outline_rounded,lib.isOnAbsorbingList(widget.itemId) ? Wording.of(context).removeFromAbsorbing : Wording.of(context).addToAbsorbing,@@ -781,6 +785,9 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {style: TextStyle(color: cs.onSurface.withValues(alpha: 0.25), fontSize: 11)),),],+ ]),+ ),+ ),]),),);@@ -1568,8 +1575,12 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {initialAuthor: author,currentMetadata: (_item?['media'] as Map<String, dynamic>?)?['metadata'] as Map<String, dynamic>?,onApplied: () {- // Reload the item to show the new override+ // Reload the item to show the new override, and repaint the+ // library so the grid/absorbing card pick up the override cover._loadItem();+ if (mounted) {+ context.read<LibraryProvider>().notifyCoverOverridesChanged();+ }},),),@@ -1599,6 +1610,8 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {setState(() => _hasLocalOverride = false);await _loadItem();if (context.mounted) {+ // Repaint the library so the grid/card drop the override cover too.+ context.read<LibraryProvider>().notifyCoverOverridesChanged();ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(l.localMetadataCleared),behavior: SnackBarBehavior.floating,diff --git a/lib/widgets/edit_metadata_sheet.dart b/lib/widgets/edit_metadata_sheet.dartindex d2b45f8b..eafc3090 100644--- a/lib/widgets/edit_metadata_sheet.dart+++ b/lib/widgets/edit_metadata_sheet.dart@@ -219,7 +219,7 @@ class _MetadataEditViewState extends State<MetadataEditView>}}- Future<void> _applyMatch(Map<String, dynamic> result) async {+ Future<void> _applyMatch(Map<String, dynamic> result, Set<String> selected) async {final book = result['book'] as Map<String, dynamic>? ?? result;final api = context.read<AuthProvider>().apiService;if (api == null) return;@@ -227,6 +227,7 @@ class _MetadataEditViewState extends State<MetadataEditView>final update = <String, dynamic>{};void add(String key, dynamic value) {+ if (!selected.contains(key)) return;final s = _safeString(value);if (s.isNotEmpty) update[key] = s;}@@ -241,46 +242,56 @@ class _MetadataEditViewState extends State<MetadataEditView>add('language', book['language']);// Authors/narrators are arrays in ABS- final authorStr = _safeString(book['author']).isNotEmpty- ? _safeString(book['author'])- : _safeString(book['authorName']);- if (authorStr.isNotEmpty) {- update['authors'] = authorStr.split(',').map((a) => {'name': a.trim()}).where((a) => (a['name'] as String).isNotEmpty).toList();+ if (selected.contains('author')) {+ final authorStr = _safeString(book['author']).isNotEmpty+ ? _safeString(book['author'])+ : _safeString(book['authorName']);+ if (authorStr.isNotEmpty) {+ update['authors'] = authorStr.split(',').map((a) => {'name': a.trim()}).where((a) => (a['name'] as String).isNotEmpty).toList();+ }}- final narratorStr = _safeString(book['narrator']).isNotEmpty- ? _safeString(book['narrator'])- : _safeString(book['narratorName']);- if (narratorStr.isNotEmpty) {- update['narrators'] = narratorStr.split(',').map((n) => {'name': n.trim()}).where((n) => (n['name'] as String).isNotEmpty).toList();+ if (selected.contains('narrator')) {+ final narratorStr = _safeString(book['narrator']).isNotEmpty+ ? _safeString(book['narrator'])+ : _safeString(book['narratorName']);+ if (narratorStr.isNotEmpty) {+ update['narrators'] = narratorStr.split(',').map((n) => {'name': n.trim()}).where((n) => (n['name'] as String).isNotEmpty).toList();+ }}// Genres- final genres = book['genres'] ?? book['tags'];- if (genres is List && genres.isNotEmpty) {- update['genres'] = genres.whereType<String>().toList();+ if (selected.contains('genres')) {+ final genres = book['genres'] ?? book['tags'];+ if (genres is List && genres.isNotEmpty) {+ update['genres'] = genres.whereType<String>().toList();+ }}// Series- final series = book['series'];- if (series is List && series.isNotEmpty) {- update['series'] = series;- } else if (series is String && series.isNotEmpty) {- update['series'] = [- {'name': series, 'sequence': _safeString(book['volumeNumber'] ?? book['sequence'])}- ];+ if (selected.contains('series')) {+ final series = book['series'];+ if (series is List && series.isNotEmpty) {+ update['series'] = series;+ } else if (series is String && series.isNotEmpty) {+ update['series'] = [+ {'name': series, 'sequence': _safeString(book['volumeNumber'] ?? book['sequence'])}+ ];+ }}setState(() => _saving = true);- bool ok = await api.updateItemMedia(widget.itemId, update);+ bool ok = update.isEmpty ? true : await api.updateItemMedia(widget.itemId, update);// Cover- final coverUrl = _safeString(book['cover']).isNotEmpty- ? _safeString(book['cover'])- : _safeString(book['image']);- if (ok && coverUrl.isNotEmpty) {- await api.updateItemCoverUrl(widget.itemId, coverUrl);+ if (ok && selected.contains('cover')) {+ final coverUrl = _safeString(book['cover']).isNotEmpty+ ? _safeString(book['cover'])+ : _safeString(book['image']);+ if (coverUrl.isNotEmpty) {+ await api.updateItemCoverUrl(widget.itemId, coverUrl);+ }}if (!mounted) return;@@ -313,24 +324,109 @@ class _MetadataEditViewState extends State<MetadataEditView>void _confirmMatch(Map<String, dynamic> result) {final book = result['book'] as Map<String, dynamic>? ?? result;- final title = _safeString(book['title']);- final author = _safeString(book['author']).isNotEmpty- ? _safeString(book['author'])- : _safeString(book['authorName']);final l = AppLocalizations.of(context)!;+ // Build the fields this match offers (key -> preview), so the user can pick+ // which to apply instead of overwriting everything.+ final fields = <String, String>{};+ void tryAdd(String key, dynamic value) {+ final s = _safeString(value);+ if (s.isNotEmpty) fields[key] = s;+ }+ tryAdd('title', book['title']);+ tryAdd('subtitle', book['subtitle']);+ tryAdd('author', book['author'] ?? book['authorName']);+ tryAdd('narrator', book['narrator'] ?? book['narratorName']);+ tryAdd('description', book['description']);+ tryAdd('publisher', book['publisher']);+ tryAdd('publishedYear', book['publishedYear'] ?? book['publishedDate']);+ tryAdd('asin', book['asin']);+ tryAdd('isbn', book['isbn']);+ tryAdd('language', book['language']);++ final genres = book['genres'] ?? book['tags'];+ if (genres is List && genres.isNotEmpty) {+ fields['genres'] = genres.whereType<String>().join(', ');+ }+ final series = book['series'];+ if (series is String && series.isNotEmpty) {+ fields['series'] = series;+ } else if (series is List && series.isNotEmpty && series[0] is Map) {+ fields['series'] = (series[0] as Map)['name']?.toString() ?? '';+ }+ final cover = _safeString(book['cover']).isNotEmpty+ ? _safeString(book['cover'])+ : _safeString(book['image']);+ if (cover.isNotEmpty) fields['cover'] = cover;++ if (fields.isEmpty) return;++ final selected = Set<String>.from(fields.keys);+ final labels = {+ 'title': l.titleLabel,+ 'subtitle': l.subtitleLabel,+ 'author': l.authorLabel,+ 'narrator': l.narratorLabel,+ 'description': l.descriptionLabel,+ 'publisher': l.publisherLabel,+ 'publishedYear': l.yearLabel,+ 'asin': l.asinLabel,+ 'isbn': l.isbnLabel,+ 'language': l.languageLabel,+ 'genres': l.genresLabel,+ 'series': l.seriesLabel,+ 'cover': l.metadataLookupCover,+ };+showDialog(context: context,- builder: (ctx) => AlertDialog(- title: Text(l.applyThisMatch),- content: Text(author.isNotEmpty- ? l.editMetadataConfirmMatchWithAuthor(title, author)- : l.editMetadataConfirmMatch(title)),- actions: [- TextButton(onPressed: () => Navigator.pop(ctx), child: Text(l.cancel)),- FilledButton(onPressed: () { Navigator.pop(ctx); _applyMatch(result); }, child: Text(l.apply)),- ],- ),+ builder: (ctx) {+ return StatefulBuilder(builder: (ctx, setDialogState) {+ final cs = Theme.of(ctx).colorScheme;+ final tt = Theme.of(ctx).textTheme;+ return AlertDialog(+ title: Text(l.metadataLookupChooseFields),+ content: SizedBox(+ width: double.maxFinite,+ child: ListView(+ shrinkWrap: true,+ children: fields.entries.map((e) {+ final label = labels[e.key] ?? e.key;+ final clean = e.value.replaceAll(RegExp(r'<[^>]*>'), '');+ final preview = clean.length > 60 ? '${clean.substring(0, 57)}...' : clean;+ return CheckboxListTile(+ dense: true,+ contentPadding: EdgeInsets.zero,+ title: Text(label, style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600)),+ subtitle: Text(preview, maxLines: 1, overflow: TextOverflow.ellipsis,+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),+ value: selected.contains(e.key),+ onChanged: (v) => setDialogState(() {+ if (v == true) {+ selected.add(e.key);+ } else {+ selected.remove(e.key);+ }+ }),+ );+ }).toList(),+ ),+ ),+ actions: [+ TextButton(onPressed: () => Navigator.pop(ctx), child: Text(l.cancel)),+ FilledButton(+ onPressed: selected.isEmpty+ ? null+ : () {+ Navigator.pop(ctx);+ _applyMatch(result, selected);+ },+ child: Text(l.metadataLookupApplyFields(selected.length)),+ ),+ ],+ );+ });+ },);}