ExtensionDetailViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/extensions/ExtensionDetailViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.extensions23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.SettingsStore6import eu.friedcutlet.yokan.data.YokanRepository7import eu.friedcutlet.yokan.data.toDomain8import eu.friedcutlet.yokan.database.DbSource9import eu.friedcutlet.yokan.database.YokanDatabase10import eu.friedcutlet.yokan.domain.Source11import eu.friedcutlet.yokan.services.catchingNonCancellation12import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory13import eu.friedcutlet.yokan.services.extensions.SourceInstallService14import eu.friedcutlet.yokan.services.extensions.SourcePreferenceValue15import eu.friedcutlet.yokan.services.extensions.mihon.MihonExtensionRuntimeService16import eu.friedcutlet.yokan.services.extensions.withSourceRuntime17import kotlinx.coroutines.CoroutineDispatcher18import kotlinx.coroutines.Dispatchers19import kotlinx.coroutines.flow.Flow20import kotlinx.coroutines.flow.MutableStateFlow21import kotlinx.coroutines.flow.StateFlow22import kotlinx.coroutines.flow.asStateFlow23import kotlinx.coroutines.flow.collectLatest24import kotlinx.coroutines.flow.combine25import kotlinx.coroutines.flow.distinctUntilChanged26import kotlinx.coroutines.flow.distinctUntilChangedBy27import kotlinx.coroutines.flow.map28import kotlinx.coroutines.flow.update29import kotlinx.coroutines.launch30import kotlinx.coroutines.withContext3132/** The source row, re-read only when the sources table changes. */33internal fun YokanRepository.observeDbSource(sourceId: Long): Flow<DbSource?> = snapshots34 .distinctUntilChangedBy { it.sources }35 .map { snapshot -> snapshot.sources.firstOrNull { it.id == sourceId } }36 .distinctUntilChanged()3738internal fun YokanRepository.currentDbSource(sourceId: Long): DbSource? =39 snapshots.value.sources.firstOrNull { it.id == sourceId }4041internal data class ExtensionDetailUiState(42 val dbSource: DbSource?,43 val actionMessage: String? = null,44 val preferences: List<SourcePreferenceValue> = emptyList(),45 val preferencesLoading: Boolean = false,46 /** Stored preference values for this source, by key. */47 val storedPreferences: Map<String, String> = emptyMap(),48) {49 val source: Source? = dbSource?.toDomain()50}5152/** Extension detail: metadata, uninstall, cookies and the runtime's preference list. */53internal class ExtensionDetailViewModel(54 private val sourceId: Long,55 repository: YokanRepository,56 private val settings: SettingsStore,57 private val sourceInstall: SourceInstallService,58 private val runtimeFactory: ExtensionRuntimeFactory,59 private val database: YokanDatabase,60 private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,61) : ViewModel() {62 private val _state = MutableStateFlow(ExtensionDetailUiState(repository.currentDbSource(sourceId)))63 val state: StateFlow<ExtensionDetailUiState> = _state.asStateFlow()64 private val preferenceReloads = MutableStateFlow(0)6566 init {67 viewModelScope.launch {68 repository.observeDbSource(sourceId).collect { db -> _state.update { it.copy(dbSource = db) } }69 }70 val storedPreferences = settings.db.map { it.sourcePreferences.orEmpty() }.distinctUntilChanged()71 viewModelScope.launch {72 storedPreferences.collect { stored ->73 _state.update { state ->74 state.copy(storedPreferences = stored.filter { it.sourceId == sourceId }.associate { it.key to it.value })75 }76 }77 }78 viewModelScope.launch {79 // The runtime reads stored values, so every preference write reloads the list.80 combine(storedPreferences, preferenceReloads) { _, reload -> reload }81 .collectLatest { reload -> loadPreferences(refresh = reload > 0) }82 }83 }8485 private suspend fun loadPreferences(refresh: Boolean) {86 _state.update { it.copy(preferencesLoading = true) }87 val preferences = catchingNonCancellation {88 withContext(workDispatcher) {89 runtimeFactory.withSourceRuntime(database, sourceId) { service ->90 if (refresh && service is MihonExtensionRuntimeService) {91 service.refreshSourcePreferences()92 } else {93 service.sourcePreferences()94 }95 }96 }97 }.getOrDefault(emptyList())98 _state.update { it.copy(preferences = preferences, preferencesLoading = false) }99 }100101 /** Mihon only: asks the extension to rebuild its preference screen. */102 fun refreshPreferences() = preferenceReloads.update { it + 1 }103104 fun setPreference(key: String, value: String) = settings.updateDb { it.withSourcePreference(sourceId, key, value) }105106 fun uninstall() {107 val source = _state.value.source ?: return108 val deleted = sourceInstall.uninstall(sourceId)109 _state.update {110 it.copy(actionMessage = if (deleted) "${source.name} was removed (obsolete)." else "${source.name} uninstalled.")111 }112 }113114 fun deleteCookies() {115 val source = _state.value.source ?: return116 sourceInstall.deleteCookies(source)117 _state.update { it.copy(actionMessage = "Cookies deleted for ${source.baseUrl}.") }118 }119}120