|
| 1 | +package ui |
| 2 | + |
| 3 | +import io.github.kdroidfilter.platformtools.getCacheDir |
| 4 | +import io.github.kdroidfilter.platformtools.releasefetcher.downloader.ReleaseFetcherConfig |
| 5 | +import io.github.oshai.kotlinlogging.KotlinLogging |
| 6 | +import io.ktor.client.HttpClient |
| 7 | +import io.ktor.client.call.* |
| 8 | +import io.ktor.client.engine.cio.CIO |
| 9 | +import io.ktor.client.plugins.* |
| 10 | +import io.ktor.client.plugins.HttpTimeoutConfig |
| 11 | +import io.ktor.client.request.* |
| 12 | +import io.ktor.http.* |
| 13 | +import io.ktor.utils.io.* |
| 14 | +import kotlinx.coroutines.Dispatchers |
| 15 | +import kotlinx.coroutines.withContext |
| 16 | +import java.io.File |
| 17 | + |
| 18 | +private val logger = KotlinLogging.logger {} |
| 19 | + |
| 20 | + |
| 21 | +/** |
| 22 | + * Downloader is responsible for handling file downloads from a given URL. |
| 23 | + * This class provides functionality to asynchronously download files, report |
| 24 | + * download progress, and handle errors that may occur during the download process. |
| 25 | + */ |
| 26 | +class Downloader { |
| 27 | + val client = HttpClient(CIO) { |
| 28 | + followRedirects = true |
| 29 | + |
| 30 | + install(HttpTimeout) { |
| 31 | + requestTimeoutMillis = 30_000 |
| 32 | + // requestTimeoutMillis = HttpTimeoutConfig.INFINITE_TIMEOUT_MS |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + private val downloaderBufferSize = 2 * 1024 * 1024 |
| 37 | + |
| 38 | + /** |
| 39 | + * Downloads an application file from the provided URL and tracks the download progress. |
| 40 | + * |
| 41 | + * @param downloadUrl The URL from which the application will be downloaded. |
| 42 | + * @param onProgress A callback function reporting download progress percentage and the downloaded file (if available). |
| 43 | + * The percentage is a `Double` ranging from 0.0 to 100.0, or -1.0 in case of errors. |
| 44 | + * The `file` parameter is the local file being downloaded, or `null` during download progress updates. |
| 45 | + * @return A `Boolean` indicating whether the download was successful. |
| 46 | + * Returns `true` if the download completes successfully, otherwise `false`. |
| 47 | + */ |
| 48 | + suspend fun downloadApp( |
| 49 | + downloadUrl: String, |
| 50 | + onProgress: (percentage: Double, file: File?) -> Unit |
| 51 | + ): Boolean { |
| 52 | + val bufferSize = downloaderBufferSize |
| 53 | + logger.debug { "Starting download from URL: $downloadUrl" } |
| 54 | + |
| 55 | + val fileName = downloadUrl.substringAfterLast('/').substringBefore('?') |
| 56 | + val cacheDir = getCacheDir() |
| 57 | + val destinationFile = File(cacheDir, fileName) |
| 58 | + |
| 59 | + onProgress(0.0, null) |
| 60 | + logger.debug { "Download initialized: 0%" } |
| 61 | + |
| 62 | + return try { |
| 63 | + val response = client.get(downloadUrl) { |
| 64 | + onDownload { bytesSentTotal, contentLength -> |
| 65 | + val progress = if (contentLength != null && contentLength > 0) { |
| 66 | + (bytesSentTotal * 100.0 / contentLength) |
| 67 | + } else 0.0 |
| 68 | + logger.debug { "Progress: $bytesSentTotal / $contentLength bytes" } |
| 69 | + onProgress(progress, null) |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + if (response.status.isSuccess()) { |
| 74 | + val channel: ByteReadChannel = response.body() |
| 75 | + val contentLength = response.contentLength() ?: -1L |
| 76 | + logger.debug { "Content length: $contentLength bytes" } |
| 77 | + |
| 78 | + withContext(Dispatchers.IO) { |
| 79 | + destinationFile.outputStream().buffered(bufferSize).use { output -> |
| 80 | + val buffer = ByteArray(bufferSize) |
| 81 | + while (!channel.isClosedForRead) { |
| 82 | + val bytesRead = channel.readAvailable(buffer) |
| 83 | + if (bytesRead == -1) break |
| 84 | + output.write(buffer, 0, bytesRead) |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + if (destinationFile.exists()) { |
| 90 | + logger.debug { "Download completed. Size: ${destinationFile.length()} bytes" } |
| 91 | + onProgress(100.0, destinationFile) |
| 92 | + true |
| 93 | + } else { |
| 94 | + logger.error { "Error: File not created" } |
| 95 | + onProgress(-1.0, null) // Keep -1.0 for errors |
| 96 | + false |
| 97 | + } |
| 98 | + } else { |
| 99 | + logger.error { "Download failed: ${response.status}" } |
| 100 | + onProgress(-1.0, null) // Keep -1.0 for errors |
| 101 | + false |
| 102 | + } |
| 103 | + } catch (e: Exception) { |
| 104 | + logger.error(e) { "Download error: ${e.message}" } |
| 105 | + onProgress(-1.0, null) // Keep -1.0 for errors |
| 106 | + false |
| 107 | + } |
| 108 | + } |
| 109 | +} |
0 commit comments