Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: simplify ProxyHelper.kt #6383

Merged
merged 1 commit into from
Aug 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
}
}
Loading