Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Instant cold-start playback via cached session metadata

Nathan Poulson92652bad0f4b
diff --git a/lib/main.dart b/lib/main.dart
index 87e74026..3f45bf1f 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -444,6 +444,12 @@ class _AuthGateState extends State<AuthGate> {
} catch (e) {
debugPrint('[Init] AudioPlayerService.init timed out or failed: $e');
}
+ // Route cold-start play() calls (headphones / lock screen tap before
+ // the UI has bootstrapped the current item) through the existing
+ // home-widget restore path. Registered as a static callback to avoid a
+ // circular import between AudioPlayerService and HomeWidgetService.
+ AudioPlayerService.onColdStartPlayRequested =
+ HomeWidgetService().resumeLastPlayedIfAvailable;
debugPrint('[Init] AudioPlayerService done (${sw.elapsedMilliseconds}ms)');
try {
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index dc7a78a9..87ad46ca 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -723,11 +723,15 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
final id = data['id'] as String?;
final ts = data['updatedAt'] as num?;
if (id != null && ts != null) _itemUpdatedAt[id] = ts.toInt();
+ // Invalidate cached session metadata - track URLs may have changed
+ if (id != null) SessionCache.clear(itemId: id);
loadPersonalizedView(force: true);
_checkSubscribedPodcastUpdate(data);
}
void _onRemoteItemRemoved(Map<String, dynamic> data) {
+ final id = data['id'] as String?;
+ if (id != null) SessionCache.clear(itemId: id);
loadPersonalizedView(force: true);
}
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dart
index 5e495a35..3634e2ec 100644
--- a/lib/providers/auth_provider.dart
+++ b/lib/providers/auth_provider.dart
@@ -5,6 +5,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/session_cache.dart';
import '../services/socket_service.dart';
import '../services/user_account_service.dart';
import '../main.dart' show scaffoldMessengerKey;
@@ -478,6 +479,10 @@ class AuthProvider extends ChangeNotifier {
// Clear Android Auto browse tree cache so it doesn't show stale data
AndroidAutoService().clearCache();
+ // Clear cached session metadata for this user (track URLs would be invalid
+ // on next login anyway)
+ await SessionCache.clearAll();
+
// Remove account from saved accounts list
final logoutServer = _serverUrl;
final logoutUser = _username;
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index 4d59527b..c836478e 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -13,6 +13,7 @@ import '../services/download_service.dart';
import '../services/android_auto_service.dart';
import '../services/chromecast_service.dart';
import '../services/bookmark_service.dart';
+import '../services/session_cache.dart';
import '../services/socket_service.dart';
import '../main.dart' show scaffoldMessengerKey;
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 16469376..b6f87baf 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -15,7 +15,10 @@ import 'sleep_timer_service.dart';
import 'equalizer_service.dart';
import 'android_auto_service.dart';
import 'chromecast_service.dart';
+import 'chapter_lookup.dart';
+import 'cold_start_play_policy.dart';
import 'player_settings.dart';
+import 'session_cache.dart';
export 'player_settings.dart';
// ─── AudioHandler (runs in background, controls notification) ───
@@ -178,16 +181,13 @@ class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
/// highlights and scrolls to the active chapter in the queue view.
int? _safeCurrentChapterIndex() {
try {
- if (_service == null || _service!.chapters.isEmpty) return null;
+ if (_service == null) return null;
final posSec = _player.position.inMilliseconds / 1000.0;
- final chapters = _service!.chapters;
- for (int i = 0; i < chapters.length; i++) {
- final ch = chapters[i] as Map<String, dynamic>;
- final start = (ch['start'] as num?)?.toDouble() ?? 0;
- final end = (ch['end'] as num?)?.toDouble() ?? _service!.totalDuration;
- if (posSec >= start && posSec < end) return i;
- }
- return null;
+ return ChapterLookup.indexAt(
+ _service!.chapters,
+ posSec,
+ _service!.totalDuration,
+ );
} catch (e) {
debugPrint('[Handler] _safeCurrentChapterIndex error: $e');
return null;
@@ -671,6 +671,13 @@ class AudioPlayerService extends ChangeNotifier {
_onPlaybackStateChangedCallback = cb;
}
+ /// Invoked when `play()` fires on a cold-started service that has no
+ /// current item loaded (typical headphone / lock-screen tap after the OS
+ /// killed the app). Registered by main.dart to delegate the restore to
+ /// HomeWidgetService (which has the item-fetch + ApiService construction
+ /// logic), avoiding a circular import.
+ static Future<void> Function()? onColdStartPlayRequested;
+
static AudioPlayerHandler? _handler;
static AudioPlayerHandler? get handler => _handler;
static Completer<void> _initCompleter = Completer<void>();
@@ -1250,7 +1257,7 @@ class AudioPlayerService extends ChangeNotifier {
_isCompletingBook = false;
// Check if downloaded — play locally
- final String? result;
+ String? result;
if (_downloadService.isDownloaded(progressKey)) {
result = await _playFromLocal(progressKey, title, author, coverUrl,
totalDuration, chapters, startTime, forceStartTime);
@@ -1263,9 +1270,25 @@ class AudioPlayerService extends ChangeNotifier {
_clearState();
return 'This item isn\'t downloaded and offline mode is on';
}
- // Stream from server
- result = await _playFromServer(api, itemId, title, author, coverUrl,
- totalDuration, chapters, startTime, forceStartTime);
+ // Try to play from cached session metadata first (instant start)
+ final cachedSession = await SessionCache.load(
+ itemId: itemId,
+ episodeId: episodeId,
+ );
+ if (cachedSession != null) {
+ result = await _playFromSessionCache(api, itemId, title, author,
+ coverUrl, totalDuration, chapters, startTime, cachedSession,
+ forceStartTime);
+ // Fall through to normal server path if cache was stale/invalid
+ if (result == 'cache-miss') {
+ result = await _playFromServer(api, itemId, title, author, coverUrl,
+ totalDuration, chapters, startTime, forceStartTime);
+ }
+ } else {
+ // No cache - stream from server
+ result = await _playFromServer(api, itemId, title, author, coverUrl,
+ totalDuration, chapters, startTime, forceStartTime);
+ }
}
_isLoadingNewItem = false;
@@ -1531,6 +1554,151 @@ class AudioPlayerService extends ChangeNotifier {
}
}
+ /// Play from cached session metadata. Starts playback instantly without
+ /// waiting for a server round-trip. Fires _refreshServerSession() in the
+ /// background to get a fresh session ID and cross-client progress check.
+ Future<String?> _playFromSessionCache(
+ ApiService api,
+ String itemId,
+ String title,
+ String author,
+ String? coverUrl,
+ double totalDuration,
+ List<dynamic> chapters,
+ double startTime,
+ Map<String, dynamic> cached, [
+ bool forceStartTime = false,
+ ]) async {
+ debugPrint('[Player] Playing from session cache: $title');
+ _isOfflineMode = false;
+ _playbackSessionId = null; // No server session yet; _refreshServerSession will set it
+
+ final audioTracks = cached['audioTracks'] as List<dynamic>?;
+ if (audioTracks == null || audioTracks.isEmpty) {
+ debugPrint('[Player] Cached session has no audio tracks - falling back');
+ return 'cache-miss';
+ }
+
+ // Pick up cached chapters if the caller didn't provide any
+ if (chapters.isEmpty) {
+ final cachedChapters = cached['chapters'] as List<dynamic>? ?? [];
+ if (cachedChapters.isNotEmpty) {
+ chapters = cachedChapters;
+ _chapters = cachedChapters;
+ _handler?.updateChaptersQueue(cachedChapters);
+ }
+ }
+
+ // Use cached duration if caller didn't have one
+ if (totalDuration <= 0) {
+ final cachedDur = (cached['totalDuration'] as num?)?.toDouble() ?? 0;
+ if (cachedDur > 0) {
+ totalDuration = cachedDur;
+ _totalDuration = cachedDur;
+ }
+ }
+
+ try {
+ _currentTrackIndex = 0;
+ final audioHeaders = api.mediaHeaders;
+ _buildTrackOffsets(audioTracks);
+ AudioSource source;
+ if (audioTracks.length == 1) {
+ final track = audioTracks.first as Map<String, dynamic>;
+ final contentUrl = track['contentUrl'] as String? ?? '';
+ final fullUrl = api.buildTrackUrl(contentUrl);
+ source = AudioSource.uri(Uri.parse(fullUrl), headers: audioHeaders);
+ } else {
+ final sources = <AudioSource>[];
+ for (final t in audioTracks) {
+ 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));
+ }
+ source = ConcatenatingAudioSource(children: sources);
+ }
+
+ await _player!.setAudioSource(source);
+
+ 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] Starting cached session playback at ${speed}x');
+ 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();
+ // Refresh server session in background - gets fresh session ID and
+ // handles cross-client progress sync without blocking playback start
+ _refreshServerSession(api, itemId);
+ return null;
+ } catch (e, stack) {
+ debugPrint('[Player] Cached session play error: $e\n$stack');
+ // Cache was stale or invalid - clear it and signal fallback
+ SessionCache.clear(itemId: itemId, episodeId: _currentEpisodeId);
+ return 'cache-miss';
+ }
+ }
+
+ /// Re-create the server playback session in the background after starting
+ /// playback from cache. Gets a fresh session ID so progress syncing works,
+ /// and handles cross-client progress (seek to server position if ahead).
+ void _refreshServerSession(ApiService api, String itemId) async {
+ if (_isOfflineMode) return;
+ try {
+ final sessionData = _currentEpisodeId != null
+ ? await api.startEpisodePlaybackSession(itemId, _currentEpisodeId!)
+ : await api.startPlaybackSession(itemId);
+ if (sessionData == null) {
+ debugPrint('[Player] Background session refresh returned null');
+ return;
+ }
+ _playbackSessionId = sessionData['id'] as String?;
+ _lastServerSync = DateTime.now();
+ debugPrint('[Player] Background session refreshed: $_playbackSessionId');
+
+ // Update cached session with fresh track data in case it changed
+ final audioTracks = sessionData['audioTracks'] as List<dynamic>?;
+ final sessionChapters = sessionData['chapters'] as List<dynamic>? ?? [];
+ final sessionDur = (sessionData['duration'] as num?)?.toDouble() ?? 0;
+ if (audioTracks != null && audioTracks.isNotEmpty) {
+ SessionCache.save(
+ itemId: itemId,
+ episodeId: _currentEpisodeId,
+ audioTracks: audioTracks,
+ chapters: sessionChapters.isNotEmpty ? sessionChapters : _chapters,
+ totalDuration: sessionDur > 0 ? sessionDur : _totalDuration,
+ );
+ }
+
+ // Check if server position is ahead (another client advanced)
+ 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 cache-start: server=${serverPos}s vs local=${localPos}s - seeking');
+ await _seekAbsolute(serverPos);
+ }
+ } catch (e) {
+ debugPrint('[Player] Background session refresh failed: $e');
+ }
+ }
+
Future<String?> _playFromServer(
ApiService api,
String itemId,
@@ -1671,6 +1839,14 @@ class AudioPlayerService extends ChangeNotifier {
final sleepTimer = SleepTimerService();
sleepTimer.resetDismiss();
sleepTimer.checkAutoSleep();
+ // Cache session metadata so next play can start instantly
+ SessionCache.save(
+ itemId: itemId,
+ episodeId: _currentEpisodeId,
+ audioTracks: audioTracks,
+ chapters: chapters,
+ totalDuration: totalDuration,
+ );
return null;
} catch (e, stack) {
debugPrint('[Player] Stream error: $e\n$stack');
@@ -2439,6 +2615,34 @@ class AudioPlayerService extends ChangeNotifier {
Future<void> play() async {
debugPrint('[Service] play() called — lastPause=${_lastPauseTime != null}');
+
+ // Cold-start play guard. If the OS killed absorb during a long pause
+ // and the user tapped play via headphones / lock screen / Android Auto,
+ // the handler routes play() into this service before any UI code has
+ // had a chance to restore the last-played item. _currentItemId is null
+ // here, so falling through to _player.play() fires on an empty player
+ // and nothing happens. Route through the cold-start callback instead.
+ final prefs = _prefs ?? await SharedPreferences.getInstance();
+ _prefs ??= prefs;
+ final decision = ColdStartPlayPolicy.decide(
+ currentItemId: _currentItemId,
+ lastPlayedItemId: prefs.getString('widget_item_id'),
+ );
+ if (decision == ColdStartPlayDecision.restoreLastPlayed) {
+ debugPrint('[Service] play() on cold-started service - routing to cold-start restore');
+ final restore = AudioPlayerService.onColdStartPlayRequested;
+ if (restore != null) {
+ unawaited(restore());
+ } else {
+ debugPrint('[Service] No cold-start restore handler registered - ignoring play');
+ }
+ return;
+ }
+ if (decision == ColdStartPlayDecision.nothing) {
+ debugPrint('[Service] play() called with no current item and no history - ignoring');
+ return;
+ }
+
_pauseStopTimer?.cancel();
_pauseStopTimer = null;
_noisyPause = false; // User explicitly resumed — allow interrupt-resume again
diff --git a/lib/services/chapter_lookup.dart b/lib/services/chapter_lookup.dart
new file mode 100644
index 00000000..5fd5962b
--- /dev/null
+++ b/lib/services/chapter_lookup.dart
@@ -0,0 +1,35 @@
+/// Pure chapter index lookup, extracted from AudioPlayerService.
+///
+/// Finds which chapter contains a given playback position. Used by the
+/// audio handler to drive Android Auto's current-chapter highlight,
+/// notification chapter mode, and the queue index.
+///
+/// Extracted so the boundary logic can be unit-tested without spinning up
+/// just_audio. Behavior must match the inline loop in
+/// `audio_player_service.dart` exactly. Change one, change both.
+class ChapterLookup {
+ /// Return the index of the chapter containing [positionSeconds], or `null`
+ /// if no chapter contains it (or if the chapter list is empty).
+ ///
+ /// Each chapter is expected to be a `Map<String, dynamic>` with `start`
+ /// and `end` numeric fields (in seconds). Missing `start` defaults to 0;
+ /// missing `end` defaults to [totalDuration].
+ ///
+ /// Boundary semantics: `start <= positionSeconds < end` (inclusive at
+ /// start, exclusive at end). This means the boundary instant belongs to
+ /// the next chapter, not the previous one.
+ static int? indexAt(
+ List<dynamic> chapters,
+ double positionSeconds,
+ double totalDuration,
+ ) {
+ if (chapters.isEmpty) return null;
+ for (int i = 0; i < chapters.length; i++) {
+ final ch = chapters[i] as Map<String, dynamic>;
+ final start = (ch['start'] as num?)?.toDouble() ?? 0;
+ final end = (ch['end'] as num?)?.toDouble() ?? totalDuration;
+ if (positionSeconds >= start && positionSeconds < end) return i;
+ }
+ return null;
+ }
+}
diff --git a/lib/services/cold_start_play_policy.dart b/lib/services/cold_start_play_policy.dart
new file mode 100644
index 00000000..b2f95ce4
--- /dev/null
+++ b/lib/services/cold_start_play_policy.dart
@@ -0,0 +1,52 @@
+/// Decision logic for `AudioPlayerService.play()` when the service may not
+/// yet have a current item.
+///
+/// Context: when absorb is woken up by a media button press (headphones,
+/// lock screen, Android Auto) after the OS killed the process, the handler
+/// routes `play()` into the service BEFORE any UI code has restored the
+/// last-played item. Without this policy, `_player.play()` is called on an
+/// empty just_audio player and nothing happens - the user taps play and
+/// audio never starts (see absorb logs from 2026-04-10 around 10:04 and
+/// 11:08 for real-world cases).
+///
+/// The policy is a pure function so the decision can be unit-tested. The
+/// actual restore work (fetching the item, loading the source) is I/O and
+/// lives in the service layer.
+enum ColdStartPlayDecision {
+ /// Normal case: a current item is loaded, play it.
+ playCurrent,
+
+ /// No current item but absorb has a last-played item on disk. The caller
+ /// should fetch it and bootstrap playback via the normal restore path.
+ restoreLastPlayed,
+
+ /// No current item and nothing to restore (first run, or the user
+ /// explicitly cleared state). Ignore the play request.
+ nothing,
+}
+
+class ColdStartPlayPolicy {
+ /// Decide how `AudioPlayerService.play()` should respond.
+ ///
+ /// [currentItemId] is the in-memory `_currentItemId` on the service.
+ /// [lastPlayedItemId] is the persisted `widget_item_id` from
+ /// SharedPreferences (or equivalent last-played marker).
+ ///
+ /// Rules:
+ /// - If a current item is loaded, always play it (ignore the last-
+ /// played marker; the current item wins).
+ /// - Else if a last-played item exists, ask the caller to restore it.
+ /// - Else do nothing.
+ static ColdStartPlayDecision decide({
+ required String? currentItemId,
+ required String? lastPlayedItemId,
+ }) {
+ if (currentItemId != null && currentItemId.isNotEmpty) {
+ return ColdStartPlayDecision.playCurrent;
+ }
+ if (lastPlayedItemId != null && lastPlayedItemId.isNotEmpty) {
+ return ColdStartPlayDecision.restoreLastPlayed;
+ }
+ return ColdStartPlayDecision.nothing;
+ }
+}
diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dart
index 95bc242c..630a792b 100644
--- a/lib/services/home_widget_service.dart
+++ b/lib/services/home_widget_service.dart
@@ -64,6 +64,14 @@ class HomeWidgetService {
}
}
+ /// Public entry point for cold-start resume of the last-played item.
+ ///
+ /// Wraps the original widget play/pause handler so the same restore path
+ /// can be invoked from elsewhere (for example from AudioPlayerService when
+ /// a media button press hits the service before the UI has bootstrapped
+ /// the current item).
+ Future<void> resumeLastPlayedIfAvailable() => _handlePlayPause();
+
Future<void> _handlePlayPause() async {
final player = AudioPlayerService();
diff --git a/lib/services/progress_sync_service.dart b/lib/services/progress_sync_service.dart
index 1923b103..12e88b9f 100644
--- a/lib/services/progress_sync_service.dart
+++ b/lib/services/progress_sync_service.dart
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'api_service.dart';
import 'scoped_prefs.dart';
+import 'sync_logic.dart';
/// Manages local progress storage and server sync.
/// Progress is ALWAYS saved locally first, then synced to server when online.
@@ -18,7 +19,6 @@ class ProgressSyncService {
bool _isFlushing = false;
bool _flushAgain = false;
int _consecutiveFailures = 0;
- static const _maxRetryDelay = Duration(minutes: 5);
static const _maxConsecutiveFailures = 10;
/// Initialize — start listening for connectivity changes.
@@ -225,8 +225,13 @@ class ProgressSyncService {
final hasOfflineListening =
(await ScopedPrefs.getInt('offline_listening_$itemId') ?? 0) > 0;
- if (serverTimestamp > localTimestamp &&
- (serverTime >= localTime || !hasOfflineListening)) {
+ if (SyncLogic.shouldPullServer(
+ serverTimestamp: serverTimestamp,
+ serverTime: serverTime,
+ localTimestamp: localTimestamp,
+ localTime: localTime,
+ hasOfflineListening: hasOfflineListening,
+ )) {
debugPrint('[Sync] Server is newer for $itemId: server=$serverTime s ($serverTimestamp) vs local=$localTime s ($localTimestamp) — pulling');
await cacheServerProgress(
itemId: itemId,
@@ -314,10 +319,7 @@ class ProgressSyncService {
debugPrint('[Sync] Too many consecutive failures ($_consecutiveFailures) - waiting for next connectivity change');
return;
}
- final delay = _consecutiveFailures == 0
- ? const Duration(milliseconds: 250)
- : Duration(seconds: 5 * (1 << (_consecutiveFailures - 1)).clamp(1, 60));
- final clampedDelay = delay > _maxRetryDelay ? _maxRetryDelay : delay;
+ final clampedDelay = SyncLogic.backoffDelay(_consecutiveFailures);
debugPrint('[Sync] Scheduling retry in ${clampedDelay.inSeconds}s (failures=$_consecutiveFailures)');
unawaited(
diff --git a/lib/services/session_cache.dart b/lib/services/session_cache.dart
new file mode 100644
index 00000000..65f6189b
--- /dev/null
+++ b/lib/services/session_cache.dart
@@ -0,0 +1,109 @@
+import 'dart:convert';
+import 'package:flutter/foundation.dart';
+import 'package:shared_preferences/shared_preferences.dart';
+import 'user_account_service.dart';
+
+/// Caches playback session metadata (track URLs, chapters, duration) per item
+/// so the app can start playback immediately on cold start without waiting for
+/// a `startPlaybackSession` network call.
+///
+/// The session ID itself is NOT cached - that's created fresh in the background
+/// on every play. Only the parts needed to build the AudioSource are stored.
+///
+/// Per-user scoped via active account prefix so accounts don't share caches.
+class SessionCache {
+ SessionCache._();
+
+ static String _key(String itemId, String? episodeId) {
+ final scope = UserAccountService().activeScopeKey;
+ final prefix = scope.isEmpty ? '' : '$scope:';
+ return episodeId != null
+ ? '${prefix}session_cache_${itemId}_$episodeId'
+ : '${prefix}session_cache_$itemId';
+ }
+
+ /// Save session metadata for an item. Only stores what we need to rebuild
+ /// the audio source on next play.
+ static Future<void> save({
+ required String itemId,
+ String? episodeId,
+ required List<dynamic> audioTracks,
+ required List<dynamic> chapters,
+ required double totalDuration,
+ }) async {
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ final data = {
+ 'audioTracks': audioTracks,
+ 'chapters': chapters,
+ 'totalDuration': totalDuration,
+ 'savedAt': DateTime.now().millisecondsSinceEpoch,
+ };
+ await prefs.setString(_key(itemId, episodeId), jsonEncode(data));
+ } catch (e) {
+ debugPrint('[SessionCache] Failed to save: $e');
+ }
+ }
+
+ /// Load cached session metadata. Returns null if not cached.
+ static Future<Map<String, dynamic>?> load({
+ required String itemId,
+ String? episodeId,
+ }) async {
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ final raw = prefs.getString(_key(itemId, episodeId));
+ if (raw == null) return null;
+ return jsonDecode(raw) as Map<String, dynamic>;
+ } catch (e) {
+ debugPrint('[SessionCache] Failed to load: $e');
+ return null;
+ }
+ }
+
+ /// Clear the cache for a single item.
+ static Future<void> clear({
+ required String itemId,
+ String? episodeId,
+ }) async {
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ if (episodeId != null) {
+ await prefs.remove(_key(itemId, episodeId));
+ } else {
+ // Clear the item key and any episode keys under it
+ await prefs.remove(_key(itemId, null));
+ final scope = UserAccountService().activeScopeKey;
+ final prefix = scope.isEmpty ? '' : '$scope:';
+ final itemPrefix = '${prefix}session_cache_${itemId}_';
+ for (final k in prefs.getKeys().toList()) {
+ if (k.startsWith(itemPrefix)) {
+ await prefs.remove(k);
+ }
+ }
+ }
+ } catch (e) {
+ debugPrint('[SessionCache] Failed to clear: $e');
+ }
+ }
+
+ /// Clear all session cache entries for the active user scope.
+ static Future<void> clearAll() async {
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ final scope = UserAccountService().activeScopeKey;
+ final prefix = scope.isEmpty ? '' : '$scope:';
+ final cachePrefix = '${prefix}session_cache_';
+ int cleared = 0;
+ for (final k in prefs.getKeys().toList()) {
+ if (k.startsWith(cachePrefix)) {
+ await prefs.remove(k);
+ cleared++;
+ }
+ }
+ debugPrint('[SessionCache] Cleared $cleared entries');
+ } catch (e) {
+ debugPrint('[SessionCache] Failed to clear all: $e');
+ }
+ }
+}
diff --git a/lib/services/sync_logic.dart b/lib/services/sync_logic.dart
new file mode 100644
index 00000000..b509130e
--- /dev/null
+++ b/lib/services/sync_logic.dart
@@ -0,0 +1,53 @@
+/// Pure decision logic for ProgressSyncService.
+///
+/// Extracted so the math can be unit-tested without mocking ApiService,
+/// SharedPreferences, or Connectivity. Behavior must match the inline code
+/// in `progress_sync_service.dart` exactly. Change one, change both.
+class SyncLogic {
+ /// Hard upper bound on retry delay. Matches `_maxRetryDelay` in
+ /// ProgressSyncService.
+ static const Duration maxRetryDelay = Duration(minutes: 5);
+
+ /// Exponential backoff used between retry attempts when flushing pending
+ /// syncs. Schedule:
+ ///
+ /// 0 failures -> 250 ms (initial fast retry)
+ /// 1 failure -> 5 s
+ /// 2 failures -> 10 s
+ /// 3 failures -> 20 s
+ /// 4 failures -> 40 s
+ /// 5 failures -> 80 s
+ /// 6 failures -> 160 s
+ /// 7+ failures -> 300 s (capped at maxRetryDelay)
+ static Duration backoffDelay(int consecutiveFailures) {
+ if (consecutiveFailures <= 0) return const Duration(milliseconds: 250);
+ final raw = Duration(
+ seconds: 5 * (1 << (consecutiveFailures - 1)).clamp(1, 60),
+ );
+ return raw > maxRetryDelay ? maxRetryDelay : raw;
+ }
+
+ /// Decide whether to pull server progress or push local progress when
+ /// flushing a pending sync.
+ ///
+ /// Returns `true` to pull server (server is authoritative for this item),
+ /// `false` to push local (local is authoritative).
+ ///
+ /// Rules:
+ /// - If local timestamp is newer or equal, always push local.
+ /// - If server timestamp is newer:
+ /// - If server position is at or ahead of local position, pull server.
+ /// - Else if there is offline listening time accumulated locally,
+ /// push local (offline progress would otherwise be lost).
+ /// - Else pull server.
+ static bool shouldPullServer({
+ required int serverTimestamp,
+ required double serverTime,
+ required int localTimestamp,
+ required double localTime,
+ required bool hasOfflineListening,
+ }) {
+ if (serverTimestamp <= localTimestamp) return false;
+ return serverTime >= localTime || !hasOfflineListening;
+ }
+}
diff --git a/lib/widgets/card_progress_bar.dart b/lib/widgets/card_progress_bar.dart
index d98faa18..84b4611e 100644
--- a/lib/widgets/card_progress_bar.dart
+++ b/lib/widgets/card_progress_bar.dart
@@ -41,6 +41,10 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with WidgetsB
double _lastKnownPos = 0;
DateTime _lastPosTime = DateTime.now();
double _currentSpeed = 1.0;
+ // Per-item speed used for the time display while the card is inactive,
+ // so the expanded card's book time row matches the small card's behavior
+ // when speed-adjusted time is enabled.
+ double _savedSpeed = 1.0;
bool _isPlaying = false;
bool _isCastMode = false;
StreamSubscription<Duration>? _posSub;
@@ -58,6 +62,14 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with WidgetsB
void _loadSettings() {
PlayerSettings.getShowBookSlider().then((v) { if (mounted && v != _showBookSlider) setState(() => _showBookSlider = v); });
PlayerSettings.getSpeedAdjustedTime().then((v) { if (mounted && v != _speedAdjustedTime) setState(() => _speedAdjustedTime = v); });
+ _loadSavedSpeed();
+ }
+
+ Future<void> _loadSavedSpeed() async {
+ final itemId = widget.itemId;
+ final bookSpeed = itemId != null ? await PlayerSettings.getBookSpeed(itemId) : null;
+ final speed = bookSpeed ?? await PlayerSettings.getDefaultSpeed();
+ if (mounted && speed != _savedSpeed) setState(() => _savedSpeed = speed);
}
void _onCastChanged() {
@@ -86,6 +98,7 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with WidgetsB
void didUpdateWidget(CardDualProgressBar old) {
super.didUpdateWidget(old);
if (old.isActive != widget.isActive) _subscribePosition();
+ if (old.itemId != widget.itemId) _loadSavedSpeed();
}
void _syncTicker() {
@@ -286,7 +299,11 @@ class _CardDualProgressBarState extends State<CardDualProgressBar> with WidgetsB
final chapterDur = chapterEnd - chapterStart;
final chapterPos = (posS - chapterStart).clamp(0.0, chapterDur);
final chapterProgress = chapterDur > 0 ? chapterPos / chapterDur : 0.0;
- final speedDiv = _speedAdjustedTime ? speed : 1.0;
+ // When inactive, fall back to the per-item saved speed (or default)
+ // so the book time row on the expanded card still reflects the
+ // user's speed-adjusted-time setting. Matches absorbing_card's
+ // inline book-time logic.
+ final speedDiv = _speedAdjustedTime ? (active ? speed : _savedSpeed) : 1.0;
final bookElapsed = posS / speedDiv;
final bookRemaining = (totalDur - posS) / speedDiv;
final chapterRemaining = (chapterDur - chapterPos) / speedDiv;
diff --git a/pubspec.lock b/pubspec.lock
index 5d7eb60a..b1a0cca8 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -580,6 +580,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.0"
+ mocktail:
+ dependency: "direct dev"
+ description:
+ name: mocktail
+ sha256: "5e1bf53cc7baa8062a33b84424deb61513858ea05c601b8509e683815b5914aa"
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.0.5"
nested:
dependency: transitive
description:
diff --git a/pubspec.yaml b/pubspec.yaml
index 26ab66f2..5cdb8089 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,7 +1,7 @@
name: absorb
description: An Audiobookshelf Client
publish_to: 'none'
-version: 1.8.65+82
+version: 1.8.66+83
# v1.8.41: JWT auth (accessToken + refreshToken), MANAGE_EXTERNAL_STORAGE removed from playstore flavor
# Build scripts (run from Git Bash):
# . ./build_bundle.sh - Play Store AAB (no MANAGE_EXTERNAL_STORAGE)
@@ -94,6 +94,7 @@ dev_dependencies:
flutter_launcher_icons: ^0.14.3
change_app_package_name: ^1.5.0
rename_app: ^1.6.5
+ mocktail: ^1.0.4
flutter:
generate: true