Yokan / rebuild
Course 1 8624561

LibraryViewModel.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/library/LibraryViewModel.kt

implementation255 lines
1package eu.friedcutlet.yokan.ui.screens.library23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.LibraryIndex6import eu.friedcutlet.yokan.data.LibraryIndexStore7import eu.friedcutlet.yokan.data.SettingsStore8import eu.friedcutlet.yokan.data.YokanRepository9import eu.friedcutlet.yokan.data.observeSnapshot10import eu.friedcutlet.yokan.data.toDb11import eu.friedcutlet.yokan.data.toDomain12import eu.friedcutlet.yokan.data.toDomainMangas13import eu.friedcutlet.yokan.domain.ItemType14import eu.friedcutlet.yokan.domain.Manga15import eu.friedcutlet.yokan.services.download.ChapterDownloads16import eu.friedcutlet.yokan.services.library.LibraryUpdateController17import eu.friedcutlet.yokan.services.library.LibraryAiringService18import kotlinx.coroutines.CancellationException19import eu.friedcutlet.yokan.services.library.LocalLibraryController20import eu.friedcutlet.yokan.ui.navigation.LibraryRequest21import eu.friedcutlet.yokan.services.library.sortedChapters22import kotlinx.coroutines.Job23import kotlinx.coroutines.delay24import eu.friedcutlet.yokan.database.DbSettings25import eu.friedcutlet.yokan.database.DbLibraryGrouping26import kotlinx.coroutines.CoroutineDispatcher27import kotlinx.coroutines.Dispatchers28import kotlinx.coroutines.flow.Flow29import kotlinx.coroutines.flow.MutableStateFlow30import kotlinx.coroutines.flow.SharingStarted31import kotlinx.coroutines.flow.StateFlow32import kotlinx.coroutines.flow.asStateFlow33import kotlinx.coroutines.flow.combine34import kotlinx.coroutines.flow.distinctUntilChanged35import kotlinx.coroutines.flow.filter36import kotlinx.coroutines.flow.filterNotNull37import kotlinx.coroutines.flow.flowOn38import kotlinx.coroutines.flow.map39import kotlinx.coroutines.flow.stateIn40import kotlinx.coroutines.flow.update41import kotlinx.coroutines.launch42import kotlinx.coroutines.withContext4344/**45 * One item type's library: filtered and sorted entries per category, badges, the category and46 * selection cursor, and the library update. Lives in the root ViewModel store for the whole app.47 */48class LibraryViewModel(49    private val itemType: ItemType,50    private val repository: YokanRepository,51    private val settings: SettingsStore,52    private val libraryIndex: LibraryIndexStore,53    private val libraryUpdates: LibraryUpdateController,54    private val localLibrary: LocalLibraryController,55    private val chapterDownloads: ChapterDownloads,56    libraryRequests: Flow<LibraryRequest?>,57    private val airings: LibraryAiringService? = null,58    trackerProviders: List<LibraryTrackerChoice> = emptyList(),59    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,60) : ViewModel() {61    private val _state = MutableStateFlow(62        LibraryState(63            itemType = itemType,64            query = settings.db.value.libraryQuery(itemType),65            display = settings.db.value.libraryDisplay(itemType),66            selectedCategoryId = defaultCategoryId(),67            trackerProviders = trackerProviders,68        ),69    )70    val state: StateFlow<LibraryState> = _state.asStateFlow()7172    private var searchJob: Job? = null73    private var pendingSearch: String? = null7475    init {76        val entries = repository.observeSnapshot({ it.mangas to it.settings.titleMetadata }, workDispatcher) { snapshot ->77            snapshot.mangas.filter { it.itemType == itemType.toDb() && it.favorite && it.parentId == null }.toDomainMangas(snapshot.settings)78        }79            .stateIn(viewModelScope, SharingStarted.Eagerly, null)80            .filterNotNull()81        // Empty is the placeholder before the first build; filtering against it would flash wrong results.82        val index = libraryIndex.index.filter { it !== LibraryIndex.Empty }83        viewModelScope.launch {84            settings.db.collect { db ->85                _state.update { it.copy(query = db.libraryQuery(itemType).let { query -> pendingSearch?.let { query.copy(search = it) } ?: query }, display = db.libraryDisplay(itemType)) }86            }87        }88        viewModelScope.launch {89            val releases = LibraryReleaseSelector()90            combine(91                entries,92                repository.observeSnapshot({ it.categories }, workDispatcher) { snapshot ->93                    snapshot.categories.filter { it.forItemType == itemType.toDb() }94                        .sortedBy { it.position ?: 0 }.map { it.toDomain() }95                },96                index,97                settings.db.map { it.libraryQuery(itemType) }.distinctUntilChanged(),98            ) { titles, categories, built, query -> libraryContent(titles, categories, built, query, releases.select(titles, built, query)) }99                .flowOn(workDispatcher)100                .collect { content -> _state.update { it.withContent(content) } }101        }102        viewModelScope.launch {103            combine(entries, index, settings.db.map { db ->104                DbSettings(chapterReleasePreferences = db.chapterReleasePreferences,105                    filterScanlatorList = db.filterScanlatorList, downloadedOnlyMode = db.downloadedOnlyMode)106            }.distinctUntilChanged()) { titles, built, db ->107                buildLibraryBadgeSummaries(108                    chaptersByManga = titles.associate { it.id to built.chapters(it.id) },109                    completedDownloadCountsByChapterId = built.completedDownloadCountsByChapterId,110                    mangaTitles = titles.associate { it.id to it.name },111                    releaseSettings = db,112                )113            }.flowOn(workDispatcher).collect { badges -> _state.update { it.copy(badges = badges) } }114        }115        viewModelScope.launch {116            libraryRequests.filterNotNull().filter { it.itemType == itemType }.collect { applyRequest(it) }117        }118    }119120    fun onEvent(event: LibraryEvent) {121        when (event) {122            LibraryEvent.Refresh -> refresh()123            LibraryEvent.RefreshAirings -> refreshAirings()124            is LibraryEvent.Search -> search(event.query)125            is LibraryEvent.SelectCategory -> _state.update { it.copy(selectedCategoryId = event.categoryId) }126            is LibraryEvent.UpdateSettings -> settings.updateDb(event.transform)127            is LibraryEvent.BeginSelection -> _state.update {128                if (it.selectionMode) it.withToggled(event.mangaId) else it.copy(selectedIds = setOf(event.mangaId))129            }130            is LibraryEvent.ToggleSelection -> _state.update { it.withToggled(event.mangaId) }131            LibraryEvent.ClearSelection -> _state.update { it.copy(selectedIds = emptySet()) }132            LibraryEvent.SelectAll -> _state.update { state ->133                state.copy(selectedIds = state.currentItems.mapTo(HashSet()) { it.id })134            }135            LibraryEvent.InvertSelection -> _state.update { state ->136                val visible = state.currentItems.mapTo(HashSet()) { it.id }137                state.copy(selectedIds = (state.selectedIds - visible) + (visible - state.selectedIds))138            }139            is LibraryEvent.MarkSelectedRead -> writeSelection { ids -> repository.setLibraryEntriesRead(ids, event.isRead) }140            is LibraryEvent.SetSelectedCategories -> writeSelection { ids ->141                ids.forEach { repository.setMangaCategories(it, event.categoryIds) }142            }143            is LibraryEvent.RemoveSelected -> writeSelection { ids ->144                val removable = if (event.downloads) chapterDownloads.deleteForMangaAwait(ids) else ids145                if (event.fromLibrary) repository.removeLibraryEntries(removable)146            }147            LibraryEvent.RescanLocalLibrary -> viewModelScope.launch { localLibrary.rescan() }148            is LibraryEvent.ImportTorrent -> viewModelScope.launch { localLibrary.importTorrent(event.pathOrMagnet) }149        }150    }151152    /**153     * Moves one visible category forward or back, wrapping at the ends. False when there are fewer154     * than two visible categories, so the caller can switch item types instead.155     */156    fun shiftCategory(delta: Int): Boolean {157        val visible = listOf(null) + _state.value.content?.tabs.orEmpty().map { it.id }158        if (visible.size < 2) return false159        val current = visible.indexOf(_state.value.selectedCategoryId).takeIf { it >= 0 } ?: 0160        val next = ((current + delta) % visible.size + visible.size) % visible.size161        _state.update { it.copy(selectedCategoryId = visible[next]) }162        return true163    }164165    /** The chapter "continue" opens: the first unread one in the title's sort order, else the first. */166    fun continueChapterId(manga: Manga): Long? {167        val chapters = sortedChapters(manga, libraryIndex.index.value.chapters(manga.id), settings.db.value)168        return (chapters.firstOrNull { !it.isRead } ?: chapters.firstOrNull())?.id169    }170171    /** A query shows every category; otherwise the library opens on its default category. */172    private fun applyRequest(request: LibraryRequest) {173        val query = request.query174        if (query != null) { searchJob?.cancel(); pendingSearch = null }175        if (query != null) settings.updateDb { it.withLibrarySearch(itemType, query) }176        _state.update {177            it.copy(178                selectedCategoryId = if (query != null) null else defaultCategoryId(),179                selectedIds = emptySet(),180            )181        }182    }183184    /** The first visible category, so the library opens on one category rather than all of them. */185    private fun defaultCategoryId(): Long? = if (settings.db.value.features.library.grouping(itemType.toDb()) == DbLibraryGrouping.Categories)186        repository.categories(itemType).firstOrNull { !it.hidden }?.id else null187188    /** Clears the selection, then runs [write] with its ids off the main thread. */189    private fun writeSelection(write: suspend (Set<Long>) -> Unit) {190        val ids = _state.value.selectedIds191        _state.update { it.copy(selectedIds = emptySet()) }192        if (ids.isEmpty()) return193        viewModelScope.launch { withContext(workDispatcher) { write(ids) } }194    }195196    private fun search(query: String) {197        searchJob?.cancel()198        pendingSearch = query199        _state.update { it.copy(query = it.query.copy(search = query)) }200        searchJob = viewModelScope.launch {201            delay(250)202            pendingSearch = null203            settings.updateDb { it.withLibrarySearch(itemType, query) }204        }205    }206207    private fun refresh() {208        if (_state.value.refreshing) return209        val current = _state.value210        val titleIds = libraryUpdateTitleIds(current.content, current.selectedCategoryId,211            settings.db.value.features.library.updateGroupMode(itemType.toDb()), libraryIndex.index.value)212        _state.update { it.copy(refreshing = true, lastRefreshSummary = null) }213        viewModelScope.launch {214            try {215                val result = libraryUpdates.run(itemType, titleIds)216                val summary = "Checked ${result.checked}, updated ${result.updated}, failed ${result.failed}"217                _state.update { it.copy(lastRefreshSummary = summary) }218            } finally { _state.update { it.copy(refreshing = false) } }219        }220    }221222    private fun refreshAirings() {223        if (itemType != ItemType.Anime || _state.value.refreshingAirings) return224        val service = airings ?: return225        _state.update { it.copy(refreshingAirings = true, airingRefreshResult = null, airingRefreshFailed = false) }226        viewModelScope.launch {227            try {228                val result = withContext(workDispatcher) { service.refresh() }229                _state.update { it.copy(airingRefreshResult = result) }230            } catch (cancel: CancellationException) { throw cancel }231            catch (_: Exception) { _state.update { it.copy(airingRefreshFailed = true) } }232            finally { _state.update { it.copy(refreshingAirings = false) } }233        }234    }235}236237private fun LibraryState.withToggled(mangaId: Long): LibraryState =238    copy(selectedIds = if (mangaId in selectedIds) selectedIds - mangaId else selectedIds + mangaId)239240/** Publishes [content]; a deleted category falls back to all categories and removed titles leave the selection. */241private fun LibraryState.withContent(content: LibraryContent): LibraryState {242    val groupingChanged = (this.content?.grouping ?: DbLibraryGrouping.Categories) != content.grouping243    val categoryGone = selectedCategoryId != null && !content.containsCategory(selectedCategoryId)244    val libraryIds: Set<Long> = if (selectedIds.isEmpty()) emptySet() else content.library.mapTo(HashSet()) { it.id }245    val keptIds = if (selectedIds.all(libraryIds::contains)) selectedIds else selectedIds.filterTo(HashSet(), libraryIds::contains)246    return copy(247        content = content,248        selectedCategoryId = when {249            groupingChanged -> content.tabs.firstOrNull()?.id250            categoryGone -> null251            else -> selectedCategoryId252        },253        selectedIds = keptIds,254    )255}256

Search chapters, reference and source filenames.