A cross platform Audiobookshelf client for Android and iOS
Dart
Fix iOS download path migration, offline display, queue advance speed, and UI tweaks
Nathan Poulson4f9405f11139
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex 25d627d4..9e37d1a3 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -621,6 +621,10 @@ class LibraryProvider extends ChangeNotifier {// and seed counts so socket updates can detect future new episodes.Future.microtask(() => checkSubscribedPodcasts());+ // Always populate progress from cached auth data so offline+ // sections show correct progress instead of 0%.+ _buildProgressMap(auth);+// If server was unreachable on startup, force offline mode and pingif (!auth.serverReachable) {debugPrint('[Library] Server not reachable — going offline');@@ -628,11 +632,11 @@ class LibraryProvider extends ChangeNotifier {_buildOfflineSections();_isLoading = false;notifyListeners();+ // Overlay local playback progress (fresher than server data)+ refreshLocalProgress();if (_deviceHasConnectivity) _startServerPingTimer();return;}-- _buildProgressMap(auth);if (_api != null && !isOffline) {ProgressSyncService().flushPendingSync(api: _api!);ProgressSyncService().flushOfflineListeningTime(api: _api!);diff --git a/lib/screens/absorbing_screen.dart b/lib/screens/absorbing_screen.dartindex 708ab9c8..2ff4cfab 100644--- a/lib/screens/absorbing_screen.dart+++ b/lib/screens/absorbing_screen.dart@@ -75,9 +75,21 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {Future<void> _loadQueueMode() async {final lib = context.read<LibraryProvider>();- final mode = lib.isPodcastLibrary- ? await PlayerSettings.getPodcastQueueMode()- : await PlayerSettings.getBookQueueMode();+ String mode;+ if (_mergeLibraries) {+ // When merged, use the more restrictive of the two modes+ // (matches Settings screen's _mergedQueueMode logic)+ final bm = await PlayerSettings.getBookQueueMode();+ final pm = await PlayerSettings.getPodcastQueueMode();+ const order = ['off', 'manual', 'auto_next'];+ final bi = order.indexOf(bm);+ final pi = order.indexOf(pm);+ mode = order[(bi < pi ? bi : pi).clamp(0, 2)];+ } else {+ mode = lib.isPodcastLibrary+ ? await PlayerSettings.getPodcastQueueMode()+ : await PlayerSettings.getBookQueueMode();+ }if (mounted && mode != _queueMode) setState(() => _queueMode = mode);}@@ -532,16 +544,19 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {borderRadius: BorderRadius.circular(20),border: Border.all(color: subtleBorder),),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- if (_isSyncing)- SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 1.5, color: muted))- else- Icon(Icons.stop_rounded, size: 18, color: muted),- const SizedBox(width: 4),- Text('Stop', style: TextStyle(color: muted, fontSize: 13, fontWeight: FontWeight.w500)),- ],+ child: SizedBox(+ height: 20,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (_isSyncing)+ SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 1.5, color: muted))+ else+ Icon(Icons.stop_rounded, size: 18, color: muted),+ const SizedBox(width: 4),+ Text('Stop', style: TextStyle(color: muted, fontSize: 13, fontWeight: FontWeight.w500)),+ ],+ ),),),)@@ -570,22 +585,25 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {GestureDetector(onTap: () => _showReorderSheet(context, lib, books),child: Container(- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),decoration: BoxDecoration(color: subtleBg,- borderRadius: BorderRadius.circular(16),+ borderRadius: BorderRadius.circular(20),border: Border.all(color: subtleBorder),),- child: Row(mainAxisSize: MainAxisSize.min, children: [- Icon(Icons.reorder_rounded, size: 18, color: muted),- if (_queueMode != 'off') ...[- const SizedBox(width: 4),- Text(- _queueMode == 'auto_next' ? 'Auto' : 'Manual',- style: TextStyle(fontSize: 10, fontWeight: FontWeight.w600, color: cs.primary),- ),- ],- ]),+ child: SizedBox(+ height: 20,+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(Icons.reorder_rounded, size: 18, color: muted),+ if (_queueMode != 'off') ...[+ const SizedBox(width: 4),+ Text(+ _queueMode == 'auto_next' ? 'Auto' : 'Manual',+ style: TextStyle(fontSize: 10, fontWeight: FontWeight.w600, color: cs.primary),+ ),+ ],+ ]),+ ),),),],@@ -715,13 +733,19 @@ class _AbsorbingScreenState extends State<AbsorbingScreen> {lib: lib,absorbingKeyFn: _absorbingKey,queueMode: _queueMode,- onQueueModeChanged: (mode) {+ onQueueModeChanged: (mode) async {setState(() => _queueMode = mode);- final isPod = lib.isPodcastLibrary;- if (isPod) {- PlayerSettings.setPodcastQueueMode(mode);+ if (_mergeLibraries) {+ // Merged view: keep both types in sync+ await PlayerSettings.setBookQueueMode(mode);+ await PlayerSettings.setPodcastQueueMode(mode);} else {- PlayerSettings.setBookQueueMode(mode);+ final isPod = lib.isPodcastLibrary;+ if (isPod) {+ await PlayerSettings.setPodcastQueueMode(mode);+ } else {+ await PlayerSettings.setBookQueueMode(mode);+ }}PlayerSettings.notifySettingsChanged();},diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dartindex b2beba72..8e2719a5 100644--- a/lib/screens/home_screen.dart+++ b/lib/screens/home_screen.dart@@ -355,31 +355,34 @@ class _HomeScreenState extends State<HomeScreen> {color:cs.onSurface.withValues(alpha: 0.08)),),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Icon(- lib.isPodcastLibrary- ? Icons.podcasts_rounded- : Icons.auto_stories_rounded,- size: 18,- color: cs.onSurfaceVariant),- const SizedBox(width: 6),- ConstrainedBox(- constraints:- const BoxConstraints(maxWidth: 140),- child: Text(libraryName,- style: TextStyle(- fontSize: 13,- fontWeight: FontWeight.w600,- color: cs.onSurfaceVariant),- overflow: TextOverflow.ellipsis,- maxLines: 1),- ),- const SizedBox(width: 4),- Icon(Icons.unfold_more_rounded,- size: 18, color: cs.onSurfaceVariant),- ],+ child: SizedBox(+ height: 20,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(+ lib.isPodcastLibrary+ ? Icons.podcasts_rounded+ : Icons.auto_stories_rounded,+ size: 18,+ color: cs.onSurfaceVariant),+ const SizedBox(width: 6),+ ConstrainedBox(+ constraints:+ const BoxConstraints(maxWidth: 140),+ child: Text(libraryName,+ style: TextStyle(+ fontSize: 13,+ fontWeight: FontWeight.w600,+ color: cs.onSurfaceVariant),+ overflow: TextOverflow.ellipsis,+ maxLines: 1),+ ),+ const SizedBox(width: 4),+ Icon(Icons.unfold_more_rounded,+ size: 18, color: cs.onSurfaceVariant),+ ],+ ),),),),@@ -394,7 +397,7 @@ class _HomeScreenState extends State<HomeScreen> {borderRadius: BorderRadius.circular(20),border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),),- child: Icon(Icons.tune_rounded, size: 14, color: cs.onSurfaceVariant),+ child: SizedBox(height: 20, child: Icon(Icons.tune_rounded, size: 18, color: cs.onSurfaceVariant)),),),],diff --git a/lib/screens/library_screen.dart b/lib/screens/library_screen.dartindex d1848529..66ae5c5c 100644--- a/lib/screens/library_screen.dart+++ b/lib/screens/library_screen.dart@@ -384,11 +384,17 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMifinal auth = context.read<AuthProvider>();final lib = context.read<LibraryProvider>();final api = auth.apiService;- if (api == null || lib.selectedLibraryId == null) {+ if (lib.selectedLibraryId == null) {setState(() => _isLoadingPage = false);return;}+ // Offline fallback: show downloaded items instead of hitting the API+ if (api == null || lib.isOffline) {+ _loadOfflinePage(lib);+ return;+ }+String sort;int desc;switch (_sort) {@@ -498,6 +504,53 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMi}}+ /// Offline fallback: populate the grid from downloaded items.+ void _loadOfflinePage(LibraryProvider lib) {+ final isPodcast = lib.isPodcastLibrary;+ final downloads = DownloadService().downloadedItems+ .where((dl) => (dl.itemId.length > 36) == isPodcast)+ .toList();++ final items = <Map<String, dynamic>>[];+ for (final dl in downloads) {+ double duration = 0;+ List<dynamic> chapters = [];+ if (dl.sessionData != null) {+ try {+ final session = jsonDecode(dl.sessionData!) as Map<String, dynamic>;+ duration = (session['duration'] as num?)?.toDouble() ?? 0;+ chapters = session['chapters'] as List<dynamic>? ?? [];+ } catch (_) {}+ }+ items.add({+ 'id': dl.itemId,+ 'media': {+ 'metadata': {+ 'title': dl.title ?? 'Unknown Title',+ 'authorName': dl.author ?? '',+ },+ 'duration': duration,+ 'chapters': chapters,+ },+ });+ }++ // Sort alphabetically by title for a clean offline view+ items.sort((a, b) {+ final ta = ((a['media'] as Map)['metadata'] as Map)['title'] as String;+ final tb = ((b['media'] as Map)['metadata'] as Map)['title'] as String;+ return ta.toLowerCase().compareTo(tb.toLowerCase());+ });++ setState(() {+ _items.clear();+ _items.addAll(items);+ _totalItems = items.length;+ _hasMore = false;+ _isLoadingPage = false;+ });+ }+// ══════════════════════════════════════════════════════════════// SERIES TAB - Load a page of series// ══════════════════════════════════════════════════════════════@@ -1093,19 +1146,22 @@ class LibraryScreenState extends State<LibraryScreen> with TickerProviderStateMiborderRadius: BorderRadius.circular(20),border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Icon(lib.isPodcastLibrary ? Icons.podcasts_rounded : Icons.auto_stories_rounded, size: 18, color: cs.onSurfaceVariant),- const SizedBox(width: 6),- ConstrainedBox(- constraints: const BoxConstraints(maxWidth: 140),- child: Text(libraryName, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant),- overflow: TextOverflow.ellipsis, maxLines: 1),- ),- const SizedBox(width: 4),- Icon(Icons.unfold_more_rounded, size: 18, color: cs.onSurfaceVariant),- ],+ child: SizedBox(+ height: 20,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(lib.isPodcastLibrary ? Icons.podcasts_rounded : Icons.auto_stories_rounded, size: 18, color: cs.onSurfaceVariant),+ const SizedBox(width: 6),+ ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 140),+ child: Text(libraryName, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: cs.onSurfaceVariant),+ overflow: TextOverflow.ellipsis, maxLines: 1),+ ),+ const SizedBox(width: 4),+ Icon(Icons.unfold_more_rounded, size: 18, color: cs.onSurfaceVariant),+ ],+ ),),),),diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dartindex 381c5d39..dd1ebb91 100644--- a/lib/screens/settings_screen.dart+++ b/lib/screens/settings_screen.dart@@ -873,6 +873,7 @@ class _SettingsScreenState extends State<SettingsScreen> {});PlayerSettings.setBookQueueMode(s.first);PlayerSettings.setPodcastQueueMode(s.first);+ PlayerSettings.notifySettingsChanged();} : null,style: const ButtonStyle(visualDensity: VisualDensity.compact),)),@@ -891,6 +892,7 @@ class _SettingsScreenState extends State<SettingsScreen> {onSelectionChanged: _loaded ? (s) {setState(() => _bookQueueMode = s.first);PlayerSettings.setBookQueueMode(s.first);+ PlayerSettings.notifySettingsChanged();} : null,style: const ButtonStyle(visualDensity: VisualDensity.compact),)),@@ -909,6 +911,7 @@ class _SettingsScreenState extends State<SettingsScreen> {onSelectionChanged: _loaded ? (s) {setState(() => _podcastQueueMode = s.first);PlayerSettings.setPodcastQueueMode(s.first);+ PlayerSettings.notifySettingsChanged();} : null,style: const ButtonStyle(visualDensity: VisualDensity.compact),)),diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex 347fff0b..1294b736 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -1860,6 +1860,7 @@ class AudioPlayerService extends ChangeNotifier {final sleepTimer = SleepTimerService();sleepTimer.resetDismiss();sleepTimer.checkAutoSleep();+return null;} catch (e, stack) {debugPrint('[Player] Local play error: $e\n$stack');@@ -2477,28 +2478,33 @@ class AudioPlayerService extends ChangeNotifier {_bgSaveTimer = null;await _player?.stop();- // Mark as finished on the server+ // Mark as finished on the server (fire-and-forget to avoid blocking+ // auto-advance — the local save below is the source of truth).final itemId = _currentItemId;final episodeId = _currentEpisodeId;if (itemId != null && _api != null) {- try {- if (episodeId != null) {- await _api!.updateEpisodeProgress(- itemId, episodeId,- currentTime: _totalDuration,- duration: _totalDuration,- isFinished: true,- );- } else {- await _api!.markFinished(itemId, _totalDuration);+ final api = _api!;+ final dur = _totalDuration;+ unawaited(() async {+ try {+ if (episodeId != null) {+ await api.updateEpisodeProgress(+ itemId, episodeId,+ currentTime: dur,+ duration: dur,+ isFinished: true,+ );+ } else {+ await api.markFinished(itemId, dur);+ }+ debugPrint('[Player] Marked as finished on server');+ } catch (e) {+ debugPrint('[Player] Failed to mark finished: $e');}- debugPrint('[Player] Marked as finished on server');- } catch (e) {- debugPrint('[Player] Failed to mark finished: $e');- }+ }());}- // Also save locally as finished (use compound key for episodes)+ // Save locally as finished (fast, ensures offline correctness)if (itemId != null) {final progressKey = episodeId != null ? '$itemId-$episodeId' : itemId;await _progressSync.saveLocal(@@ -2510,12 +2516,16 @@ class AudioPlayerService extends ChangeNotifier {);}- // Close the playback session+ // Close the playback session (fire-and-forget)if (_playbackSessionId != null && _api != null) {- try {- debugPrint('[Player] Closing session (book finished)');- await _api!.closePlaybackSession(_playbackSessionId!);- } catch (_) {}+ final api = _api!;+ final sessionId = _playbackSessionId!;+ unawaited(() async {+ try {+ debugPrint('[Player] Closing session (book finished)');+ await api.closePlaybackSession(sessionId);+ } catch (_) {}+ }());}// Notify LibraryProvider before clearing state so it can update isFinished locally.diff --git a/lib/services/download_service.dart b/lib/services/download_service.dartindex ed1fc8d9..b1b61493 100644--- a/lib/services/download_service.dart+++ b/lib/services/download_service.dart@@ -315,6 +315,9 @@ class DownloadService extends ChangeNotifier {debugPrint('[Download] Init error: $e');}}+ // On iOS, remap paths when the app container UUID changes after updates+ await _migrateIOSPaths();+// Re-save to persist any metadata extracted from sessionDataif (_downloads.isNotEmpty) await _save();notifyListeners();@@ -323,6 +326,73 @@ class DownloadService extends ChangeNotifier {_validateDownloads();}+ /// On iOS, the app container UUID changes on every update, which breaks+ /// stored absolute paths. Detect stale prefixes and remap to the current+ /// container path so downloads survive TestFlight / App Store updates.+ Future<void> _migrateIOSPaths() async {+ if (!Platform.isIOS || _downloads.isEmpty) return;++ final appDir = await getApplicationDocumentsDirectory();+ final currentPrefix = appDir.path; // .../Documents++ bool changed = false;+ final entries = Map<String, DownloadInfo>.from(_downloads);++ for (final entry in entries.entries) {+ final info = entry.value;+ bool needsUpdate = false;++ // Remap localPaths+ final newPaths = <String>[];+ for (final path in info.localPaths) {+ final remapped = _remapIOSPath(path, currentPrefix);+ newPaths.add(remapped);+ if (remapped != path) needsUpdate = true;+ }++ final newCoverPath = info.localCoverPath != null+ ? _remapIOSPath(info.localCoverPath!, currentPrefix)+ : null;+ if (newCoverPath != info.localCoverPath) needsUpdate = true;++ final newDirPath = info.localDirPath != null+ ? _remapIOSPath(info.localDirPath!, currentPrefix)+ : null;+ if (newDirPath != info.localDirPath) needsUpdate = true;++ if (needsUpdate) {+ _downloads[entry.key] = DownloadInfo(+ itemId: info.itemId,+ status: info.status,+ localPaths: newPaths,+ sessionData: info.sessionData,+ title: info.title,+ author: info.author,+ coverUrl: info.coverUrl,+ localCoverPath: newCoverPath,+ localDirPath: newDirPath,+ );+ changed = true;+ }+ }++ if (changed) {+ debugPrint('[Download] Migrated iOS paths to current container');+ await _save();+ }+ }++ /// Replace a stale iOS container prefix with the current one.+ /// Paths contain `.../Documents/...` — we split on `/Documents/` and+ /// rejoin with the current prefix.+ String _remapIOSPath(String path, String currentPrefix) {+ if (path.startsWith(currentPrefix)) return path;+ final marker = '/Documents/';+ final idx = path.indexOf(marker);+ if (idx < 0) return path;+ return '$currentPrefix/${path.substring(idx + marker.length)}';+ }+/// Validate that downloaded files still exist on disk and clean up orphans./// Runs in background so it doesn't block app startup.Future<void> _validateDownloads() async {diff --git a/pubspec.yaml b/pubspec.yamlindex 280fb60b..0ffaf5b2 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -1,7 +1,7 @@name: absorbdescription: An Audiobookshelf Clientpublish_to: 'none'-version: 1.8.34+57+version: 1.8.35+58environment:sdk: '>=3.1.0 <4.0.0'