LibreTube/app/src/main/java/com/github/libretube/helpers/ProxyHelper.kt

53 lines
1.5 KiB
Kotlin
Raw Normal View History

package com.github.libretube.helpers
2022-11-21 18:42:46 +05:30
import com.github.libretube.api.RetrofitInstance
import com.github.libretube.constants.PreferenceKeys
import java.net.URI
2022-11-21 19:05:09 +05:30
import java.net.URLDecoder
import java.nio.charset.StandardCharsets
import java.util.*
2022-12-19 21:28:34 +05:30
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
2022-11-21 18:42:46 +05:30
object ProxyHelper {
private fun getImageProxyUrl(): String? {
val url = PreferenceHelper.getString(PreferenceKeys.IMAGE_PROXY_URL, "")
return if (url != "") url else null
}
private fun setImageProxyUrl(url: String) {
PreferenceHelper.putString(PreferenceKeys.IMAGE_PROXY_URL, url)
}
fun fetchProxyUrl() {
CoroutineScope(Dispatchers.IO).launch {
runCatching {
RetrofitInstance.api.getConfig().imageProxyUrl?.let {
setImageProxyUrl(it)
}
}
}
}
fun rewriteUrl(url: String?): String? {
url ?: return null
val proxyUrl = getImageProxyUrl()
proxyUrl ?: return url
runCatching {
val originalUri = URI(url)
2022-11-21 19:05:09 +05:30
val newUri = URI(
originalUri.scheme.lowercase(Locale.US),
URI(proxyUrl).authority,
2022-11-21 18:42:46 +05:30
originalUri.path,
originalUri.query,
originalUri.fragment
2022-11-21 19:05:09 +05:30
)
return URLDecoder.decode(newUri.toString(), StandardCharsets.UTF_8.toString())
2022-11-21 18:42:46 +05:30
}
return url
}
}