Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Stop a wrong app-side duration from skewing the progress percent on the server

Barnabas65d1662469e8
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index d19689fe..493673c2 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -1801,8 +1801,10 @@ class ApiService {
body: jsonEncode({
'currentTime': currentTime,
'timeListened': timeListened,
+ // Older servers use this duration unconditionally for the progress
+ // row, so it must be sent; progress is ignored by every version
+ // (the server derives it from the session).
'duration': duration,
- 'progress': duration > 0 ? currentTime / duration : 0,
}),
timeout: const Duration(seconds: 10));
return response.statusCode == 200;
@@ -2035,7 +2037,7 @@ class ApiService {
final body = jsonEncode({
'currentTime': currentTime,
'duration': duration,
- 'progress': duration > 0 ? currentTime / duration : 0,
+ 'progress': duration > 0 ? (currentTime / duration).clamp(0.0, 1.0) : 0,
'isFinished': isFinished,
});
final progressPath = itemId.length > 36
@@ -2261,7 +2263,7 @@ class ApiService {
body: jsonEncode({
'currentTime': currentTime,
'duration': duration,
- 'progress': duration > 0 ? currentTime / duration : 0,
+ 'progress': duration > 0 ? (currentTime / duration).clamp(0.0, 1.0) : 0,
'isFinished': isFinished,
}),
timeout: const Duration(seconds: 10));
diff --git a/lib/services/local_session_service.dart b/lib/services/local_session_service.dart
index 36bc31c6..765b0117 100644
--- a/lib/services/local_session_service.dart
+++ b/lib/services/local_session_service.dart
@@ -2,6 +2,7 @@ import 'dart:convert';
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'api_service.dart';
+import 'progress_sync_service.dart';
import 'scoped_prefs.dart';
/// Owns client-built LOCAL playback sessions for downloaded/offline plays.
@@ -107,6 +108,24 @@ class LocalSessionService {
'dayOfWeek': s['dayOfWeek'],
};
+ /// Swap the payload's duration for the item's server-side duration when it
+ /// can be fetched - a wrong player duration on a session otherwise corrupts
+ /// the server's progress percent (abs issue #5468).
+ Future<Map<String, dynamic>> _trustedPayload(
+ ApiService api, Map<String, dynamic> s) async {
+ final payload = _payload(s);
+ final key = s['progressKey'] as String? ??
+ (s['episodeId'] != null
+ ? '${s['libraryItemId']}-${s['episodeId']}'
+ : s['libraryItemId'] as String? ?? '');
+ if (key.isNotEmpty) {
+ final local = (payload['duration'] as num?)?.toDouble() ?? 0;
+ payload['duration'] =
+ await ProgressSyncService().serverTrustedDuration(api, key, local);
+ }
+ return payload;
+ }
+
/// Reset in-memory state between tests.
@visibleForTesting
void debugReset() {
@@ -260,7 +279,8 @@ class LocalSessionService {
await _legacyFlush(api, _active!);
return true;
}
- final result = await api.syncLocalSession(_payload(_active!));
+ final result =
+ await api.syncLocalSession(await _trustedPayload(api, _active!));
if (result.serverTooOld) {
debugPrint('[LocalSession] Server lacks /api/session/local — falling back to /play');
_localUnsupported = true;
@@ -308,8 +328,11 @@ class LocalSessionService {
return;
}
- final result =
- await api.syncLocalSessionsAll(combined.map(_payload).toList());
+ final payloads = <Map<String, dynamic>>[];
+ for (final s in combined) {
+ payloads.add(await _trustedPayload(api, s));
+ }
+ final result = await api.syncLocalSessionsAll(payloads);
if (result.ok) {
// Keep the active session live; only clear the finalized queue.
await ScopedPrefs.setStringList(_kPending, []);
diff --git a/lib/services/progress_sync_service.dart b/lib/services/progress_sync_service.dart
index ec58ad87..d60cf3f5 100644
--- a/lib/services/progress_sync_service.dart
+++ b/lib/services/progress_sync_service.dart
@@ -142,6 +142,46 @@ class ProgressSyncService {
await ScopedPrefs.setStringList('pending_syncs', pendingList);
}
+ /// The duration sent with a progress write becomes the divisor for the
+ /// server's percentage, so a bad local duration corrupts the displayed
+ /// percent forever even while currentTime stays right (abs issue #5468).
+ /// Prefer the item's own server-side duration whenever it can be fetched.
+ final Map<String, double> _serverDurationCache = {};
+
+ Future<double> serverTrustedDuration(
+ ApiService api, String itemId, double localDuration) async {
+ final cached = _serverDurationCache[itemId];
+ if (cached != null) return cached;
+ final isCompound = itemId.length > 36;
+ final apiItemId = isCompound ? itemId.substring(0, 36) : itemId;
+ final episodeId = isCompound ? itemId.substring(37) : null;
+ try {
+ final item = await api.getLibraryItem(apiItemId);
+ final media = item?['media'] as Map<String, dynamic>?;
+ double serverDur = 0;
+ if (episodeId != null) {
+ for (final e in (media?['episodes'] as List<dynamic>? ?? const [])) {
+ if (e is Map<String, dynamic> && e['id'] == episodeId) {
+ serverDur = (e['duration'] as num?)?.toDouble() ?? 0;
+ break;
+ }
+ }
+ } else {
+ serverDur = (media?['duration'] as num?)?.toDouble() ?? 0;
+ }
+ if (serverDur > 0) {
+ if ((serverDur - localDuration).abs() > 1) {
+ debugPrint('[Sync] $itemId: using server duration '
+ '${serverDur.toStringAsFixed(0)}s over local '
+ '${localDuration.toStringAsFixed(0)}s');
+ }
+ _serverDurationCache[itemId] = serverDur;
+ return serverDur;
+ }
+ } catch (_) {}
+ return localDuration;
+ }
+
/// Sync a single item to the server. Returns true if synced.
Future<bool> syncToServer({
required ApiService api,
@@ -175,7 +215,7 @@ class ProgressSyncService {
await api.updateProgress(
itemId,
currentTime: currentTime,
- duration: duration,
+ duration: await serverTrustedDuration(api, itemId, duration),
isFinished: isFinished,
);
}
@@ -286,18 +326,20 @@ class ProgressSyncService {
final episodeId = isCompound ? itemId.substring(37) : null;
final localFinished = data['isFinished'] as bool? ?? false;
+ final syncDuration =
+ await serverTrustedDuration(api, itemId, localDuration);
if (episodeId != null) {
await api.updateEpisodeProgress(
apiItemId, episodeId,
currentTime: localTime,
- duration: localDuration,
+ duration: syncDuration,
isFinished: localFinished,
);
} else {
await api.updateProgress(
apiItemId,
currentTime: localTime,
- duration: localDuration,
+ duration: syncDuration,
isFinished: localFinished,
);
}