Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Show how many Audible ratings a book's score is based on

Barnabas4250406464f1
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 318e9001..151be390 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -2812,9 +2812,14 @@ class ApiService {
return [];
}
- /// Fetch Audible rating from Audnexus API using ASIN.
- /// Returns { rating, asin } or null.
+ /// Audible rating for an ASIN: the score and how many ratings it rests on.
+ /// Audible's own catalog answers both, on the store matching the device
+ /// locale like every other Audible lookup here. Audnexus stays as the
+ /// fallback; it knows the score but not the count.
+ /// Returns { rating, count, asin } or null.
static Future<Map<String, dynamic>?> getAudibleRating(String asin) async {
+ final catalog = await _audibleCatalogRating(asin);
+ if (catalog != null) return catalog;
try {
final response = await http.get(
Uri.parse('https://api.audnex.us/books/$asin?region=$_region&update=1'),
@@ -2826,6 +2831,7 @@ class ApiService {
if (rating != null) {
return {
'rating': double.tryParse(rating) ?? 0.0,
+ 'count': null,
'asin': asin,
};
}
@@ -2836,6 +2842,35 @@ class ApiService {
return null;
}
+ static Future<Map<String, dynamic>?> _audibleCatalogRating(String asin) async {
+ try {
+ final response = await http.get(
+ Uri.parse(
+ 'https://api.audible$_audibleTld/1.0/catalog/products/'
+ '${Uri.encodeComponent(asin)}?response_groups=rating',
+ ),
+ ).timeout(const Duration(seconds: 10));
+ if (response.statusCode != 200) return null;
+ final data = jsonDecode(response.body) as Map<String, dynamic>;
+ final product = data['product'] as Map<String, dynamic>?;
+ final overall = (product?['rating'] as Map<String, dynamic>?)
+ ?['overall_distribution'] as Map<String, dynamic>?;
+ final score = (overall?['average_rating'] as num?)?.toDouble();
+ final count = (overall?['num_ratings'] as num?)?.toInt();
+ if (score == null || !score.isFinite || score <= 0 || score > 5) {
+ return null;
+ }
+ return {
+ 'rating': score,
+ 'count': count != null && count >= 0 ? count : null,
+ 'asin': asin,
+ };
+ } catch (e) {
+ debugPrint('[API] Audible catalog rating $asin error: $e');
+ return null;
+ }
+ }
+
/// Read a previously-fetched Audible rating from local cache, keyed by
/// library item id. Used so the rating shows immediately on book detail
/// open even when Audnexus is slow or unreachable, and so a transient
@@ -2850,6 +2885,7 @@ class ApiService {
if (rating == null || rating <= 0) return null;
return {
'rating': rating,
+ 'count': (data['count'] as num?)?.toInt(),
'asin': data['asin'] as String?,
};
} catch (_) {
@@ -2860,12 +2896,13 @@ class ApiService {
/// Persist a fresh Audible rating so subsequent book detail opens render
/// the stars instantly without waiting on Audnexus.
static Future<void> setCachedAudibleRating(
- String itemId, double rating, String? asin) async {
+ String itemId, double rating, String? asin, {int? count}) async {
if (rating <= 0) return;
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('audible_rating_$itemId', jsonEncode({
'rating': rating,
+ 'count': count,
'asin': asin,
'fetchedAt': DateTime.now().millisecondsSinceEpoch,
}));
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index 0d0193e1..6f5f86fd 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -17,6 +17,7 @@ import 'package:http/http.dart' as http;
import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
+import 'package:intl/intl.dart';
import '../l10n/app_localizations.dart';
import 'book_stats_sheet.dart';
import '../services/wording.dart';
@@ -345,7 +346,8 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
_asin = freshAsin;
});
await ApiService.setCachedAudibleRating(
- widget.itemId, freshRating, freshAsin);
+ widget.itemId, freshRating, freshAsin,
+ count: (rating['count'] as num?)?.toInt());
}
return;
}
@@ -645,6 +647,11 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
const SizedBox(width: 6),
Text((_rating!['rating'] as num).toStringAsFixed(1),
style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant)),
+ if (((_rating!['count'] as num?) ?? 0) > 0) ...[
+ const SizedBox(width: 3),
+ Text('(${_formatRatingCount((_rating!['count'] as num).toInt(), l.localeName)})',
+ style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant)),
+ ],
const SizedBox(width: 4),
Text(l.onAudible, style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant)),
]),
@@ -1631,6 +1638,14 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
return domains[code] ?? 'audible.com';
}
+ static String _formatRatingCount(int count, String locale) {
+ try {
+ return NumberFormat.decimalPattern(locale).format(count);
+ } catch (_) {
+ return NumberFormat.decimalPattern().format(count);
+ }
+ }
+
void _showAudibleReviews(BuildContext context) {
final asin = _asin;
if (asin == null) return;