Yokan / rebuild
Course 1 8624561

TrackerLibraryViewModel.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/activity/TrackerLibraryViewModel.kt

implementation275 lines
1package eu.friedcutlet.yokan.ui.screens.activity23import 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.DbTrackPreference9import eu.friedcutlet.yokan.database.DbTrackSearch10import eu.friedcutlet.yokan.domain.ItemType11import eu.friedcutlet.yokan.domain.Manga12import eu.friedcutlet.yokan.services.catchingNonCancellation13import eu.friedcutlet.yokan.services.tracking.AnilistTrackerSyncId14import eu.friedcutlet.yokan.services.tracking.KitsuTrackerSyncId15import eu.friedcutlet.yokan.services.tracking.MalTrackerSyncId16import eu.friedcutlet.yokan.services.tracking.SimklTrackerSyncId17import eu.friedcutlet.yokan.services.tracking.TrackerService18import eu.friedcutlet.yokan.services.tracking.TraktTrackerSyncId19import eu.friedcutlet.yokan.services.tracking.orderedTrackers20import kotlinx.coroutines.CoroutineDispatcher21import kotlinx.coroutines.Dispatchers22import kotlinx.coroutines.Job23import kotlinx.coroutines.flow.MutableStateFlow24import kotlinx.coroutines.flow.StateFlow25import kotlinx.coroutines.flow.asStateFlow26import kotlinx.coroutines.flow.combine27import kotlinx.coroutines.flow.distinctUntilChanged28import kotlinx.coroutines.flow.flowOn29import kotlinx.coroutines.flow.map30import kotlinx.coroutines.flow.update31import kotlinx.coroutines.launch32import kotlinx.coroutines.withContext3334data class TrackerLibraryState(35    val trackers: List<TrackerService> = emptyList(),36    val selectedTracker: TrackerService? = null,37    /** The tracker library's own item-type cursor, seeded from the root one. */38    val itemType: ItemType = ItemType.Manga,39    /** Signed-in account of [selectedTracker], if any. */40    val account: DbTrackPreference? = null,41    val sections: List<TrackerLibrarySectionSpec> = emptyList(),42    /** Section label → loaded entries. */43    val sectionResults: Map<String, List<DbTrackSearch>> = emptyMap(),44    /** Non-blank while a search result section is shown. */45    val submittedQuery: String = "",46    val searchResults: List<DbTrackSearch> = emptyList(),47    val loading: Boolean = false,48    val error: String? = null,49    /** Library titles of [itemType] keyed by trimmed, lower-cased name. */50    val libraryByTitle: Map<String, Manga> = emptyMap(),51)5253/**54 * Tracker entries don't carry a library id, so a case-insensitive title match is the closest55 * approximation of "already in the library".56 */57internal fun TrackerLibraryState.matchInLibrary(search: DbTrackSearch): Manga? =58    search.title?.trim()?.lowercase()?.let(libraryByTitle::get)5960class TrackerLibraryViewModel(61    allTrackers: List<TrackerService>,62    private val repository: YokanRepository,63    settings: SettingsStore,64    initialItemType: ItemType,65    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,66) : ViewModel() {67    private val _state = MutableStateFlow(68        TrackerLibraryState(itemType = initialItemType, sections = trackerLibrarySections(-1, initialItemType)),69    )70    val state: StateFlow<TrackerLibraryState> = _state.asStateFlow()7172    private var loadJob: Job? = null73    private var searchJob: Job? = null7475    init {76        viewModelScope.launch {77            settings.db.map { orderedTrackers(allTrackers, it) }.distinctUntilChanged().collect { trackers ->78                val current = state.value79                // A changed tracker count resets the selection to the first tracker; a reorder keeps it.80                val keep = current.selectedTracker != null && trackers.size == current.trackers.size81                val selected = if (keep) current.selectedTracker else trackers.firstOrNull()82                _state.update { it.copy(trackers = trackers) }83                selectTracker(selected)84            }85        }86        viewModelScope.launch {87            combine(88                _state.map { it.selectedTracker?.syncId }.distinctUntilChanged(),89                repository.snapshots.map { it.trackPreferences }.distinctUntilChanged(),90            ) { syncId, preferences -> syncId?.let { id -> preferences.firstOrNull { it.syncId == id.toLong() } } }91                .collect { account -> _state.update { it.copy(account = account) } }92        }93        viewModelScope.launch {94            combine(95                _state.map { it.itemType }.distinctUntilChanged(),96                repository.observe({ it.mangas to it.settings }, workDispatcher) { },97            ) { type, _ -> type }98                .map { type -> repository.allTitles(type).associateBy { it.name.trim().lowercase() } }99                .flowOn(workDispatcher)100                .collect { titles -> _state.update { it.copy(libraryByTitle = titles) } }101        }102    }103104    fun selectTracker(tracker: TrackerService?) {105        if (tracker === state.value.selectedTracker) return106        _state.update { it.copy(selectedTracker = tracker) }107        clearSearch()108        load()109    }110111    fun selectItemType(itemType: ItemType) {112        if (itemType == state.value.itemType) return113        _state.update { it.copy(itemType = itemType) }114        clearSearch()115        load()116    }117118    /** Reloads every section of the selected tracker, one after another. */119    fun load() {120        val current = state.value121        val sections = trackerLibrarySections(current.selectedTracker?.syncId ?: -1, current.itemType)122        _state.update { it.copy(sections = sections) }123        val tracker = current.selectedTracker ?: return124        loadJob?.cancel()125        _state.update { it.copy(loading = true, error = null, sectionResults = emptyMap()) }126        loadJob = viewModelScope.launch {127            sections.forEach { spec ->128                catchingNonCancellation {129                    withContext(workDispatcher) {130                        if (spec.rankingType == null) {131                            tracker.fetchUserData(spec.isMangaFlag)132                        } else {133                            tracker.fetchGeneralData(spec.isMangaFlag, spec.rankingType)134                        }135                    }136                }.onSuccess { entries ->137                    _state.update { it.copy(sectionResults = it.sectionResults + (spec.label to entries)) }138                }.onFailure { failure ->139                    // User lists often require auth; only surface errors from public sections.140                    if (spec.rankingType != null) _state.update { it.copy(error = it.error ?: failure.message) }141                }142            }143            _state.update { it.copy(loading = false) }144        }145    }146147    fun search(text: String) {148        val current = state.value149        val tracker = current.selectedTracker ?: return150        if (text.isBlank()) {151            clearSearch()152            return153        }154        val isManga = current.itemType != ItemType.Anime155        _state.update { it.copy(submittedQuery = text) }156        searchJob?.cancel()157        searchJob = viewModelScope.launch {158            catchingNonCancellation { withContext(workDispatcher) { tracker.search(text, isManga) } }159                .onSuccess { results -> _state.update { it.copy(searchResults = results) } }160                .onFailure { failure -> _state.update { it.copy(error = failure.message ?: "Search failed") } }161        }162    }163164    fun clearSearch() {165        searchJob?.cancel()166        _state.update { it.copy(submittedQuery = "", searchResults = emptyList()) }167    }168169    /** Binds [manga] to [search], tagged with the selected tracker. */170    fun bindToLibrary(manga: Manga, search: DbTrackSearch) {171        val syncId = state.value.selectedTracker?.syncId172        val payload = if (syncId != null) search.copy(syncId = syncId) else search173        repository.bindTrack(manga.id, payload, manga.itemType)174    }175}176177/**178 * One horizontally-scrolling row in the tracker library. `rankingType == null`179 * loads the user's own list (Continue reading/watching); otherwise the key is180 * handed to [TrackerService.fetchGeneralData].181 * `isMangaFlag` mirrors Mangayomi's parameter reuse — for Simkl/Trakt it means182 * "movies" instead of "manga".183 */184data class TrackerLibrarySectionSpec(185    val label: String,186    val rankingType: String?,187    val isMangaFlag: Boolean,188)189190/** Ranking/browse sections exist for the Mangayomi providers and the metadata source only ([trackerLibrarySections]). */191internal val TrackerService.hasTrackerLibrary: Boolean192    get() = isMetadataSource ||193        syncId in setOf(MalTrackerSyncId, AnilistTrackerSyncId, KitsuTrackerSyncId, SimklTrackerSyncId, TraktTrackerSyncId)194195/** Provider-specific section lists mirroring Mangayomi's tracker_library_screen.dart. */196internal fun trackerLibrarySections(syncId: Int, itemType: ItemType): List<TrackerLibrarySectionSpec> {197    val isAnime = itemType == ItemType.Anime198    return when (syncId) {199        MalTrackerSyncId -> if (isAnime) {200            listOf(201                TrackerLibrarySectionSpec("Continue watching", null, false),202                TrackerLibrarySectionSpec("Airing Anime", "airing", false),203                TrackerLibrarySectionSpec("Popular Anime", "bypopularity", false),204                TrackerLibrarySectionSpec("Upcoming Anime", "upcoming", false),205            )206        } else {207            listOf(208                TrackerLibrarySectionSpec("Continue reading", null, true),209                TrackerLibrarySectionSpec("Popular Manga", "bypopularity", true),210                TrackerLibrarySectionSpec("Top Manga", "manga", true),211                TrackerLibrarySectionSpec("Top Manhwa", "manhwa", true),212                TrackerLibrarySectionSpec("Top Manhua", "manhua", true),213            )214        }215        AnilistTrackerSyncId -> if (isAnime) {216            listOf(217                TrackerLibrarySectionSpec("Continue watching", null, false),218                TrackerLibrarySectionSpec("Upcoming Anime", "upcoming", false),219                TrackerLibrarySectionSpec("Popular Anime", "popular", false),220                TrackerLibrarySectionSpec("Trending Anime", "trending", false),221                TrackerLibrarySectionSpec("Latest Anime", "latest", false),222            )223        } else {224            listOf(225                TrackerLibrarySectionSpec("Continue reading", null, true),226                TrackerLibrarySectionSpec("Upcoming Manga", "upcoming", true),227                TrackerLibrarySectionSpec("Popular Manga", "popular", true),228                TrackerLibrarySectionSpec("Trending Manga", "trending", true),229                TrackerLibrarySectionSpec("Latest Manga", "latest", true),230            )231        }232        KitsuTrackerSyncId -> if (isAnime) {233            listOf(234                TrackerLibrarySectionSpec("Continue watching", null, false),235                TrackerLibrarySectionSpec("Popular Anime", "popular", false),236                TrackerLibrarySectionSpec("Latest Anime", "latest", false),237                TrackerLibrarySectionSpec("Best Rated Anime", "best", false),238            )239        } else {240            listOf(241                TrackerLibrarySectionSpec("Continue reading", null, true),242                TrackerLibrarySectionSpec("Popular Manga", "popular", true),243                TrackerLibrarySectionSpec("Latest Manga", "latest", true),244                TrackerLibrarySectionSpec("Best Rated Manga", "best", true),245            )246        }247        SimklTrackerSyncId -> listOf(248            TrackerLibrarySectionSpec("Continue watching movies", null, true),249            TrackerLibrarySectionSpec("Continue watching series", null, false),250            TrackerLibrarySectionSpec("Trending Movies", "trending", true),251            TrackerLibrarySectionSpec("Trending Series", "trending", false),252            TrackerLibrarySectionSpec("Airing Series", "airing", false),253            TrackerLibrarySectionSpec("Top Series (All Time)", "best", false),254        )255        TraktTrackerSyncId -> listOf(256            TrackerLibrarySectionSpec("Continue watching movies", null, true),257            TrackerLibrarySectionSpec("Continue watching series", null, false),258            TrackerLibrarySectionSpec("Trending Movies", "trending", true),259            TrackerLibrarySectionSpec("Trending Series", "trending", false),260            TrackerLibrarySectionSpec("Popular Movies", "popular", true),261            TrackerLibrarySectionSpec("Popular Series", "popular", false),262            TrackerLibrarySectionSpec("Top Movies (All Time)", "favorited/all", true),263            TrackerLibrarySectionSpec("Top Series (All Time)", "favorited/all", false),264        )265        else -> {266            val isManga = !isAnime267            listOf(268                TrackerLibrarySectionSpec(if (isAnime) "Continue watching" else "Continue reading", null, isManga),269                TrackerLibrarySectionSpec("Trending", "trending", isManga),270                TrackerLibrarySectionSpec("Popular", "popular", isManga),271                TrackerLibrarySectionSpec("Top", "top", isManga),272            )273        }274    }275}276

Search chapters, reference and source filenames.