A cross platform Audiobookshelf client for Android and iOS
Dart
Add trust-all-certs toggle for self-signed certificates (#107), fix fetchAll pagination
Nathan Poulsonf6adaf4d9f41
diff --git a/lib/main.dart b/lib/main.dartindex b4e9f360..9116d8da 100644--- a/lib/main.dart+++ b/lib/main.dart@@ -44,6 +44,22 @@ final ValueNotifier<String> colorSourceNotifier = ValueNotifier('wallpaper');/// null when nothing is playing or cover hasn't loaded yet.final ValueNotifier<ColorScheme?> coverSchemeNotifier = ValueNotifier(null);+/// Allows Dart's HTTP stack to trust user-installed / self-signed certificates.+/// Android's network_security_config.xml only covers the native layer; Dart's+/// BoringSSL ignores it, so we override badCertificateCallback globally.+class _TrustAllCertsOverrides extends HttpOverrides {+ @override+ HttpClient createHttpClient(SecurityContext? context) {+ return super.createHttpClient(context)+ ..badCertificateCallback = (_, __, ___) => true;+ }+}++/// Enable or disable the global trust-all-certs override.+void applyTrustAllCerts(bool enabled) {+ HttpOverrides.global = enabled ? _TrustAllCertsOverrides() : null;+}+/// Global key so non-widget code (e.g. providers) can show snackbars.final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =GlobalKey<ScaffoldMessengerState>();@@ -100,6 +116,13 @@ void main() async {}} catch (_) {}+ // Trust user-installed / self-signed certificates if the user opted in+ try {+ if (await PlayerSettings.getTrustAllCerts()) {+ applyTrustAllCerts(true);+ }+ } catch (_) {}+// Capture Flutter framework errors (widget build failures, etc.)FlutterError.onError = (details) {FlutterError.presentError(details);diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dartindex 746c5710..ba82a2d7 100644--- a/lib/screens/library_screen.dart+++ b/lib/screens/library_screen.dart@@ -414,51 +414,78 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMifinal useClientFilter = _filter == LibraryFilter.downloaded;final fetchAll = _sort == LibrarySort.random || useClientFilter;- final limit = fetchAll ? 1000 : _pageSize;- final result = await api.getLibraryItems(- lib.selectedLibraryId!,- page: fetchAll ? 0 : _page,- limit: limit,- sort: sort,- desc: desc,- filter: filter,- collapseSeries: _collapseSeries && !useClientFilter && !lib.isPodcastLibrary,- );-- if (result != null && mounted && gen == _loadGeneration) {- final results = (result['results'] as List<dynamic>?) ?? [];- final total = (result['total'] as int?) ?? 0;- setState(() {- _totalItems = total;+ if (fetchAll) {+ // Paginate through ALL items for client-side filters / random sort+ const fetchLimit = 500;+ int fetchPage = 0;+ int total = 0;+ while (mounted && gen == _loadGeneration) {+ final result = await api.getLibraryItems(+ lib.selectedLibraryId!,+ page: fetchPage,+ limit: fetchLimit,+ sort: sort,+ desc: desc,+ filter: filter,+ collapseSeries: _collapseSeries && !useClientFilter && !lib.isPodcastLibrary,+ );+ if (result == null || !mounted || gen != _loadGeneration) break;+ final results = (result['results'] as List<dynamic>?) ?? [];+ total = (result['total'] as int?) ?? 0;for (final r in results) {if (r is Map<String, dynamic>) {- // Register updatedAt for cover cache-bustingfinal id = r['id'] as String?;final ts = r['updatedAt'] as num?;if (id != null && ts != null) lib.registerUpdatedAt(id, ts.toInt());- // Client-side filters- if (_filter == LibraryFilter.downloaded) {- final id = r['id'] as String? ?? '';- if (!DownloadService().isDownloaded(id)) continue;- }+ if (useClientFilter && !DownloadService().isDownloaded(id ?? '')) continue;if (_hideEbookOnly && PlayerSettings.isEbookOnly(r)) continue;_items.add(r);}}- if (_sort == LibrarySort.random) {- _items.shuffle(Random(_randomSeed));+ fetchPage++;+ if (fetchPage * fetchLimit >= total) break;+ }+ if (mounted && gen == _loadGeneration) {+ setState(() {+ _totalItems = total;+ if (_sort == LibrarySort.random) _items.shuffle(Random(_randomSeed));_hasMore = false;- } else if (useClientFilter) {- _hasMore = false; // All loaded and filtered at once- } else {+ _isLoadingPage = false;+ });+ }+ } else {+ final result = await api.getLibraryItems(+ lib.selectedLibraryId!,+ page: _page,+ limit: _pageSize,+ sort: sort,+ desc: desc,+ filter: filter,+ collapseSeries: _collapseSeries && !lib.isPodcastLibrary,+ );++ if (result != null && mounted && gen == _loadGeneration) {+ final results = (result['results'] as List<dynamic>?) ?? [];+ final total = (result['total'] as int?) ?? 0;+ setState(() {+ _totalItems = total;+ for (final r in results) {+ if (r is Map<String, dynamic>) {+ final id = r['id'] as String?;+ final ts = r['updatedAt'] as num?;+ if (id != null && ts != null) lib.registerUpdatedAt(id, ts.toInt());+ if (_hideEbookOnly && PlayerSettings.isEbookOnly(r)) continue;+ _items.add(r);+ }+ }_page++;_hasMore = _items.length < total;- }- _isLoadingPage = false;- });- } else if (mounted && gen == _loadGeneration) {- setState(() => _isLoadingPage = false);+ _isLoadingPage = false;+ });+ } else if (mounted && gen == _loadGeneration) {+ setState(() => _isLoadingPage = false);+ }}}diff --git a/lib/screens/login_screen.dart b/lib/screens/login_screen.dartindex a7719a47..f97c5df1 100644--- a/lib/screens/login_screen.dart+++ b/lib/screens/login_screen.dart@@ -12,7 +12,8 @@ import '../services/backup_service.dart';import '../services/oidc_service.dart';import '../services/user_account_service.dart';import '../widgets/absorb_wave_icon.dart';-import '../main.dart' show oledNotifier;+import '../services/audio_player_service.dart';+import '../main.dart' show applyTrustAllCerts, oledNotifier;class LoginScreen extends StatefulWidget {const LoginScreen({super.key});@@ -48,6 +49,7 @@ class _LoginScreenState extends State<LoginScreen>// Custom headers (advanced)bool _showAdvanced = false;+ bool _trustAllCerts = false;final List<(TextEditingController, TextEditingController)> _headerControllers = [];// App version@@ -82,6 +84,10 @@ class _LoginScreenState extends State<LoginScreen>final info = await PackageInfo.fromPlatform();if (mounted) setState(() => _appVersion = 'v${info.version}');} catch (_) {}+ try {+ final trust = await PlayerSettings.getTrustAllCerts();+ if (mounted) setState(() => _trustAllCerts = trust);+ } catch (_) {}}@override@@ -584,6 +590,32 @@ class _LoginScreenState extends State<LoginScreen>),),),+ const SizedBox(height: 8),+ const Divider(height: 1),+ const SizedBox(height: 4),+ Text('Self-signed Certificates', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant.withValues(alpha: 0.7))),+ Row(+ children: [+ Expanded(+ child: Text(+ 'Trust all certificates (for self-signed / custom CA setups)',+ style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant.withValues(alpha: 0.4)),+ ),+ ),+ Transform.scale(+ scale: 0.8,+ child: Switch(+ value: _trustAllCerts,+ onChanged: (v) async {+ setState(() => _trustAllCerts = v);+ await PlayerSettings.setTrustAllCerts(v);+ applyTrustAllCerts(v);+ _revalidateServer();+ },+ ),+ ),+ ],+ ),],// SSO / OIDC button — only shown when server supports itdiff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dartindex 811443f6..64b36973 100644--- a/lib/screens/settings_screen.dart+++ b/lib/screens/settings_screen.dart@@ -21,7 +21,7 @@ import '../screens/app_shell.dart';import '../screens/admin_screen.dart';import '../screens/downloads_screen.dart';import '../screens/bookmarks_screen.dart';-import '../main.dart' show applyThemeMode, oledNotifier, snappyTransitionsNotifier, colorSourceNotifier;+import '../main.dart' show applyThemeMode, applyTrustAllCerts, oledNotifier, snappyTransitionsNotifier, colorSourceNotifier;import '../widgets/absorb_page_header.dart';import '../widgets/absorb_slider.dart';@@ -77,6 +77,7 @@ class _SettingsScreenState extends State<SettingsScreen> {String _localServerUrl = '';late final TextEditingController _localServerController;bool _disableAudioFocus = false;+ bool _trustAllCerts = false;bool _loaded = false;String _downloadLocationLabel = 'App Internal Storage (Default)';int _totalDownloadSizeBytes = 0;@@ -163,6 +164,7 @@ class _SettingsScreenState extends State<SettingsScreen> {PlayerSettings.getPodcastQueueMode(), // 37PlayerSettings.getCardButtonLayout(), // 38PlayerSettings.getRectangleCovers(), // 39+ PlayerSettings.getTrustAllCerts(), // 40]);final s = results[0] as AutoRewindSettings;final speed = results[1] as double;@@ -204,6 +206,7 @@ class _SettingsScreenState extends State<SettingsScreen> {final podcastQueueMode = results[37] as String;final cardBtnLayout = results[38] as String;final rectCovers = results[39] as bool;+ final trustCerts = results[40] as bool;if (mounted) setState(() {_rewindSettings = s;_defaultSpeed = speed;@@ -249,6 +252,7 @@ class _SettingsScreenState extends State<SettingsScreen> {_startScreen = startScreen;_cardButtonLayout = cardBtnLayout;_rectangleCovers = rectCovers;+ _trustAllCerts = trustCerts;_loaded = true;});}@@ -1893,6 +1897,27 @@ class _SettingsScreenState extends State<SettingsScreen> {}} : null,),+ const Divider(height: 1, indent: 16, endIndent: 16),+ SwitchListTile(+ title: Row(children: [+ const Text('Trust all certificates'),+ _infoIcon('Self-signed Certificates',+ 'Enable this if your Audiobookshelf server uses a self-signed certificate or a custom root CA. '+ 'When enabled, Absorb will skip TLS certificate verification for all connections. '+ 'Only enable this if you trust your network.'),+ ]),+ subtitle: Text(+ _trustAllCerts+ ? 'On - accepting all certificates'+ : 'Off - only trusted certificates accepted',+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ value: _trustAllCerts,+ onChanged: _loaded ? (v) async {+ setState(() => _trustAllCerts = v);+ await PlayerSettings.setTrustAllCerts(v);+ applyTrustAllCerts(v);+ } : null,+ ),],),const SizedBox(height: 16),diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dartindex 1a59aefd..4eeab79d 100644--- a/lib/services/backup_service.dart+++ b/lib/services/backup_service.dart@@ -63,6 +63,7 @@ class BackupService {'authorSort': await PlayerSettings.getAuthorSort(),'authorSortAsc': await PlayerSettings.getAuthorSortAsc(),'disableAudioFocus': await PlayerSettings.getDisableAudioFocus(),+ 'trustAllCerts': await PlayerSettings.getTrustAllCerts(),'localServerEnabled': await PlayerSettings.getLocalServerEnabled(),'localServerUrl': await PlayerSettings.getLocalServerUrl(),'startScreen': await PlayerSettings.getStartScreen(),@@ -244,6 +245,7 @@ class BackupService {if (s['authorSort'] != null) PlayerSettings.setAuthorSort(s['authorSort'] as String);if (s['authorSortAsc'] != null) PlayerSettings.setAuthorSortAsc(s['authorSortAsc'] as bool);if (s['disableAudioFocus'] != null) PlayerSettings.setDisableAudioFocus(s['disableAudioFocus'] as bool);+ if (s['trustAllCerts'] != null) PlayerSettings.setTrustAllCerts(s['trustAllCerts'] as bool);if (s['localServerEnabled'] != null) PlayerSettings.setLocalServerEnabled(s['localServerEnabled'] as bool);if (s['localServerUrl'] != null) PlayerSettings.setLocalServerUrl(s['localServerUrl'] as String);if (s['startScreen'] != null) PlayerSettings.setStartScreen(s['startScreen'] as int);diff --git a/pubspec.yaml b/pubspec.yamlindex b1cc5c75..3a359318 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -1,7 +1,7 @@name: absorbdescription: A Material 3 Audiobookshelf client.publish_to: 'none'-version: 1.8.18+46+version: 1.8.19+47environment:sdk: '>=3.1.0 <4.0.0'