GlobalStatusViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/status/GlobalStatusViewModel.kt
1package eu.friedcutlet.yokan.ui.status23import androidx.compose.runtime.Immutable4import androidx.lifecycle.ViewModel5import androidx.lifecycle.viewModelScope6import eu.friedcutlet.yokan.database.DbDownload7import eu.friedcutlet.yokan.database.DbGlobalStatusVisibility8import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot9import eu.friedcutlet.yokan.services.download.DownloadProgress10import eu.friedcutlet.yokan.services.download.downloadTaskId11import eu.friedcutlet.yokan.services.library.LibraryUpdateProgressState12import eu.friedcutlet.yokan.services.sync.SyncOperationOutcome13import eu.friedcutlet.yokan.services.sync.SyncOperationState14import kotlinx.coroutines.flow.Flow15import kotlinx.coroutines.flow.MutableStateFlow16import kotlinx.coroutines.flow.StateFlow17import kotlinx.coroutines.flow.asStateFlow18import kotlinx.coroutines.flow.combine19import kotlinx.coroutines.flow.collect20import kotlinx.coroutines.flow.distinctUntilChanged21import kotlinx.coroutines.flow.map22import kotlinx.coroutines.flow.update23import kotlinx.coroutines.launch2425@Immutable26data class GlobalDownloadStatus(27 val pendingCount: Int = 0,28 val activeCount: Int = 0,29 val pausedCount: Int = 0,30 val failedCount: Int = 0,31 val completedUnits: Int = 0,32 val totalUnits: Int = 0,33 val progress: Float? = null,34) {35 val isRelevant: Boolean get() = pendingCount > 0 || activeCount > 0 || pausedCount > 0 || failedCount > 036}3738@Immutable39data class GlobalLibraryUpdateStatus(40 val label: String,41 val checked: Int,42 val total: Int,43 val updated: Int,44 val failed: Int,45 val running: Boolean,46 val cancelRequested: Boolean,47 val cancelled: Boolean,48) {49 val progress: Float? get() = total.takeIf { it > 0 }?.let { (checked.toFloat() / it).coerceIn(0f, 1f) }50}5152@Immutable53data class GlobalStatusUiState(54 val downloadedOnly: Boolean = false,55 val incognito: Boolean = false,56 val downloads: GlobalDownloadStatus = GlobalDownloadStatus(),57 val sync: SyncOperationState = SyncOperationState(),58 val libraryUpdate: GlobalLibraryUpdateStatus? = null,59 val visibility: DbGlobalStatusVisibility = DbGlobalStatusVisibility.Automatic,60 val expanded: Boolean = false,61 /** The top route is a reader or player (the status chrome moves out of the way). */62 val immersive: Boolean = false,63 val playerMinimized: Boolean = false,64 val onboarding: Boolean = false,65 val appLocked: Boolean = false,66 val pictureInPicture: Boolean = false,67) {68 val hasRelevantStatus: Boolean69 get() = downloadedOnly || incognito || downloads.isRelevant || sync.isActive ||70 sync.lastOutcome == SyncOperationOutcome.Failed || libraryUpdate != null71}7273@Immutable74data class StatusOverlayPolicy(75 val showCollapsed: Boolean,76 val showExpanded: Boolean,77)7879internal fun reduceGlobalStatusExpansion(state: GlobalStatusUiState, expanded: Boolean): GlobalStatusUiState =80 state.copy(expanded = expanded)8182internal fun statusOverlayPolicy(state: GlobalStatusUiState): StatusOverlayPolicy {83 if (state.onboarding || state.appLocked || state.pictureInPicture) {84 return StatusOverlayPolicy(showCollapsed = false, showExpanded = false)85 }86 if (state.expanded) return StatusOverlayPolicy(showCollapsed = false, showExpanded = true)87 val immersive = state.immersive && !state.playerMinimized88 val collapsed = when (state.visibility) {89 DbGlobalStatusVisibility.Hidden -> false90 DbGlobalStatusVisibility.AlwaysVisible -> true91 DbGlobalStatusVisibility.Automatic -> state.hasRelevantStatus && !immersive92 }93 return StatusOverlayPolicy(showCollapsed = collapsed, showExpanded = false)94}9596internal fun aggregateDownloads(97 persisted: List<DbDownload>,98 active: List<DownloadProgress>,99): GlobalDownloadStatus {100 val activeByTask = active.associateBy(DownloadProgress::taskId)101 val pending = persisted.filter { it.isDownload != true }102 val pendingTaskIds = pending.mapTo(mutableSetOf()) { downloadTaskId(it.chapterId, it.id) }103 val merged = pending.map { record ->104 val taskId = downloadTaskId(record.chapterId, record.id)105 val progress = activeByTask[taskId]106 DownloadAggregateEntry(107 taskId = taskId,108 succeeded = progress?.succeeded ?: record.succeeded.orZero(),109 failed = progress?.failed ?: record.failed.orZero(),110 total = progress?.total ?: record.total.orZero(),111 active = progress?.isCompleted == false,112 paused = progress?.isPaused == true,113 )114 } + active.filter { progress ->115 progress.taskId !in pendingTaskIds && !progress.isCompleted116 }.map { progress ->117 DownloadAggregateEntry(118 taskId = progress.taskId,119 succeeded = progress.succeeded,120 failed = progress.failed,121 total = progress.total,122 active = true,123 paused = progress.isPaused,124 )125 }126 val totalUnits = merged.sumOf { it.total.coerceAtLeast(0) }127 val completedUnits = merged.sumOf { (it.succeeded + it.failed).coerceIn(0, it.total.coerceAtLeast(0)) }128 val determinate = merged.isNotEmpty() && merged.all { it.total > 0 } && totalUnits > 0129 return GlobalDownloadStatus(130 pendingCount = merged.size,131 activeCount = merged.count { it.active && !it.paused },132 pausedCount = merged.count { it.paused },133 failedCount = merged.count { it.failed > 0 },134 completedUnits = completedUnits,135 totalUnits = totalUnits,136 progress = if (determinate) (completedUnits.toFloat() / totalUnits).coerceIn(0f, 1f) else null,137 )138}139140private data class DownloadAggregateEntry(141 val taskId: String,142 val succeeded: Int,143 val failed: Int,144 val total: Int,145 val active: Boolean,146 val paused: Boolean,147)148149private fun Int?.orZero(): Int = this ?: 0150151private data class StatusSnapshotInput(152 val downloadedOnly: Boolean,153 val incognito: Boolean,154 val visibility: DbGlobalStatusVisibility,155 val downloads: List<DbDownload>,156)157158private fun YokanDatabaseSnapshot.toStatusInput() = StatusSnapshotInput(159 downloadedOnly = settings.downloadedOnlyMode,160 incognito = settings.incognitoMode,161 visibility = settings.globalStatusVisibility,162 downloads = downloads,163)164165class GlobalStatusViewModel(166 databaseSnapshots: StateFlow<YokanDatabaseSnapshot>,167 activeDownloads: StateFlow<List<DownloadProgress>>,168 syncOperations: StateFlow<SyncOperationState>,169 libraryUpdates: Flow<LibraryUpdateProgressState?>,170) : ViewModel() {171 private val initialSnapshot = databaseSnapshots.value172 private val _state = MutableStateFlow(173 GlobalStatusUiState(174 downloadedOnly = initialSnapshot.settings.downloadedOnlyMode,175 incognito = initialSnapshot.settings.incognitoMode,176 downloads = aggregateDownloads(initialSnapshot.downloads, activeDownloads.value),177 sync = syncOperations.value,178 visibility = initialSnapshot.settings.globalStatusVisibility,179 ),180 )181 val state: StateFlow<GlobalStatusUiState> = _state.asStateFlow()182183 init {184 viewModelScope.launch {185 val statusSnapshots = databaseSnapshots186 .map(YokanDatabaseSnapshot::toStatusInput)187 .distinctUntilChanged()188 combine(statusSnapshots, activeDownloads, syncOperations) { snapshot, downloads, sync ->189 Triple(snapshot, downloads, sync)190 }.collect { (snapshot, downloads, sync) ->191 _state.update { current ->192 current.copy(193 downloadedOnly = snapshot.downloadedOnly,194 incognito = snapshot.incognito,195 downloads = aggregateDownloads(snapshot.downloads, downloads),196 sync = sync,197 visibility = snapshot.visibility,198 )199 }200 }201 }202 viewModelScope.launch {203 libraryUpdates.collect { progress ->204 _state.update { it.copy(libraryUpdate = progress?.toGlobalStatus()) }205 }206 }207 }208209 fun open() = _state.update { reduceGlobalStatusExpansion(it, expanded = true) }210211 fun dismiss() = _state.update { reduceGlobalStatusExpansion(it, expanded = false) }212213 fun updateHostContext(214 immersive: Boolean,215 playerMinimized: Boolean,216 onboarding: Boolean,217 appLocked: Boolean,218 pictureInPicture: Boolean,219 ) = _state.update {220 it.copy(221 immersive = immersive,222 playerMinimized = playerMinimized,223 onboarding = onboarding,224 appLocked = appLocked,225 pictureInPicture = pictureInPicture,226 expanded = if (onboarding || appLocked || pictureInPicture) false else it.expanded,227 )228 }229}230231private fun LibraryUpdateProgressState.toGlobalStatus() = GlobalLibraryUpdateStatus(232 label = itemType.label,233 checked = checked,234 total = total,235 updated = updated,236 failed = failed,237 running = running,238 cancelRequested = cancelRequested,239 cancelled = cancelled,240)241