From 47de8220d52dde525d107ee076d090a48ee02c2e Mon Sep 17 00:00:00 2001 From: Bryson Steck Date: Sun, 7 May 2023 16:52:51 -0600 Subject: might as well commit before I go further --- .../brysonsteck/serverfordummies/downloadFile.kt | 37 ++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 app/src/main/kotlin/xyz/brysonsteck/serverfordummies/downloadFile.kt (limited to 'app/src/main/kotlin/xyz/brysonsteck/serverfordummies/downloadFile.kt') diff --git a/app/src/main/kotlin/xyz/brysonsteck/serverfordummies/downloadFile.kt b/app/src/main/kotlin/xyz/brysonsteck/serverfordummies/downloadFile.kt new file mode 100644 index 0000000..bbaeab5 --- /dev/null +++ b/app/src/main/kotlin/xyz/brysonsteck/serverfordummies/downloadFile.kt @@ -0,0 +1,37 @@ +import java.net.http.HttpClient +import kotlinx.coroutines.flow + +sealed class DownloadStatus { + + object Success : DownloadStatus() + + data class Error(val message: String) : DownloadStatus() + + data class Progress(val progress: Int): DownloadStatus() + +} + +// function from https://gist.githubusercontent.com/SG-K/63e379efcc3d1cd3ce4fb56ee0e29c42/raw/cd9a4a016401b7c54ec01303415b5871ffa26066/downloadFile.kt +suspend fun HttpClient.downloadFile(file: File, url: String): Flow { + return flow { + val response = call { + url(url) + method = HttpMethod.Get + }.response + val byteArray = ByteArray(response.contentLength()!!.toInt()) + var offset = 0 + do { + val currentRead = response.content.readAvailable(byteArray, offset, byteArray.size) + offset += currentRead + val progress = (offset * 100f / byteArray.size).roundToInt() + emit(DownloadStatus.Progress(progress)) + } while (currentRead > 0) + response.close() + if (response.status.isSuccess()) { + file.writeBytes(byteArray) + emit(DownloadStatus.Success) + } else { + emit(DownloadStatus.Error("File not downloaded")) + } + } +} \ No newline at end of file -- cgit v1.2.3