Yokan / rebuild
Course 1 8624561

SourceHomeViewModel.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/browse/SourceHomeViewModel.kt

implementation452 lines
1package eu.friedcutlet.yokan.ui.screens.browse23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.SettingsStore6import eu.friedcutlet.yokan.data.YokanRepository7import eu.friedcutlet.yokan.data.observe8import eu.friedcutlet.yokan.database.DbSavedSearch9import eu.friedcutlet.yokan.database.DbSource10import eu.friedcutlet.yokan.database.presetIdentity11import eu.friedcutlet.yokan.domain.Source12import eu.friedcutlet.yokan.services.extensions.FilterSelection13import eu.friedcutlet.yokan.services.extensions.RemoteManga14import eu.friedcutlet.yokan.services.extensions.SourceFilter15import eu.friedcutlet.yokan.services.extensions.SourceListing16import eu.friedcutlet.yokan.services.extensions.webViewUserAgent17import eu.friedcutlet.yokan.services.extensions.PresetIssue18import eu.friedcutlet.yokan.services.extensions.PresetIssueReason19import eu.friedcutlet.yokan.services.extensions.PresetValidation20import eu.friedcutlet.yokan.services.extensions.validateSourcePreset21import eu.friedcutlet.yokan.services.catchingNonCancellation22import kotlinx.coroutines.Job23import eu.friedcutlet.yokan.ui.navigation.Route24import eu.friedcutlet.yokan.util.PlatformLock25import kotlinx.coroutines.CancellationException26import kotlinx.coroutines.CoroutineDispatcher27import kotlinx.coroutines.Dispatchers28import kotlinx.coroutines.flow.MutableStateFlow29import kotlinx.coroutines.flow.StateFlow30import kotlinx.coroutines.flow.asStateFlow31import kotlinx.coroutines.flow.collectLatest32import kotlinx.coroutines.flow.distinctUntilChanged33import kotlinx.coroutines.flow.map34import kotlinx.coroutines.flow.update35import kotlinx.coroutines.launch36import kotlinx.coroutines.withContext3738internal data class SourceHomeLoadKey(39    val sourceId: Long,40    val tab: SourceTab,41    val query: String,42    val filterSelections: Map<String, FilterSelection>,43    val filtersApplied: Boolean,44    val revision: Long,45)4647internal data class SourceHomeUiState(48    val source: Source?,49    val genre: String? = null,50    // Match the Flutter source-home modes: Popular (0), Latest (1), Filter/Search (2).51    val selectedTab: SourceTab = SourceTab.Popular,52    val supportsLatest: Boolean = false,53    val isSearchMode: Boolean = false,54    val searchQuery: String = "",55    val submittedQuery: String = "",56    val filters: List<SourceFilter> = emptyList(),57    val selectedFilterValues: Map<String, FilterSelection> = emptyMap(),58    val appliedFilterValues: Map<String, FilterSelection> = emptyMap(),59    val filtersApplied: Boolean = false,60    val items: List<RemoteManga> = emptyList(),61    val page: Int = 1,62    val hasNextPage: Boolean = false,63    val appendExhausted: Boolean = false,64    val loading: Boolean = false,65    val loadingMore: Boolean = false,66    val error: String? = null,67    val loadedKey: SourceHomeLoadKey? = null,68    /** False while a genre request waits for the source's filter schema. */69    val filtersReady: Boolean = true,70    /** Links of favourited titles from this source (matched by source name and language). */71    val libraryLinks: Set<String> = emptySet(),72    val savedSearches: List<DbSavedSearch> = emptyList(),73    val filterSchemaReady: Boolean = false,74    val requestRevision: Long = 0,75    val presetEditor: PresetEditor? = null,76    val presetReview: PresetReview? = null,77    val reviewFiltersRequested: Boolean = false,78    /** "Hide entries already in library" for this source's media type ([DbBrowsePreferences]). */79    val hideLibrary: Boolean = false,80) {81    internal val loadKey: SourceHomeLoadKey?82        get() = source?.let {83            SourceHomeLoadKey(it.id, selectedTab, submittedQuery, appliedFilterValues, filtersApplied, requestRevision)84        }8586    /** [items] as shown: re-derived from the loaded pages, so toggling or library changes never refetch. */87    val visibleItems: List<RemoteManga> by lazy { items.withoutLibrary(hideLibrary, libraryLinks) }88}8990/** Drops listing entries whose url is a favourite of the same source (the "in library" badge key). */91internal fun List<RemoteManga>.withoutLibrary(hide: Boolean, libraryLinks: Set<String>): List<RemoteManga> =92    if (hide && libraryLinks.isNotEmpty()) filterNot { it.url in libraryLinks } else this9394/** Bound on consecutive pages fetched automatically because every entry was hidden as in-library. */95internal const val MaxHiddenPageFills = 59697/**98 * Last listing of recently closed Source Homes, so re-opening a source after a pop restores it.99 * Written only from [SourceHomeViewModel.onCleared]; entries are immutable states.100 */101internal class SourceHomeCache(private val capacity: Int) {102    private val lock = PlatformLock()103    private val entries = LinkedHashMap<Long, Pair<String?, SourceHomeUiState>>()104105    fun get(sourceId: Long, genre: String?): SourceHomeUiState? = lock.withLock {106        entries[sourceId]?.takeIf { it.first == genre }?.second107    }108109    fun put(sourceId: Long, genre: String?, state: SourceHomeUiState) = lock.withLock {110        entries.remove(sourceId)111        entries[sourceId] = genre to state112        while (entries.size > capacity) entries.remove(entries.keys.first())113    }114115}116117/**118 * Listing, search and filter state of one Source Home entry. Opening marks the source as last used119 * and heals a missing payload through [healPayload].120 */121internal class SourceHomeViewModel(122    private val sourceId: Long,123    genre: String?,124    private val repository: YokanRepository,125    private val settings: SettingsStore,126    healPayload: (sourceId: Long) -> Unit,127    private val cache: SourceHomeCache,128    private val loadListing: suspend (Source, SourceTab, String, Int, List<SourceFilter>) -> RuntimeLoad<SourceListing>,129    private val loadFilters: suspend (Source) -> List<SourceFilter>,130    private val loadLatestSupport: suspend (Source) -> Boolean,131    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,132) : ViewModel() {133    private val genre = genre?.trim()?.takeIf(String::isNotEmpty)134    private val _state: MutableStateFlow<SourceHomeUiState>135    val state: StateFlow<SourceHomeUiState>136    private var appendJob: Job? = null137    private var presetApplyJob: Job? = null138139    init {140        repository.markSourceUsed(sourceId)141        val source = repository.source(sourceId)142        val cached = cache.get(sourceId, this.genre)143        _state = MutableStateFlow(144            (cached?.copy(source = source)145                ?: SourceHomeUiState(146                    source = source,147                    genre = this.genre,148                    supportsLatest = source?.supportLatest ?: false,149                    filtersReady = this.genre == null,150                )).copy(hideLibrary = source != null && settings.db.value.features.browse.hidesLibrary(source.itemType)),151        )152        state = _state.asStateFlow()153        if (source != null) {154            healPayload(sourceId)155            collectSourceData(source)156            viewModelScope.launch { initialize(source, restored = cached != null) }157            viewModelScope.launch {158                // Re-fetch page 1 whenever the mode, the submitted query, or applied filters change.159                _state.map { if (it.filtersReady) it.loadKey else null }160                    .distinctUntilChanged()161                    .collectLatest { key ->162                        appendJob?.cancel()163                        if (key == null || _state.value.loadedKey == key) return@collectLatest164                        _state.update { it.copy(items = emptyList(), page = 1, hasNextPage = false, appendExhausted = false) }165                        if (loadPage(targetPage = 1, append = false)) _state.update { if (it.loadKey == key) it.copy(loadedKey = key) else it }166                    }167            }168            viewModelScope.launch { fillHiddenPages() }169        }170    }171172    private fun collectSourceData(initial: Source) {173        viewModelScope.launch {174            repository.observe({ it.sources }, workDispatcher) { source(sourceId) }.collect { source ->175                _state.update { it.copy(source = source) }176            }177        }178        viewModelScope.launch {179            // Mirror Flutter's library overlay: match favourites by source name + lang.180            repository.observe({ it.mangas }, workDispatcher) {181                allTitles(initial.itemType).asSequence()182                    .filter {183                        it.favorite && it.source.equals(initial.name, ignoreCase = true) &&184                            it.lang.equals(initial.lang, ignoreCase = true)185                    }186                    .map { it.link }187                    .toSet()188            }.collect { links -> _state.update { it.copy(libraryLinks = links) } }189        }190        viewModelScope.launch {191            settings.db.map { db -> db.savedSearches.orEmpty().filter { it.sourceId == sourceId } }192                .distinctUntilChanged()193                .collect { saved -> _state.update { it.copy(savedSearches = saved) } }194        }195        viewModelScope.launch {196            settings.db.map { it.features.browse.hidesLibrary(initial.itemType) }197                .distinctUntilChanged()198                .collect { hide -> _state.update { it.copy(hideLibrary = hide) } }199        }200    }201202    /**203     * Loading is manual (Load more tile), so a page whose entries are all in the library would leave204     * an empty screen without that tile: fetch following pages until something shows, at most205     * [MaxHiddenPageFills] in a row. A failed fetch keeps [SourceHomeUiState.page], which stops the run.206     */207    private suspend fun fillHiddenPages() {208        var filled = 0209        var lastPage = 0210        _state.collect { s ->211            if (!s.hideLibrary || s.items.isEmpty() || s.visibleItems.isNotEmpty()) {212                filled = 0213                lastPage = 0214                return@collect215            }216            if (s.loading || s.loadingMore || !s.hasNextPage || s.page == lastPage || filled >= MaxHiddenPageFills) return@collect217            filled++218            lastPage = s.page219            loadMore()220        }221    }222223    private suspend fun initialize(source: Source, restored: Boolean) {224        val latest = withContext(workDispatcher) { loadLatestSupport(source) }225        _state.update {226            it.copy(227                supportsLatest = latest,228                selectedTab = if (!latest && it.selectedTab == SourceTab.Latest) SourceTab.Popular else it.selectedTab,229            )230        }231        val fetched = catchingNonCancellation { withContext(workDispatcher) { loadFilters(source) } }232        val filters = fetched.getOrDefault(emptyList())233        _state.update { current ->234            val withFilters = current.copy(filters = filters, filtersReady = true, filterSchemaReady = fetched.isSuccess)235            // A restored home keeps its own search instead of re-running the genre request.236            if (genre == null || restored) return@update withFilters237            val request = genreSearchRequest(genre, filters)238            withFilters.copy(239                selectedFilterValues = request.selections,240                appliedFilterValues = request.selections,241                submittedQuery = request.query,242                searchQuery = request.query,243                selectedTab = SourceTab.Search,244                filtersApplied = request.selections.isNotEmpty(),245                isSearchMode = request.query.isNotEmpty(),246            )247        }248    }249250    private suspend fun loadPage(targetPage: Int, append: Boolean): Boolean {251        val current = _state.value252        val source = current.source ?: return false253        if (append && (current.loadingMore || current.loading)) return false254        _state.update { if (append) it.copy(loadingMore = true, error = null) else it.copy(loading = true, error = null) }255        return try {256            // Applied schema = schema with the user's selections folded in; the runtime receives it.257            val appliedFilters = current.filters.map { it.copy(selection = current.appliedFilterValues[it.id]) }258            val load = withContext(workDispatcher) {259                loadListing(source, current.selectedTab, current.submittedQuery, targetPage, appliedFilters)260            }261            _state.update { s ->262                if (s.loadKey != current.loadKey) return@update s263                val combined = if (append) s.items + load.value.items else load.value.items264                val seen = HashSet<String>(combined.size)265                val items = combined.filter { seen.add(it.url) }266                s.copy(267                    items = items,268                    page = targetPage,269                    hasNextPage = load.value.hasNextPage,270                    appendExhausted = append && items.size == s.items.size && !load.value.hasNextPage,271                    error = load.warning,272                )273            }274            true275        } catch (throwable: Throwable) {276            if (throwable is CancellationException) throw throwable277            val message = throwable.message.orEmpty().ifBlank { throwable::class.simpleName.orEmpty() }278            _state.update { if (it.loadKey == current.loadKey) it.copy(items = if (append) it.items else emptyList(), error = message) else it }279            false280        } finally {281            _state.update { if (it.loadKey == current.loadKey) it.copy(loading = false, loadingMore = false) else it }282        }283    }284285    fun retry() {286        viewModelScope.launch { loadPage(1, append = false) }287    }288289    fun loadMore() {290        val current = _state.value291        if (!current.loadingMore && (current.hasNextPage || current.selectedTab != SourceTab.Popular)) {292            appendJob = viewModelScope.launch { loadPage(current.page + 1, append = true) }293        }294    }295296    /** Per media type, shared with Home source feeds; the settings collector re-filters loaded pages. */297    fun setHideLibrary(hide: Boolean) {298        val type = _state.value.source?.itemType ?: return299        settings.updateDb { it.copy(features = it.features.copy(browse = it.features.browse.withHideLibrary(type, hide))) }300    }301302    fun setSearchQuery(query: String) = _state.update { it.copy(searchQuery = query) }303304    fun enterSearchMode() = _state.update { it.copy(isSearchMode = true, searchQuery = it.submittedQuery) }305306    fun submitSearch() = _state.update {307        val trimmed = it.searchQuery.trim()308        if (trimmed.isEmpty()) {309            it.copy(selectedTab = SourceTab.Popular, submittedQuery = "")310        } else {311            it.copy(selectedTab = SourceTab.Search, submittedQuery = trimmed)312        }313    }314315    /** Clears the query; a running search falls back to Popular. */316    fun clearSearch() = _state.update { it.clearedSearch() }317318    /** Back arrow or Escape inside search mode: first clear the text, then leave search mode. */319    fun backFromSearch() = _state.update {320        if (it.searchQuery.isBlank()) {321            it.copy(322                isSearchMode = false,323                submittedQuery = "",324                selectedTab = if (it.selectedTab == SourceTab.Search) SourceTab.Popular else it.selectedTab,325            )326        } else {327            it.copy(searchQuery = "")328        }329    }330331    /** Popular / Latest chips. */332    fun selectListing(tab: SourceTab) = _state.update {333        it.copy(selectedTab = tab, submittedQuery = "", searchQuery = "", isSearchMode = false)334    }335336    fun setFilterSelection(filterId: String, selection: FilterSelection?) = _state.update {337        it.copy(338            selectedFilterValues = if (selection == null) {339                it.selectedFilterValues - filterId340            } else {341                it.selectedFilterValues + (filterId to selection)342            },343        )344    }345346    fun resetFilters() {347        _state.update { it.copy(selectedFilterValues = emptyMap()) }348        val source = _state.value.source ?: return349        viewModelScope.launch {350            catchingNonCancellation { withContext(workDispatcher) { loadFilters(source) } }351                .onSuccess { filters -> _state.update { it.copy(filters = filters, filterSchemaReady = true) } }352                .onFailure { failure -> _state.update { it.copy(filterSchemaReady = false, error = failure.message) } }353        }354    }355356    fun applyFilters() = _state.update {357        it.copy(appliedFilterValues = it.selectedFilterValues, submittedQuery = it.searchQuery.trim(),358            selectedTab = SourceTab.Search, filtersApplied = !it.filtersApplied,359            reviewFiltersRequested = false)360    }361362    private fun savedPreset(id: String): DbSavedSearch? = settings.db.value.sourcePreset(sourceId, id)363364    private fun sourceRow(): DbSource? = repository.snapshots.value.sources.firstOrNull { it.id == sourceId }365366    fun onPresetEvent(event: SourcePresetEvent) {367        val current = _state.value368        when (event) {369            SourcePresetEvent.SaveCurrent -> if (current.filterSchemaReady) _state.update {370                it.copy(presetEditor = PresetEditor(PresetEditMode.Save, it.searchQuery.trim()))371            }372            is SourcePresetEvent.Rename -> savedPreset(event.id)?.let { saved -> _state.update {373                it.copy(presetEditor = PresetEditor(PresetEditMode.Rename, saved.name, saved.id))374            } }375            is SourcePresetEvent.Update -> if (current.filterSchemaReady) savedPreset(event.id)?.let { saved -> _state.update {376                it.copy(presetEditor = PresetEditor(PresetEditMode.Update, saved.name, saved.id))377            } }378            is SourcePresetEvent.NameChanged -> _state.update { it.copy(presetEditor = it.presetEditor?.copy(379                name = event.name, conflictId = null, invalidName = false)) }380            is SourcePresetEvent.Commit -> commitPresetEdit(event.replace)381            SourcePresetEvent.CancelEdit -> _state.update { it.copy(presetEditor = null) }382            is SourcePresetEvent.Apply -> {383                presetApplyJob?.cancel()384                presetApplyJob = viewModelScope.launch {385                    val saved = savedPreset(event.id) ?: return@launch386                    val source = _state.value.source ?: return@launch387                    if (saved.sourceIdentity != null && sourceRow()?.presetIdentity() != saved.sourceIdentity) {388                        applyPreset(saved)389                        return@launch390                    }391                    val fetched = catchingNonCancellation { withContext(workDispatcher) { loadFilters(source) } }392                    fetched.onSuccess { filters ->393                        _state.update { it.copy(filters = filters, filterSchemaReady = true) }394                        // Read the current stored row again in case it was deleted or renamed during fetch.395                        savedPreset(event.id)?.let(::applyPreset)396                    }.onFailure {397                        _state.update { it.copy(presetReview = PresetReview(saved, PresetValidation(emptyMap(),398                            listOf(PresetIssue(saved.name, PresetIssueReason.SchemaUnavailable))))) }399                    }400                }401            }402            is SourcePresetEvent.Delete -> settings.updateDb { it.withoutSourcePreset(sourceId, event.id) }403            SourcePresetEvent.CancelReview -> _state.update { it.copy(presetReview = null) }404            SourcePresetEvent.CloseReviewFilters -> _state.update { it.copy(reviewFiltersRequested = false) }405            SourcePresetEvent.ReviewFilters -> {406                val saved = current.presetReview?.preset ?: return407                val source = sourceRow() ?: return408                val checked = validateSourcePreset(saved, source, current.filters)409                if (!current.filterSchemaReady || !checked.canReview) return410                // Only stage the recoverable combination. No request runs until Filter is pressed.411                _state.update { it.copy(presetReview = null, searchQuery = saved.query, isSearchMode = true,412                    selectedFilterValues = checked.selections, reviewFiltersRequested = true) }413            }414        }415    }416417    private fun commitPresetEdit(replace: Boolean) {418        val source = sourceRow() ?: return419        val commit = commitPreset(_state.value, settings.db.value, source, replace) ?: return420        commit.save?.let { preset -> settings.updateDb { it.withSourcePreset(preset) } }421        _state.update { it.copy(presetEditor = commit.editor) }422    }423424    private fun applyPreset(preset: DbSavedSearch) {425        val source = sourceRow() ?: return426        _state.update { it.withPresetApplied(preset, source) }427    }428429    /** Caches [remote] as a browsed title and returns its id for the Detail route. */430    fun cacheRemote(remote: RemoteManga): Long? =431        _state.value.source?.let { repository.upsertRemoteTitle(it, remote).id }432433    fun webViewRoute(): Route.InAppWebView? {434        val source = _state.value.source?.takeIf { it.baseUrl.isNotBlank() } ?: return null435        val userAgent = settings.db.value.webViewUserAgent(source).takeIf { it.isNotBlank() }436        return Route.InAppWebView(source.baseUrl, source.name, userAgent)437    }438439    override fun onCleared() {440        val current = _state.value441        // Do not restore an interrupted genre request as an already initialized home.442        if (current.filtersReady && current.source != null) {443            cache.put(sourceId, genre, current.copy(loading = false, loadingMore = false, presetEditor = null, presetReview = null, reviewFiltersRequested = false))444        }445    }446}447448private fun SourceHomeUiState.clearedSearch() = copy(449    searchQuery = "",450    submittedQuery = "",451    selectedTab = if (selectedTab == SourceTab.Search) SourceTab.Popular else selectedTab,452)453

Search chapters, reference and source filenames.