Skip to content

Commit

Permalink
Merge pull request #6383 from Bnyro/master
Browse files Browse the repository at this point in the history
refactor: simplify ProxyHelper.kt
  • Loading branch information
Bnyro authored Aug 23, 2024
2 parents 0a8a790 + b71636b commit 04e328f
Showing 1 changed file with 14 additions and 30 deletions.
44 changes: 14 additions & 30 deletions app/src/main/java/com/github/libretube/helpers/ProxyHelper.kt
Original file line number Diff line number Diff line change
@@ -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() {
Expand Down Expand Up @@ -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")
// 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
fun unwrapUrl(url: String, unwrap: Boolean = true): String {
val parsedUrl = url.toHttpUrlOrNull()

it.newBuilder()
.host(host)
.removeAllQueryParameters("host")
// .removeAllQueryParameters("ump")
.removeAllQueryParameters("qhash")
.build()
.toString()
} ?: url
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 (!unwrap || parsedUrl == null || host.isNullOrEmpty()) {
return 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)
return parsedUrl.newBuilder()
.host(host)
.removeAllQueryParameters("host")
.removeAllQueryParameters("qhash")
.build()
.toString()
}
}

0 comments on commit 04e328f

Please sign in to comment.