archive-97f2350/app/src/main/java/uk/orllewin/sianel/ui/MainViewModel.kt 12.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
package uk.orllewin.sianel.ui

import android.app.Application
import android.graphics.Bitmap
import android.net.Uri
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.OutOfQuotaPolicy
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.workDataOf
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import uk.orllewin.sianel.data.Prefs
import uk.orllewin.sianel.data.Quality
import uk.orllewin.sianel.data.UploadWorker
import uk.orllewin.sianel.data.SianelService
import uk.orllewin.sianel.data.VideoHelper
import uk.orllewin.sianel.data.VideoPagingSource
import java.util.UUID

sealed interface VerifyState {
    data object Idle : VerifyState
    data object Checking : VerifyState
    data class Done(val ok: Boolean, val message: String) : VerifyState
}

class MainViewModel(app: Application) : AndroidViewModel(app) {

    var password by mutableStateOf(Prefs.getPassword(getApplication()))
        private set
    var verifyState by mutableStateOf<VerifyState>(VerifyState.Idle)
        private set
    var baseUrl by mutableStateOf(Prefs.getBaseUrl(getApplication()))
        private set
    var status by mutableStateOf("")
        private set
    var uploadProgress by mutableStateOf<Float?>(null)
        private set
    var uploadPhase by mutableStateOf<String?>(null)
        private set
    var pendingDeleteHash by mutableStateOf<String?>(null)
        private set
    var quality by mutableStateOf(Quality.HIGH)
        private set
    var unlisted by mutableStateOf(false)
        private set
    var pending by mutableStateOf<PendingVideo?>(null)
        private set
    var thumbnails by mutableStateOf<List<Bitmap>>(emptyList())
        private set
    var selectedThumbnailIndex by mutableIntStateOf(0)
        private set

    fun selectThumbnail(index: Int) {
        if (index in thumbnails.indices) selectedThumbnailIndex = index
    }

    data class PendingVideo(
        val uri: Uri,
        val mime: String,
        val filename: String,
        val sizeBytes: Long,
        val durationMs: Long?,
        val heightPx: Int?,
    )

    private val workManager get() = WorkManager.getInstance(getApplication())
    private var watchJob: Job? = null
    private val videoHelper = VideoHelper(app)

    // Paging 3: the UI collects this; the source reads the current password/baseUrl
    // each time it's (re)created, so invalidateList() after auth changes reloads cleanly.
    private var pagingSource: VideoPagingSource? = null
    val videoPager: Flow<PagingData<SianelService.VideoItem>> =
        Pager(PagingConfig(pageSize = PAGE_SIZE, initialLoadSize = PAGE_SIZE)) {
            VideoPagingSource(client()).also { pagingSource = it }
        }.flow.cachedIn(viewModelScope)

    /** Force the list to reload from the first page (after upload / delete / auth change). */
    fun invalidateList() { pagingSource?.invalidate() }

    init {
        viewModelScope.launch {
            val infos = workManager.getWorkInfosByTag(UploadWorker.TAG).get()
            infos.firstOrNull { !it.state.isFinished }?.let { watch(it.id) }
        }
    }

    private fun client() = SianelService(password, baseUrl)

    fun saveSettings(passwordValue: String, baseUrlValue: String) {
        password = passwordValue.trim()
        baseUrl = baseUrlValue.trim().trimEnd('/').ifBlank { Prefs.DEFAULT_BASE_URL }
        Prefs.setPassword(getApplication(), password)
        Prefs.setBaseUrl(getApplication(), baseUrl)
        invalidateList()
    }

    fun savePassword(value: String) = saveSettings(value, baseUrl)

    /** Probe the verify endpoint with the given (unsaved) credentials. */
    fun verifyCredentials(passwordValue: String, baseUrlValue: String) {
        val pw = passwordValue.trim()
        val base = baseUrlValue.trim().trimEnd('/').ifBlank { Prefs.DEFAULT_BASE_URL }
        verifyState = VerifyState.Checking
        viewModelScope.launch {
            val result = withContext(Dispatchers.IO) {
                runCatching { SianelService(pw, base).verify() }
            }
            verifyState = result.fold(
                onSuccess = { VerifyState.Done(it.ok, verifyMessage(it)) },
                onFailure = { VerifyState.Done(false, it.message ?: "Couldn't reach server") },
            )
        }
    }

    fun resetVerify() { verifyState = VerifyState.Idle }

    private fun verifyMessage(r: SianelService.VerifyResult): String = when {
        r.ok -> "Connection OK"
        r.code == 401 -> r.serverError ?: "Invalid password"
        r.code == 429 -> r.serverError ?: "Too many failed attempts, try again later"
        r.code == 400 -> r.serverError ?: "HTTPS required"
        else -> r.serverError ?: "Error (HTTP ${r.code})"
    }

    fun clearPassword() {
        password = ""
        Prefs.clearPassword(getApplication())
        invalidateList()
    }

    fun  clearBaseUrl(){
        baseUrl = ""
        Prefs.clearBaseUrl(getApplication())
        invalidateList()
    }

    fun selectQuality(q: Quality) { quality = q }

    fun updateUnlisted(value: Boolean) { unlisted = value }

    fun selectVideo(uri: Uri) {
        if (password.isBlank()) {
            status = "Set your password first."
            return
        }
        val mime = getApplication<Application>().contentResolver.getType(uri) ?: "video/mp4"
        val (name, size) = videoHelper.displayInfo(uri)
        status = ""
        pending = PendingVideo(
            uri = uri,
            mime = mime,
            filename = name ?: "video.mp4",
            sizeBytes = size ?: 0L,
            durationMs = null,
            heightPx = null,
        )
        thumbnails = emptyList()
        selectedThumbnailIndex = 0
        // Decode off the main thread, but keep the state writes on it.
        viewModelScope.launch {
            val (durationMs, heightPx) = withContext(Dispatchers.IO) { videoHelper.probeMetadata(uri) }
            pending = pending?.copy(durationMs = durationMs, heightPx = heightPx)
            if (durationMs != null && durationMs > 0) {
                val frames = withContext(Dispatchers.IO) { videoHelper.extractFrames(uri, durationMs, FRAME_COUNT) }
                thumbnails = frames
            }
        }
    }

    fun cancelPending() {
        pending = null
        thumbnails = emptyList()
        selectedThumbnailIndex = 0
        unlisted = false
        status = ""
    }

    fun confirmUpload() {
        val p = pending ?: return
        if (password.isBlank()) {
            status = "Set your password first."
            return
        }
        // Capture selection before clearing. We re-extract the chosen frame at full
        // thumbnail resolution below; the strip bitmap is the low-res fallback.
        val selIndex = selectedThumbnailIndex.coerceIn(0, (thumbnails.size - 1).coerceAtLeast(0))
        val fallbackThumb = thumbnails.getOrNull(selIndex)
        pending = null
        thumbnails = emptyList()
        selectedThumbnailIndex = 0
        val pickedQuality = quality
        val pickedUnlisted = unlisted
        unlisted = false

        viewModelScope.launch {
            uploadProgress = 0f
            uploadPhase = null
            status = "Preparing ${p.filename}…"

            val file = runCatching {
                withContext(Dispatchers.IO) { videoHelper.copyToCache(p.uri, p.filename) }
            }.getOrElse {
                status = "Couldn't read picked file: ${it.message}"
                uploadProgress = null
                return@launch
            }

            val thumbFile = if (fallbackThumb != null) {
                runCatching {
                    withContext(Dispatchers.IO) {
                        val hi = p.durationMs
                            ?.takeIf { it > 0 }
                            ?.let { videoHelper.extractUploadFrame(p.uri, videoHelper.frameUsec(it, selIndex, FRAME_COUNT)) }
                        videoHelper.saveThumbnailToCache(hi ?: fallbackThumb)
                    }
                }.getOrNull()
            } else null

            val request = OneTimeWorkRequestBuilder<UploadWorker>()
                .addTag(UploadWorker.TAG)
                .setInputData(
                    workDataOf(
                        UploadWorker.KEY_FILE_PATH to file.absolutePath,
                        UploadWorker.KEY_MIME to p.mime,
                        UploadWorker.KEY_QUALITY to pickedQuality.name,
                        UploadWorker.KEY_THUMB_PATH to thumbFile?.absolutePath,
                        UploadWorker.KEY_UNLISTED to pickedUnlisted,
                    )
                )
                // Try expedited first (no FGS, runs immediately on API 31+); fall
                // back to normal-priority work if quota's exhausted — at which
                // point the worker's getForegroundInfo() promotes it to an FGS.
                .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
                .build()
            workManager.enqueue(request)
            status = if (pickedQuality.transcodes) "Compressing ${p.filename}…" else "Uploading ${p.filename}…"
            watch(request.id)
        }
    }

    private fun watch(id: UUID) {
        watchJob?.cancel()
        watchJob = viewModelScope.launch {
            workManager.getWorkInfoByIdFlow(id).filterNotNull().collect { info ->
                val p = info.progress.getFloat(UploadWorker.KEY_PROGRESS, -1f)
                val phase = info.progress.getString(UploadWorker.KEY_PHASE)
                val chunkIndex = info.progress.getInt(UploadWorker.KEY_CHUNK_INDEX, 0)
                val chunkTotal = info.progress.getInt(UploadWorker.KEY_CHUNK_TOTAL, 0)
                if (info.state == WorkInfo.State.RUNNING && p >= 0f) uploadProgress = p
                if (phase != null) {
                    uploadPhase = phase
                    val pct = (p * 100).toInt()
                    val chunkSuffix = if (chunkTotal > 0) " (part $chunkIndex of $chunkTotal)" else ""
                    status = when (phase) {
                        UploadWorker.PHASE_COMPRESS -> "Compressing… $pct%"
                        UploadWorker.PHASE_UPLOAD -> "Uploading… $pct%$chunkSuffix"
                        else -> status
                    }
                }
                when (info.state) {
                    WorkInfo.State.SUCCEEDED -> {
                        status = "Uploaded: ${info.outputData.getString(UploadWorker.KEY_URL)}"
                        uploadProgress = null
                        uploadPhase = null
                        invalidateList()
                    }
                    WorkInfo.State.FAILED -> {
                        status = "Failed: " +
                            (info.outputData.getString(UploadWorker.KEY_ERROR) ?: "unknown error")
                        uploadProgress = null
                        uploadPhase = null
                    }
                    WorkInfo.State.CANCELLED -> {
                        status = "Cancelled"
                        uploadProgress = null
                        uploadPhase = null
                    }
                    else -> {}
                }
            }
        }
    }

    fun askDelete(hash: String) { pendingDeleteHash = hash }
    fun cancelDelete() { pendingDeleteHash = null }

    fun confirmDelete() {
        val hash = pendingDeleteHash ?: return
        pendingDeleteHash = null
        viewModelScope.launch {
            runCatching {
                withContext(Dispatchers.IO) { client().delete(hash) }
            }.onSuccess { invalidateList() }
                .onFailure { status = "Delete failed: ${it.message}" }
        }
    }

    companion object {
        const val PAGE_SIZE = 20
        const val FRAME_COUNT = 20
    }
}