Yokan / rebuild
Course 1 8624561

HomeViewModel.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeViewModel.kt

implementation170 lines
1package eu.friedcutlet.yokan.ui.screens.home23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.SettingsStore6import eu.friedcutlet.yokan.data.YokanRepository7import eu.friedcutlet.yokan.database.*8import eu.friedcutlet.yokan.services.discovery.*9import eu.friedcutlet.yokan.ui.navigation.AwaitedViewModelCleanup10import kotlinx.coroutines.*11import kotlinx.coroutines.flow.*12import kotlinx.coroutines.sync.Semaphore13import kotlinx.coroutines.sync.withPermit1415@OptIn(ExperimentalCoroutinesApi::class)16internal class HomeViewModel(17    private val repository: YokanRepository,18    private val settings: SettingsStore,19    private val discovery: DiscoveryService,20    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,21    private val trackerScoreRanges: Map<Int, IntRange> = emptyMap(),22) : ViewModel(), AwaitedViewModelCleanup {23    private val _state = MutableStateFlow(HomeState(preferences = settings.db.value.home.forPresentation()))24    val state = _state.asStateFlow()25    private val active = MutableStateFlow(false)26    private val local = MutableStateFlow(HomeLocalData())27    private val remote = MutableStateFlow<List<HomeRemoteShelf>>(emptyList())28    private var requestKey: RequestKey? = null29    private var loadJob: Job? = null30    private val jobs = mutableListOf<Job>()31    private var generation = 0L3233    private data class RequestKey(34        val aniList: Boolean, val tmdb: Boolean, val token: String, val adult: Boolean,35        val hidden: Set<HomeSection>, val featured: Boolean, val libraryOnly: Boolean,36        val seedTitle: String?, val seedKind: HomeMediaFilter?, val feeds: List<DbHomeSourceFeed>,37        val sourceRevisions: List<Pair<Long, Long>>, val presets: List<DbSavedSearch>,38        val sourcePreferences: List<DbSourcePreference>, val hiddenTypes: Set<eu.friedcutlet.yokan.domain.ItemType>,39        val tmdbSeeds: List<TmdbSeed>,40    )4142    init {43        jobs += viewModelScope.launch {44            combine(active, repository.snapshots.distinctUntilChanged { old, new ->45                old.mangas === new.mangas && old.chapters === new.chapters && old.histories === new.histories &&46                    old.tracks === new.tracks && old.sources === new.sources && old.downloads === new.downloads &&47                    old.pageCache === new.pageCache && old.settings === new.settings48            }) { visible, snapshot -> visible to snapshot }.collectLatest { (visible, snapshot) ->49                if (visible) local.value = withContext(workDispatcher) { projectHomeLocal(snapshot, trackerScoreRanges) }50            }51        }52        jobs += viewModelScope.launch {53            combine(local, remote, settings.db) { data, shelves, db -> Triple(data, shelves, db) }54                .mapLatest { (data, shelves, db) -> withContext(workDispatcher) { buildHomeState(data, shelves, db) } }55                .collect { content -> _state.update { content.copy(customizeOpen = it.customizeOpen, searchOpen = it.searchOpen, searchQuery = it.searchQuery, openIssue = it.openIssue) } }56        }57        jobs += viewModelScope.launch {58            combine(active, local, settings.db) { visible, data, db -> Triple(visible, data, db) }59                .collect { (visible, data, db) ->60                    if (!visible) {61                        generation++62                        loadJob?.cancel()63                        requestKey = null64                    } else {65                        val prefs = db.home66                        val key = RequestKey(prefs.enableAniList, prefs.enableTmdb, prefs.tmdbReadAccessToken, db.showNsfw,67                            prefs.hiddenSections, prefs.showFeatured, prefs.featuredLibraryOnly, data.seed?.media?.title, data.seed?.media?.kind,68                            prefs.sourceFeeds.distinctBy { it.key }.take(8), data.sources.map { it.id to it.updatedAt }, data.presets,69                            db.sourcePreferences.orEmpty(), data.hiddenTypes,70                            // Sorted: re-watching only reorders seeds and must not reload every shelf.71                            data.tmdbSeeds.sortedBy { it.key })72                        if (key != requestKey) load(key, refresh = false)73                    }74                }75        }76    }7778    fun setActive(value: Boolean) { active.value = value }79    fun customize(value: Boolean) { _state.update { it.copy(customizeOpen = value) } }80    fun search(value: Boolean) { _state.update { it.copy(searchOpen = value) } }81    fun query(value: String) { _state.update { it.copy(searchQuery = value) } }82    fun openIssue(value: DiscoveryIssue?) { _state.update { it.copy(openIssue = value) } }83    fun updatePreferences(transform: (DbHomePreferences) -> DbHomePreferences) = settings.updateDb { it.copy(features = it.features.copy(home = transform(it.home))) }84    fun setTmdbToken(value: String) = updatePreferences { it.copy(tmdbReadAccessToken = value.trim().removePrefix("Bearer ")) }85    fun addFeed(feed: DbHomeSourceFeed) = updatePreferences {86        it.copy(sourceFeeds = (it.sourceFeeds + feed).distinctBy(DbHomeSourceFeed::key).take(8))87    }88    fun removeFeed(key: String) = updatePreferences { it.copy(sourceFeeds = it.sourceFeeds.filterNot { feed -> feed.key == key }) }89    fun moveFeed(key: String, delta: Int) = updatePreferences { prefs ->90        val feeds = prefs.sourceFeeds.toMutableList()91        val from = feeds.indexOfFirst { it.key == key }92        if (from >= 0) feeds.add((from + delta).coerceIn(0, feeds.lastIndex), feeds.removeAt(from))93        prefs.copy(sourceFeeds = feeds)94    }95    fun refresh() { requestKey?.let { load(it, refresh = true) } }9697    private fun load(key: RequestKey, refresh: Boolean) {98        val oldKey = requestKey99        requestKey = key100        generation++101        val revision = generation102        loadJob?.cancel()103        val requests = buildList<Pair<HomeRemoteShelf, suspend () -> List<DiscoveryMedia>>> {104            fun popularity(kind: HomeMediaFilter, section: HomeSection) {105                if (DiscoveryMedia("", "", kind).itemType in key.hiddenTypes) return106                if (section !in key.hidden || (key.featured && !key.libraryOnly) || HomeSection.Recommended !in key.hidden) {107                    add(HomeRemoteShelf(section.name, section) to { discovery.popular(kind, key.token, key.adult, refresh) })108                }109            }110            if (key.aniList) {111                popularity(HomeMediaFilter.Anime, HomeSection.PopularAnime)112                popularity(HomeMediaFilter.Manga, HomeSection.PopularManga)113                popularity(HomeMediaFilter.Novel, HomeSection.PopularNovels)114                if (key.seedTitle != null && key.seedKind != null && HomeSection.BecauseYouRead !in key.hidden) {115                    add(HomeRemoteShelf("because", HomeSection.BecauseYouRead) to {116                        discovery.recommendations(key.seedTitle, key.seedKind, key.adult, refresh)117                    })118                }119            }120            if (key.tmdb) {121                if (key.tmdbSeeds.isNotEmpty() && HomeSection.TmdbRecommended !in key.hidden &&122                    eu.friedcutlet.yokan.domain.ItemType.Anime !in key.hiddenTypes) {123                    add(HomeRemoteShelf("tmdb-recommended", HomeSection.TmdbRecommended) to {124                        discovery.tmdbRecommendations(key.tmdbSeeds, key.token, key.adult, refresh)125                    })126                }127                popularity(HomeMediaFilter.Movie, HomeSection.PopularMovies)128                popularity(HomeMediaFilter.Series, HomeSection.PopularSeries)129            }130            if (HomeSection.Sources !in key.hidden) key.feeds.forEach { feed ->131                val source = local.value.sources.firstOrNull { it.id == feed.sourceId }132                val name = source?.name.orEmpty() + key.presets.firstOrNull { it.id == feed.presetId }?.name?.let { " · $it" }.orEmpty()133                add(HomeRemoteShelf("feed:${feed.key}", HomeSection.Sources, sourceName = name) to { discovery.sourceFeed(feed, key.adult, refresh) })134            }135        }136        val keep = oldKey != null && oldKey.adult == key.adult && oldKey.token == key.token137        val previous = remote.value.associateBy { it.id }138        remote.value = requests.map { (shelf, _) -> shelf.copy(139            items = if (keep && (shelf.id != "because" || oldKey.seedTitle == key.seedTitle)) previous[shelf.id]?.items.orEmpty() else emptyList(), loading = true) }140        loadJob = viewModelScope.launch {141            val gate = Semaphore(3)142            supervisorScope {143                requests.map { (shelf, request) -> launch {144                    val result = try {145                        Result.success(gate.withPermit { request() })146                    } catch (timeout: TimeoutCancellationException) { Result.failure(timeout) }147                    catch (cancel: CancellationException) { throw cancel }148                    catch (failure: Throwable) { Result.failure(failure) }149                    ensureActive()150                    if (revision != generation) return@launch151                    remote.update { rows -> rows.map { row -> if (row.id != shelf.id) row else result.fold(152                        { row.copy(items = it, loading = false, issue = null) },153                        { row.copy(loading = false, issue = (it as? DiscoveryException)?.issue ?: DiscoveryIssue.Network) },154                    ) } }155                } }.joinAll()156            }157        }158    }159160    override suspend fun awaitCleanup() {161        generation++162        // Stop producers first, then join every request generation, including cancelled loads163        // still releasing a source-runtime lease in a non-cancellable finalizer.164        jobs.forEach { it.cancel() }165        jobs.joinAll()166        val owned = viewModelScope.coroutineContext[Job]?.children?.toList().orEmpty()167        owned.forEach { it.cancel() }168        owned.joinAll()169    }170}171

Search chapters, reference and source filenames.