Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Stop streams from cutting out for a few seconds every hour

Barnabas140a67dce809
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dart
index 414c9aec..df9c0b76 100644
--- a/lib/providers/auth_provider.dart
+++ b/lib/providers/auth_provider.dart
@@ -139,7 +139,11 @@ class AuthProvider extends ChangeNotifier {
void applyServerSettings(Map<String, dynamic> settings) {
_serverSettings = settings;
final v = settings['version'] as String?;
- if (v != null && v.isNotEmpty) _serverVersion = v;
+ if (v != null && v.isNotEmpty) {
+ _serverVersion = v;
+ final url = activeServerUrl;
+ if (url != null) ApiService.cacheServerVersion(url, v);
+ }
notifyListeners();
}
@@ -707,6 +711,7 @@ class AuthProvider extends ChangeNotifier {
(_serverSettings?['version'] as String?);
if (loginVersion != null && loginVersion.isNotEmpty) {
_serverVersion = loginVersion;
+ ApiService.cacheServerVersion(url, loginVersion);
} else {
_fetchServerVersion(url);
}
@@ -907,6 +912,7 @@ class AuthProvider extends ChangeNotifier {
(_serverSettings?['version'] as String?);
if (oidcVersion != null && oidcVersion.isNotEmpty) {
_serverVersion = oidcVersion;
+ ApiService.cacheServerVersion(url, oidcVersion);
} else {
_fetchServerVersion(url);
}
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 81fd05a7..fda5e6bd 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -191,7 +191,9 @@ class ApiService {
_refreshToken = refreshToken,
_isLegacyToken = isLegacyToken,
_refreshRetryDelay = refreshRetryDelay,
- _httpClient = httpClient;
+ _httpClient = httpClient {
+ _loadCachedServerVersion(baseUrl);
+ }
/// Current access token (for external use like cover URLs, socket auth).
String get token => _accessToken;
@@ -644,12 +646,79 @@ class ApiService {
.timeout(const Duration(seconds: 10));
if (response.statusCode == 200) {
final data = jsonDecode(response.body) as Map<String, dynamic>;
- return data['serverVersion'] as String?;
+ final version = data['serverVersion'] as String?;
+ cacheServerVersion(serverUrl, version);
+ return version;
}
} catch (_) {}
return null;
}
+ // Last-known version per server origin. Stream URL shape depends on the
+ // server's capabilities, and buildTrackUrl is synchronous, so the version
+ // has to already be in memory by the time playback starts. Persisted per
+ // origin and re-hydrated on construction to cover cold starts where the
+ // /status fetch hasn't answered yet.
+ static final Map<String, String> _serverVersions = {};
+ static final Set<String> _serverVersionLoads = {};
+
+ static String? _originOf(String url) {
+ try {
+ return Uri.parse(normalizeServerUrl(url)).origin;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// Remember [version] for the server at [serverUrl], in memory and in prefs.
+ /// Called from every place a version is learned: login responses, /status,
+ /// and admin settings saves.
+ static void cacheServerVersion(String serverUrl, String? version) {
+ if (version == null || version.isEmpty) return;
+ final origin = _originOf(serverUrl);
+ if (origin == null) return;
+ _serverVersionLoads.add(origin);
+ if (_serverVersions[origin] == version) return;
+ _serverVersions[origin] = version;
+ unawaited(
+ SharedPreferences.getInstance()
+ .then((p) => p.setString('server_version_$origin', version))
+ .catchError((Object _) => false),
+ );
+ }
+
+ static void _loadCachedServerVersion(String serverUrl) {
+ final origin = _originOf(serverUrl);
+ if (origin == null || !_serverVersionLoads.add(origin)) return;
+ unawaited(
+ SharedPreferences.getInstance().then((p) {
+ final v = p.getString('server_version_$origin');
+ if (v != null && v.isNotEmpty) {
+ _serverVersions.putIfAbsent(origin, () => v);
+ }
+ }).catchError((Object _) {}),
+ );
+ }
+
+ /// True when [version] parses as `major.minor[.patch]` (optionally with a
+ /// leading `v`) and is at least [major].[minor]. Unparseable = false.
+ static bool serverVersionAtLeast(String? version, int major, int minor) {
+ final m = RegExp(r'^\s*v?(\d+)\.(\d+)').firstMatch(version ?? '');
+ if (m == null) return false;
+ final vMajor = int.parse(m.group(1)!);
+ if (vMajor != major) return vMajor > major;
+ return int.parse(m.group(2)!) >= minor;
+ }
+
+ /// Whether this server has the tokenless public session track endpoint
+ /// (added in Audiobookshelf v2.22.0). False while the version is unknown,
+ /// which safely degrades to the tokened URL form.
+ bool get _hasPublicSessionTracks {
+ final origin = _originOf(_cleanBaseUrl);
+ if (origin == null) return false;
+ return serverVersionAtLeast(_serverVersions[origin], 2, 22);
+ }
+
/// Get all libraries.
Future<List<dynamic>> getLibraries() async {
try {
@@ -1417,8 +1486,19 @@ class ApiService {
return null;
}
- /// Build a full audio track URL from a contentUrl returned by the play session.
- String buildTrackUrl(String contentUrl) {
+ /// Build a full audio track URL from a contentUrl returned by the play
+ /// session. When the caller passes the session context ([sessionId], the
+ /// track's own [trackIndex], [playMethod]) and the session is direct play
+ /// on a server with the public session endpoint, the URL is synthesized
+ /// with no token in it at all - the unguessable session id is the
+ /// credential, so token rotation can't 401 a stream mid-book. Everything
+ /// else keeps the contentUrl-based forms.
+ String buildTrackUrl(
+ String contentUrl, {
+ String? sessionId,
+ int? trackIndex,
+ int? playMethod,
+ }) {
// ABS servers with ROUTER_BASE_PATH set return contentUrls that already
// include the base path (e.g. "/abs/public/session/.../track/0"). If the
// user's server URL also includes that base path, blindly concatenating
@@ -1451,6 +1531,17 @@ class ApiService {
if (isAbsolute) return contentUrl;
+ // playMethod 0 = direct play. Transcode sessions must keep their HLS
+ // contentUrl, and pre-2.22 servers lack the endpoint but hand out legacy
+ // tokens that never expire, so both fall through safely.
+ if (sessionId != null &&
+ sessionId.isNotEmpty &&
+ trackIndex != null &&
+ playMethod == 0 &&
+ _hasPublicSessionTracks) {
+ return '$_cleanBaseUrl/public/session/$sessionId/track/$trackIndex';
+ }
+
// No per-track logging here: this runs in a hot loop over every track, and
// books with thousands of files would flood (and roll over) the log buffer.
// The session's "First track contentUrl" line already gives a sample.
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index d52db5b4..1af090ab 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -2275,15 +2275,32 @@ class AudioPlayerService extends ChangeNotifier {
/// Phase 1.7: snapshot the URLs and HTTP headers used to build the
/// streaming AudioSource so the iOS native widget core can hit the same
- /// endpoints if Flutter dies. Token is already in the URL; custom headers
- /// (Cloudflare Access etc.) ride along for reverse-proxy auth.
- void _captureStreamUrls(List<dynamic> audioTracks, ApiService api) {
+ /// endpoints if Flutter dies. Auth is in the URL (session id or token);
+ /// custom headers (Cloudflare Access etc.) ride along for reverse-proxy auth.
+ void _captureStreamUrls(
+ List<dynamic> audioTracks,
+ ApiService api, {
+ String? sessionId,
+ int? playMethod,
+ }) {
final urls = <String>[];
for (final t in audioTracks) {
final track = t as Map<String, dynamic>;
final contentUrl = track['contentUrl'] as String? ?? '';
if (contentUrl.isEmpty) continue;
- urls.add(api.buildTrackUrl(contentUrl));
+ urls.add(api.buildTrackUrl(
+ contentUrl,
+ sessionId: sessionId,
+ trackIndex: (track['index'] as num?)?.toInt(),
+ playMethod: playMethod,
+ ));
+ }
+ if (urls.isNotEmpty) {
+ final u = Uri.parse(urls.first);
+ final form = u.path.contains('/public/session/')
+ ? 'public session'
+ : (u.queryParameters.containsKey('token') ? 'tokened' : 'other');
+ debugPrint('[Player] Stream URL form: $form (${u.path})');
}
_activeStreamUrls = urls;
_activeStreamHeaders = Map<String, String>.from(api.playbackSessionHeaders);
@@ -3898,6 +3915,7 @@ class AudioPlayerService extends ChangeNotifier {
_lastServerSync = DateTime.now();
_logEvent(PlaybackEventType.sessionStart, detail: 'stream');
var audioTracks = sessionData['audioTracks'] as List<dynamic>?;
+ var sessionPlayMethod = (sessionData['playMethod'] as num?)?.toInt();
if (audioTracks == null || audioTracks.isEmpty) {
_clearState();
return 'No audio files found - this item may be missing on the server';
@@ -3943,6 +3961,7 @@ class AudioPlayerService extends ChangeNotifier {
}
_playbackSessionId = retrySession['id'] as String?;
audioTracks = retrySession['audioTracks'] as List<dynamic>? ?? [];
+ sessionPlayMethod = (retrySession['playMethod'] as num?)?.toInt();
if (audioTracks.isEmpty) {
_clearState();
return 'No audio files in transcoded session';
@@ -4058,12 +4077,22 @@ class AudioPlayerService extends ChangeNotifier {
// Build audio source - one source per track file
_buildTrackOffsets(audioTracks);
- _captureStreamUrls(audioTracks, api);
+ _captureStreamUrls(
+ audioTracks,
+ api,
+ sessionId: _playbackSessionId,
+ playMethod: sessionPlayMethod,
+ );
final trackSources = <AudioSource>[];
for (final t in audioTracks) {
final track = t as Map<String, dynamic>;
final contentUrl = track['contentUrl'] as String? ?? '';
- final fullUrl = api.buildTrackUrl(contentUrl);
+ final fullUrl = api.buildTrackUrl(
+ contentUrl,
+ sessionId: _playbackSessionId,
+ trackIndex: (track['index'] as num?)?.toInt(),
+ playMethod: sessionPlayMethod,
+ );
trackSources.add(
AudioSource.uri(
Uri.parse(fullUrl),
diff --git a/lib/services/chromecast_service.dart b/lib/services/chromecast_service.dart
index c2651037..672a5669 100644
--- a/lib/services/chromecast_service.dart
+++ b/lib/services/chromecast_service.dart
@@ -37,6 +37,7 @@ class ChromecastService extends ChangeNotifier {
Duration _castPosition = Duration.zero;
String? _connectedDeviceName;
String? _playbackSessionId;
+ int? _castPlayMethod;
DateTime _lastSyncTime = DateTime.now();
// Multi-track fallback state (when queueLoadItems fails)
@@ -526,6 +527,7 @@ class ChromecastService extends ChangeNotifier {
}
_playbackSessionId = sessionData['id'] as String?;
+ _castPlayMethod = (sessionData['playMethod'] as num?)?.toInt();
_lastSyncTime = DateTime.now();
// Promote Absorb's process to foreground so Doze doesn't throttle the
// per-15s sync timer when the user locks their screen. See GH #184.
@@ -571,7 +573,12 @@ class ChromecastService extends ChangeNotifier {
Future<bool> _loadSingleTrack(ApiService api, dynamic track, String title,
String author, String? coverUrl, double totalDuration, double startTime) async {
final m = track as Map<String, dynamic>;
- final fullUrl = api.buildTrackUrl(m['contentUrl'] as String? ?? '');
+ final fullUrl = api.buildTrackUrl(
+ m['contentUrl'] as String? ?? '',
+ sessionId: _playbackSessionId,
+ trackIndex: (m['index'] as num?)?.toInt(),
+ playMethod: _castPlayMethod,
+ );
debugPrint('[Cast] Loading single track URL: $fullUrl');
final subtitle = _buildSubtitle(author, startTime);
try {
@@ -624,7 +631,12 @@ class ChromecastService extends ChangeNotifier {
final items = <GoogleCastQueueItem>[];
for (int i = 0; i < tracks.length; i++) {
final m = tracks[i] as Map<String, dynamic>;
- final fullUrl = api.buildTrackUrl(m['contentUrl'] as String? ?? '');
+ final fullUrl = api.buildTrackUrl(
+ m['contentUrl'] as String? ?? '',
+ sessionId: _playbackSessionId,
+ trackIndex: (m['index'] as num?)?.toInt(),
+ playMethod: _castPlayMethod,
+ );
debugPrint('[Cast] Track $i URL: $fullUrl');
items.add(GoogleCastQueueItem(
mediaInformation: GoogleCastMediaInformation(
@@ -678,7 +690,12 @@ class ChromecastService extends ChangeNotifier {
List<double> offsets, int trackIdx, double localStart,
String title, String author, String? coverUrl, double totalDuration) async {
final m = tracks[trackIdx] as Map<String, dynamic>;
- final fallbackUrl = api.buildTrackUrl(m['contentUrl'] as String? ?? '');
+ final fallbackUrl = api.buildTrackUrl(
+ m['contentUrl'] as String? ?? '',
+ sessionId: _playbackSessionId,
+ trackIndex: (m['index'] as num?)?.toInt(),
+ playMethod: _castPlayMethod,
+ );
final trackDur = (m['duration'] as num?)?.toDouble() ?? totalDuration;
debugPrint('[Cast] Fallback: loading track $trackIdx/${tracks.length} at ${localStart}s');
await GoogleCastRemoteMediaClient.instance.loadMedia(