From b71636be0a5f6a2356998eb03e780feccc4d5dd8 Mon Sep 17 00:00:00 2001 From: Bnyro Date: Fri, 23 Aug 2024 13:09:56 +0200 Subject: [PATCH] refactor: simplify ProxyHelper.kt --- .../github/libretube/helpers/ProxyHelper.kt | 44 ++++++------------- 1 file changed, 14 insertions(+), 30 deletions(-) diff --git a/app/src/main/java/com/github/libretube/helpers/ProxyHelper.kt b/app/src/main/java/com/github/libretube/helpers/ProxyHelper.kt index f521dcac55..293eb185db 100644 --- a/app/src/main/java/com/github/libretube/helpers/ProxyHelper.kt +++ b/app/src/main/java/com/github/libretube/helpers/ProxyHelper.kt @@ -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") - // 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() } }