Yokan / rebuild
Course 1 8624561

LocalLibraryViewModel.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalLibraryViewModel.kt

implementation313 lines
1package eu.friedcutlet.yokan.ui.screens.local23import kotlinx.coroutines.CoroutineDispatcher4import eu.friedcutlet.yokan.services.library.LocalMetadataSourceResult5import eu.friedcutlet.yokan.services.library.LocalLibraryOverview6import androidx.lifecycle.ViewModel7import androidx.lifecycle.viewModelScope8import eu.friedcutlet.yokan.data.LibraryIndexStore9import eu.friedcutlet.yokan.data.SettingsStore10import eu.friedcutlet.yokan.data.toDb11import eu.friedcutlet.yokan.domain.Chapter12import eu.friedcutlet.yokan.domain.ItemType13import eu.friedcutlet.yokan.domain.Manga14import eu.friedcutlet.yokan.services.catchingNonCancellation15import eu.friedcutlet.yokan.services.colorization.ColorizationJob16import eu.friedcutlet.yokan.services.colorization.LocalColorizationQueue17import eu.friedcutlet.yokan.services.library.LocalEntryManagementApplyStatus18import eu.friedcutlet.yokan.services.library.LocalEntryManagementOperation19import eu.friedcutlet.yokan.services.library.LocalEntryManagementPreview20import eu.friedcutlet.yokan.services.library.LocalLibraryController21import eu.friedcutlet.yokan.services.library.LocalLibraryDuplicateGroup22import eu.friedcutlet.yokan.services.library.LocalImportProgress23import eu.friedcutlet.yokan.services.library.PendingLocalImport24import eu.friedcutlet.yokan.services.files.LocalMediaSelection25import eu.friedcutlet.yokan.services.files.pickLocalMedia26import eu.friedcutlet.yokan.services.metadata.LocalMetadataField27import eu.friedcutlet.yokan.services.metadata.MetadataMedia28import eu.friedcutlet.yokan.services.library.visibleChapters29import kotlinx.coroutines.CancellationException30import kotlinx.coroutines.Dispatchers31import kotlinx.coroutines.Job32import kotlinx.coroutines.flow.MutableStateFlow33import kotlinx.coroutines.flow.StateFlow34import kotlinx.coroutines.flow.asStateFlow35import kotlinx.coroutines.flow.combine36import kotlinx.coroutines.flow.distinctUntilChanged37import kotlinx.coroutines.flow.flowOn38import kotlinx.coroutines.flow.map39import kotlinx.coroutines.flow.update40import kotlinx.coroutines.launch41import kotlinx.coroutines.withContext4243/** Candidate search and field selection for one local title; nothing is written until applied. */44data class LocalMetadataReviewState(45    val manga: Manga,46    val sourceResults: List<LocalMetadataSourceResult> = emptyList(),47    val selectedCandidate: MetadataMedia? = null,48    val selectedFields: Set<LocalMetadataField> = emptySet(),49    val error: String? = null,50    val loading: Boolean = false,51) {52    val candidates: List<MetadataMedia> = sourceResults.flatMap { it.candidates }53}5455data class LocalLibraryUiState(56    val overview: LocalLibraryOverview = LocalLibraryOverview(folders = emptyList(), manga = 0, anime = 0, novels = 0),57    val titlesByType: Map<ItemType, List<Manga>> = emptyMap(),58    val reviewQueue: List<Manga> = emptyList(),59    /** Names of the titles the reconciliation refers to, for the stale and duplicate rows. */60    val titleNames: Map<Long, String> = emptyMap(),61    val message: String? = null,62    val managementPreview: LocalEntryManagementPreview? = null,63    val selectedEntry: Manga? = null,64    val selectedEntryChapters: List<Chapter> = emptyList(),65    val metadataReview: LocalMetadataReviewState? = null,66    val colorizationJobs: List<ColorizationJob> = emptyList(),67    val colorizationSupported: Boolean = false,68    val colorizationError: String? = null,69    val importBusy: Boolean = false,70    val importProgress: LocalImportProgress? = null,71    val importFailed: Boolean = false,72    val importError: String? = null,73    val importCompleted: Boolean = false,74    val pendingImports: List<PendingLocalImport> = emptyList(),75)7677sealed interface LocalLibraryEvent {78    data object Rescan : LocalLibraryEvent79    data object FullRescan : LocalLibraryEvent80    data class ImportMedia(val type: ItemType, val directory: Boolean) : LocalLibraryEvent81    data object CancelImport : LocalLibraryEvent82    data class RecoverImport(val id: String) : LocalLibraryEvent83    data class DiscardIncompleteImport(val id: String) : LocalLibraryEvent84    data class PreviewOperation(val operation: LocalEntryManagementOperation) : LocalLibraryEvent85    data class PreviewMerge(val group: LocalLibraryDuplicateGroup, val canonicalTitleId: Long) : LocalLibraryEvent86    data object ConfirmOperation : LocalLibraryEvent87    data object DismissOperation : LocalLibraryEvent88    data class SelectEntry(val manga: Manga?) : LocalLibraryEvent89    data class OpenMetadataReview(val manga: Manga) : LocalLibraryEvent90    data object DismissMetadataReview : LocalLibraryEvent91    data object SearchMetadataCandidates : LocalLibraryEvent92    data class SelectCandidate(val candidate: MetadataMedia) : LocalLibraryEvent93    data class SetFieldSelected(val field: LocalMetadataField, val selected: Boolean) : LocalLibraryEvent94    data object ApplyMetadata : LocalLibraryEvent95    data class EnqueueColorization(val manga: Manga) : LocalLibraryEvent96    data class ColorizationAction(val jobId: String, val action: ColorizationJobAction) : LocalLibraryEvent97}9899enum class ColorizationJobAction { Pause, Resume, Retry, Cancel }100101/** Local media overview: folders, scan state, metadata review queue, and forget/merge management. */102class LocalLibraryViewModel(103    private val controller: LocalLibraryController,104    settings: SettingsStore,105    libraryIndex: LibraryIndexStore,106    private val colorizationQueue: LocalColorizationQueue? = null,107    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,108    private val mediaPicker: suspend (Boolean) -> LocalMediaSelection? = ::pickLocalMedia,109) : ViewModel() {110    private val _state = MutableStateFlow(LocalLibraryUiState())111    val state: StateFlow<LocalLibraryUiState> = _state.asStateFlow()112    private var searchJob: Job? = null113    private var importJob: Job? = null114115    init {116        refreshPendingImports()117        viewModelScope.launch {118            combine(controller.observeLibrary(workDispatcher),119                settings.db.map(controller::folders).distinctUntilChanged(), controller.scan) { library, folders, scan ->120                Derived(121                    overview = library.overview(folders, scan),122                    titlesByType = library.titlesByType,123                    reviewQueue = library.reviewQueue,124                    titleNames = library.titleNames(scan.reconciliation),125                )126            }.flowOn(workDispatcher).collect { derived ->127                _state.update {128                    it.copy(129                        overview = derived.overview,130                        titlesByType = derived.titlesByType,131                        reviewQueue = derived.reviewQueue,132                        titleNames = derived.titleNames,133                    )134                }135            }136        }137        colorizationQueue?.let { queue ->138            viewModelScope.launch {139                queue.jobs.collect { jobs -> _state.update { it.copy(colorizationJobs = jobs) } }140            }141            _state.update { it.copy(colorizationSupported = queue.supported) }142        }143        viewModelScope.launch {144            combine(_state.map { it.selectedEntry }.distinctUntilChanged(), libraryIndex.index, settings.db) { manga, index, db ->145                manga to manga?.let { visibleChapters(it, index.chapters(it.id), db, index.downloadedChapterIds) }.orEmpty()146            }.flowOn(workDispatcher).collect { (manga, chapters) ->147                _state.update { if (it.selectedEntry?.id == manga?.id) it.copy(selectedEntryChapters = chapters) else it }148            }149        }150    }151152    fun onEvent(event: LocalLibraryEvent) {153        when (event) {154            LocalLibraryEvent.Rescan -> rescan()155            LocalLibraryEvent.FullRescan -> rescan(forceRefresh = true)156            is LocalLibraryEvent.ImportMedia -> importMedia(event)157            LocalLibraryEvent.CancelImport -> importJob?.cancel()158            is LocalLibraryEvent.RecoverImport -> importAction { controller.recoverImport(event.id); controller.rescanAndReconcile() }159            is LocalLibraryEvent.DiscardIncompleteImport -> importAction { controller.discardIncompleteImport(event.id) }160            is LocalLibraryEvent.PreviewOperation -> preview(event.operation)161            is LocalLibraryEvent.PreviewMerge -> _state.value.overview.reconciliation?.let { evidence ->162                preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, event.group.ids, event.canonicalTitleId))163            }164            LocalLibraryEvent.ConfirmOperation -> confirmOperation()165            LocalLibraryEvent.DismissOperation -> _state.update { it.copy(managementPreview = null) }166            is LocalLibraryEvent.SelectEntry -> _state.update {167                it.copy(selectedEntry = event.manga, selectedEntryChapters = emptyList())168            }169            is LocalLibraryEvent.OpenMetadataReview -> {170                searchJob?.cancel()171                _state.update { it.copy(selectedEntry = null, metadataReview = LocalMetadataReviewState(event.manga)) }172            }173            LocalLibraryEvent.DismissMetadataReview -> {174                searchJob?.cancel()175                _state.update { it.copy(metadataReview = null) }176            }177            LocalLibraryEvent.SearchMetadataCandidates -> searchCandidates()178            is LocalLibraryEvent.SelectCandidate -> updateReview { it.copy(selectedCandidate = event.candidate) }179            is LocalLibraryEvent.SetFieldSelected -> updateReview {180                it.copy(selectedFields = if (event.selected) it.selectedFields + event.field else it.selectedFields - event.field)181            }182            LocalLibraryEvent.ApplyMetadata -> applyMetadata()183            is LocalLibraryEvent.EnqueueColorization -> colorizationQueue?.let { queue ->184                if (event.manga.itemType == ItemType.Manga && event.manga.isLocalArchive && !event.manga.source.equals("torrent", true)) {185                    viewModelScope.launch {186                        try {187                            withContext(workDispatcher) { queue.enqueue(event.manga.id) }188                            _state.update { it.copy(colorizationError = null) }189                        } catch (error: CancellationException) {190                            throw error191                        } catch (error: Throwable) {192                            _state.update { it.copy(colorizationError = error.message ?: "Could not start colorization.") }193                        }194                    }195                }196            }197            is LocalLibraryEvent.ColorizationAction -> colorizationQueue?.let { queue ->198                viewModelScope.launch {199                    try {200                        withContext(workDispatcher) {201                            when (event.action) {202                                ColorizationJobAction.Pause -> queue.pause(event.jobId)203                                ColorizationJobAction.Resume -> queue.resume(event.jobId)204                                ColorizationJobAction.Retry -> queue.retry(event.jobId)205                                ColorizationJobAction.Cancel -> queue.cancel(event.jobId)206                            }207                        }208                        _state.update { it.copy(colorizationError = null) }209                    } catch (error: CancellationException) {210                        throw error211                    } catch (error: Throwable) {212                        _state.update { it.copy(colorizationError = error.message ?: "Could not update colorization.") }213                    }214                }215            }216        }217    }218219    private fun refreshPendingImports() {220        viewModelScope.launch {221            catchingNonCancellation { controller.pendingImports() }222                .onSuccess { pending -> _state.update { it.copy(pendingImports = pending) } }223        }224    }225226    private fun importMedia(event: LocalLibraryEvent.ImportMedia) = importAction {227        // Keep the picker on Main and before any dispatcher hop so browsers retain user activation.228        val selection = mediaPicker(event.directory) ?: return@importAction229        try {230            controller.importMedia(selection, event.type.toDb()) { progress ->231                _state.update { it.copy(importProgress = progress) }232            }233        } finally { selection.close() }234        controller.rescanAndReconcile()235        _state.update { it.copy(importCompleted = true) }236    }237238    private fun importAction(action: suspend () -> Unit) {239        if (importJob?.isActive == true) return240        _state.update { it.copy(importBusy = true, importProgress = null, importFailed = false, importError = null, importCompleted = false) }241        importJob = viewModelScope.launch {242            try { action() }243            catch (cancelled: CancellationException) { throw cancelled }244            catch (error: Throwable) { _state.update { it.copy(importFailed = true, importError = error.message) } }245            finally {246                _state.update { it.copy(importBusy = false, importProgress = null) }247                refreshPendingImports()248            }249        }250    }251252    private fun rescan(forceRefresh: Boolean = false) {253        _state.update { it.copy(message = null) }254        viewModelScope.launch {255            catchingNonCancellation { controller.rescanAndReconcile(forceRefresh) }256                .onFailure { error -> _state.update { it.copy(message = error.message ?: "Scan or reconciliation failed") } }257        }258    }259260    private fun preview(operation: LocalEntryManagementOperation) {261        viewModelScope.launch {262            val preview = withContext(workDispatcher) { controller.preview(operation) }263            _state.update { it.copy(managementPreview = preview) }264        }265    }266267    private fun confirmOperation() {268        val preview = _state.value.managementPreview ?: return269        viewModelScope.launch {270            val result = controller.apply(preview.command)271            _state.update {272                if (result.status == LocalEntryManagementApplyStatus.Applied) {273                    it.copy(managementPreview = null)274                } else {275                    it.copy(message = "Operation blocked: ${result.blocker ?: "unknown reason"}")276                }277            }278        }279    }280281    private fun searchCandidates() {282        val review = _state.value.metadataReview ?: return283        if (review.loading) return284        updateReview { it.copy(sourceResults = emptyList(), error = null, loading = true) }285        searchJob = viewModelScope.launch {286            val result = catchingNonCancellation { controller.searchMetadataCandidates(review.manga) }287            updateReview { current ->288                result.fold(289                    onSuccess = { current.copy(sourceResults = it, loading = false) },290                    onFailure = { current.copy(error = it.message ?: "Search failed", loading = false) },291                )292            }293        }294    }295296    private fun applyMetadata() {297        val review = _state.value.metadataReview ?: return298        val candidate = review.selectedCandidate ?: return299        controller.applyMetadataCandidate(review.manga, candidate, review.selectedFields)300        onEvent(LocalLibraryEvent.DismissMetadataReview)301    }302303    private fun updateReview(transform: (LocalMetadataReviewState) -> LocalMetadataReviewState) {304        _state.update { state -> state.metadataReview?.let { state.copy(metadataReview = transform(it)) } ?: state }305    }306307    private class Derived(308        val overview: LocalLibraryOverview,309        val titlesByType: Map<ItemType, List<Manga>>,310        val reviewQueue: List<Manga>,311        val titleNames: Map<Long, String>,312    )313}314

Search chapters, reference and source filenames.