A cross platform Audiobookshelf client for Android and iOS
Dart
Stabilize pending sync flush with single-flight batching
Kevin Gatera95e16640a63a
diff --git a/lib/services/progress_sync_service.dart b/lib/services/progress_sync_service.dartindex 67a4270d..4c1a190d 100644--- a/lib/services/progress_sync_service.dart+++ b/lib/services/progress_sync_service.dart@@ -15,6 +15,8 @@ class ProgressSyncService {StreamSubscription? _connectivitySub;bool _isOnline = true;+ bool _isFlushing = false;+ bool _flushAgain = false;/// Initialize — start listening for connectivity changes.Future<void> init() async {@@ -131,66 +133,100 @@ class ProgressSyncService {/// Flush all pending syncs (call when coming back online)./// Compares local vs server timestamps — last-write-wins.- Future<void> flushPendingSync({ApiService? api}) async {+ Future<void> flushPendingSync({ApiService? api, int maxItems = 5}) async {if (!_isOnline || api == null) return;- final pendingList = List<String>.from(- await ScopedPrefs.getStringList('pending_syncs'));-- if (pendingList.isEmpty) return;- debugPrint('[Sync] Flushing ${pendingList.length} pending syncs');-- for (final itemId in pendingList) {- final data = await getLocal(itemId);- if (data == null) continue;-- final localTime = (data['currentTime'] as num?)?.toDouble() ?? 0;- final localDuration = (data['duration'] as num?)?.toDouble() ?? 0;- final localTimestamp = (data['timestamp'] as num?)?.toInt() ?? 0;- if (localTime <= 0) continue;-- try {- final serverProgress = await api.getItemProgress(itemId);- if (serverProgress != null) {- final serverTimestamp = (serverProgress['lastUpdate'] as num?)?.toInt() ?? 0;- final serverTime = (serverProgress['currentTime'] as num?)?.toDouble() ?? 0;-- if (serverTimestamp > localTimestamp) {- debugPrint('[Sync] Server is newer for $itemId: server=${serverTime}s (${serverTimestamp}) vs local=${localTime}s (${localTimestamp}) — pulling');- await saveLocal(- itemId: itemId,- currentTime: serverTime,- duration: localDuration,- speed: (data['speed'] as num?)?.toDouble() ?? 1.0,- );- final updated = await ScopedPrefs.getStringList('pending_syncs');- updated.remove(itemId);- await ScopedPrefs.setStringList('pending_syncs', updated);- continue;- }- debugPrint('[Sync] Local is newer for $itemId: local=${localTime}s (${localTimestamp}) vs server=${serverTime}s (${serverTimestamp}) — pushing');+ if (_isFlushing) {+ _flushAgain = true;+ return;+ }++ _isFlushing = true;+ try {+ final pendingList = List<String>.from(+ await ScopedPrefs.getStringList('pending_syncs'));++ if (pendingList.isEmpty) return;++ final batch = pendingList.take(maxItems).toList();+ debugPrint('[Sync] Flushing ${batch.length}/${pendingList.length} pending syncs');++ for (final itemId in batch) {+ final data = await getLocal(itemId);+ if (data == null) {+ final updated = await ScopedPrefs.getStringList('pending_syncs');+ updated.remove(itemId);+ await ScopedPrefs.setStringList('pending_syncs', updated);+ continue;}- final session = await api.startPlaybackSession(itemId);- if (session != null) {- final sessionId = session['id'] as String?;- if (sessionId != null) {- await api.syncPlaybackSession(- sessionId,- currentTime: localTime,- duration: localDuration,- );- await api.closePlaybackSession(sessionId);- debugPrint('[Sync] Flushed $itemId via session: ${localTime}s');- }+ final localTime = (data['currentTime'] as num?)?.toDouble() ?? 0;+ final localDuration = (data['duration'] as num?)?.toDouble() ?? 0;+ final localTimestamp = (data['timestamp'] as num?)?.toInt() ?? 0;+ if (localTime <= 0) {+ final updated = await ScopedPrefs.getStringList('pending_syncs');+ updated.remove(itemId);+ await ScopedPrefs.setStringList('pending_syncs', updated);+ continue;}- final updated = await ScopedPrefs.getStringList('pending_syncs');- updated.remove(itemId);- await ScopedPrefs.setStringList('pending_syncs', updated);- } catch (e) {- debugPrint('[Sync] Flush failed for $itemId: $e');+ try {+ final serverProgress = await api.getItemProgress(itemId);+ if (serverProgress != null) {+ final serverTimestamp = (serverProgress['lastUpdate'] as num?)?.toInt() ?? 0;+ final serverTime = (serverProgress['currentTime'] as num?)?.toDouble() ?? 0;++ if (serverTimestamp > localTimestamp) {+ debugPrint('[Sync] Server is newer for $itemId: server=$serverTime s ($serverTimestamp) vs local=$localTime s ($localTimestamp) — pulling');+ await saveLocal(+ itemId: itemId,+ currentTime: serverTime,+ duration: localDuration,+ speed: (data['speed'] as num?)?.toDouble() ?? 1.0,+ );+ final updated = await ScopedPrefs.getStringList('pending_syncs');+ updated.remove(itemId);+ await ScopedPrefs.setStringList('pending_syncs', updated);+ continue;+ }+ debugPrint('[Sync] Local is newer for $itemId: local=$localTime s ($localTimestamp) vs server=$serverTime s ($serverTimestamp) — pushing');+ }++ final session = await api.startPlaybackSession(itemId);+ if (session != null) {+ final sessionId = session['id'] as String?;+ if (sessionId != null) {+ await api.syncPlaybackSession(+ sessionId,+ currentTime: localTime,+ duration: localDuration,+ );+ await api.closePlaybackSession(sessionId);+ debugPrint('[Sync] Flushed $itemId via session: ${localTime}s');+ }+ }++ final updated = await ScopedPrefs.getStringList('pending_syncs');+ updated.remove(itemId);+ await ScopedPrefs.setStringList('pending_syncs', updated);+ } catch (e) {+ debugPrint('[Sync] Flush failed for $itemId: $e');+ }}+ } finally {+ _isFlushing = false;+ }++ final remaining = await ScopedPrefs.getStringList('pending_syncs');+ if ((_flushAgain || remaining.isNotEmpty) && _isOnline) {+ _flushAgain = false;+ unawaited(+ Future<void>.delayed(const Duration(milliseconds: 250), () {+ return flushPendingSync(api: api, maxItems: maxItems);+ }),+ );+ } else {+ _flushAgain = false;}}