Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Report downloaded books as local plays and credit offline listening to the right day

Barnabas8b5d151fdd64
diff --git a/lib/main.dart b/lib/main.dart
index 94663ac7..4daf1d6d 100644
--- a/lib/main.dart
+++ b/lib/main.dart
@@ -21,6 +21,7 @@ import 'services/audio_player_service.dart';
import 'services/api_service.dart';
import 'services/download_service.dart';
import 'services/progress_sync_service.dart';
+import 'services/local_session_service.dart';
import 'services/equalizer_service.dart';
import 'services/sleep_timer_service.dart';
import 'services/scoped_prefs.dart';
@@ -520,6 +521,7 @@ class _AuthGateState extends State<AuthGate> {
debugPrint('[Init] remaining services... (${sw.elapsedMilliseconds}ms)');
try {
await ProgressSyncService().init();
+ await LocalSessionService().init();
await EqualizerService().init();
await SleepTimerService().loadAutoSleepSettings();
if (Platform.isAndroid) {
diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dart
index 9daa4341..a5bf5931 100644
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@ -138,6 +138,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
debugPrint('[Library] Manual offline off — flushing pending syncs');
ProgressSyncService().flushPendingSync(api: _api!);
ProgressSyncService().flushOfflineListeningTime(api: _api!);
+ LocalSessionService().flushPending(api: _api!);
}
if (_selectedLibraryId == null) {
(this as LibraryProvider).loadLibraries();
@@ -238,6 +239,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {
debugPrint('[Library] Back online — flushing pending syncs');
ProgressSyncService().flushPendingSync(api: _api!);
ProgressSyncService().flushOfflineListeningTime(api: _api!);
+ LocalSessionService().flushPending(api: _api!);
}
if (_selectedLibraryId == null) {
(this as LibraryProvider).loadLibraries();
diff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dart
index a7f46368..795ca687 100644
--- a/lib/providers/library_provider.dart
+++ b/lib/providers/library_provider.dart
@@ -9,6 +9,7 @@ import '../services/audio_player_service.dart';
import 'auth_provider.dart';
import '../services/api_service.dart';
import '../services/progress_sync_service.dart';
+import '../services/local_session_service.dart';
import '../services/download_service.dart';
import '../services/android_auto_service.dart';
import '../services/carplay_service.dart';
@@ -172,6 +173,7 @@ class LibraryProvider extends ChangeNotifier
if (_api != null && !isOffline) {
ProgressSyncService().flushPendingSync(api: _api!);
ProgressSyncService().flushOfflineListeningTime(api: _api!);
+ LocalSessionService().flushPending(api: _api!);
DownloadService().enrichMetadata(_api!);
// Start proactive reachability verification so the cloud icon
// reflects actual server state, not just the initial login result.
diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart
index 311bee58..46f90d12 100644
--- a/lib/services/api_service.dart
+++ b/lib/services/api_service.dart
@@ -5,6 +5,15 @@ import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:package_info_plus/package_info_plus.dart';
+/// Outcome of a local-session upsert. [serverTooOld] flags a 404/501 (the
+/// server predates /api/session/local) so the caller can fall back to the
+/// legacy /play flush instead of stranding the session in the replay queue.
+class LocalSessionResult {
+ final bool ok;
+ final bool serverTooOld;
+ const LocalSessionResult({required this.ok, required this.serverTooOld});
+}
+
class ApiService {
static String appVersion = '1.3.0'; // fallback; overwritten by initVersion()
@@ -788,6 +797,17 @@ class ApiService {
/// Expose clean base URL for audio player to build URLs
String get cleanBaseUrl => _cleanBaseUrl;
+ /// The device descriptor ABS attaches to playback sessions. Shared by the
+ /// /play session calls and the client-owned local-session calls.
+ Map<String, dynamic> get _deviceInfo => {
+ 'clientName': 'Absorb',
+ 'clientVersion': appVersion,
+ 'deviceId': deviceId,
+ 'deviceName': '${deviceManufacturer.isNotEmpty ? "$deviceManufacturer " : ""}$deviceModel'.trim(),
+ 'manufacturer': deviceManufacturer,
+ 'model': deviceModel,
+ };
+
/// Start a playback session for a library item.
/// POST /api/items/:id/play
/// Returns the full session object including audioTracks with contentUrl.
@@ -797,14 +817,7 @@ class ApiService {
final url = '$_cleanBaseUrl/api/items/$itemId/play$epPath';
debugPrint('[ABS] Starting playback session: POST $url (forceDirectPlay: $forceDirectPlay, forceTranscode: $forceTranscode)');
final body = <String, dynamic>{
- 'deviceInfo': {
- 'clientName': 'Absorb',
- 'clientVersion': appVersion,
- 'deviceId': deviceId,
- 'deviceName': '${deviceManufacturer.isNotEmpty ? "$deviceManufacturer " : ""}$deviceModel'.trim(),
- 'manufacturer': deviceManufacturer,
- 'model': deviceModel,
- },
+ 'deviceInfo': _deviceInfo,
'forceDirectPlay': !forceTranscode,
'forceTranscode': forceTranscode,
// Match what the native ABS Android app sends so the server treats us
@@ -914,6 +927,57 @@ class ApiService {
} catch (_) {}
}
+ /// Upsert a client-owned local playback session (downloaded/offline plays).
+ /// POST /api/session/local — preserves our playMethod (LOCAL) and the
+ /// client-supplied date/timestamps, unlike /play which forces Direct Play.
+ /// [session] is a fully-built session map; deviceInfo/mediaPlayer/playMethod
+ /// are stamped here so they can't be omitted.
+ Future<LocalSessionResult> syncLocalSession(Map<String, dynamic> session) async {
+ try {
+ final body = {
+ ...session,
+ 'deviceInfo': _deviceInfo,
+ 'mediaPlayer': 'exo-player',
+ 'playMethod': 3, // LOCAL
+ };
+ final resp = await _authPost(
+ Uri.parse('$_cleanBaseUrl/api/session/local'),
+ body: jsonEncode(body),
+ timeout: const Duration(seconds: 10));
+ return LocalSessionResult(
+ ok: resp.statusCode == 200,
+ serverTooOld: resp.statusCode == 404 || resp.statusCode == 501,
+ );
+ } catch (_) {
+ return const LocalSessionResult(ok: false, serverTooOld: false);
+ }
+ }
+
+ /// Batch-upsert local sessions, used to replay the offline queue on reconnect.
+ /// POST /api/session/local-all
+ Future<LocalSessionResult> syncLocalSessionsAll(
+ List<Map<String, dynamic>> sessions) async {
+ if (sessions.isEmpty) return const LocalSessionResult(ok: true, serverTooOld: false);
+ try {
+ final body = {
+ 'sessions': sessions
+ .map((s) => {...s, 'mediaPlayer': 'exo-player', 'playMethod': 3})
+ .toList(),
+ 'deviceInfo': _deviceInfo,
+ };
+ final resp = await _authPost(
+ Uri.parse('$_cleanBaseUrl/api/session/local-all'),
+ body: jsonEncode(body),
+ timeout: const Duration(seconds: 20));
+ return LocalSessionResult(
+ ok: resp.statusCode == 200,
+ serverTooOld: resp.statusCode == 404 || resp.statusCode == 501,
+ );
+ } catch (_) {
+ return const LocalSessionResult(ok: false, serverTooOld: false);
+ }
+ }
+
/// Get server progress for a single item.
/// GET /api/me/progress/:id
Future<Map<String, dynamic>?> getItemProgress(String itemId) async {
@@ -1072,14 +1136,7 @@ class ApiService {
final response = await _authPost(
Uri.parse(url),
body: jsonEncode({
- 'deviceInfo': {
- 'clientName': 'Absorb',
- 'clientVersion': appVersion,
- 'deviceId': deviceId,
- 'deviceName': '${deviceManufacturer.isNotEmpty ? "$deviceManufacturer " : ""}$deviceModel'.trim(),
- 'manufacturer': deviceManufacturer,
- 'model': deviceModel,
- },
+ 'deviceInfo': _deviceInfo,
'forceDirectPlay': !forceTranscode,
'forceTranscode': forceTranscode,
'mediaPlayer': 'exo-player',
diff --git a/lib/services/audio_player_service.dart b/lib/services/audio_player_service.dart
index 10c1c382..913e5c0f 100644
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@ -12,6 +12,7 @@ import 'download_service.dart';
import 'offline_source.dart';
import 'playback_history_service.dart' hide PlaybackEvent;
import 'progress_sync_service.dart';
+import 'local_session_service.dart';
import 'sync_logic.dart';
import 'sleep_timer_service.dart';
import 'equalizer_service.dart';
@@ -1114,6 +1115,11 @@ class AudioPlayerService extends ChangeNotifier {
Map<String, String> get activeStreamHeaders => _activeStreamHeaders;
bool _isOfflineMode = false;
+ /// True while the current play started from downloaded files and is reporting
+ /// to the server via the client-owned LOCAL session model (GH #276/#280)
+ /// instead of a live `/play` session. Position still syncs via /me/progress.
+ bool _localSessionMode = false;
+
/// Externally-pushed signal that the server is currently unreachable.
/// AuthProvider mirrors `serverReachable` here on each ping result so we
/// can short-circuit pre-play server calls (e.g. session creation) for
@@ -2528,114 +2534,65 @@ class AudioPlayerService extends ChangeNotifier {
final manualOffline = prefs.getBool('manual_offline_mode') ?? false;
debugPrint('[Player] manualOffline=$manualOffline, api=${_api != null}');
- // Try to start a server session for sync. Skip entirely if the user
- // is in manual offline mode OR if AuthProvider has told us the server
- // is unreachable (skip = instant local playback). Otherwise the call
- // is capped at 5s so a silently-dropping reverse proxy doesn't hold
- // up local playback for the full 20s api-level timeout.
+ // Downloaded plays report to the server via the client-owned LOCAL session
+ // model (GH #276 Local label, GH #280 per-day attribution), NOT a live
+ // /play session. Position still syncs through /me/progress; here we only
+ // reconcile the start position against the server's saved progress (when
+ // online) the way the /play response used to, sourced from GET /me/progress.
+ _localSessionMode = true;
+ _logEvent(PlaybackEventType.sessionStart, detail: 'local-session');
+ final pKey = _currentEpisodeId != null ? '$itemId-$_currentEpisodeId' : itemId;
if (_api != null && !manualOffline && !_knownOffline) {
try {
- debugPrint('[Player] Starting server session for local playback...');
- final sessionData = await (_currentEpisodeId != null
- ? _api!.startEpisodePlaybackSession(_currentItemId!, _currentEpisodeId!)
- : _api!.startPlaybackSession(itemId)
- ).timeout(const Duration(seconds: 5), onTimeout: () => null);
- if (sessionData != null) {
- _playbackSessionId = sessionData['id'] as String?;
- debugPrint('[Player] Got server session for local playback: $_playbackSessionId');
- _logEvent(PlaybackEventType.sessionStart, detail: 'local');
-
- // Alpha [PodDur]: which duration fields did the session response carry?
- // If the server ships a usable duration here and we ignore it, we
- // know the fix is to pick it up. Dump all plausible keys.
- final sdDuration = (sessionData['duration'] as num?)?.toDouble();
- final sdMediaDuration = (sessionData['mediaDuration'] as num?)?.toDouble();
- final sdMetaDur = (sessionData['mediaMetadata'] is Map<String, dynamic>)
- ? ((sessionData['mediaMetadata'] as Map<String, dynamic>)['duration'] as num?)?.toDouble()
- : null;
- debugPrint('[PodDur] session response: duration=$sdDuration mediaDuration=$sdMediaDuration mediaMetadata.duration=$sdMetaDur keys=${sessionData.keys.toList()}');
-
- // Fall back to session duration when the caller didn't have one.
- // Without this, podcast cold-starts from Android Auto push a first
- // MediaItem with dur=0, and AA never renders the progress bar.
- if (totalDuration <= 0 && sdDuration != null && sdDuration > 0) {
- totalDuration = sdDuration;
- _totalDuration = sdDuration;
- }
-
- // Pick up chapters from session (e.g. podcast episodes with embedded chapters)
- if (chapters.isEmpty) {
- final sessionChapters = sessionData['chapters'] as List<dynamic>? ?? [];
- if (sessionChapters.isNotEmpty) {
- chapters = sessionChapters;
- _chapters = sessionChapters;
- _handler?.updateChaptersQueue(sessionChapters);
- debugPrint('[Player] Loaded ${sessionChapters.length} chapters from session');
- }
- }
-
- // Compare server position vs local.
- // Usually the furthest position wins, but if local is ahead we also
- // check timestamps: a stale local save (e.g. from a crashed write)
- // shouldn't override a more recently synced server position.
- final serverPos = (sessionData['currentTime'] as num?)?.toDouble() ?? 0;
- final pKey = _currentEpisodeId != null ? '$itemId-$_currentEpisodeId' : itemId;
- final localTs = await _progressSync.getSavedTimestamp(pKey);
- if (serverPos > startTime + 1.0) {
- debugPrint('[Player] Server position is ahead: server=${serverPos}s vs local=${startTime}s — using server');
+ final serverProgress = await _api!
+ .getItemProgress(pKey)
+ .timeout(const Duration(seconds: 5), onTimeout: () => null);
+ final serverPos = (serverProgress?['currentTime'] as num?)?.toDouble() ?? 0;
+ final serverLastUpdate =
+ (serverProgress?['lastUpdate'] as num?)?.toInt() ?? 0;
+ final localTs = await _progressSync.getSavedTimestamp(pKey);
+ if (serverPos > startTime + 1.0) {
+ debugPrint('[Player] Server position is ahead: server=${serverPos}s vs local=${startTime}s — using server');
+ startTime = serverPos;
+ await _progressSync.saveLocal(
+ itemId: itemId,
+ currentTime: serverPos,
+ duration: totalDuration,
+ speed: 1.0,
+ );
+ } else if (startTime > 0) {
+ // Local is ahead — verify via timestamp that this isn't stale data.
+ // Skip the override if we have a pending local sync: local is the
+ // truth, we just haven't shipped it to the server yet.
+ bool useServer = false;
+ final hasPending = await _progressSync.hasPendingSync(pKey);
+ final gap = startTime - serverPos;
+ if (localTs > 0 &&
+ !hasPending &&
+ gap <= SyncLogic.localAheadSafetySeconds &&
+ serverLastUpdate > localTs) {
+ debugPrint('[Player] Local position is ahead but stale: local=${startTime}s (ts=$localTs) vs server=${serverPos}s (ts=$serverLastUpdate) — using server');
startTime = serverPos;
- await _progressSync.saveLocal(
- itemId: itemId,
- currentTime: serverPos,
- duration: totalDuration,
- speed: 1.0,
- );
- } else if (startTime > 0) {
- // Local is ahead — verify via timestamp that this isn't stale data.
- // Fetch the server's lastUpdate to compare with the local save time.
- // Skip the override if we have a pending local sync: local is the
- // truth, we just haven't shipped it to the server yet.
- bool useServer = false;
- final hasPending = await _progressSync.hasPendingSync(pKey);
- final gap = startTime - serverPos;
- if (localTs > 0 && !hasPending && gap <= SyncLogic.localAheadSafetySeconds) {
- try {
- final serverProgress = await _api!.getItemProgress(pKey);
- final serverLastUpdate = (serverProgress?['lastUpdate'] as num?)?.toInt() ?? 0;
- if (serverLastUpdate > localTs) {
- debugPrint('[Player] Local position is ahead but stale: local=${startTime}s (ts=$localTs) vs server=${serverPos}s (ts=$serverLastUpdate) — using server');
- startTime = serverPos;
- useServer = true;
- }
- } catch (_) {}
- }
- if (!useServer) {
- if (hasPending) {
- debugPrint('[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local (pending sync)');
- } else if (gap > SyncLogic.localAheadSafetySeconds) {
- debugPrint('[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local (gap ${gap.toStringAsFixed(1)}s exceeds safety threshold)');
- } else {
- debugPrint('[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local');
- }
+ useServer = true;
+ }
+ if (!useServer) {
+ if (hasPending) {
+ debugPrint('[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local (pending sync)');
+ } else if (gap > SyncLogic.localAheadSafetySeconds) {
+ debugPrint('[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local (gap ${gap.toStringAsFixed(1)}s exceeds safety threshold)');
+ } else {
+ debugPrint('[Player] Local position is ahead: local=${startTime}s vs server=${serverPos}s — keeping local');
}
- } else if (serverPos > 0) {
- debugPrint('[Player] No local position, using server: ${serverPos}s');
- startTime = serverPos;
}
- } else {
- debugPrint('[Player] startPlaybackSession returned null');
+ } else if (serverPos > 0) {
+ debugPrint('[Player] No local position, using server: ${serverPos}s');
+ startTime = serverPos;
}
} catch (e) {
- debugPrint('[Player] Could not start server session: $e');
+ debugPrint('[Player] Local-play progress reconcile failed: $e');
}
} else {
- debugPrint('[Player] Skipping server session — manual offline or no API');
- }
-
- // If no session, fall back to offline mode
- if (_playbackSessionId == null) {
- _isOfflineMode = true;
- debugPrint('[Player] No server session — true offline mode');
+ debugPrint('[Player] Skipping progress reconcile — manual offline or no API');
}
final localPaths = _downloadService.getLocalPaths(itemId);
@@ -2652,6 +2609,16 @@ class AudioPlayerService extends ChangeNotifier {
try {
final session = jsonDecode(cachedJson) as Map<String, dynamic>;
audioTracks = session['audioTracks'] as List<dynamic>?;
+ // Fall back to the cached session duration when the caller didn't have
+ // one (e.g. podcast cold-start from Android Auto pushes dur=0). Replaces
+ // the old /play-response duration fallback now that local plays skip it.
+ if (totalDuration <= 0) {
+ final cachedDur = (session['duration'] as num?)?.toDouble();
+ if (cachedDur != null && cachedDur > 0) {
+ totalDuration = cachedDur;
+ _totalDuration = cachedDur;
+ }
+ }
// Pick up chapters from cached session when not already loaded
if (chapters.isEmpty) {
final cachedChapters = session['chapters'] as List<dynamic>? ?? [];
@@ -2729,6 +2696,14 @@ class AudioPlayerService extends ChangeNotifier {
_scheduleAudioDiagnostics('local');
notifyListeners();
_setupSync();
+ await LocalSessionService().beginSession(
+ progressKey: pKey,
+ libraryItemId: itemId,
+ episodeId: _currentEpisodeId,
+ mediaType: _currentEpisodeId != null ? 'podcast' : 'book',
+ duration: totalDuration,
+ startTime: startTime,
+ );
Future.delayed(const Duration(milliseconds: 500), () {
_handler?.refreshPlaybackState();
});
@@ -3413,6 +3388,7 @@ class AudioPlayerService extends ChangeNotifier {
_currentCoverUrl = null;
_playbackSessionId = null;
_isOfflineMode = false;
+ _localSessionMode = false;
_trackStartOffsets = [];
_currentTrackIndex = 0;
_lastNotifiedChapterIndex = -1;
@@ -3757,7 +3733,9 @@ class AudioPlayerService extends ChangeNotifier {
// playback resumed), recreate it before the accumulator branch.
// Without this the offline accumulator fills for hours and gets
// dumped later as one phantom session with startTime==lastTime.
- if (!manualOffline &&
+ // Skipped for local-session plays — they never open a /play session.
+ if (!_localSessionMode &&
+ !manualOffline &&
!_isOfflineMode &&
_playbackSessionId == null &&
_api != null &&
@@ -3783,7 +3761,28 @@ class AudioPlayerService extends ChangeNotifier {
}
}
- if (manualOffline || _isOfflineMode || _playbackSessionId == null) {
+ if (_localSessionMode) {
+ // Downloaded play: accrue listening into the client-owned local
+ // session (per-day, reported to the server as Local). Position
+ // still syncs via /me/progress in the block below — independent
+ // of this listening session.
+ final progressKey = _currentEpisodeId != null
+ ? '$_currentItemId-$_currentEpisodeId'
+ : _currentItemId!;
+ final secs = sinceLastSync.clamp(0, 300);
+ final online = !manualOffline && !_isOfflineMode && _api != null;
+ await LocalSessionService().accrue(
+ progressKey: progressKey,
+ seconds: secs,
+ currentTime: absolutePos.inMilliseconds / 1000.0,
+ api: online ? _api : null,
+ );
+ unawaited(
+ _progressSync.addTimeSaved(secs, _player?.speed ?? 1.0));
+ unawaited(HomeWidgetService().addLocalListeningSeconds(secs));
+ // Reset the sync clock so the next tick waits a full interval.
+ _lastServerSync = DateTime.now();
+ } else if (manualOffline || _isOfflineMode || _playbackSessionId == null) {
// Offline or no session - accumulate listening time locally
final progressKey = _currentEpisodeId != null
? '$_currentItemId-$_currentEpisodeId'
@@ -4090,6 +4089,17 @@ class AudioPlayerService extends ChangeNotifier {
}());
}
+ // Local-session play: push the final accrued listening and finalize before
+ // any auto-advance begins a new session (awaited to avoid racing it).
+ if (_localSessionMode) {
+ _logEvent(PlaybackEventType.sessionEnd, detail: 'local book finished');
+ bool pushed = false;
+ if (_api != null) {
+ pushed = await LocalSessionService().pushActive(api: _api!);
+ }
+ await LocalSessionService().finalizeActive(pushed: pushed);
+ }
+
// Notify LibraryProvider before clearing state so it can update isFinished locally.
if (itemId != null) {
final key = episodeId != null ? '$itemId-$episodeId' : itemId;
@@ -4366,6 +4376,10 @@ class AudioPlayerService extends ChangeNotifier {
);
return;
}
+ // Restart the listening-time clock so the paused span isn't counted as
+ // listening on the first sync tick after resume (a long/overnight pause
+ // would otherwise be credited as up to 300s of phantom listening).
+ _lastServerSync = DateTime.now();
// Start playback immediately — don't wait for server calls
_player?.play();
_scheduleAudioDiagnostics('resume');
@@ -4405,8 +4419,8 @@ class AudioPlayerService extends ChangeNotifier {
if (_recreatingSession) return;
final manualOffline = (_prefs ?? await SharedPreferences.getInstance())
.getBool('manual_offline_mode') ?? false;
- if (manualOffline || _isOfflineMode) {
- debugPrint('[Player] Skipping session re-create on resume (manualOffline=$manualOffline, isOffline=$_isOfflineMode)');
+ if (manualOffline || _isOfflineMode || _localSessionMode) {
+ debugPrint('[Player] Skipping session re-create on resume (manualOffline=$manualOffline, isOffline=$_isOfflineMode, localSession=$_localSessionMode)');
return;
}
// Skip server position override if user manually seeked while paused
@@ -4501,6 +4515,30 @@ class AudioPlayerService extends ChangeNotifier {
// Check manual offline before syncing
final manualOffline = (_prefs ?? await SharedPreferences.getInstance())
.getBool('manual_offline_mode') ?? false;
+
+ // Local-session play: credit the real listening since the last tick — we
+ // were playing right up to this pause — then push. resume (play()) resets
+ // the sync clock so the paused span isn't counted. Runs even under manual
+ // offline since accrual works offline.
+ if (_localSessionMode) {
+ final pk = _currentEpisodeId != null
+ ? '$_currentItemId-$_currentEpisodeId'
+ : _currentItemId!;
+ final tail =
+ DateTime.now().difference(_lastServerSync).inSeconds.clamp(0, 300);
+ final online = !manualOffline && !_isOfflineMode && _api != null;
+ if (tail > 0) {
+ await LocalSessionService().accrue(
+ progressKey: pk,
+ seconds: tail,
+ currentTime: pos.inMilliseconds / 1000.0,
+ api: online ? _api : null);
+ } else if (online) {
+ unawaited(LocalSessionService().pushActive(api: _api!));
+ }
+ _lastServerSync = DateTime.now();
+ }
+
if (manualOffline) return;
if (!_isOfflineMode && _playbackSessionId != null) {
@@ -4742,6 +4780,16 @@ class AudioPlayerService extends ChangeNotifier {
}
}
+ // Local-session play: push the final accrued listening, then finalize.
+ // Runs even under manual offline so the session is queued for replay.
+ if (_localSessionMode) {
+ bool pushed = false;
+ if (!manualOffline && _api != null) {
+ pushed = await LocalSessionService().pushActive(api: _api!);
+ }
+ await LocalSessionService().finalizeActive(pushed: pushed);
+ }
+
await _player?.stop();
_onPlaybackStateChangedCallback?.call(false);
@@ -4769,6 +4817,11 @@ class AudioPlayerService extends ChangeNotifier {
await _api!.closePlaybackSession(_playbackSessionId!);
} catch (_) {}
}
+ // Local-session play: queue the accrued listening for replay (the user did
+ // listen; resetting position shouldn't erase that).
+ if (_localSessionMode) {
+ await LocalSessionService().finalizeActive();
+ }
await _player?.stop();
_clearState();
_chapters = [];
diff --git a/lib/services/local_session_service.dart b/lib/services/local_session_service.dart
new file mode 100644
index 00000000..842be4f3
--- /dev/null
+++ b/lib/services/local_session_service.dart
@@ -0,0 +1,345 @@
+import 'dart:convert';
+import 'dart:math';
+import 'package:flutter/foundation.dart';
+import 'api_service.dart';
+import 'scoped_prefs.dart';
+
+/// Owns client-built LOCAL playback sessions for downloaded/offline plays.
+///
+/// Why this exists: routing downloaded listening through the live `/play`
+/// session makes the server log "Direct Play" (GH #276) and, when offline,
+/// collapses days of listening into one session dated "now" (GH #280). This
+/// service instead builds Audiobookshelf local sessions (`playMethod: 3`),
+/// accrues `timeListening` as a cumulative total, and mints a fresh session id
+/// at each calendar-day boundary so each day's listening is attributed to the
+/// right day. Position/progress is NOT handled here — it stays on the existing
+/// `/me/progress` path (see [ProgressSyncService]).
+///
+/// Timestamps (`startedAt`/`updatedAt`/`date`) are captured at accrual time and
+/// replayed verbatim; they are never restamped at flush, which is what would
+/// re-collapse multi-day offline listening onto the reconnect day.
+class LocalSessionService {
+ LocalSessionService._();
+ static final LocalSessionService _instance = LocalSessionService._();
+ factory LocalSessionService() => _instance;
+
+ static const _kActive = 'local_session_active';
+ static const _kPending = 'local_session_pending';
+
+ static const _weekdays = [
+ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'
+ ];
+
+ /// Clock seam — overridden in tests to simulate day boundaries.
+ @visibleForTesting
+ DateTime Function() clock = DateTime.now;
+
+ Map<String, dynamic>? _active;
+ bool _loaded = false;
+ bool _flushing = false;
+ // Set once a server returns 404/501 for /api/session/local: that server is
+ // too old, so route everything through the legacy /play flush instead.
+ bool _localUnsupported = false;
+
+ // ── Date helpers (must match home_widget_service._dateKey so day buckets
+ // line up with the streak calculation). ──
+
+ String _dateKey(DateTime d) =>
+ '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';
+
+ String _dayOfWeek(DateTime d) => _weekdays[d.weekday - 1];
+
+ String _uuid() {
+ final r = Random.secure();
+ final b = List<int>.generate(16, (_) => r.nextInt(256));
+ b[6] = (b[6] & 0x0f) | 0x40; // version 4
+ b[8] = (b[8] & 0x3f) | 0x80; // variant
+ String h(int x) => x.toRadixString(16).padLeft(2, '0');
+ final s = b.map(h).join();
+ return '${s.substring(0, 8)}-${s.substring(8, 12)}-${s.substring(12, 16)}-${s.substring(16, 20)}-${s.substring(20)}';
+ }
+
+ // ── Persistence ──
+
+ Future<void> _loadActive() async {
+ if (_loaded) return;
+ final raw = await ScopedPrefs.getString(_kActive);
+ if (raw != null) {
+ try {
+ _active = jsonDecode(raw) as Map<String, dynamic>;
+ } catch (_) {
+ _active = null;
+ }
+ }
+ _loaded = true;
+ }
+
+ Future<void> _persistActive() async {
+ if (_active == null) {
+ await ScopedPrefs.remove(_kActive);
+ } else {
+ await ScopedPrefs.setString(_kActive, jsonEncode(_active));
+ }
+ }
+
+ Future<void> _enqueue(Map<String, dynamic> session) async {
+ final pending = await ScopedPrefs.getStringList(_kPending);
+ pending.add(jsonEncode(session));
+ await ScopedPrefs.setStringList(_kPending, pending);
+ }
+
+ /// The subset sent to the server. deviceInfo/mediaPlayer/playMethod are
+ /// stamped by [ApiService.syncLocalSession]/[ApiService.syncLocalSessionsAll].
+ Map<String, dynamic> _payload(Map<String, dynamic> s) => {
+ 'id': s['id'],
+ 'libraryItemId': s['libraryItemId'],
+ 'episodeId': s['episodeId'],
+ 'mediaType': s['mediaType'],
+ 'duration': s['duration'],
+ 'startTime': s['startTime'],
+ 'currentTime': s['currentTime'],
+ 'timeListening': s['timeListening'],
+ 'startedAt': s['startedAt'],
+ 'updatedAt': s['updatedAt'],
+ 'date': s['date'],
+ 'dayOfWeek': s['dayOfWeek'],
+ };
+
+ /// Reset in-memory state between tests.
+ @visibleForTesting
+ void debugReset() {
+ _active = null;
+ _loaded = false;
+ _flushing = false;
+ _localUnsupported = false;
+ clock = DateTime.now;
+ }
+
+ // ── Public API ──
+
+ /// On startup, treat any surviving active session as orphaned (the process
+ /// that owned it is gone): move it to the replay queue so it ships on the
+ /// next connection, and start clean.
+ Future<void> init() async {
+ await _loadActive();
+ if (_active != null) {
+ debugPrint('[LocalSession] Recovering orphaned active session ${_active!['id']} into pending');
+ await _enqueue(_active!);
+ _active = null;
+ await _persistActive();
+ }
+ }
+
+ /// Begin a local session for a freshly started downloaded play. Finalizes any
+ /// leftover active session for a different item first.
+ Future<void> beginSession({
+ required String progressKey,
+ required String libraryItemId,
+ String? episodeId,
+ required String mediaType,
+ required double duration,
+ required double startTime,
+ }) async {
+ await _loadActive();
+ final now = clock();
+ final nowMs = now.millisecondsSinceEpoch;
+ final today = _dateKey(now);
+ // Resume the existing session only if it's the same item on the same day.
+ if (_active != null &&
+ _active!['progressKey'] == progressKey &&
+ _active!['date'] == today) {
+ return;
+ }
+ // Any other lingering session — a different item, or the same item from a
+ // prior day (e.g. paused overnight, resumed by re-tapping the next day) —
+ // must be queued for replay before starting fresh, or its accrued
+ // listening would be dropped.
+ if (_active != null) {
+ await finalizeActive();
+ }
+ _active = {
+ 'id': _uuid(),
+ 'progressKey': progressKey,
+ 'libraryItemId': libraryItemId,
+ 'episodeId': episodeId,
+ 'mediaType': mediaType,
+ 'duration': duration,
+ 'startTime': startTime,
+ 'currentTime': startTime,
+ 'timeListening': 0,
+ 'startedAt': nowMs,
+ 'updatedAt': nowMs,
+ 'date': today,
+ 'dayOfWeek': _dayOfWeek(now),
+ };
+ await _persistActive();
+ debugPrint('[LocalSession] Began session ${_active!['id']} for $progressKey ($today)');
+ }
+
+ /// Accrue [seconds] of listening at [currentTime]. Rolls over to a new
+ /// session id when the calendar day changes. When [api] is non-null (online),
+ /// also upserts the active session.
+ Future<void> accrue({
+ required String progressKey,
+ required int seconds,
+ required double currentTime,
+ ApiService? api,
+ }) async {
+ if (seconds <= 0) return;
+ await _loadActive();
+ if (_active == null) {
+ debugPrint('[LocalSession] accrue with no active session — skipping');
+ return;
+ }
+ if (_active!['progressKey'] != progressKey) {
+ debugPrint('[LocalSession] accrue key mismatch (${_active!['progressKey']} != $progressKey) — finalizing stale session');
+ await finalizeActive();
+ return;
+ }
+
+ final lastMs = (_active!['updatedAt'] as num).toInt();
+ // A backward device clock must never move the session to an earlier day or
+ // mint a spurious session — clamp to the last accrual time so the day is
+ // derived from a non-decreasing timestamp.
+ final rawMs = clock().millisecondsSinceEpoch;
+ final nowMs = rawMs < lastMs ? lastMs : rawMs;
+ final effective = DateTime.fromMillisecondsSinceEpoch(nowMs);
+ final today = _dateKey(effective);
+
+ if (_active!['date'] != today) {
+ // Day boundary: freeze the old session (verbatim timestamps) and start a
+ // new one for today so listening is attributed to the correct day.
+ final old = _active!;
+ debugPrint('[LocalSession] Day rollover: ${old['date']} -> $today (session ${old['id']})');
+ await _enqueue(old);
+ _active = {
+ 'id': _uuid(),
+ 'progressKey': progressKey,
+ 'libraryItemId': old['libraryItemId'],
+ 'episodeId': old['episodeId'],
+ 'mediaType': old['mediaType'],
+ 'duration': old['duration'],
+ 'startTime': currentTime,
+ 'currentTime': currentTime,
+ 'timeListening': 0,
+ 'startedAt': nowMs,
+ 'updatedAt': nowMs,
+ 'date': today,
+ 'dayOfWeek': _dayOfWeek(effective),
+ };
+ // Ship the just-closed day promptly when online.
+ if (api != null) await flushPending(api: api);
+ }
+
+ _active!['timeListening'] = (_active!['timeListening'] as num).toInt() + seconds;
+ _active!['currentTime'] = currentTime;
+ _active!['updatedAt'] = nowMs;
+ _active!['date'] = today;
+ _active!['dayOfWeek'] = _dayOfWeek(effective);
+ await _persistActive();
+
+ if (api != null) await pushActive(api: api);
+ }
+
+ /// Upsert the active session now (idempotent — cumulative total). Returns
+ /// true when the server durably recorded it (so the caller can skip queuing).
+ Future<bool> pushActive({required ApiService api}) async {
+ await _loadActive();
+ if (_active == null) return true;
+ if (_localUnsupported) {
+ await _legacyFlush(api, _active!);
+ return true;
+ }
+ final result = await api.syncLocalSession(_payload(_active!));
+ if (result.serverTooOld) {
+ debugPrint('[LocalSession] Server lacks /api/session/local — falling back to /play');
+ _localUnsupported = true;
+ await _legacyFlush(api, _active!);
+ return true;
+ }
+ return result.ok;
+ }
+
+ /// Clear the active session (stop / finish / item change). When [pushed] is
+ /// false (offline, or the push failed) it's queued for replay; when true it's
+ /// already on the server so we just drop it.
+ Future<void> finalizeActive({bool pushed = false}) async {
+ await _loadActive();
+ if (_active == null) return;
+ if (!pushed) await _enqueue(_active!);
+ _active = null;
+ await _persistActive();
+ }
+
+ /// Replay queued sessions (plus the in-progress active session) to the
+ /// server. Called on reconnect / manual-offline-off.
+ Future<void> flushPending({required ApiService api}) async {
+ if (_flushing) return;
+ _flushing = true;
+ try {
+ await _loadActive();
+ final pendingRaw = await ScopedPrefs.getStringList(_kPending);
+ final sessions = <Map<String, dynamic>>[];
+ for (final raw in pendingRaw) {
+ try {
+ sessions.add(jsonDecode(raw) as Map<String, dynamic>);
+ } catch (_) {}
+ }
+ // Include the active session so its accrued time isn't stranded until the
+ // next finalize (e.g. reconnect while paused).
+ final combined = [...sessions, if (_active != null) _active!];
+ if (combined.isEmpty) return;
+
+ if (_localUnsupported) {
+ for (final s in combined) {
+ await _legacyFlush(api, s);
+ }
+ await ScopedPrefs.setStringList(_kPending, []);
+ return;
+ }
+
+ final result =
+ await api.syncLocalSessionsAll(combined.map(_payload).toList());
+ if (result.ok) {
+ // Keep the active session live; only clear the finalized queue.
+ await ScopedPrefs.setStringList(_kPending, []);
+ debugPrint('[LocalSession] Flushed ${combined.length} local session(s)');
+ } else if (result.serverTooOld) {
+ debugPrint('[LocalSession] Server lacks /api/session/local-all — falling back to /play');
+ _localUnsupported = true;
+ for (final s in combined) {
+ await _legacyFlush(api, s);
+ }
+ await ScopedPrefs.setStringList(_kPending, []);
+ }
+ // Network failure: leave the queue intact for the next trigger.
+ } finally {
+ _flushing = false;
+ }
+ }
+
+ /// Fallback for servers without /api/session/local: record the listening time
+ /// via the legacy open `/play` session. Loses per-day attribution and logs as
+ /// Direct Play (the old behavior), but doesn't lose the time.
+ Future<void> _legacyFlush(ApiService api, Map<String, dynamic> s) async {
+ try {
+ final libId = s['libraryItemId'] as String;
+ final epId = s['episodeId'] as String?;
+ final currentTime = (s['currentTime'] as num?)?.toDouble() ?? 0;
+ final duration = (s['duration'] as num?)?.toDouble() ?? 0;
+ final secs = (s['timeListening'] as num?)?.toInt() ?? 0;
+ if (secs <= 0) return;
+ final data = epId != null
+ ? await api.startEpisodePlaybackSession(libId, epId)
+ : await api.startPlaybackSession(libId);
+ final sid = data?['id'] as String?;
+ if (sid != null) {
+ await api.syncPlaybackSession(sid,
+ currentTime: currentTime, duration: duration, timeListened: secs);
+ await api.closePlaybackSession(sid);
+ }
+ } catch (e) {
+ debugPrint('[LocalSession] legacy flush failed: $e');
+ }
+ }
+}