Files
genie-android/app/src/main/java/com/amz/genie/helpers/AttachmentDownloader.kt
2026-03-03 01:25:13 +07:00

40 lines
1.1 KiB
Kotlin

package com.amz.genie.helpers
import android.content.Context
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
object AttachmentDownloader {
fun downloadToCache(
ctx: Context,
url: String,
fileName: String,
token: String
): File {
val safeName = fileName.ifBlank { "attachment_${System.currentTimeMillis()}" }
val outFile = File(ctx.cacheDir, safeName)
val client = OkHttpClient.Builder().build()
val req = Request.Builder()
.url(url)
.addHeader("Authorization", token)
.build()
client.newCall(req).execute().use { resp ->
if (!resp.isSuccessful) {
throw RuntimeException("Download gagal: ${resp.code} ${resp.message}")
}
val body = resp.body ?: throw RuntimeException("Body kosong")
outFile.outputStream().use { os ->
body.byteStream().use { input ->
input.copyTo(os)
}
}
}
return outFile
}
}