Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Fix cross-client progress sync, home screen live progress, podcast sheet access, and sheet swipe-to-dismiss

Nathan Poulson11c0c3b7abaf
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index fc57f10d..e309d25d 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -698,8 +698,8 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
final playingKey = player.currentEpisodeId != null
? '${player.currentItemId}-${player.currentEpisodeId}'
: player.currentItemId;
- if (key == playingKey && player.hasBook) {
- if (mp['isFinished'] == true && !player.isPlaying) {
+ if (key == playingKey && player.hasBook && player.isPlaying) {
+ if (mp['isFinished'] == true) {
(this as _AbsorbingMixin).markFinishedLocally(key, skipAutoAdvance: true);
}
return;
diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart
index bf92d498..69863946 100644
--- a/lib/screens/home_screen.dart
+++ b/lib/screens/home_screen.dart
@@ -734,12 +734,22 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {
final progressData = episodeId != null
? lib.getEpisodeProgressData(itemId, episodeId)
: lib.getProgressData(itemId);
- final currentTime = (progressData?['currentTime'] as num?)?.toDouble() ?? 0;
- final totalDuration = (progressData?['duration'] as num?)?.toDouble() ??
- (recentEpisode != null
- ? (recentEpisode['duration'] as num?)?.toDouble() ?? 0
- : (media['duration'] as num?)?.toDouble() ?? 0);
final isCurrentItem = player.currentItemId == itemId;
+ final serverCurrentTime = (progressData?['currentTime'] as num?)?.toDouble() ?? 0;
+
+ // For the active item, prefer live player data over stale _progressMap
+ double currentTime;
+ double totalDuration;
+ if (isCurrentItem && player.hasBook) {
+ currentTime = player.position.inMilliseconds / 1000.0;
+ totalDuration = player.totalDuration;
+ } else {
+ currentTime = (progressData?['currentTime'] as num?)?.toDouble() ?? 0;
+ totalDuration = (progressData?['duration'] as num?)?.toDouble() ??
+ (recentEpisode != null
+ ? (recentEpisode['duration'] as num?)?.toDouble() ?? 0
+ : (media['duration'] as num?)?.toDouble() ?? 0);
+ }
return Material(
color: isCurrentItem
@@ -812,7 +822,19 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {
? null
: () {
if (isCurrentItem) {
- player.togglePlayPause();
+ if (player.isPlaying) {
+ player.pause();
+ } else {
+ // If server progress is ahead of the player's
+ // position (e.g. user listened on another client),
+ // re-start so the full server comparison runs.
+ final playerPosSec = player.position.inMilliseconds / 1000.0;
+ if (serverCurrentTime > playerPosSec + 5.0) {
+ _startBook(context, itemId);
+ } else {
+ player.play();
+ }
+ }
} else {
_startBook(context, itemId);
}
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 34373100..450eeea2 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -2443,22 +2443,46 @@ class AudioPlayerService extends ChangeNotifier {
// 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) {
+ // and check if server progress is ahead (e.g. user listened on another client)
+ if (_api != null && _currentItemId != null) {
final prefs = await SharedPreferences.getInstance();
final manualOffline = prefs.getBool('manual_offline_mode') ?? false;
if (manualOffline || _isOfflineMode) {
debugPrint('[Player] Skipping session re-create on resume (manualOffline=$manualOffline, isOffline=$_isOfflineMode)');
} else {
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');
+ if (_playbackSessionId == null) {
+ // Session expired — re-create it
+ 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');
+ final serverPos = (sessionData['currentTime'] as num?)?.toDouble() ?? 0;
+ final localPos = position.inMilliseconds / 1000.0;
+ if (serverPos > localPos + 5.0) {
+ debugPrint('[Player] Server is ahead on resume: server=${serverPos}s vs local=${localPos}s — seeking');
+ await _seekAbsolute(serverPos);
+ }
+ }
+ } else {
+ // Session still active — check server progress in case another client advanced
+ final pKey = _currentEpisodeId != null
+ ? '$_currentItemId-$_currentEpisodeId'
+ : _currentItemId!;
+ final serverProgress = await _api!.getItemProgress(pKey);
+ if (serverProgress != null) {
+ final serverPos = (serverProgress['currentTime'] as num?)?.toDouble() ?? 0;
+ final localPos = position.inMilliseconds / 1000.0;
+ if (serverPos > localPos + 5.0) {
+ debugPrint('[Player] Server is ahead on resume: server=${serverPos}s vs local=${localPos}s — seeking');
+ await _seekAbsolute(serverPos);
+ }
+ }
}
} catch (e) {
- debugPrint('[Player] Failed to re-create session on resume: $e');
+ debugPrint('[Player] Failed to check server progress on resume: $e');
}
}
}
diff --git a/lib/widgets/audible_series_sheet.dart b/lib/widgets/audible_series_sheet.dart
index e6bb300b..72f3df1f 100644
--- a/lib/widgets/audible_series_sheet.dart
+++ b/lib/widgets/audible_series_sheet.dart
@@ -190,25 +190,30 @@ class _AudibleSeriesSheetState extends State<AudibleSeriesSheet> {
// Content
if (_isLoading)
- Expanded(child: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
- const CircularProgressIndicator(strokeWidth: 2),
+ Expanded(child: ListView(controller: widget.scrollController, children: [
+ const SizedBox(height: 80),
+ const Center(child: CircularProgressIndicator(strokeWidth: 2)),
const SizedBox(height: 12),
- Text('Searching Audible...', style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.4))),
- ])))
+ Center(child: Text('Searching Audible...', style: tt.bodySmall?.copyWith(color: cs.onSurface.withValues(alpha: 0.4)))),
+ ]))
else if (_error != null)
- Expanded(child: Center(child: Text(_error!, style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant))))
+ Expanded(child: ListView(controller: widget.scrollController, children: [
+ const SizedBox(height: 80),
+ Center(child: Text(_error!, style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant))),
+ ]))
else if (displayBooks.isEmpty)
- Expanded(child: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Expanded(child: ListView(controller: widget.scrollController, children: [
+ const SizedBox(height: 80),
Icon(
_filter == 1 ? Icons.event_available_rounded : Icons.check_circle_outline_rounded,
size: 48, color: cs.primary.withValues(alpha: 0.5)),
const SizedBox(height: 12),
- Text(
+ Center(child: Text(
_filter == 0 ? 'You have the complete series!'
: _filter == 1 ? 'No upcoming releases found'
: 'No books found',
- style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant)),
- ])))
+ style: tt.bodyLarge?.copyWith(color: cs.onSurfaceVariant))),
+ ]))
else
Expanded(
child: ListView.builder(
diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dart
index e012b376..d272e3be 100644
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@ -1215,6 +1215,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {
minChildSize: 0.05, snap: true,
maxChildSize: 0.95,
builder: (ctx, sc) => MetadataLookupSheet(
+ scrollController: sc,
itemId: widget.itemId,
api: api,
initialTitle: title,
diff --git a/lib/widgets/edit_metadata_sheet.dart b/lib/widgets/edit_metadata_sheet.dart
index 66713f0a..5803ee37 100644
--- a/lib/widgets/edit_metadata_sheet.dart
+++ b/lib/widgets/edit_metadata_sheet.dart
@@ -479,14 +479,21 @@ class _EditMetadataContentState extends State<_EditMetadataContent>
Divider(color: cs.onSurface.withValues(alpha: 0.08), height: 1),
Expanded(
child: _isSearching
- ? Center(child: CircularProgressIndicator(strokeWidth: 2, color: cs.onSurfaceVariant))
+ ? ListView(controller: widget.scrollController, children: [
+ const SizedBox(height: 80),
+ Center(child: CircularProgressIndicator(strokeWidth: 2, color: cs.onSurfaceVariant)),
+ ])
: _searchResults.isEmpty
- ? Center(child: Text(
- _hasSearched ? 'No results found.\nTry adjusting your search or provider.' : 'Search for metadata above',
- textAlign: TextAlign.center,
- style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
- ))
+ ? ListView(controller: widget.scrollController, children: [
+ const SizedBox(height: 80),
+ Center(child: Text(
+ _hasSearched ? 'No results found.\nTry adjusting your search or provider.' : 'Search for metadata above',
+ textAlign: TextAlign.center,
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ )),
+ ])
: ListView.separated(
+ controller: widget.scrollController,
padding: EdgeInsets.fromLTRB(16, 12, 16, 16 + MediaQuery.of(context).viewPadding.bottom),
itemCount: _searchResults.length,
separatorBuilder: (_, __) => const SizedBox(height: 8),
diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dart
index 0038236f..82df7287 100644
--- a/lib/widgets/episode_list_sheet.dart
+++ b/lib/widgets/episode_list_sheet.dart
@@ -573,7 +573,7 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
),
SizedBox(
width: 48,
- child: _episodes.isNotEmpty ? _buildOverflowMenu(cs) : null,
+ child: _buildOverflowMenu(cs),
),
],
),
@@ -684,15 +684,14 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {
child: _isLoading
? Center(child: CircularProgressIndicator(strokeWidth: 2, color: cs.onSurface.withValues(alpha: 0.24)))
: _episodes.isEmpty
- ? Center(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(Icons.podcasts_rounded, size: 48, color: cs.onSurface.withValues(alpha: 0.15)),
- const SizedBox(height: 12),
- Text('No episodes found', style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
- ],
- ),
+ ? ListView(
+ controller: widget.scrollController,
+ children: [
+ SizedBox(height: 120),
+ Icon(Icons.podcasts_rounded, size: 48, color: cs.onSurface.withValues(alpha: 0.15)),
+ const SizedBox(height: 12),
+ Center(child: Text('No episodes found', style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant))),
+ ],
)
: Builder(builder: (context) {
final visibleEpisodes = _hideFinished
diff --git a/lib/widgets/home_customize_sheet.dart b/lib/widgets/home_customize_sheet.dart
index 591d0d18..300c03ef 100644
--- a/lib/widgets/home_customize_sheet.dart
+++ b/lib/widgets/home_customize_sheet.dart
@@ -139,7 +139,10 @@ class _HomeCustomizeSheetState extends State<HomeCustomizeSheet> {
Divider(height: 1, color: cs.outlineVariant.withValues(alpha: 0.3), indent: 20, endIndent: 20),
Expanded(
child: genres.isEmpty
- ? Center(child: Text('No genres found', style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)))
+ ? ListView(controller: sc, children: [
+ const SizedBox(height: 60),
+ Center(child: Text('No genres found', style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant))),
+ ])
: ListView.builder(
controller: sc,
padding: EdgeInsets.only(top: 8, bottom: MediaQuery.of(ctx).padding.bottom + 8),
diff --git a/lib/widgets/metadata_lookup_sheet.dart b/lib/widgets/metadata_lookup_sheet.dart
index 4ee25bab..300ff520 100644
--- a/lib/widgets/metadata_lookup_sheet.dart
+++ b/lib/widgets/metadata_lookup_sheet.dart
@@ -14,6 +14,7 @@ class MetadataLookupSheet extends StatefulWidget {
final VoidCallback onApplied;
/// Current metadata so the Custom tab can pre-fill fields.
final Map<String, dynamic>? currentMetadata;
+ final ScrollController? scrollController;
const MetadataLookupSheet({
super.key,
@@ -23,6 +24,7 @@ class MetadataLookupSheet extends StatefulWidget {
required this.initialAuthor,
required this.onApplied,
this.currentMetadata,
+ this.scrollController,
});
@override
@@ -455,14 +457,21 @@ class _MetadataLookupSheetState extends State<MetadataLookupSheet>
Expanded(
child: _isSearching
- ? const Center(child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white24))
+ ? ListView(controller: widget.scrollController, children: const [
+ SizedBox(height: 80),
+ Center(child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white24)),
+ ])
: _results.isEmpty
- ? Center(child: Text(
- _hasSearched ? 'No results found.\nTry adjusting your search or provider.' : 'Search for metadata above',
- textAlign: TextAlign.center,
- style: tt.bodyMedium?.copyWith(color: Colors.white38),
- ))
+ ? ListView(controller: widget.scrollController, children: [
+ const SizedBox(height: 80),
+ Center(child: Text(
+ _hasSearched ? 'No results found.\nTry adjusting your search or provider.' : 'Search for metadata above',
+ textAlign: TextAlign.center,
+ style: tt.bodyMedium?.copyWith(color: Colors.white38),
+ )),
+ ])
: ListView.separated(
+ controller: widget.scrollController,
padding: EdgeInsets.fromLTRB(16, 12, 16, 16 + MediaQuery.of(context).viewPadding.bottom),
itemCount: _results.length,
separatorBuilder: (_, __) => const SizedBox(height: 8),
diff --git a/lib/widgets/notes_sheet.dart b/lib/widgets/notes_sheet.dart
index 26b77da8..82f867a1 100644
--- a/lib/widgets/notes_sheet.dart
+++ b/lib/widgets/notes_sheet.dart
@@ -226,21 +226,22 @@ class _NotesSheetState extends State<NotesSheet> {
// Notes list
Expanded(
child: _isLoading
- ? const Center(child: CircularProgressIndicator())
+ ? ListView(controller: widget.scrollController, children: const [
+ SizedBox(height: 80),
+ Center(child: CircularProgressIndicator()),
+ ])
: _notes.isEmpty
- ? Center(child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(Icons.note_add_rounded, size: 48,
- color: cs.onSurface.withValues(alpha: 0.15)),
- const SizedBox(height: 12),
- Text('No notes yet', style: tt.bodyMedium?.copyWith(
- color: cs.onSurface.withValues(alpha: 0.4))),
- const SizedBox(height: 8),
- Text('Markdown is supported', style: tt.bodySmall?.copyWith(
- color: cs.onSurface.withValues(alpha: 0.25))),
- ],
- ))
+ ? ListView(controller: widget.scrollController, children: [
+ const SizedBox(height: 80),
+ Icon(Icons.note_add_rounded, size: 48,
+ color: cs.onSurface.withValues(alpha: 0.15)),
+ const SizedBox(height: 12),
+ Center(child: Text('No notes yet', style: tt.bodyMedium?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.4)))),
+ const SizedBox(height: 8),
+ Center(child: Text('Markdown is supported', style: tt.bodySmall?.copyWith(
+ color: cs.onSurface.withValues(alpha: 0.25)))),
+ ])
: ListView.separated(
controller: widget.scrollController,
padding: const EdgeInsets.fromLTRB(16, 8, 16, 32),
diff --git a/lib/widgets/playlist_detail_sheet.dart b/lib/widgets/playlist_detail_sheet.dart
index d164d8f2..a5fbd342 100644
--- a/lib/widgets/playlist_detail_sheet.dart
+++ b/lib/widgets/playlist_detail_sheet.dart
@@ -253,7 +253,10 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {
).firstOrNull;
if (playlist == null) {
- return const Center(child: Text('Playlist not found'));
+ return ListView(controller: widget.scrollController, children: const [
+ SizedBox(height: 80),
+ Center(child: Text('Playlist not found')),
+ ]);
}
final name = playlist['name'] as String? ?? 'Playlist';