Yokan / rebuild
Course 1 8624561

SourceRelatedViewModel.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/discovery/SourceRelatedViewModel.kt

implementation91 lines
1package eu.friedcutlet.yokan.ui.screens.discovery23import androidx.compose.runtime.Immutable4import androidx.lifecycle.ViewModel5import androidx.lifecycle.viewModelScope6import eu.friedcutlet.yokan.data.YokanRepository7import eu.friedcutlet.yokan.database.YokanDatabase8import eu.friedcutlet.yokan.services.catchingNonCancellation9import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory10import eu.friedcutlet.yokan.services.extensions.RemoteManga11import eu.friedcutlet.yokan.services.extensions.SourceRelatedGroup12import eu.friedcutlet.yokan.services.extensions.withSourceRuntime13import kotlinx.coroutines.CoroutineDispatcher14import kotlinx.coroutines.Dispatchers15import kotlinx.coroutines.Job16import kotlinx.coroutines.flow.MutableStateFlow17import kotlinx.coroutines.flow.asStateFlow18import kotlinx.coroutines.flow.update19import kotlinx.coroutines.launch20import kotlinx.coroutines.withContext2122@Immutable23internal data class SourceRelatedState(24    val title: String = "",25    val loading: Boolean = false,26    val supported: Boolean? = null,27    val groups: List<SourceRelatedGroup> = emptyList(),28    val error: String? = null,29    val sourceId: Long? = null,30    val parentUrl: String? = null,31    val openedTitleId: Long? = null,32    val opening: Boolean = false,33)3435internal class SourceRelatedViewModel(36    private val mangaId: Long,37    private val repository: YokanRepository,38    private val database: YokanDatabase,39    private val runtimes: ExtensionRuntimeFactory,40    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,41) : ViewModel() {42    private val _state = MutableStateFlow(SourceRelatedState(loading = true))43    val state = _state.asStateFlow()44    private var loadJob: Job? = null4546    init { refresh() }4748    fun refresh() {49        if (loadJob?.isActive == true) return50        loadJob = viewModelScope.launch {51            _state.update { it.copy(loading = true, error = null) }52            catchingNonCancellation {53                val manga = withContext(workDispatcher) { repository.manga(mangaId) }54                val source = manga?.sourceId?.let { withContext(workDispatcher) { repository.source(it) } }55                if (manga == null || source == null || manga.isLocalArchive || manga.link.isBlank()) {56                    _state.update { it.copy(title = manga?.name.orEmpty(), supported = false, sourceId = null, groups = emptyList()) }57                } else {58                    val result = runtimes.withSourceRuntime(database, source.id) { it.related(manga.link) }59                    // The source/title may have been removed or rebound during the request.60                    val current = withContext(workDispatcher) { repository.manga(mangaId) }61                    check(current != null && current.sourceId == source.id && current.link == manga.link && repository.source(source.id) != null) {62                        "The source or title changed. Open related entries again."63                    }64                    _state.update { it.copy(title = current.name, supported = result.supported, groups = result.groups, sourceId = source.id, parentUrl = manga.link) }65                }66            }.onFailure { error -> _state.update { it.copy(error = error.message ?: "Unable to load related entries") } }67            _state.update { it.copy(loading = false) }68        }69    }7071    fun open(item: RemoteManga) {72        val current = _state.value73        if (current.opening || current.openedTitleId != null || current.groups.none { item in it.items }) return74        val sourceId = current.sourceId ?: return75        _state.update { it.copy(opening = true) }76        // One transaction validates ownership and resolves an existing entry without changing favourites.77        viewModelScope.launch {78            catchingNonCancellation { withContext(workDispatcher) { database.batch {79                    val source = repository.source(sourceId) ?: error("The source was removed. Reload related entries.")80                    val parent = repository.manga(mangaId)81                    check(parent != null && parent.sourceId == sourceId && parent.link == current.parentUrl) { "The title changed. Reload related entries." }82                    repository.upsertRemoteTitle(source, item).id83                } }84            }.onSuccess { id -> _state.update { it.copy(openedTitleId = id) } }85                .onFailure { error -> _state.update { it.copy(error = error.message ?: "Unable to open related entry") } }86            _state.update { it.copy(opening = false) }87        }88    }8990    fun opened() { _state.update { it.copy(openedTitleId = null) } }91}92

Search chapters, reference and source filenames.