A cross platform Audiobookshelf client for Android and iOS
Dart
Load the last played book paused at launch so a headset press always has a target
Barnabas2a73e9ce65e3
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dartindex 17f2bb09..94262264 100644--- a/lib/services/audio_player_service.dart+++ b/lib/services/audio_player_service.dart@@ -2207,16 +2207,24 @@ class AudioPlayerService extends ChangeNotifier {if (player == null) return;try {final state = await player.engineState();- if (state == null || !state.isLoaded || !state.isPlaying) return;- debugPrint(- '[Player] boot: native engine already playing at '- '${state.globalPositionS.toStringAsFixed(1)}s with no book loaded - adopting',- );- if (state.globalPositionS > 0) {- await HomeWidgetService().stashLivePosition(state.globalPositionS);+ if (state != null && state.isLoaded && state.isPlaying) {+ debugPrint(+ '[Player] boot: native engine already playing at '+ '${state.globalPositionS.toStringAsFixed(1)}s with no book loaded - adopting',+ );+ if (state.globalPositionS > 0) {+ await HomeWidgetService().stashLivePosition(state.globalPositionS);+ }+ final restore = AudioPlayerService.onColdStartPlayRequested;+ if (restore != null) await restore();+ return;}- final restore = AudioPlayerService.onColdStartPlayRequested;- if (restore != null) await restore();+ // Idle engine: load the last played item paused instead, so a headset+ // press in the first seconds of a cold start has a live target - the+ // native core defers presses to Flutter the moment its heartbeat+ // exists, and with nothing loaded that press used to land on neither+ // layer.+ await HomeWidgetService().loadLastPlayedPaused();} catch (e) {debugPrint('[Player] boot engine adopt failed: $e');}@@ -3133,9 +3141,10 @@ class AudioPlayerService extends ChangeNotifier {// phone's own position immediately. See play().bool fromUi = false,// Load the item into the player at its resume position but leave it- // paused, with no playback session: the live transcript needs the book- // up so its runway can build, without deciding for the user that audio- // starts now. Downloaded items only - a streamed item plays normally.+ // paused, with no playback session: a headset press then always has a+ // live target and the live transcript can build its runway, without+ // deciding for the user that audio starts now. Downloaded items only -+ // a streamed item plays normally.bool loadOnly = false,}) async {_pauseRequested = false;@@ -3875,10 +3884,10 @@ class AudioPlayerService extends ChangeNotifier {);await EqualizerService().switchItem(speedKey);if (loadOnly) {- // Loaded and idle at the resume position: the transcript can build- // its runway and the lock screen shows the book paused, but nothing- // plays and no session exists until the user presses play - the- // normal play() path creates the session then.+ // Loaded and idle at the resume position: the lock screen shows the+ // book paused, a headset press has a live target, and the transcript+ // can build its runway - but nothing plays and no session exists+ // until the user presses play, which creates the session then.debugPrint('[Player] Loaded paused (no session) at ''${startTime.toStringAsFixed(0)}s');_pendingLoadOnlySession = (diff --git a/lib/services/home_widget_service.dart b/lib/services/home_widget_service.dartindex 9d52245f..b7bdae06 100644--- a/lib/services/home_widget_service.dart+++ b/lib/services/home_widget_service.dart@@ -428,41 +428,11 @@ class HomeWidgetService {debugPrint('[HomeWidget] play_pause: cold resume, itemId=$itemId');if (itemId == null) return;- final serverUrl = prefs.getString('server_url');- final token = prefs.getString('token');- final refreshToken = prefs.getString('refresh_token');- final username = prefs.getString('username');+ final api = _apiFromPrefs(prefs);debugPrint(- '[HomeWidget] play_pause: server=${serverUrl != null}, token=${token != null}',- );- if (serverUrl == null || token == null) return;-- Map<String, String>? customHeaders;- final headersJson = prefs.getString('custom_headers');- if (headersJson != null) {- try {- customHeaders = Map<String, String>.from(- jsonDecode(headersJson) as Map,- );- } catch (_) {}- }-- final api = ApiService(- baseUrl: serverUrl,- token: token,- refreshToken: refreshToken,- isLegacyToken: refreshToken == null,- customHeaders: customHeaders ?? const {},- loadPersistedTokens: () =>- UserAccountService().loadPersistedTokens(serverUrl, username),- onTokensRefreshed: (access, refresh) =>- UserAccountService().persistRefreshedTokens(- access,- refresh,- serverUrl: serverUrl,- username: username,- ),+ '[HomeWidget] play_pause: api=${api != null}',);+ if (api == null) return;final episodeId = prefs.getString('widget_episode_id');@@ -535,12 +505,80 @@ class HomeWidgetService {/// Cold-resume a downloaded item straight from its download record. Returns/// false when the item isn't downloaded (or the record is unusable) so the/// caller falls back to fetching it from the server.+ /// A saved session rebuilt from prefs, for paths that run before (or+ /// without) the providers - the widget cold resume and the launch-time+ /// load-paused. Null when no server credentials are saved.+ ApiService? _apiFromPrefs(SharedPreferences prefs) {+ final serverUrl = prefs.getString('server_url');+ final token = prefs.getString('token');+ if (serverUrl == null || token == null) return null;+ final refreshToken = prefs.getString('refresh_token');+ final username = prefs.getString('username');+ Map<String, String>? customHeaders;+ final headersJson = prefs.getString('custom_headers');+ if (headersJson != null) {+ try {+ customHeaders = Map<String, String>.from(+ jsonDecode(headersJson) as Map,+ );+ } catch (_) {}+ }+ return ApiService(+ baseUrl: serverUrl,+ token: token,+ refreshToken: refreshToken,+ isLegacyToken: refreshToken == null,+ customHeaders: customHeaders ?? const {},+ loadPersistedTokens: () =>+ UserAccountService().loadPersistedTokens(serverUrl, username),+ onTokensRefreshed: (access, refresh) =>+ UserAccountService().persistRefreshedTokens(+ access,+ refresh,+ serverUrl: serverUrl,+ username: username,+ ),+ );+ }++ /// iOS cold start: load the last played item into the player paused, so a+ /// headset press always has a live target. Without this, a press arriving+ /// after Dart boots gets deferred by the native core to an audio_service+ /// with nothing loaded, and lands on neither layer. Downloaded items only+ /// (a stream would need a server session just to sit paused); no session+ /// starts until a real play.+ Future<void> loadLastPlayedPaused() async {+ final player = AudioPlayerService();+ if (player.hasBook) return;+ final prefs = await SharedPreferences.getInstance();+ final itemId = prefs.getString('widget_item_id');+ if (itemId == null) return;+ final api = _apiFromPrefs(prefs);+ if (api == null) return;+ final episodeId = prefs.getString('widget_episode_id');+ try {+ final ok = await _resumeFromDownloadRecord(+ player,+ api,+ itemId,+ episodeId,+ loadOnly: true,+ );+ debugPrint(+ '[HomeWidget] launch load-paused: ${ok ? "loaded $itemId" : "last played not downloaded - skipped"}',+ );+ } catch (e) {+ debugPrint('[HomeWidget] launch load-paused failed: $e');+ }+ }+Future<bool> _resumeFromDownloadRecord(AudioPlayerService player,ApiService api,String itemId,- String? episodeId,- ) async {+ String? episodeId, {+ bool loadOnly = false,+ }) async {final downloads = DownloadService();final dlKey = episodeId != null ? '$itemId-$episodeId' : itemId;if (!downloads.isDownloaded(dlKey)) return false;@@ -573,6 +611,7 @@ class HomeWidgetService {episodeId: episodeId,episodeTitle: episodeId != null ? title : null,libraryId: info.libraryId,+ loadOnly: loadOnly,);return true;}