Skip to content

Commit

Permalink
refactor: Update DownloadManagerUtils
Browse files Browse the repository at this point in the history
  • Loading branch information
sirambd committed Dec 20, 2024
1 parent 9eed6b7 commit d52fa0a
Showing 1 changed file with 8 additions and 9 deletions.
17 changes: 8 additions & 9 deletions Core2/src/main/java/com/infomaniak/core2/DownloadManagerUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package com.infomaniak.core2

import android.app.DownloadManager
import android.app.DownloadManager.Request
import android.content.Context
import android.database.Cursor
import android.net.Uri
Expand All @@ -40,40 +41,38 @@ object DownloadManagerUtils {
url: String,
name: String,
userAgent: String,
extraHeaders: Iterable<Pair<String, String>> = emptySet()
extraHeaders: Iterable<Pair<String, String>> = emptySet(),
) {
val formattedName = name.replace(regexInvalidSystemChar, "_").replace("%", "_").let {
// fix IllegalArgumentException only on Android 10 if multi dot
if (SDK_INT == 29) it.replace(Regex("\\.{2,}"), ".") else it
}

DownloadManager.Request(Uri.parse(url)).apply {
setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
Request(Uri.parse(url)).apply {
setAllowedNetworkTypes(Request.NETWORK_WIFI or Request.NETWORK_MOBILE)
setTitle(formattedName)
setDescription(appName)
setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, name)
addHeaders(userAgent, extraHeaders)

setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)

val downloadManager = appCtx.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val downloadReference = downloadManager.enqueue(this)
handleDownloadManagerErrors(downloadManager, downloadReference)
}
}

private fun DownloadManager.Request.addHeaders(userAgent: String, extraHeaders: Iterable<Pair<String, String>>) {
private fun Request.addHeaders(userAgent: String, extraHeaders: Iterable<Pair<String, String>>) {
addRequestHeader("Accept-Encoding", "gzip")
addRequestHeader("App-Version", "Android $appVersionName")
addRequestHeader("User-Agent", userAgent)
extraHeaders.forEach { (key, value) ->
addRequestHeader(key, value)
}
extraHeaders.forEach { (key, value) -> addRequestHeader(key, value) }
}

private fun handleDownloadManagerErrors(downloadManager: DownloadManager, downloadReference: Long) {
scope.launch {
delay(1_000L)
delay(1_000L) // We wait a little to make sure we have the errors from the query
DownloadManager.Query().also { query ->
query.setFilterById(downloadReference)
Dispatchers.IO {
Expand Down

0 comments on commit d52fa0a

Please sign in to comment.