|
| 1 | +package com.aliucord.manager.installer.steps.base |
| 2 | + |
| 3 | +import android.content.Context |
| 4 | +import androidx.compose.runtime.Stable |
| 5 | +import com.aliucord.manager.R |
| 6 | +import com.aliucord.manager.installer.steps.StepGroup |
| 7 | +import com.aliucord.manager.installer.steps.StepRunner |
| 8 | +import com.aliucord.manager.manager.DownloadManager |
| 9 | +import com.aliucord.manager.util.showToast |
| 10 | +import kotlinx.coroutines.Dispatchers |
| 11 | +import kotlinx.coroutines.withContext |
| 12 | +import org.koin.core.component.KoinComponent |
| 13 | +import org.koin.core.component.inject |
| 14 | +import java.io.File |
| 15 | + |
| 16 | +@Stable |
| 17 | +abstract class DownloadStep : Step(), KoinComponent { |
| 18 | + private val context: Context by inject() |
| 19 | + private val downloads: DownloadManager by inject() |
| 20 | + |
| 21 | + /** |
| 22 | + * The remote url to download |
| 23 | + */ |
| 24 | + abstract val targetUrl: String |
| 25 | + |
| 26 | + /** |
| 27 | + * Target path to store the download in. If this file already exists, |
| 28 | + * then the cached version is used and the step is marked as cancelled/skipped. |
| 29 | + */ |
| 30 | + abstract val targetFile: File |
| 31 | + |
| 32 | + /** |
| 33 | + * Verify that the download completely successfully without errors. |
| 34 | + * @throws Throwable If verification fails. |
| 35 | + */ |
| 36 | + open suspend fun verify() { |
| 37 | + if (!targetFile.exists()) |
| 38 | + throw Error("Downloaded file is missing!") |
| 39 | + |
| 40 | + if (targetFile.length() <= 0) |
| 41 | + throw Error("Downloaded file is empty!") |
| 42 | + } |
| 43 | + |
| 44 | + override val group = StepGroup.Download |
| 45 | + |
| 46 | + override suspend fun execute(container: StepRunner) { |
| 47 | + if (targetFile.exists()) { |
| 48 | + if (targetFile.length() > 0) { |
| 49 | + state = StepState.Skipped |
| 50 | + return |
| 51 | + } |
| 52 | + |
| 53 | + targetFile.delete() |
| 54 | + } |
| 55 | + |
| 56 | + val result = downloads.download(targetUrl, targetFile) { newProgress -> |
| 57 | + progress = newProgress ?: -1f |
| 58 | + } |
| 59 | + |
| 60 | + when (result) { |
| 61 | + is DownloadManager.Result.Success -> { |
| 62 | + try { |
| 63 | + verify() |
| 64 | + } catch (t: Throwable) { |
| 65 | + withContext(Dispatchers.Main) { |
| 66 | + context.showToast(R.string.installer_dl_verify_fail) |
| 67 | + } |
| 68 | + |
| 69 | + throw t |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + is DownloadManager.Result.Error -> { |
| 74 | + withContext(Dispatchers.Main) { |
| 75 | + context.showToast(result.localizedReason) |
| 76 | + } |
| 77 | + |
| 78 | + throw Error("Failed to download: ${result.debugReason}") |
| 79 | + } |
| 80 | + |
| 81 | + is DownloadManager.Result.Cancelled -> |
| 82 | + state = StepState.Error |
| 83 | + } |
| 84 | + } |
| 85 | +} |
0 commit comments