Last active
September 8, 2022 06:41
-
-
Save tfcporciuncula/f783ae39a88c1a028b99a84c7eb38f2a to your computer and use it in GitHub Desktop.
PdfDownloader.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PdfDownloader @Inject constructor( | |
private val context: Context, | |
private val yourApi: YourApi | |
) { | |
private class DownloadException(message: String, cause: Throwable? = null) : RuntimeException(message, cause) | |
suspend fun download(url: String, fileName: String): String = withContext(Dispatchers.IO) { | |
val file = createFile(fileName) | |
val response = yourApi.downloadPdf(url) | |
// this would look like this in YourApi: | |
// @Streaming @GET | |
// suspend fun downloadPdf(@Url url: String): Response<ResponseBody> | |
val inputStream = response.body()?.byteStream() ?: throw DownloadException("Download body is null") | |
inputStream.use { input -> | |
FileOutputStream(file).use { output -> input.copyTo(output) } | |
} | |
file.absolutePath | |
} | |
private fun createFile(fileName: String) = try { | |
val directory = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) | |
File.createTempFile("download_", fileName, directory) | |
} catch (e: IOException) { | |
throw DownloadException("Error while creating download file", e) | |
} | |
} | |
private fun InputStream.copyTo(output: FileOutputStream) { | |
val buffer = ByteArray(4 * 1024) | |
while (true) { | |
val byteCount = read(buffer) | |
if (byteCount < 0) break | |
output.write(buffer, 0, byteCount) | |
} | |
output.flush() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment