A cross platform Audiobookshelf client for Android and iOS
Dart
Fix session sync reliability, admin user perf, and codec fallback
Nathan Poulson5ebfe060bde2
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dartindex dc2b5b86..5e495a35 100644--- a/lib/providers/auth_provider.dart+++ b/lib/providers/auth_provider.dart@@ -389,6 +389,9 @@ class AuthProvider extends ChangeNotifier {Future<void> _loadLocalServerSettings() async {_localServerEnabled = await PlayerSettings.getLocalServerEnabled();_localServerUrl = await PlayerSettings.getLocalServerUrl();+ if (_localServerEnabled) {+ debugPrint('[Auth] Local server config loaded: enabled=$_localServerEnabled, url=${_localServerUrl.isNotEmpty ? "(set)" : "(empty)"}');+ }}/// Check if the configured local server is reachable.diff --git a/lib/screens/admin_users_screen.dart b/lib/screens/admin_users_screen.dartindex 2ccd692a..8d3ba01c 100644--- a/lib/screens/admin_users_screen.dart+++ b/lib/screens/admin_users_screen.dart@@ -150,13 +150,17 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {List<dynamic> _sessions = [];bool _loadingSessions = false;bool _sessionsExpanded = false;+ int _visibleCount = 25;+ bool _fetchingMore = false;++ static const _pageSize = 25;@overridevoid initState() { super.initState(); _load(); }Future<void> _load() async {final api = context.read<AuthProvider>().apiService; if (api == null) return;- setState(() => _loading = true);+ setState(() { _loading = true; _visibleCount = _pageSize; });final userId = widget.user['id'] as String? ?? '';final userData = await api.getUser(userId);@@ -166,25 +170,8 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {final progress = (userData['mediaProgress'] as List<dynamic>?) ?? [];final items = <Map<String, dynamic>>[];- final fetchFutures = <Future>[];-for (final p in progress) {- if (p is Map<String, dynamic>) {- items.add(p);- final itemId = p['libraryItemId'] as String? ?? '';- if (itemId.isNotEmpty && !_itemCache.containsKey(itemId)) {- fetchFutures.add(- api.getLibraryItem(itemId).then((item) {- if (item != null) _itemCache[itemId] = item;- }),- );- }- }- }-- // Fetch items in batches of 15- for (var i = 0; i < fetchFutures.length; i += 15) {- await Future.wait(fetchFutures.skip(i).take(15));+ if (p is Map<String, dynamic>) items.add(p);}// Sort: in-progress first (by last update), then finished@@ -198,11 +185,44 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {});_progressItems = items;+ _itemCache.clear();++ // Only fetch item details for the first visible page+ await _fetchItemDetails(api, items.take(_pageSize).toList());}if (mounted) setState(() => _loading = false);}+ Future<void> _fetchItemDetails(dynamic api, List<Map<String, dynamic>> items) async {+ final futures = <Future>[];+ for (final p in items) {+ final itemId = p['libraryItemId'] as String? ?? '';+ if (itemId.isNotEmpty && !_itemCache.containsKey(itemId)) {+ futures.add(+ api.getLibraryItem(itemId).then((item) {+ if (item != null) _itemCache[itemId] = item;+ }),+ );+ }+ }+ for (var i = 0; i < futures.length; i += 15) {+ await Future.wait(futures.skip(i).take(15));+ }+ }++ Future<void> _loadMore() async {+ if (_fetchingMore) return;+ final api = context.read<AuthProvider>().apiService; if (api == null) return;+ setState(() => _fetchingMore = true);+ final nextItems = _progressItems.skip(_visibleCount).take(_pageSize).toList();+ await _fetchItemDetails(api, nextItems);+ if (mounted) setState(() {+ _visibleCount = (_visibleCount + _pageSize).clamp(0, _progressItems.length);+ _fetchingMore = false;+ });+ }+Future<void> _loadSessions() async {final api = context.read<AuthProvider>().apiService; if (api == null) return;final userId = widget.user['id'] as String? ?? '';@@ -373,7 +393,33 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {child: Text('Library Progress', style: tt.titleSmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.5), fontWeight: FontWeight.w600, letterSpacing: 0.5)),),- ..._progressItems.map((p) => _progressTile(cs, tt, p)),+ ..._progressItems.take(_visibleCount).map((p) => _progressTile(cs, tt, p)),+ if (_visibleCount < _progressItems.length)+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 4, 16, 12),+ child: GestureDetector(+ onTap: _fetchingMore ? null : _loadMore,+ child: Container(+ padding: const EdgeInsets.symmetric(vertical: 12),+ decoration: BoxDecoration(+ color: cs.surfaceContainerHigh,+ borderRadius: BorderRadius.circular(14),+ ),+ child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [+ if (_fetchingMore)+ SizedBox(width: 14, height: 14,+ child: CircularProgressIndicator(strokeWidth: 2, color: cs.onSurface.withValues(alpha: 0.3)))+ else+ Icon(Icons.expand_more_rounded, size: 16, color: cs.onSurface.withValues(alpha: 0.4)),+ const SizedBox(width: 8),+ Text(+ _fetchingMore ? 'Loading...' : 'Load More (${_progressItems.length - _visibleCount} remaining)',+ style: tt.bodySmall?.copyWith(+ color: cs.onSurface.withValues(alpha: 0.5), fontWeight: FontWeight.w600)),+ ]),+ ),+ ),+ ),],],),diff --git a/lib/services/api_service.dart b/lib/services/api_service.dartindex 3d80f603..ed8f412a 100644--- a/lib/services/api_service.dart+++ b/lib/services/api_service.dart@@ -613,16 +613,16 @@ class ApiService {return url;}- /// Sync playback progress.+ /// Sync playback progress. Returns true if sync succeeded./// POST /api/session/:id/sync- Future<void> syncPlaybackSession(+ Future<bool> syncPlaybackSession(String sessionId, {required double currentTime,required double duration,int timeListened = 60,}) async {try {- await _authPost(+ final response = await _authPost(Uri.parse('$_cleanBaseUrl/api/session/$sessionId/sync'),body: jsonEncode({'currentTime': currentTime,@@ -631,7 +631,10 @@ class ApiService {'progress': duration > 0 ? currentTime / duration : 0,}),timeout: const Duration(seconds: 10));- } catch (_) {}+ return response.statusCode == 200;+ } catch (_) {+ return false;+ }}/// Close a playback session.@@ -783,10 +786,10 @@ class ApiService {/// Start a playback session for a podcast episode./// POST /api/items/:itemId/play/:episodeIdFuture<Map<String, dynamic>?> startEpisodePlaybackSession(- String itemId, String episodeId) async {+ String itemId, String episodeId, {bool forceTranscode = false}) async {try {final url = '$_cleanBaseUrl/api/items/$itemId/play/$episodeId';- debugPrint('[ABS] Starting episode session: POST $url');+ debugPrint('[ABS] Starting episode session: POST $url (forceTranscode: $forceTranscode)');final response = await _authPost(Uri.parse(url),body: jsonEncode({@@ -798,8 +801,8 @@ class ApiService {'manufacturer': deviceManufacturer,'model': deviceModel,},- 'forceDirectPlay': true,- 'forceTranscode': false,+ 'forceDirectPlay': !forceTranscode,+ 'forceTranscode': forceTranscode,'mediaPlayer': 'unknown','supportedMimeTypes': ['audio/flac',diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex 86d272f7..8c4e3486 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -1645,6 +1645,82 @@ class AudioPlayerService extends ChangeNotifier {return null;} catch (e, stack) {debugPrint('[Player] Stream error: $e\n$stack');++ // If this looks like a codec/renderer error, retry with server-side+ // transcoding. Common with Dolby Atmos, EAC-3, multi-channel audio, etc.+ final errStr = e.toString();+ if (!forceStartTime && // avoid infinite retry loops (forceStartTime is reused as retry guard)+ (errStr.contains('MediaCodecAudioRenderer') ||+ errStr.contains('AudioTrack') ||+ errStr.contains('Decoder') ||+ errStr.contains('format_supported'))) {+ debugPrint('[Player] Codec error detected - retrying with server transcoding');+ _clearState();+ // Close the failed session+ if (_playbackSessionId != null) {+ try { await api.closePlaybackSession(_playbackSessionId!); } catch (_) {}+ _playbackSessionId = null;+ }+ // Retry with transcode+ final retrySession = _currentEpisodeId != null+ ? await api.startEpisodePlaybackSession(_currentItemId!, _currentEpisodeId!, forceTranscode: true)+ : await api.startPlaybackSession(itemId, forceTranscode: true);+ if (retrySession != null) {+ _playbackSessionId = retrySession['id'] as String?;+ _lastServerSync = DateTime.now();+ final retryTracks = retrySession['audioTracks'] as List<dynamic>?;+ if (retryTracks != null && retryTracks.isNotEmpty) {+ try {+ _currentTrackIndex = 0;+ _buildTrackOffsets(retryTracks);+ AudioSource retrySource;+ final audioHeaders = api.mediaHeaders;+ if (retryTracks.length == 1) {+ final track = retryTracks.first as Map<String, dynamic>;+ final contentUrl = track['contentUrl'] as String? ?? '';+ final fullUrl = api.buildTrackUrl(contentUrl);+ retrySource = AudioSource.uri(Uri.parse(fullUrl), headers: audioHeaders);+ } else {+ final sources = <AudioSource>[];+ for (final t in retryTracks) {+ final track = t as Map<String, dynamic>;+ final contentUrl = track['contentUrl'] as String? ?? '';+ final fullUrl = api.buildTrackUrl(contentUrl);+ sources.add(AudioSource.uri(Uri.parse(fullUrl), headers: audioHeaders));+ }+ retrySource = ConcatenatingAudioSource(children: sources);+ }+ await _player!.setAudioSource(retrySource);+ if (totalDuration > 0 && startTime >= totalDuration - 1.0) startTime = 0;+ if (startTime > 0) await _seekAbsolute(startTime);+ clearSeekTarget();+ _subscribeTrackIndex();+ final initChapter = _initChapterInfo(startTime);+ _pushMediaItem(itemId, title, author, coverUrl, totalDuration, chapter: initChapter);+ final bookSpeed = await PlayerSettings.getBookSpeed(itemId);+ final speed = bookSpeed ?? await PlayerSettings.getDefaultSpeed();+ await _player!.setSpeed(speed);+ debugPrint('[Player] Transcoded playback starting at ${speed}x');+ if (!_audioFocusDisabled) {+ try { (await AudioSession.instance).setActive(true); } catch (_) {}+ }+ _player!.play();+ notifyListeners();+ _setupSync();+ Future.delayed(const Duration(milliseconds: 500), () {+ _handler?.refreshPlaybackState();+ });+ final sleepTimer = SleepTimerService();+ sleepTimer.resetDismiss();+ sleepTimer.checkAutoSleep();+ return null;+ } catch (retryError) {+ debugPrint('[Player] Transcoded playback also failed: $retryError');+ }+ }+ }+ }+_clearState();return 'Playback failed: ${e.toString().split('\n').first}';}@@ -1864,6 +1940,7 @@ class AudioPlayerService extends ChangeNotifier {_lastSyncSecond = -1;_lastChapterCheckSec = -1;_lastKnownPositionSec = 0;+ _lastServerSync = DateTime.now();// Safety-net timer for position persistence when Android throttles the// Dart position stream in the background. The primary positionStream@@ -2222,6 +2299,7 @@ class AudioPlayerService extends ChangeNotifier {}DateTime _lastServerSync = DateTime.now();+ bool _syncRecoveryInProgress = false;Future<void> _syncToServer(Duration pos) async {if (_api == null || _playbackSessionId == null) return;@@ -2229,15 +2307,50 @@ class AudioPlayerService extends ChangeNotifier {final now = DateTime.now();final elapsed = now.difference(_lastServerSync).inSeconds.clamp(0, 300);_lastServerSync = now;+ debugPrint('[Player] Sync session ${_playbackSessionId!.substring(0, 8)}... | currentTime=${ct.toStringAsFixed(1)}s, timeListened=${elapsed}s');+ final ok = await _api!.syncPlaybackSession(+ _playbackSessionId!,+ currentTime: ct,+ duration: _totalDuration,+ timeListened: elapsed,+ );+ if (!ok && !_syncRecoveryInProgress) {+ debugPrint('[Player] Session sync failed - attempting recovery');+ _syncRecoveryInProgress = true;+ try {+ await _recoverSession(ct, elapsed);+ } finally {+ _syncRecoveryInProgress = false;+ }+ }+ }++ /// Try to start a new server session when the current one becomes invalid.+ Future<void> _recoverSession(double currentTime, int lostTimeListened) async {+ if (_api == null || _currentItemId == null) return;try {- debugPrint('[Player] Sync session ${_playbackSessionId!.substring(0, 8)}... | currentTime=${ct.toStringAsFixed(1)}s, timeListened=${elapsed}s');- await _api!.syncPlaybackSession(- _playbackSessionId!,- currentTime: ct,- duration: _totalDuration,- timeListened: elapsed,- );- } catch (_) {}+ final sessionData = _currentEpisodeId != null+ ? await _api!.startEpisodePlaybackSession(_currentItemId!, _currentEpisodeId!)+ : await _api!.startPlaybackSession(_currentItemId!);+ if (sessionData != null) {+ _playbackSessionId = sessionData['id'] as String?;+ debugPrint('[Player] Recovered session: $_playbackSessionId');+ // Re-sync the lost time to the new session+ if (_playbackSessionId != null && lostTimeListened > 0) {+ await _api!.syncPlaybackSession(+ _playbackSessionId!,+ currentTime: currentTime,+ duration: _totalDuration,+ timeListened: lostTimeListened,+ );+ }+ } else {+ debugPrint('[Player] Session recovery failed - no session returned');+ _playbackSessionId = null;+ }+ } catch (e) {+ debugPrint('[Player] Session recovery error: $e');+ }}DateTime? _lastPauseTime;@@ -2300,6 +2413,27 @@ class AudioPlayerService extends ChangeNotifier {}}_lastPauseTime = null;+ // Reset server sync clock so the first sync after resume doesn't+ // include pause duration as timeListened+ _lastServerSync = DateTime.now();+ // Re-create server session if it was closed (e.g. pause timeout)+ if (_playbackSessionId == null && _api != null && _currentItemId != null) {+ final prefs = await SharedPreferences.getInstance();+ final manualOffline = prefs.getBool('manual_offline_mode') ?? false;+ if (!manualOffline && !_isOfflineMode) {+ try {+ final sessionData = _currentEpisodeId != null+ ? await _api!.startEpisodePlaybackSession(_currentItemId!, _currentEpisodeId!)+ : await _api!.startPlaybackSession(_currentItemId!);+ if (sessionData != null) {+ _playbackSessionId = sessionData['id'] as String?;+ debugPrint('[Player] Re-created session on resume: $_playbackSessionId');+ }+ } catch (e) {+ debugPrint('[Player] Failed to re-create session on resume: $e');+ }+ }+ }// Re-activate audio session (needed after stop() releases it)if (!_audioFocusDisabled) {try { (await AudioSession.instance).setActive(true); } catch (_) {}diff --git a/lib/services/bookmark_service.dart b/lib/services/bookmark_service.dartindex ef77637d..bedd5ee2 100644--- a/lib/services/bookmark_service.dart+++ b/lib/services/bookmark_service.dart@@ -84,6 +84,8 @@ class BookmarkService {static const _keyPrefix = 'bookmarks_';// Track bookmarks not yet pushed to server (created offline)final Set<String> _unpushed = {}; // "itemId::position" keys+ // Track bookmarks deleted offline that need to be deleted on server+ final Map<String, Set<double>> _pendingDeletes = {}; // itemId -> positions/// Get all bookmarks for a book.Future<List<Bookmark>> getBookmarks(String itemId, {String sort = 'newest'}) async {@@ -212,8 +214,15 @@ class BookmarkService {debugPrint('[Bookmarks] Deleted bookmark $bookmarkId');// Delete on server- if (api != null && time != null) {- await api.deleteBookmark(itemId, time: time);+ if (time != null) {+ if (api != null) {+ final ok = await api.deleteBookmark(itemId, time: time);+ if (!ok) {+ _pendingDeletes.putIfAbsent(itemId, () => {}).add(time);+ }+ } else {+ _pendingDeletes.putIfAbsent(itemId, () => {}).add(time);+ }}}@@ -222,6 +231,15 @@ class BookmarkService {/// If [preloadedServerBookmarks] is provided, uses that instead of fetching.Future<void> syncBookmarks(String itemId, ApiService api, {List<Map<String, dynamic>>? preloadedServerBookmarks}) async {try {+ // Flush any pending deletes first+ final pendingDels = _pendingDeletes.remove(itemId);+ if (pendingDels != null) {+ for (final time in pendingDels) {+ await api.deleteBookmark(itemId, time: time);+ debugPrint('[Bookmarks] Flushed pending delete at ${time}s');+ }+ }+final serverBookmarks = preloadedServerBookmarks ?? await api.getServerBookmarks(itemId);if (serverBookmarks == null) return; // offline or error