Yokan / rebuild
Course 1 8624561

DownloadQueueViewModel.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadQueueViewModel.kt

implementation177 lines
1package eu.friedcutlet.yokan.ui.screens.downloads23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.SettingsStore6import eu.friedcutlet.yokan.data.YokanRepository7import eu.friedcutlet.yokan.database.DbChapter8import eu.friedcutlet.yokan.database.DbManga9import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot10import eu.friedcutlet.yokan.services.download.ChapterDownloads11import eu.friedcutlet.yokan.services.download.DownloadProgress12import eu.friedcutlet.yokan.services.download.DownloadQueueOrder13import eu.friedcutlet.yokan.services.download.DownloadService14import eu.friedcutlet.yokan.services.files.LocalFileService15import kotlinx.coroutines.CoroutineDispatcher16import kotlinx.coroutines.Dispatchers17import kotlinx.coroutines.flow.MutableStateFlow18import kotlinx.coroutines.flow.StateFlow19import kotlinx.coroutines.flow.asStateFlow20import kotlinx.coroutines.flow.combine21import kotlinx.coroutines.flow.distinctUntilChanged22import kotlinx.coroutines.flow.flowOn23import kotlinx.coroutines.flow.map24import kotlinx.coroutines.flow.update25import kotlinx.coroutines.launch2627/** A download row with the names it shows; null names render as "unknown". */28internal data class DownloadQueueEntry(29    val row: DownloadManagerRow,30    val mangaName: String?,31    val chapterName: String?,32    val source: String?,33    val missingDetails: Boolean,34)3536internal enum class DownloadActionError { Failed, RetryUnavailable }3738internal data class DownloadQueueState(39    val entries: List<DownloadQueueEntry> = emptyList(),40    /** Queued entries in the user's queue order. */41    val queued: List<DownloadQueueEntry> = emptyList(),42    /** Wi-Fi-only holds the pending downloads on a metered network. */43    val waitingForWifi: Boolean = false,44    val actionError: DownloadActionError? = null,45)4647internal class DownloadQueueViewModel(48    private val repository: YokanRepository,49    private val downloader: DownloadService,50    private val chapterDownloads: ChapterDownloads,51    private val localFiles: LocalFileService,52    settings: SettingsStore,53    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,54) : ViewModel() {55    private val entryBuilder = DownloadQueueEntryBuilder()56    // Seeded synchronously so the first frame never flashes the empty state.57    private val _state = MutableStateFlow(58        queueState(59            repository.snapshots.value,60            downloader.activeDownloadProgress.value,61            settings.db.value.downloadQueueOrder,62            downloader.queueStatus.value.waitingForWifi,63        ),64    )65    val state: StateFlow<DownloadQueueState> = _state.asStateFlow()6667    init {68        viewModelScope.launch {69            combine(70                repository.snapshots.distinctUntilChanged { old, new ->71                    old.downloads === new.downloads && old.chapters === new.chapters && old.mangas === new.mangas72                },73                downloader.activeDownloadProgress,74                settings.db.map { it.downloadQueueOrder }.distinctUntilChanged(),75                downloader.queueStatus.map { it.waitingForWifi }.distinctUntilChanged(),76            ) { snapshot, active, order, waitingForWifi -> queueState(snapshot, active, order, waitingForWifi) }77                .flowOn(workDispatcher)78                .collect { built -> _state.update { built.copy(actionError = it.actionError) } }79        }80    }8182    fun move(from: Int, to: Int) {83        // Recheck after a drag: a worker may have started while the gesture was in flight.84        val current = currentRows()85        val ids = _state.value.queued.mapNotNull { it.row.record?.id }.toMutableList()86        if (from !in ids.indices || to !in ids.indices || ids.any { id -> current.none { it.record?.id == id && it.queued } }) return87        ids.add(to, ids.removeAt(from))88        chapterDownloads.reorderQueue(ids)89        // Publish the new order now so the dropped row never snaps back for a frame.90        _state.update { state -> state.copy(queued = ids.mapNotNull { id -> state.queued.find { it.row.record?.id == id } }) }91    }9293    fun cancel(row: DownloadManagerRow) {94        row.record?.let { chapterDownloads.cancel(it.id) } ?: downloader.cancel(row.taskId)95    }9697    fun pause(row: DownloadManagerRow) = downloader.pause(row.taskId)9899    fun resume(row: DownloadManagerRow) = downloader.resume(row.taskId)100101    fun retry(row: DownloadManagerRow) {102        val retried = runCatching { downloader.retry(row.taskId) }103        if (retried.isFailure) return failed()104        if (!retried.getOrDefault(false)) _state.update { it.copy(actionError = DownloadActionError.RetryUnavailable) }105    }106107    fun open(row: DownloadManagerRow) {108        val opened = runCatching { row.location?.let(localFiles::openLocation) == true }.getOrDefault(false)109        if (!opened) failed()110    }111112    /** Deletes [row] as confirmed; refuses when it changed since (a new request or a moved location). */113    fun delete(row: DownloadManagerRow) {114        if (currentRows().find { it.taskId == row.taskId } != row) return failed()115        val record = row.record ?: return116        if (runCatching { chapterDownloads.remove(record.id) }.isFailure) failed()117    }118119    fun dismissActionFailed() = _state.update { it.copy(actionError = null) }120121    private fun failed() = _state.update { it.copy(actionError = DownloadActionError.Failed) }122123    private fun queueState(124        snapshot: YokanDatabaseSnapshot,125        active: List<DownloadProgress>,126        order: List<Long>,127        waitingForWifi: Boolean,128    ): DownloadQueueState {129        val entries = entryBuilder.build(snapshot, active, downloader::storageLocation)130        val byRecordId = entries.filter { it.row.queued }.mapNotNull { entry -> entry.row.record?.let { it.id to entry } }.toMap()131        val queued = DownloadQueueOrder.sorted(byRecordId.values.mapNotNull { it.row.record }, order).mapNotNull { byRecordId[it.id] }132        return DownloadQueueState(entries, queued, waitingForWifi)133    }134135    private fun currentRows() = downloadManagerRows(repository.downloads(), downloader.activeDownloads(), downloader::storageLocation)136}137138internal fun downloadQueueEntries(139    snapshot: YokanDatabaseSnapshot,140    active: List<DownloadProgress>,141    location: (String) -> String?,142): List<DownloadQueueEntry> = DownloadQueueEntryBuilder().build(snapshot, active, location)143144/** Owned by one collector; progress changes reuse the library lookups. */145internal class DownloadQueueEntryBuilder {146    private var previous: YokanDatabaseSnapshot? = null147    private var chapters = emptyMap<Long, DbChapter>()148    private var mangas = emptyMap<Long, DbManga>()149    private var previousEntries = emptyMap<String, DownloadQueueEntry>()150151    fun build(152        snapshot: YokanDatabaseSnapshot,153        active: List<DownloadProgress>,154        location: (String) -> String?,155    ): List<DownloadQueueEntry> {156        val detailsChanged = snapshot.chapters !== previous?.chapters || snapshot.mangas !== previous?.mangas157        if (snapshot.chapters !== previous?.chapters) chapters = snapshot.chapters.associateBy { it.id }158        if (snapshot.mangas !== previous?.mangas) mangas = snapshot.mangas.associateBy { it.id }159        previous = snapshot160        val entries = downloadManagerRows(snapshot.downloads, active, location).map { row ->161            val cached = previousEntries[row.taskId]162            if (!detailsChanged && cached?.row == row) return@map cached163            val chapterId = row.record?.chapterId ?: row.taskId.takeIf { it.startsWith("chapter-") }?.removePrefix("chapter-")?.toLongOrNull()164            val chapter = chapterId?.let(chapters::get)165            val manga = chapter?.mangaId?.let(mangas::get)166            DownloadQueueEntry(167                row = row,168                mangaName = manga?.name?.takeIf { it.isNotBlank() },169                chapterName = chapter?.name?.takeIf { it.isNotBlank() },170                source = manga?.source?.takeIf { it.isNotBlank() },171                missingDetails = chapter == null || manga == null,172            )173        }174        previousEntries = entries.associateBy { it.row.taskId }175        return entries176    }177}178

Search chapters, reference and source filenames.