TrackingSettingsViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/tracking/TrackingSettingsViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.settings.tracking23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.YokanRepository6import eu.friedcutlet.yokan.data.observe7import eu.friedcutlet.yokan.database.DbTrackPreference8import eu.friedcutlet.yokan.database.DbTrackStatus9import eu.friedcutlet.yokan.domain.Track10import eu.friedcutlet.yokan.services.catchingNonCancellation11import eu.friedcutlet.yokan.services.system.openSystemBrowser12import eu.friedcutlet.yokan.services.tracking.AnilistTrackerSyncId13import eu.friedcutlet.yokan.services.tracking.KitsuTrackerSyncId14import eu.friedcutlet.yokan.services.tracking.MalTrackerSyncId15import eu.friedcutlet.yokan.services.tracking.SimklTrackerSyncId16import eu.friedcutlet.yokan.services.tracking.TrackerAccounts17import eu.friedcutlet.yokan.services.tracking.TrackerLoginField18import eu.friedcutlet.yokan.services.tracking.TrackerService19import eu.friedcutlet.yokan.services.tracking.TraktTrackerSyncId20import kotlinx.coroutines.Job21import kotlinx.coroutines.flow.MutableStateFlow22import kotlinx.coroutines.flow.SharingStarted23import kotlinx.coroutines.flow.StateFlow24import kotlinx.coroutines.flow.asStateFlow25import kotlinx.coroutines.flow.combine26import kotlinx.coroutines.flow.distinctUntilChanged27import kotlinx.coroutines.flow.map28import kotlinx.coroutines.flow.stateIn29import kotlinx.coroutines.flow.update30import kotlinx.coroutines.launch31import org.jetbrains.compose.resources.getString32import yokan.composeapp.generated.resources.Res33import yokan.composeapp.generated.resources.tracking_login_enter_fields34import yokan.composeapp.generated.resources.tracking_login_failed35import yokan.composeapp.generated.resources.tracking_login_start_failed3637internal data class TrackingSettingsState(38 /** Tracker preference by sync id. */39 val preferences: Map<Long, DbTrackPreference> = emptyMap(),40 val tracks: List<Track> = emptyList(),41)4243/** What the tracker tiles and connect dialogs need from a [TrackerService]. */44internal data class TrackerUi(45 val syncId: Int,46 val name: String,47 val loginFields: List<TrackerLoginField> = emptyList(),48 val browserSignIn: Boolean = false,49)5051internal fun TrackerService.toUi() = TrackerUi(syncId, name, loginFields, browserSignIn)5253/** The credentials dialog of the tracker [syncId]; null when no dialog is open. */54internal data class TrackerLoginState(55 val syncId: Int? = null,56 val busy: Boolean = false,57 val status: String? = null,58)5960/** Shared by the Tracking, Manage trackers and Tracking detail pages (one instance per page entry). */61internal class TrackingSettingsViewModel(62 private val repository: YokanRepository,63 private val accounts: TrackerAccounts,64 private val trackers: List<TrackerService>,65 private val openBrowser: (String) -> Unit = { openSystemBrowser(it) },66) : ViewModel() {67 val state: StateFlow<TrackingSettingsState> = combine(68 repository.snapshots.map { it.trackPreferences }.distinctUntilChanged(),69 repository.observe({ it.tracks }) { tracks() },70 ) { preferences, tracks -> TrackingSettingsState(preferences.bySyncId(), tracks) }71 // Seeded synchronously so the first frame never shows "not connected".72 .stateIn(73 viewModelScope,74 SharingStarted.WhileSubscribed(5_000),75 TrackingSettingsState(repository.snapshots.value.trackPreferences.bySyncId(), repository.tracks()),76 )7778 /** The Tracking page's trackers: AniList, Kitsu, MAL, SIMKL, Trakt first; the metadata tracker belongs to the metadata server. */79 val connectable: List<TrackerUi> = trackers.filterNot { it.isMetadataSource }80 .sortedBy { LegacyOrder.indexOf(it.syncId).takeIf { i -> i >= 0 } ?: it.syncId }81 .map { it.toUi() }8283 private val _login = MutableStateFlow(TrackerLoginState())84 val login: StateFlow<TrackerLoginState> = _login.asStateFlow()85 private var loginJob: Job? = null86 private var authorizeJob: Job? = null8788 fun connect(syncId: Long, username: String, token: String) = accounts.connect(syncId, username, token)8990 fun openLogin(syncId: Int) {91 cancelLoginWork()92 _login.value = TrackerLoginState(syncId)93 }9495 /** Closes the dialog; a sign-in or sign-in page request still running is cancelled and never reports back. */96 fun dismissLogin() {97 cancelLoginWork()98 _login.value = TrackerLoginState()99 }100101 /** A message from the dialog itself (the OAuth callback arrived or failed). */102 fun showLoginStatus(status: String) = _login.update { it.copy(status = status) }103104 fun login(values: Map<TrackerLoginField, String>) {105 val current = _login.value106 val syncId = current.syncId ?: return107 if (current.busy) return108 _login.update { it.copy(busy = true, status = null) }109 loginJob = viewModelScope.launch {110 catchingNonCancellation { accounts.login(syncId.toLong(), values) }111 .onSuccess { _login.value = TrackerLoginState() }112 .onFailure { failure ->113 val message = failure.message ?: getString(Res.string.tracking_login_failed)114 _login.update { it.copy(busy = false, status = message) }115 }116 }117 }118119 /** Opens the provider's sign-in page for [values]. */120 fun authorize(values: Map<TrackerLoginField, String>) {121 val tracker = trackers.firstOrNull { it.syncId == _login.value.syncId } ?: return122 authorizeJob?.cancel()123 authorizeJob = viewModelScope.launch {124 catchingNonCancellation { tracker.authorizeUrl(values) }125 .onSuccess { url ->126 if (url != null) openBrowser(url)127 else showLoginStatus(getString(Res.string.tracking_login_enter_fields))128 }129 .onFailure { failure -> showLoginStatus(failure.message ?: getString(Res.string.tracking_login_start_failed)) }130 }131 }132133 fun disconnect(syncId: Long) = accounts.disconnect(syncId)134135 fun updateTrack(track: Track, progress: Int, status: DbTrackStatus, score: Int) =136 repository.updateTrack(track.id, progress, status, score)137138 fun removeTrack(track: Track, removeRemote: Boolean) = repository.removeTrack(track.id, removeRemote)139140 private fun cancelLoginWork() {141 loginJob?.cancel()142 authorizeJob?.cancel()143 }144}145146private val LegacyOrder = listOf(AnilistTrackerSyncId, KitsuTrackerSyncId, MalTrackerSyncId, SimklTrackerSyncId, TraktTrackerSyncId)147148private fun List<DbTrackPreference>.bySyncId(): Map<Long, DbTrackPreference> =149 mapNotNull { pref -> pref.syncId?.let { it to pref } }.toMap()150