Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Add Audible region selector to Find Missing Books, persists choice

Nathan Poulsonbffc75251ac9
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 14c37477..3f56c599 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -203,6 +203,7 @@ class LibraryProvider extends ChangeNotifier
? bookLibraries.first['id']
: _libraries.first['id'];
}
+
await _loadSectionPrefs();
await loadPersonalizedView(force: true);
}
@@ -247,6 +248,7 @@ class LibraryProvider extends ChangeNotifier
AndroidAutoService().refresh(force: true);
}
+
Future<void> refresh() async {
if (isOffline) {
_buildOfflineSections();
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index a3da8ebd..6d77e092 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -8,11 +8,10 @@ import 'package:package_info_plus/package_info_plus.dart';
class ApiService {
static String appVersion = '1.3.0'; // fallback; overwritten by initVersion()
- /// Device country code (e.g. "us", "uk", "de") derived from the platform locale.
+ /// Audible region code derived from device locale.
static String get _region {
final locale = PlatformDispatcher.instance.locale;
final code = (locale.countryCode ?? 'us').toLowerCase();
- // Audnexus uses "uk" not "gb"
return code == 'gb' ? 'uk' : code;
}
@@ -1229,16 +1228,33 @@ class ApiService {
// ─── Audible Series Discovery ─────────────────────────────
+ /// Supported Audible regions for series discovery.
+ static const audibleRegions = {
+ 'us': 'Audible.com (US)',
+ 'uk': 'Audible.co.uk (UK)',
+ 'au': 'Audible.com.au (AU)',
+ 'ca': 'Audible.ca (CA)',
+ 'de': 'Audible.de (DE)',
+ 'fr': 'Audible.fr (FR)',
+ 'it': 'Audible.it (IT)',
+ 'es': 'Audible.es (ES)',
+ 'jp': 'Audible.co.jp (JP)',
+ 'in': 'Audible.in (IN)',
+ 'br': 'Audible.com.br (BR)',
+ };
+
/// Map region code to Audible API TLD.
- static String get _audibleTld {
+ static String _audibleTldFor(String region) {
const tlds = {
'us': '.com', 'uk': '.co.uk', 'gb': '.co.uk', 'au': '.com.au',
'ca': '.ca', 'de': '.de', 'fr': '.fr', 'it': '.it', 'es': '.es',
'jp': '.co.jp', 'in': '.in', 'br': '.com.br',
};
- return tlds[_region] ?? '.com';
+ return tlds[region] ?? '.com';
}
+ static String get _audibleTld => _audibleTldFor(_region);
+
/// Fetch full book metadata from Audnexus by ASIN.
/// Returns the raw Audnexus response including seriesPrimary, releaseDate, etc.
/// If [region] is provided, it overrides the device locale region.
@@ -1259,9 +1275,10 @@ class ApiService {
/// Get all book ASINs in an Audible series using the catalog relationships endpoint.
/// Returns a list of { asin, sequence, sort } maps.
- static Future<List<Map<String, dynamic>>> getAudibleSeriesBooks(String seriesAsin) async {
+ static Future<List<Map<String, dynamic>>> getAudibleSeriesBooks(String seriesAsin, {String? region}) async {
try {
- final url = 'https://api.audible$_audibleTld/1.0/catalog/products/$seriesAsin'
+ final tld = region != null ? _audibleTldFor(region) : _audibleTld;
+ final url = 'https://api.audible$tld/1.0/catalog/products/$seriesAsin'
'?response_groups=relationships';
debugPrint('[API] getAudibleSeriesBooks: $url');
final response = await http.get(Uri.parse(url))
@@ -1294,9 +1311,10 @@ class ApiService {
/// Fetch details for a single book from the Audible catalog API.
/// Returns title, authors, narrators, release_date, runtime, rating, cover, etc.
- static Future<Map<String, dynamic>?> getAudibleBookDetails(String asin) async {
+ static Future<Map<String, dynamic>?> getAudibleBookDetails(String asin, {String? region}) async {
try {
- final url = 'https://api.audible$_audibleTld/1.0/catalog/products/$asin'
+ final tld = region != null ? _audibleTldFor(region) : _audibleTld;
+ final url = 'https://api.audible$tld/1.0/catalog/products/$asin'
'?response_groups=product_attrs,product_desc,product_details,series,rating,media';
final response = await http.get(Uri.parse(url))
.timeout(const Duration(seconds: 10));
@@ -1316,8 +1334,8 @@ class ApiService {
/// Returns a list of book maps with: asin, title, subtitle, authors, narrators,
/// releaseDate, runtimeMinutes, rating, coverUrl, sequence.
/// Books are deduplicated by sequence (prefers user's region) and sorted.
- static Future<List<Map<String, dynamic>>> discoverAudibleSeries(String seriesAsin) async {
- final relationships = await getAudibleSeriesBooks(seriesAsin);
+ static Future<List<Map<String, dynamic>>> discoverAudibleSeries(String seriesAsin, {String? region}) async {
+ final relationships = await getAudibleSeriesBooks(seriesAsin, region: region);
if (relationships.isEmpty) return [];
final bySequence = <String, List<Map<String, dynamic>>>{};
@@ -1341,7 +1359,7 @@ class ApiService {
final batch = uniqueBooks.skip(i).take(10);
final futures = batch.map((book) async {
final asin = book['asin'] as String;
- final details = await getAudibleBookDetails(asin);
+ final details = await getAudibleBookDetails(asin, region: region);
if (details == null) return null;
final authors = (details['authors'] as List<dynamic>? ?? [])
diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dart
index 19ac660b..56181788 100644
--- a/lib/services/player_settings.dart
+++ b/lib/services/player_settings.dart
@@ -86,6 +86,11 @@ class PlayerSettings {
static Future<double> getDefaultSpeed() => _get('defaultSpeed', 1.0);
static Future<void> setDefaultSpeed(double speed) => _set('defaultSpeed', speed);
+ /// Audible region override for Find Missing Books (e.g. "us", "uk", "de").
+ /// Empty string means use device locale.
+ static Future<String> getAudibleRegion() => _get('audibleRegion', '');
+ static Future<void> setAudibleRegion(String value) => _set('audibleRegion', value);
+
static Future<bool> getWifiOnlyDownloads() => _get('wifiOnlyDownloads', false);
static Future<void> setWifiOnlyDownloads(bool value) => _set('wifiOnlyDownloads', value);
diff --git a/lib/widgets/audible_series_sheet.dart b/lib/widgets/audible_series_sheet.dart
index c3bb740c..198196aa 100644
--- a/lib/widgets/audible_series_sheet.dart
+++ b/lib/widgets/audible_series_sheet.dart
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../services/api_service.dart';
+import '../services/player_settings.dart';
import 'stackable_sheet.dart';
/// Show a bottom sheet with Audible series discovery results.
@@ -49,16 +50,27 @@ class _AudibleSeriesSheetState extends State<AudibleSeriesSheet> {
bool _isLoading = true;
String? _error;
int _filter = 0; // 0 = missing, 1 = upcoming, 2 = all
+ late String _region;
@override
void initState() {
super.initState();
+ _region = ApiService.debugRegion;
+ _loadRegionAndFetch();
+ }
+
+ Future<void> _loadRegionAndFetch() async {
+ final saved = await PlayerSettings.getAudibleRegion();
+ if (saved.isNotEmpty && ApiService.audibleRegions.containsKey(saved)) {
+ _region = saved;
+ }
_fetchSeries();
}
Future<void> _fetchSeries() async {
+ setState(() { _isLoading = true; _error = null; _allBooks = []; });
try {
- final books = await ApiService.discoverAudibleSeries(widget.seriesAsin);
+ final books = await ApiService.discoverAudibleSeries(widget.seriesAsin, region: _region);
if (!mounted) return;
if (books.isEmpty) {
setState(() { _isLoading = false; _error = 'No books found on Audible'; });
@@ -72,6 +84,61 @@ class _AudibleSeriesSheetState extends State<AudibleSeriesSheet> {
}
}
+ void _showRegionPicker() {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ showModalBottomSheet(
+ context: context,
+ backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
+ ),
+ isScrollControlled: true,
+ constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.6),
+ builder: (ctx) => SafeArea(
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
+ child: Column(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)))),
+ Text('Audible Region', style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),
+ const SizedBox(height: 12),
+ ]),
+ ),
+ Flexible(
+ child: ListView(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
+ shrinkWrap: true,
+ children: ApiService.audibleRegions.entries.map((e) => Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: GestureDetector(
+ onTap: () {
+ Navigator.pop(ctx);
+ if (e.key != _region) {
+ setState(() => _region = e.key);
+ PlayerSettings.setAudibleRegion(e.key);
+ _fetchSeries();
+ }
+ },
+ child: Container(height: 40,
+ decoration: BoxDecoration(
+ color: e.key == _region ? cs.primary.withValues(alpha: 0.15) : cs.onSurface.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(14),
+ border: Border.all(color: e.key == _region ? cs.primary.withValues(alpha: 0.3) : cs.onSurface.withValues(alpha: 0.1)),
+ ),
+ child: Center(child: Text(e.value, style: TextStyle(
+ color: e.key == _region ? cs.primary : cs.onSurfaceVariant,
+ fontSize: 13, fontWeight: FontWeight.w500)))),
+ ),
+ )).toList(),
+ ),
+ ),
+ ]),
+ ),
+ );
+ }
+
static final _parenthetical = RegExp(r'\s*\([^)]*\)\s*');
static final _nonAlphaNum = RegExp(r'[^a-z0-9 ]');
static final _multiSpace = RegExp(r'\s+');
@@ -170,6 +237,20 @@ class _AudibleSeriesSheetState extends State<AudibleSeriesSheet> {
'${_allBooks.length} on Audible · $missingCount missing${upcomingCount > 0 ? ' · $upcomingCount upcoming' : ''}',
style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant),
),
+ const SizedBox(height: 4),
+ GestureDetector(
+ onTap: _showRegionPicker,
+ child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.language_rounded, size: 12, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ const SizedBox(width: 4),
+ Text(
+ ApiService.audibleRegions[_region] ?? _region.toUpperCase(),
+ style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ ),
+ const SizedBox(width: 2),
+ Icon(Icons.arrow_drop_down_rounded, size: 14, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ ]),
+ ),
const SizedBox(height: 8),
// Filter toggle