A cross platform Audiobookshelf client for Android and iOS
Dart
Add local server auto-switch on WiFi
Nathan Poulson6584e4b716de
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dartindex 0ebadf42..1614b928 100644--- a/lib/providers/auth_provider.dart+++ b/lib/providers/auth_provider.dart@@ -4,6 +4,7 @@ import 'package:shared_preferences/shared_preferences.dart';import '../services/api_service.dart';import '../services/android_auto_service.dart';import '../services/audio_player_service.dart';+import '../services/socket_service.dart';import '../services/user_account_service.dart';class AuthProvider extends ChangeNotifier {@@ -18,6 +19,11 @@ class AuthProvider extends ChangeNotifier {bool _serverReachable = true;Map<String, String> _customHeaders = {};+ // Local server auto-switch+ String _localServerUrl = '';+ bool _localServerEnabled = false;+ bool _useLocalServer = false;+bool _isLoading = true;String? _errorMessage;@@ -27,6 +33,10 @@ class AuthProvider extends ChangeNotifier {bool get serverReachable => _serverReachable;String? get token => _token;String? get serverUrl => _serverUrl;+ String? get activeServerUrl => (_useLocalServer && _localServerUrl.isNotEmpty) ? _localServerUrl : _serverUrl;+ bool get useLocalServer => _useLocalServer;+ bool get localServerEnabled => _localServerEnabled;+ String get localServerUrl => _localServerUrl;String? get username => _username;String? get userId => _userId;String? get defaultLibraryId => _defaultLibraryId;@@ -43,8 +53,9 @@ class AuthProvider extends ChangeNotifier {bool get isRoot => _userJson?['type'] == 'root';ApiService? get apiService {- if (_serverUrl != null && _token != null) {- return ApiService(baseUrl: _serverUrl!, token: _token!, customHeaders: _customHeaders);+ final url = activeServerUrl;+ if (url != null && _token != null) {+ return ApiService(baseUrl: url, token: _token!, customHeaders: _customHeaders);}return null;}@@ -85,6 +96,9 @@ class AuthProvider extends ChangeNotifier {} catch (_) {}}+ // Load local server config+ await _loadLocalServerSettings();+// Check if server is actually reachabledebugPrint('[Auth] pinging server... (${sw.elapsedMilliseconds}ms)');final reachable = await ApiService.pingServer(savedUrl, customHeaders: _customHeaders);@@ -265,6 +279,51 @@ class AuthProvider extends ChangeNotifier {return true;}+ /// Load local server settings from PlayerSettings.+ Future<void> _loadLocalServerSettings() async {+ _localServerEnabled = await PlayerSettings.getLocalServerEnabled();+ _localServerUrl = await PlayerSettings.getLocalServerUrl();+ }++ /// Check if the configured local server is reachable.+ /// Called on WiFi connectivity changes by LibraryProvider.+ Future<void> checkLocalServer() async {+ if (!_localServerEnabled || _localServerUrl.isEmpty || _serverUrl == null) return;+ final wasLocal = _useLocalServer;+ try {+ final reachable = await ApiService.pingServer(_localServerUrl, customHeaders: _customHeaders)+ .timeout(const Duration(seconds: 3), onTimeout: () => false);+ _useLocalServer = reachable;+ } catch (_) {+ _useLocalServer = false;+ }+ if (_useLocalServer != wasLocal) {+ debugPrint('[Auth] Local server switch: useLocal=$_useLocalServer');+ SocketService().switchServer(activeServerUrl!);+ notifyListeners();+ }+ }++ /// Revert to the remote server URL (e.g. when WiFi disconnects).+ void clearLocalOverride() {+ if (!_useLocalServer) return;+ _useLocalServer = false;+ debugPrint('[Auth] Cleared local server override, back to remote');+ if (_serverUrl != null) {+ SocketService().switchServer(_serverUrl!);+ }+ notifyListeners();+ }++ /// Update local server settings from the UI.+ Future<void> setLocalServerConfig({required bool enabled, required String url}) async {+ _localServerEnabled = enabled;+ _localServerUrl = url;+ await PlayerSettings.setLocalServerEnabled(enabled);+ await PlayerSettings.setLocalServerUrl(url);+ if (!enabled) clearLocalOverride();+ }+/// Logout and clear stored session./// Fetch server version asynchronously (non-blocking).void _fetchServerVersion(String url) async {diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex 57bc2d81..26fad93a 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -548,14 +548,20 @@ class LibraryProvider extends ChangeNotifier {if (!hasConnectivity) {_stopServerPingTimer();setNetworkOffline(true);+ _auth?.clearLocalOverride();} else if (!_manualOffline) {// Connectivity restored — optimistically go online; if server is still// down the API call will fail and _goOfflineWithPing() will be called.setNetworkOffline(false);- // WiFi restored — catch up on any pending rolling downloadsif (result.contains(ConnectivityResult.wifi)) {+ // WiFi available — check if local server is reachable+ _auth?.checkLocalServer();if (_rollingDownloadSeries.isNotEmpty) _catchUpRollingDownloads();_catchUpQueueAutoDownloads();+ } else {+ // WiFi dropped but still have connectivity (e.g. mobile data) —+ // local server won't be reachable, revert to remote URL.+ _auth?.clearLocalOverride();}}});diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dartindex eceef858..809b4ae4 100644--- a/lib/screens/settings_screen.dart+++ b/lib/screens/settings_screen.dart@@ -10,6 +10,7 @@ import 'package:package_info_plus/package_info_plus.dart';import 'package:just_audio/just_audio.dart' show AudioPlayer;import '../providers/auth_provider.dart';import '../providers/library_provider.dart';+import '../services/api_service.dart';import '../services/audio_player_service.dart';import '../services/download_service.dart';import '../services/sleep_timer_service.dart';@@ -59,6 +60,9 @@ class _SettingsScreenState extends State<SettingsScreen> {bool _snappyTransitions = false;String _themeMode = 'dark';int _streamingCacheSizeMb = 0;+ bool _localServerEnabled = false;+ String _localServerUrl = '';+ bool _disableAudioFocus = false;bool _loaded = false;String _downloadLocationLabel = 'App Internal Storage (Default)';int _totalDownloadSizeBytes = 0;@@ -129,6 +133,9 @@ class _SettingsScreenState extends State<SettingsScreen> {AutoSleepSettings.load(), // 28PackageInfo.fromPlatform(), // 29PlayerSettings.getStreamingCacheSizeMb(), // 30+ PlayerSettings.getLocalServerEnabled(), // 31+ PlayerSettings.getLocalServerUrl(), // 32+ PlayerSettings.getDisableAudioFocus(), // 33]);final s = results[0] as AutoRewindSettings;final speed = results[1] as double;@@ -161,6 +168,9 @@ class _SettingsScreenState extends State<SettingsScreen> {final autoSleep = results[28] as AutoSleepSettings;final pkgInfo = results[29] as PackageInfo;final cacheSizeMb = results[30] as int;+ final localEnabled = results[31] as bool;+ final localUrl = results[32] as String;+ final audioFocusOff = results[33] as bool;if (mounted) setState(() {_rewindSettings = s;_defaultSpeed = speed;@@ -196,6 +206,9 @@ class _SettingsScreenState extends State<SettingsScreen> {_autoSleepSettings = autoSleep;_appVersion = pkgInfo.version;_streamingCacheSizeMb = cacheSizeMb;+ _localServerEnabled = localEnabled;+ _localServerUrl = localUrl;+ _disableAudioFocus = audioFocusOff;_loaded = true;});}@@ -1495,6 +1508,130 @@ class _SettingsScreenState extends State<SettingsScreen> {),const SizedBox(height: 16),+ // ── Advanced ──+ _CollapsibleSection(+ key: _keyFor('Advanced'),+ icon: Icons.tune_rounded,+ title: 'Advanced',+ cs: cs,+ isExpanded: _expandedSection == 'Advanced',+ onExpansionChanged: (v) => _onSectionExpanded('Advanced', v),+ children: [+ SwitchListTile(+ title: const Text('Local server'),+ subtitle: Text(+ _localServerEnabled+ ? (auth.useLocalServer+ ? 'Connected via local server'+ : 'Enabled - using remote server')+ : 'Auto-switch to a LAN server on your home WiFi',+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ value: _localServerEnabled,+ onChanged: _loaded ? (v) {+ setState(() => _localServerEnabled = v);+ auth.setLocalServerConfig(enabled: v, url: _localServerUrl);+ } : null,+ ),+ if (_localServerEnabled) ...[+ const Divider(height: 1, indent: 16, endIndent: 16),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),+ child: TextField(+ controller: TextEditingController(text: _localServerUrl),+ decoration: InputDecoration(+ labelText: 'Local server URL',+ hintText: 'http://192.168.1.100:13378',+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),+ suffixIcon: IconButton(+ icon: const Icon(Icons.check_rounded),+ tooltip: 'Save',+ onPressed: () {+ // URL is saved via onChanged+ FocusScope.of(context).unfocus();+ ScaffoldMessenger.of(context).showSnackBar(+ SnackBar(+ content: const Text('Local server URL saved'),+ behavior: SnackBarBehavior.floating,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ ),+ );+ },+ ),+ ),+ onChanged: (v) {+ _localServerUrl = v.trim();+ auth.setLocalServerConfig(enabled: _localServerEnabled, url: _localServerUrl);+ },+ ),+ ),+ const Divider(height: 1, indent: 16, endIndent: 16),+ ListTile(+ leading: Icon(Icons.wifi_find_rounded, color: cs.primary),+ title: const Text('Test local connection'),+ subtitle: Text(+ auth.useLocalServer ? 'Currently using local server' : 'Tap to ping the local server',+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ trailing: auth.useLocalServer+ ? Icon(Icons.check_circle_rounded, color: Colors.greenAccent.shade400)+ : Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant),+ onTap: () async {+ if (_localServerUrl.isEmpty) {+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(+ content: const Text('Enter a local server URL first'),+ behavior: SnackBarBehavior.floating,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ ));+ return;+ }+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(+ content: const Text('Pinging local server...'),+ duration: const Duration(seconds: 1),+ behavior: SnackBarBehavior.floating,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ ));+ final reachable = await ApiService.pingServer(_localServerUrl)+ .timeout(const Duration(seconds: 3), onTimeout: () => false);+ if (!mounted) return;+ ScaffoldMessenger.of(context).clearSnackBars();+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(+ content: Text(reachable+ ? 'Local server is reachable'+ : 'Could not reach local server'),+ behavior: SnackBarBehavior.floating,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ ));+ if (reachable) {+ await auth.checkLocalServer();+ if (mounted) setState(() {});+ }+ },+ ),+ ],+ const Divider(height: 1, indent: 16, endIndent: 16),+ SwitchListTile(+ title: const Text('Disable audio focus'),+ subtitle: Text(+ _disableAudioFocus+ ? 'On - plays alongside other audio (still pauses for calls)'+ : 'Off - other audio pauses when Absorb plays',+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ value: _disableAudioFocus,+ onChanged: _loaded ? (v) {+ setState(() => _disableAudioFocus = v);+ PlayerSettings.setDisableAudioFocus(v);+ ScaffoldMessenger.of(context).showSnackBar(SnackBar(+ content: Text(v+ ? 'Audio focus disabled - restart app to apply'+ : 'Audio focus enabled - restart app to apply'),+ behavior: SnackBarBehavior.floating,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),+ ));+ } : null,+ ),+ ],+ ),+ const SizedBox(height: 16),+// ── Support the Dev ──Padding(padding: const EdgeInsets.symmetric(horizontal: 16),diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex 838818ff..8d0f6f01 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -16,6 +16,7 @@ import 'equalizer_service.dart';import 'android_auto_service.dart';import 'chromecast_service.dart';import 'scoped_prefs.dart';+import '../widgets/card_button_config.dart';// ─── Auto-rewind settings ───@@ -246,14 +247,33 @@ class PlayerSettings {static Future<bool> getSnappyTransitions() => _get('snappyTransitions', false);static Future<void> setSnappyTransitions(bool value) => _set('snappyTransitions', value);+ // ── Audio focus ──++ static Future<bool> getDisableAudioFocus() => _get('disableAudioFocus', false);+ static Future<void> setDisableAudioFocus(bool value) => _set('disableAudioFocus', value);++ // ── Local server ──++ static Future<bool> getLocalServerEnabled() => _get('localServerEnabled', false);+ static Future<void> setLocalServerEnabled(bool value) => _set('localServerEnabled', value);++ static Future<String> getLocalServerUrl() => _get('localServerUrl', '');+ static Future<void> setLocalServerUrl(String value) => _set('localServerUrl', value);+// ── Card button order ──- static const defaultButtonOrder = ['chapters', 'speed', 'sleep', 'bookmarks', 'details', 'equalizer', 'cast', 'history', 'remove'];+ static const defaultButtonOrder = ['chapters', 'speed', 'sleep', 'bookmarks', 'details', 'equalizer', 'cast', 'history', 'remove', 'car'];static Future<List<String>> getCardButtonOrder() async {final stored = await ScopedPrefs.getStringList('card_button_order');- if (stored.isNotEmpty && stored.length == defaultButtonOrder.length) return stored;- return List.from(defaultButtonOrder);+ if (stored.isEmpty) return List.from(defaultButtonOrder);+ // Append any new buttons that were added since the user last saved their order+ final knownIds = allCardButtons.map((b) => b.id).toSet();+ final result = stored.where((id) => knownIds.contains(id)).toList();+ for (final b in allCardButtons) {+ if (!result.contains(b.id)) result.add(b.id);+ }+ return result;}static Future<void> setCardButtonOrder(List<String> order) async {@@ -1177,8 +1197,60 @@ class AudioPlayerService extends ChangeNotifier {/// starting new playback to avoid blasting audio on the phone speaker.static bool get wasNoisyPause => _noisyPause;+ static bool _audioFocusDisabled = false;+static Future<void> _configureAudioSession() async {+ _audioFocusDisabled = await PlayerSettings.getDisableAudioFocus();final session = await AudioSession.instance;++ if (_audioFocusDisabled) {+ // Allow mixing with other audio - don't request exclusive focus+ await session.configure(const AudioSessionConfiguration(+ avAudioSessionCategory: AVAudioSessionCategory.playback,+ avAudioSessionMode: AVAudioSessionMode.defaultMode,+ avAudioSessionCategoryOptions: AVAudioSessionCategoryOptions.mixWithOthers,+ androidAudioAttributes: AndroidAudioAttributes(+ contentType: AndroidAudioContentType.music,+ usage: AndroidAudioUsage.media,+ ),+ androidAudioFocusGainType: AndroidAudioFocusGainType.gainTransientMayDuck,+ ));+ debugPrint('[AudioSession] Audio focus disabled - mixing with other apps');++ // Still pause for phone calls (AudioInterruptionType.pause)+ _interruptSub?.cancel();+ _interruptSub = session.interruptionEventStream.listen((event) async {+ final service = _instance;+ if (event.type != AudioInterruptionType.pause) return;+ if (event.begin) {+ if (service.isPlaying) {+ debugPrint('[AudioSession] Phone call - pausing');+ await service._player?.pause();+ service._wasPlayingBeforeInterrupt = true;+ }+ } else if (service._wasPlayingBeforeInterrupt) {+ service._wasPlayingBeforeInterrupt = false;+ await Future.delayed(const Duration(milliseconds: 600));+ debugPrint('[AudioSession] Phone call ended - resuming');+ await service.play();+ }+ });++ // Still pause when headphones/BT disconnect+ _noisySub?.cancel();+ _noisySub = session.becomingNoisyEventStream.listen((_) async {+ final service = _instance;+ debugPrint('[AudioSession] Becoming noisy - pausing');+ _noisyPause = true;+ service._wasPlayingBeforeInterrupt = false;+ _handler?.cancelPendingClick();+ if (service.isPlaying) {+ await service.pause();+ }+ });+ return;+ }+await session.configure(const AudioSessionConfiguration.speech());await session.setActive(true);@@ -2180,7 +2252,9 @@ class AudioPlayerService extends ChangeNotifier {}_lastPauseTime = null;// Re-activate audio session (needed after stop() releases it)- try { (await AudioSession.instance).setActive(true); } catch (_) {}+ if (!_audioFocusDisabled) {+ try { (await AudioSession.instance).setActive(true); } catch (_) {}+ }_player?.play();_logEvent(PlaybackEventType.play);_onPlaybackStateChangedCallback?.call(true);@@ -2345,7 +2419,9 @@ class AudioPlayerService extends ChangeNotifier {SleepTimerService().cancel();}// Release audio focus so other apps can use it- try { (await AudioSession.instance).setActive(false); } catch (_) {}+ if (!_audioFocusDisabled) {+ try { (await AudioSession.instance).setActive(false); } catch (_) {}+ }}/// Stop playback without saving progress — used by reset progress.diff --git a/lib/services/socket_service.dart b/lib/services/socket_service.dartindex 8ac09df3..7d8d946f 100644--- a/lib/services/socket_service.dart+++ b/lib/services/socket_service.dart@@ -153,6 +153,19 @@ class SocketService {_socket = null;}+ /// Switch to a different server URL (e.g. local/remote swap).+ /// Does a soft disconnect then reconnect with the new URL.+ void switchServer(String newUrl) {+ if (_serverUrl == newUrl) return;+ debugPrint('[Socket] Switching server: $_serverUrl -> $newUrl');+ _serverUrl = newUrl;+ if (_socket != null) {+ _socket!.dispose();+ _socket = null;+ softReconnect();+ }+ }+/// Reconnect after a soft disconnect, reusing saved credentials.void softReconnect() {if (_socket != null) return; // already connected