refactor: simplify ProxyHelper.kt

This commit is contained in:
Bnyro 2024-08-23 13:09:56 +02:00
parent 0a8a7905f9
commit b71636be0a

View File

@ -1,15 +1,11 @@
package com.github.libretube.helpers
import com.github.libretube.api.CronetHelper
import com.github.libretube.api.RetrofitInstance
import com.github.libretube.constants.PreferenceKeys
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import java.net.HttpURLConnection
import java.net.URL
object ProxyHelper {
fun fetchProxyUrl() {
@ -54,33 +50,21 @@ object ProxyHelper {
/**
* Convert a proxied Piped url to a YouTube url that's not proxied
*/
fun unwrapUrl(url: String, unwrap: Boolean = true) = url.toHttpUrlOrNull()
?.takeIf { unwrap }
?.let {
val host = it.queryParameter("host")
fun unwrapUrl(url: String, unwrap: Boolean = true): String {
val parsedUrl = url.toHttpUrlOrNull()
val host = parsedUrl?.queryParameter("host")
// if there's no host parameter specified, there's no way to unwrap the URL
// and the proxied one must be used. That's the case if using LBRY.
if (host.isNullOrEmpty()) return@let url
if (!unwrap || parsedUrl == null || host.isNullOrEmpty()) {
return url
}
it.newBuilder()
return parsedUrl.newBuilder()
.host(host)
.removeAllQueryParameters("host")
// .removeAllQueryParameters("ump")
.removeAllQueryParameters("qhash")
.build()
.toString()
} ?: url
/**
* Parse the Piped url to a YouTube url (or not) based on preferences
*/
private suspend fun isUrlUsable(url: String): Boolean = withContext(Dispatchers.IO) {
return@withContext runCatching {
val connection = CronetHelper.cronetEngine.openConnection(URL(url)) as HttpURLConnection
connection.requestMethod = "HEAD"
val isSuccess = connection.responseCode == 200
connection.disconnect()
return@runCatching isSuccess
}.getOrDefault(false)
}
}