Yokan / rebuild
Course 1 8624561

MigrationViewModel.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MigrationViewModel.kt

implementation151 lines
1package eu.friedcutlet.yokan.ui.screens.migration23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.YokanRepository6import eu.friedcutlet.yokan.data.observe7import eu.friedcutlet.yokan.database.YokanDatabase8import eu.friedcutlet.yokan.domain.Manga9import eu.friedcutlet.yokan.domain.Source10import eu.friedcutlet.yokan.services.catchingNonCancellation11import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory12import eu.friedcutlet.yokan.services.extensions.RemoteDetail13import eu.friedcutlet.yokan.services.extensions.RemoteManga14import eu.friedcutlet.yokan.services.extensions.SourceListing15import eu.friedcutlet.yokan.services.extensions.withSourceRuntime16import eu.friedcutlet.yokan.services.migration.MigrationService17import kotlinx.coroutines.Job18import kotlinx.coroutines.flow.MutableStateFlow19import kotlinx.coroutines.flow.StateFlow20import kotlinx.coroutines.flow.asStateFlow21import kotlinx.coroutines.flow.update22import kotlinx.coroutines.launch2324/** The candidate the user tapped, with its destination detail. */25internal data class MigrationPreview(26    val source: Source,27    val candidate: RemoteManga,28    val detail: RemoteDetail? = null,29    val loading: Boolean = true,30    val error: String? = null,31    val migrating: Boolean = false,32)3334internal data class MigrationState(35    val manga: Manga?,36    val query: String,37    val submittedQuery: String,38    /** The installed sources the submitted query ran on. */39    val sources: List<Source> = emptyList(),40    val listings: Map<Long, SourceListing?> = emptyMap(),41    val loadingSourceIds: Set<Long> = emptySet(),42    /** Lower-cased names of favorite titles of the title's type, for the "already in library" badge. */43    val libraryTitleNames: Set<String> = emptySet(),44    val preview: MigrationPreview? = null,45)4647/** Searches every installed source for [mangaId]'s replacement and migrates it to the chosen candidate. */48internal class MigrationViewModel(49    mangaId: Long,50    private val repository: YokanRepository,51    private val database: YokanDatabase,52    private val runtimeFactory: ExtensionRuntimeFactory,53    private val migration: MigrationService,54) : ViewModel() {55    private val _state = MutableStateFlow(56        repository.manga(mangaId).let { MigrationState(manga = it, query = it?.name.orEmpty(), submittedQuery = it?.name.orEmpty()) },57    )58    val state: StateFlow<MigrationState> = _state.asStateFlow()59    private var searchJob: Job? = null60    private var previewJob: Job? = null6162    init {63        _state.value.manga?.let { manga ->64            viewModelScope.launch {65                repository.observe({ it.mangas }) {66                    allTitles(manga.itemType).filter { it.favorite }.mapTo(HashSet()) { it.name.lowercase() }67                }.collect { names -> _state.update { it.copy(libraryTitleNames = names) } }68            }69            search()70        }71    }7273    fun changeQuery(query: String) {74        _state.update { it.copy(query = query) }75    }7677    fun submit() {78        val state = _state.value79        if (state.query == state.submittedQuery) return80        _state.update { it.copy(submittedQuery = state.query) }81        search()82    }8384    fun clear() {85        searchJob?.cancel()86        _state.update { it.copy(query = "", submittedQuery = "", listings = emptyMap(), loadingSourceIds = emptySet()) }87    }8889    fun openPreview(source: Source, candidate: RemoteManga) {90        previewJob?.cancel()91        _state.update { it.copy(preview = MigrationPreview(source, candidate)) }92        previewJob = viewModelScope.launch {93            catchingNonCancellation {94                runtimeFactory.withSourceRuntime(database, source.id) { it.detail(candidate.url) }95            }.fold(96                onSuccess = { detail -> updatePreview { it.copy(detail = detail, loading = false) } },97                onFailure = { error ->98                    val message = error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }99                    updatePreview { it.copy(error = message, loading = false) }100                },101            )102        }103    }104105    /** Also cancels a migration in flight, as closing the sheet always did. */106    fun dismissPreview() {107        previewJob?.cancel()108        _state.update { it.copy(preview = null) }109    }110111    /** Migrates to the previewed candidate; [onMigrated] runs once the new title exists. */112    fun migrate(onMigrated: () -> Unit) {113        val state = _state.value114        val manga = state.manga ?: return115        val preview = state.preview ?: return116        if (preview.migrating) return117        updatePreview { it.copy(migrating = true) }118        previewJob = viewModelScope.launch {119            val newId = migration.migrate(manga, preview.source, preview.candidate)120            updatePreview { it.copy(migrating = false) }121            if (newId != null) {122                _state.update { it.copy(preview = null) }123                onMigrated()124            }125        }126    }127128    private fun search() {129        searchJob?.cancel()130        val state = _state.value131        val manga = state.manga ?: return132        val query = state.submittedQuery133        if (query.isBlank()) return134        val sources = repository.sources(manga.itemType).filter { it.isActive && it.isAdded }135        _state.update { it.copy(sources = sources, listings = emptyMap(), loadingSourceIds = sources.mapTo(HashSet()) { source -> source.id }) }136        searchJob = viewModelScope.launch {137            sources.forEach { source ->138                launch {139                    val listing = catchingNonCancellation {140                        runtimeFactory.withSourceRuntime(database, source.id) { it.search(query, 1, emptyList()) }141                    }.getOrNull()142                    _state.update { it.copy(listings = it.listings + (source.id to listing), loadingSourceIds = it.loadingSourceIds - source.id) }143                }144            }145        }146    }147148    private fun updatePreview(transform: (MigrationPreview) -> MigrationPreview) {149        _state.update { state -> state.preview?.let { state.copy(preview = transform(it)) } ?: state }150    }151}152

Search chapters, reference and source filenames.