DownloadManagerRows.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadManagerRows.kt
1package eu.friedcutlet.yokan.ui.screens.downloads23import eu.friedcutlet.yokan.database.DbDownload4import eu.friedcutlet.yokan.services.download.DownloadProgress5import eu.friedcutlet.yokan.services.download.downloadTaskId67internal enum class DownloadSection { InProgress, NeedsAttention, Completed }89internal data class DownloadManagerRow(10 val taskId: String,11 val record: DbDownload?,12 val live: DownloadProgress?,13 val location: String?,14) {15 val succeeded: Int get() = (live?.succeeded ?: record?.succeeded ?: 0).coerceAtLeast(0)16 val failed: Int get() = (live?.failed ?: record?.failed ?: 0).coerceAtLeast(0)17 val total: Int get() = live?.total ?: record?.total ?: 018 val fraction: Float? get() = total.takeIf { it > 0 }?.let { (succeeded.toFloat() / it).coerceIn(0f, 1f) }19 // The current service retains a location with each in-memory request, including queued ones.20 // ponytail: no persisted request/queue API; require session evidence rather than trust a stale start flag.21 val queued: Boolean get() = live == null && record?.isStartDownload == true &&22 record.isDownload != true && succeeded == 0 && failed == 0 && !location.isNullOrBlank()23 val section: DownloadSection get() = when {24 live != null && !live.isCompleted -> DownloadSection.InProgress25 live != null && failed > 0 -> DownloadSection.NeedsAttention26 record?.isDownload == true && failed == 0 -> DownloadSection.Completed27 live != null || queued -> DownloadSection.InProgress28 else -> DownloadSection.NeedsAttention29 }30 // Retry rebuilds the request from the chapter, so any stopped chapter download can retry, also after a restart.31 val canRetry: Boolean get() = section == DownloadSection.NeedsAttention && record?.chapterId != null32}3334internal fun downloadManagerRows(35 records: List<DbDownload>,36 active: List<DownloadProgress>,37 location: (String) -> String?,38): List<DownloadManagerRow> {39 val saved = records.associateBy { downloadTaskId(it.chapterId, it.id) }40 val live = active.associateBy { it.taskId }41 return (saved.keys + live.keys).map { taskId ->42 DownloadManagerRow(taskId, saved[taskId], live[taskId], location(taskId)?.takeIf { it.isNotBlank() })43 }44}45