TorrentSettingsViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/player/TorrentSettingsViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.settings.player23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.SettingsStore6import eu.friedcutlet.yokan.database.DbTorrentPreferences7import eu.friedcutlet.yokan.database.DefaultTorrentTrackers8import eu.friedcutlet.yokan.services.catchingNonCancellation9import eu.friedcutlet.yokan.services.torrent.TorrentStreams10import kotlinx.coroutines.flow.MutableStateFlow11import kotlinx.coroutines.flow.StateFlow12import kotlinx.coroutines.flow.asStateFlow13import kotlinx.coroutines.flow.update14import kotlinx.coroutines.launch1516internal data class TorrentSettingsState(17 val busy: Boolean = false,18 val message: String? = null,19 val hostStatus: String? = null,20 val canHost: Boolean = false,21 val installedPath: String? = null,22)2324/** TorrServer install/check/stop; every check re-pushes the tracker list to the server. */25internal class TorrentSettingsViewModel(26 private val settings: SettingsStore,27 private val torrents: TorrentStreams,28) : ViewModel() {29 private val host = torrents.host30 private val _state = MutableStateFlow(TorrentSettingsState(canHost = host != null, installedPath = installed()))31 val state: StateFlow<TorrentSettingsState> = _state.asStateFlow()3233 init {34 host?.let { viewModelScope.launch { it.status.collect { status -> _state.update { s -> s.copy(hostStatus = status) } } } }35 }3637 fun update(transform: (DbTorrentPreferences) -> DbTorrentPreferences) =38 settings.updateDb { it.copy(features = it.features.copy(torrent = transform(it.features.torrent))) }3940 fun check() = run("Checking TorrServer…") { "Connected to TorrServer ${torrents.applySettings()}; trackers applied." }4142 fun resetTrackers() {43 update { it.copy(trackers = DefaultTorrentTrackers) }44 if (settings.db.value.features.torrent.enabled) check()45 }4647 fun install() = run("Downloading TorrServer…") {48 val path = checkNotNull(host).install { done, total ->49 if (total > 0) _state.update { it.copy(message = "Downloading TorrServer… ${done * 100 / total}%") }50 }51 _state.update { it.copy(installedPath = path) }52 "TorrServer installed and verified: $path"53 }5455 fun stop() = run("Stopping…") { torrents.stop(); "TorrServer stopped." }5657 fun dismissMessage() = _state.update { it.copy(message = null) }5859 private fun installed() = host?.executable(settings.db.value.features.torrent.executablePath)6061 private fun run(progress: String, action: suspend () -> String) {62 if (_state.value.busy) return63 _state.update { it.copy(busy = true, message = progress) }64 viewModelScope.launch {65 val message = catchingNonCancellation { action() }.getOrElse { it.message ?: "TorrServer request failed" }66 _state.update { it.copy(busy = false, message = message, installedPath = installed()) }67 }68 }69}70