feat: auto-sync the library on a timer while the app is open

While the app is in the foreground a timer checks the auto-sync setting and
syncs when due (default every 24h; the interval is selectable from 15 minutes
to 24 hours). It stops when the app is backgrounded. "Sync automatically"
is one setting: Off, Wi-Fi only (default) or Always.

A running sync is shown by a silent, dismissible notification and a small
spinner on the library tab bar's settings button. A manual pull-to-refresh
still holds the pull spinner; only an automatic sync does not. The library
and Home sync actions no-op while a sync is running, and SyncManager
coalesces a request that arrives mid-run into a single follow-up, so repeated
pull-to-refresh cannot pile up runs while adding a server still syncs it.

The time of the last sync attempt is recorded, so a failing server is retried
once per interval rather than every poll. The sync consumer and the auto-sync
loop both survive an unexpected failure instead of silently disabling syncing
for the rest of the process.

The poll sleeps for the interval (capped at 15 minutes) instead of a fixed
minute, the network mode is collected once rather than re-registering a
connectivity callback each poll, and the decision is logged at DEBUG (visible
with Verbose logging) rather than writing to the log file every poll.
This commit is contained in:
austinried
2026-10-10 03:36:16 +00:00
parent 8e7431cc2e
commit e396671ac7
17 changed files with 653 additions and 34 deletions
@@ -4,7 +4,9 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.subtracks.data.model.Source
import com.subtracks.data.net.NetworkMode
import com.subtracks.data.prefs.DEFAULT_SYNC_INTERVAL_MINUTES
import com.subtracks.data.prefs.StreamQuality
import com.subtracks.data.prefs.SyncMode
import com.subtracks.data.prefs.UserPreferences
import com.subtracks.data.repo.SourceRepository
import com.subtracks.data.source.DEFAULT_FETCH_CONCURRENCY
@@ -48,6 +50,16 @@ class SettingsViewModel(
.syncConcurrency()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), DEFAULT_FETCH_CONCURRENCY)
val syncMode: StateFlow<SyncMode> =
userPreferences
.syncMode()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SyncMode.WifiOnly)
val syncIntervalMinutes: StateFlow<Int> =
userPreferences
.syncIntervalMinutes()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), DEFAULT_SYNC_INTERVAL_MINUTES)
val scrobbling: StateFlow<Boolean> =
userPreferences
.scrobbling()
@@ -92,6 +104,14 @@ class SettingsViewModel(
viewModelScope.launch { userPreferences.setSyncConcurrency(value) }
}
fun setSyncMode(mode: SyncMode) {
viewModelScope.launch { userPreferences.setSyncMode(mode) }
}
fun setSyncIntervalMinutes(value: Int) {
viewModelScope.launch { userPreferences.setSyncIntervalMinutes(value) }
}
fun setScrobbling(enabled: Boolean) {
viewModelScope.launch { userPreferences.setScrobbling(enabled) }
}