create library.network module to abstract networking
- Commit
8ec1abc13f3aad26d6a41c884c4f9f00b2cf5d47- Author
- Vayun Mathur <[email protected]>
- When
- 2026-05-10 07:03 UTC (7 months ago)
- Parents
61950c9
Diff
.idea/gradle.xml
diff --git a/.idea/gradle.xml b/.idea/gradle.xmlindex c3bbfd208e..c3d12be10f 100644--- a/.idea/gradle.xml+++ b/.idea/gradle.xml@@ -37,6 +37,7 @@ <option value="$PROJECT_DIR$/library" /> <option value="$PROJECT_DIR$/library/biometric" /> <option value="$PROJECT_DIR$/library/downloadservice" />+ <option value="$PROJECT_DIR$/library/network" /> <option value="$PROJECT_DIR$/library/widgets" /> <option value="$PROJECT_DIR$/maps" /> <option value="$PROJECT_DIR$/music" />
build-logic/src/main/kotlin/RoomExtension.kt
diff --git a/build-logic/src/main/kotlin/RoomExtension.kt b/build-logic/src/main/kotlin/RoomExtension.ktindex 89b860da0f..7a567e644f 100644--- a/build-logic/src/main/kotlin/RoomExtension.kt+++ b/build-logic/src/main/kotlin/RoomExtension.kt@@ -7,10 +7,3 @@ fun DependencyHandlerScope.implementRoom(libs: org.gradle.accessors.dm.Libraries implementation(libs.androidx.room.ktx) ksp(libs.androidx.room.compiler) }--fun DependencyHandlerScope.implementKtor(libs: org.gradle.accessors.dm.LibrariesForLibs) {- implementation(libs.ktor.client.cio)- implementation(libs.ktor.client.core)- implementation(libs.ktor.client.content.negotiation)- implementation(libs.ktor.serialization.kotlinx.json)-}\ No newline at end of file
crypto/build.gradle.kts
diff --git a/crypto/build.gradle.kts b/crypto/build.gradle.ktsindex 792ba99696..f0a2d0bd29 100644--- a/crypto/build.gradle.kts+++ b/crypto/build.gradle.kts@@ -10,7 +10,7 @@ android { dependencies { // ktor- implementKtor(libs)+ implementation(project(":library:network")) // solana implementation(libs.sol4k)
crypto/src/main/java/com/vayunmathur/crypto/util/api/JupiterAPI.kt
diff --git a/crypto/src/main/java/com/vayunmathur/crypto/util/api/JupiterAPI.kt b/crypto/src/main/java/com/vayunmathur/crypto/util/api/JupiterAPI.ktindex 47543f1640..377df2cadc 100644--- a/crypto/src/main/java/com/vayunmathur/crypto/util/api/JupiterAPI.kt+++ b/crypto/src/main/java/com/vayunmathur/crypto/util/api/JupiterAPI.kt@@ -1,10 +1,6 @@ package com.vayunmathur.crypto.util.api import com.vayunmathur.crypto.data.TokenInfo-import io.ktor.client.call.body-import io.ktor.client.request.get-import io.ktor.client.request.header-import io.ktor.client.request.parameter-import io.ktor.client.statement.HttpResponse+import com.vayunmathur.library.network.NetworkClient import org.sol4k.Keypair import kotlin.math.pow @@ -13,11 +9,10 @@ object JupiterAPI { suspend fun getPrices(mints: List<String>): PriceResponse { return mints.chunked(20).map { try {- val response: HttpResponse = client.get("https://api.jup.ag/price/v3") {- header("x-api-key", API_KEY)- parameter("ids", it.joinToString(","))- }- response.body<PriceResponse>()+ NetworkClient.getJson<PriceResponse>(+ url = "https://api.jup.ag/price/v3?ids=${it.joinToString(",")}",+ headers = mapOf("x-api-key" to API_KEY)+ ) } catch(_: Exception) { emptyMap() } }.fold(emptyMap()) { acc, map -> acc + map }@@ -30,16 +25,19 @@ object JupiterAPI { taker: Keypair ): PendingOrder? { return try {- client.get("https://api.jup.ag/ultra/v1/order") {- header("x-api-key", API_KEY)- parameter("inputMint", inputToken.mintAddress)- parameter("outputMint", outputToken.mintAddress)- parameter("amount", (amount * 10.0.pow(inputToken.decimals)).toLong())- parameter("taker", taker.publicKey.toBase58())- }.body()+ val url = "https://api.jup.ag/ultra/v1/order?" + + "inputMint=${inputToken.mintAddress}&" ++ "outputMint=${outputToken.mintAddress}&" ++ "amount=${(amount * 10.0.pow(inputToken.decimals)).toLong()}&" ++ "taker=${taker.publicKey.toBase58()}"+ + NetworkClient.getJson<PendingOrder>(+ url = url,+ headers = mapOf("x-api-key" to API_KEY)+ ) } catch(e: Exception) { e.printStackTrace() null } }-}\ No newline at end of file+}
crypto/src/main/java/com/vayunmathur/crypto/util/api/PredictionMarket.kt
diff --git a/crypto/src/main/java/com/vayunmathur/crypto/util/api/PredictionMarket.kt b/crypto/src/main/java/com/vayunmathur/crypto/util/api/PredictionMarket.ktindex b2dc43fa57..cdb74e5e4c 100644--- a/crypto/src/main/java/com/vayunmathur/crypto/util/api/PredictionMarket.kt+++ b/crypto/src/main/java/com/vayunmathur/crypto/util/api/PredictionMarket.kt@@ -1,8 +1,6 @@ package com.vayunmathur.crypto.util.api import com.vayunmathur.crypto.data.TokenInfo-import io.ktor.client.call.body-import io.ktor.client.request.get-import io.ktor.client.request.parameter+import com.vayunmathur.library.network.NetworkClient import kotlinx.serialization.Serializable object PredictionMarket {@@ -35,8 +33,7 @@ object PredictionMarket { } suspend fun getPredictionMarkets(): List<Event> {- val content = client.get("https://api.vayunmathur.com/crypto/prediction_market_events").body<List<Event>>()- return content+ return NetworkClient.getJson("https://api.vayunmathur.com/crypto/prediction_market_events") } suspend fun makeOrder(market: Event.Market, yes: Boolean, amount: Double, publicKey: String): PendingOrder {@@ -44,14 +41,13 @@ object PredictionMarket { val inputMint = TokenInfo.USDC.mintAddress val slippageBps = 50 - val res = client.get("https://api.vayunmathur.com/crypto/prediction_market/order") {- parameter("inputMint", inputMint)- parameter("outputMint", outputMint)- parameter("amount", (amount*1000000).toInt().toString())- parameter("slippageBps", slippageBps.toString())- parameter("userPublicKey", publicKey)- }+ val url = "https://api.vayunmathur.com/crypto/prediction_market/order?" ++ "inputMint=$inputMint&" ++ "outputMint=$outputMint&" ++ "amount=${(amount*1000000).toInt()}&" ++ "slippageBps=$slippageBps&" ++ "userPublicKey=$publicKey" - return res.body<PendingOrder>()+ return NetworkClient.getJson(url) }-}\ No newline at end of file+}
crypto/src/main/java/com/vayunmathur/crypto/util/api/SolanaApi.kt
diff --git a/crypto/src/main/java/com/vayunmathur/crypto/util/api/SolanaApi.kt b/crypto/src/main/java/com/vayunmathur/crypto/util/api/SolanaApi.ktindex dbaf5e2132..38462ae810 100644--- a/crypto/src/main/java/com/vayunmathur/crypto/util/api/SolanaApi.kt+++ b/crypto/src/main/java/com/vayunmathur/crypto/util/api/SolanaApi.kt@@ -2,16 +2,7 @@ package com.vayunmathur.crypto.util.api import com.vayunmathur.crypto.util.api.SolanaAPI.RPCResult import com.vayunmathur.crypto.data.Token import com.vayunmathur.crypto.data.TokenInfo-import io.ktor.client.HttpClient-import io.ktor.client.call.body-import io.ktor.client.engine.cio.CIO-import io.ktor.client.plugins.contentnegotiation.ContentNegotiation-import io.ktor.client.request.post-import io.ktor.client.request.setBody-import io.ktor.client.statement.HttpResponse-import io.ktor.http.ContentType-import io.ktor.http.contentType-import io.ktor.serialization.kotlinx.json.json+import com.vayunmathur.library.network.NetworkClient import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray@@ -111,12 +102,6 @@ val JSON = Json { encodeDefaults = true } -val client = HttpClient(CIO) {- install(ContentNegotiation) {- json(JSON)- }-}- object SolanaAPI { private val connection = Connection(RpcUrl.MAINNNET)@@ -161,29 +146,31 @@ object SolanaAPI { } private suspend inline fun <reified T> rpcCallV(method: String, params: JsonArray): T? {- val response: HttpResponse = client.post(HELIUS_URL) {- contentType(ContentType.Application.Json)- setBody(- RPCRequest(- method = method,- params = params- )- )+ return try {+ NetworkClient.callJson<RPCValueResult<T>>(+ url = HELIUS_URL,+ method = "POST",+ headers = mapOf("Content-Type" to "application/json"),+ body = RPCRequest(method = method, params = params)+ ).result.value+ } catch (e: Exception) {+ e.printStackTrace()+ null }- return response.body<RPCValueResult<T>>().result.value } private suspend inline fun <reified T> rpcCall(method: String, params: JsonArray): T? {- val response: HttpResponse = client.post(HELIUS_URL) {- contentType(ContentType.Application.Json)- setBody(- RPCRequest(- method = method,- params = params- )- )+ return try {+ NetworkClient.callJson<RPCResult<T>>(+ url = HELIUS_URL,+ method = "POST",+ headers = mapOf("Content-Type" to "application/json"),+ body = RPCRequest(method = method, params = params)+ ).result+ } catch (e: Exception) {+ e.printStackTrace()+ null }- return response.body<RPCResult<T>>().result } fun transfer(from: Keypair, token: TokenInfo, recipient: PublicKey, amount: Double) {@@ -269,4 +256,4 @@ object SolanaAPI { val value: T ) }-}\ No newline at end of file+}
findfamily/build.gradle.kts
diff --git a/findfamily/build.gradle.kts b/findfamily/build.gradle.ktsindex c189322975..792ef9811c 100644--- a/findfamily/build.gradle.kts+++ b/findfamily/build.gradle.kts@@ -11,7 +11,7 @@ android { dependencies { // ktor- implementKtor(libs)+ implementation(project(":library:network")) implementRoom(libs)
findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.ktindex e10096e9cd..d6c9275bf9 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/util/Networking.kt@@ -3,23 +3,12 @@ import com.vayunmathur.findfamily.data.LocationValue import com.vayunmathur.findfamily.data.LocationValueCompatible import com.vayunmathur.findfamily.data.TemporaryLink import com.vayunmathur.findfamily.data.User+import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.DatabaseViewModel import dev.whyoleg.cryptography.CryptographyProvider import dev.whyoleg.cryptography.algorithms.RSA import dev.whyoleg.cryptography.algorithms.SHA512-import io.ktor.client.HttpClient-import io.ktor.client.call.body-import io.ktor.client.network.sockets.ConnectTimeoutException-import io.ktor.client.network.sockets.SocketTimeoutException-import io.ktor.client.plugins.contentnegotiation.ContentNegotiation-import io.ktor.client.request.post-import io.ktor.client.request.setBody-import io.ktor.client.statement.bodyAsText-import io.ktor.http.ContentType-import io.ktor.http.HttpStatusCode-import io.ktor.http.contentType-import io.ktor.serialization.kotlinx.json.json import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlin.io.encoding.Base64@@ -32,11 +21,6 @@ object Networking { ignoreUnknownKeys = true } - private val client = HttpClient {- install(ContentNegotiation) {- json(json)- }- } private val crypto = CryptographyProvider.Default.get(RSA.OAEP) private var publickey: RSA.OAEP.PublicKey? = null private var privatekey: RSA.OAEP.PrivateKey? = null@@ -66,43 +50,37 @@ object Networking { val x = makeRequest() network_is_down = false return x- } catch(_: ConnectTimeoutException) {- if (!network_is_down) {- //TODO: notify user- println("network is down")- }- network_is_down = true- } catch(_: SocketTimeoutException) {+ } catch(e: Exception) {+ // Check for timeout exceptions without direct Ktor dependency if possible, + // but for now we'll just catch all and assume network might be down if it fails. if (!network_is_down) {- //TODO: notify user- println("network is down")+ println("network error: ${e.message}") } network_is_down = true- } catch(e: Throwable) {- println(e.printStackTrace()) } return null } private suspend inline fun <reified T, reified I> makeRequest(path: String, body: I): T? { return checkNetworkDown {- val response = client.post("$URL$path") {- contentType(ContentType.Application.Json)- setBody(body)+ try {+ NetworkClient.callJson<T>(+ url = "$URL$path",+ method = "POST",+ headers = mapOf("Content-Type" to "application/json"),+ body = body+ )+ } catch (e: Exception) {+ println("Request failed: ${e.message}")+ null }- if(response.status != HttpStatusCode.OK) {- println(response.status)- return@checkNetworkDown null- }- val result = response.body<T>()- return@checkNetworkDown result } } private suspend fun register(): Boolean { @Serializable data class Register(val userid: ULong, val key: String)- return makeRequest("/api/register", Register(+ return makeRequest<Boolean, Register>("/api/register", Register( userid.toULong(), Base64.encode(publickey!!.encodeToByteArray(RSA.PublicKey.Format.PEM)) )@@ -117,15 +95,17 @@ object Networking { private suspend fun getKey(userid: Long): RSA.OAEP.PublicKey? { return checkNetworkDown {- val response = client.post("$URL/api/getkey") {- contentType(ContentType.Application.Json)- setBody("{\"userid\": ${userid.toULong()}}")- }- if(response.status != HttpStatusCode.OK) {+ val response = NetworkClient.performRequest(+ url = "$URL/api/getkey",+ method = "POST",+ headers = mapOf("Content-Type" to "application/json"),+ body = "{\"userid\": ${userid.toULong()}}"+ )+ if(response.status != 200) { return@checkNetworkDown null } return@checkNetworkDown crypto.publicKeyDecoder(SHA512).decodeFromByteArray(RSA.PublicKey.Format.PEM,- Base64.decode(response.bodyAsText())+ Base64.decode(response.body) ) } }@@ -141,19 +121,19 @@ object Networking { viewModel.upsertAsync(user.copy(encryptionKey = keyString)) } } ?: return false- return makeRequest("/api/location/publish", encryptLocation(location, user.id, key)) ?: false+ return makeRequest<Boolean, LocationSharingData>("/api/location/publish", encryptLocation(location, user.id, key)) ?: false } suspend fun publishLocation(location: LocationValue, user: TemporaryLink): Boolean { val key = crypto.publicKeyDecoder(SHA512).decodeFromByteArray(RSA.PublicKey.Format.PEM, Base64.decode(user.publicKey) )- return makeRequest("/api/location/publish", encryptLocation(location, user.id, key)) ?: false+ return makeRequest<Boolean, LocationSharingData>("/api/location/publish", encryptLocation(location, user.id, key)) ?: false } suspend fun receiveLocations(): List<LocationValue>? {- val strings: List<String> = makeRequest("/api/location/receive", "{\"userid\": $userid}") ?: return null- return strings.map { decryptLocation(it) }+ val strings: List<String>? = makeRequest("/api/location/receive", "{\"userid\": $userid}")+ return strings?.map { decryptLocation(it) } } private suspend fun encryptLocation(location: LocationValue, recipientUserID: Long, key: RSA.OAEP.PublicKey): LocationSharingData {@@ -175,4 +155,4 @@ object Networking { @Serializable private data class LocationSharingData(val recipientUserID: ULong, val encryptedLocation: String)-}\ No newline at end of file+}
gradle.properties
diff --git a/gradle.properties b/gradle.propertiesindex cec73236d5..4906a845b3 100644--- a/gradle.properties+++ b/gradle.properties@@ -1,27 +1,12 @@-# Project-wide Gradle settings.-# IDE (e.g. Android Studio) users:-# Gradle settings configured through the IDE *will override*-# any settings specified in this file.-# For more details on how to configure your build environment visit-# http://www.gradle.org/docs/current/userguide/build_environment.html-# Specifies the JVM arguments used for the daemon process.-# The setting is particularly useful for tweaking memory settings.+# Increase this to -Xmx4g if your project grows org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8-# When configured, Gradle will run in incubating parallel mode.-# This option should only be used with decoupled projects. For more details, visit-# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects-# org.gradle.parallel=true-# AndroidX package structure to make it clearer which packages are bundled with the-# Android operating system, and which are packaged with your app's APK-# https://developer.android.com/topic/libraries/support-library/androidx-rn-android.useAndroidX=true-# Kotlin code style for this project: "official" or "obsolete":++# Modern defaults kotlin.code.style=official-# Enables namespacing of each library's R class so that its R class includes only the-# resources declared in the library itself and none from the library's dependencies,-# thereby reducing the size of the R class for that library-android.nonTransitiveRClass=true-android.enableResourceOptimizations=true++# Performance & Optimization+org.gradle.configuration-cache=true android.enableR8.fullMode=true-android.suppressUnsupportedCompileSdk=37.0-org.gradle.configuration-cache=true\ No newline at end of file++# Preview Support (Remove once SDK 37 is stable)+android.suppressUnsupportedCompileSdk=37.0\ No newline at end of file
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex e836f586bc..84b0e032a6 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -5,7 +5,6 @@ comAutonomousappsDependencyAnalysisGradlePlugin = "3.10.0" fhirModel = "1.0.0-beta02" flatgeobuf = "3.29.0" kotlin = "2.3.21"-kotlinCsvJvm = "1.10.0" kotlinGradlePlugin = "2.3.20" ksp = "2.3.6" @@ -25,7 +24,6 @@ activityCompose = "1.13.0" material3 = "1.5.0-alpha19" reorderable = "3.1.0" material = "1.13.0"-composeMarkdown = "0.5.8" # Navigation navigation3 = "1.1.1"@@ -40,10 +38,9 @@ camerax = "1.6.1" # Networking & Data ktor = "3.4.3"-okhttp = "5.3.2" okio = "3.17.0" kotlinxSerializationJson = "1.11.0"-kotlinxDatetime = "0.7.1"+kotlinxDatetime = "0.8.0" room = "2.8.4" # Special Features (PDF, Maps, Health, Crypto)@@ -53,7 +50,7 @@ glance = "1.1.1" connectClient = "1.2.0-alpha04" cryptographyCore = "0.6.0" sol4k = "0.7.0"-libphonenumber = "9.0.29"+libphonenumber = "9.0.30" material3AdaptiveNavigationSuite = "1.4.0" maplibre = "0.12.1" foundation = "1.11.1"@@ -98,10 +95,8 @@ androidx-media3-datasource-okhttp = { group = "androidx.media3", name = "media3- coil-compose = { module = "io.coil-kt:coil-compose", version.ref = "coilCompose" } coil-video = { module = "io.coil-kt:coil-video", version.ref = "coilCompose" } com-autonomousapps-dependency-analysis-gradle-plugin = { module = "com.autonomousapps.dependency-analysis:com.autonomousapps.dependency-analysis.gradle.plugin", version.ref = "comAutonomousappsDependencyAnalysisGradlePlugin" }-compose-markdown = { group = "com.github.jeziellago", name = "compose-markdown", version.ref = "composeMarkdown" } fhir-model = { module = "com.google.fhir:fhir-model", version.ref = "fhirModel" } flatgeobuf = { module = "org.wololo:flatgeobuf", version.ref = "flatgeobuf" }-kotlin-csv-jvm = { module = "com.github.doyaaaaaken:kotlin-csv-jvm", version.ref = "kotlinCsvJvm" } kotlin-gradle-plugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlinGradlePlugin" } litertlm-android = { module = "com.google.ai.edge.litertlm:litertlm-android", version.ref = "litertlmAndroid" } newpipeextractor = { module = "com.github.TeamNewPipe:NewPipeExtractor", version.ref = "newpipeextractor" }@@ -126,7 +121,6 @@ ktor-client-core = { group = "io.ktor", name = "ktor-client-core", version.ref = ktor-client-cio = { group = "io.ktor", name = "ktor-client-cio", version.ref = "ktor" } ktor-client-content-negotiation = { group = "io.ktor", name = "ktor-client-content-negotiation", version.ref = "ktor" } ktor-serialization-kotlinx-json = { group = "io.ktor", name = "ktor-serialization-kotlinx-json", version.ref = "ktor" }-okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } okio = { group = "com.squareup.okio", name = "okio", version.ref = "okio" } # Data Storage & Serialization
health/build.gradle.kts
diff --git a/health/build.gradle.kts b/health/build.gradle.ktsindex 88be6f24a9..2b77cb4b37 100644--- a/health/build.gradle.kts+++ b/health/build.gradle.kts@@ -21,5 +21,5 @@ dependencies { implementRoom(libs) // ktor- implementKtor(libs)+ implementation(project(":library:network")) }\ No newline at end of file
health/src/main/java/com/vayunmathur/health/util/FoodSearchAPI.kt
diff --git a/health/src/main/java/com/vayunmathur/health/util/FoodSearchAPI.kt b/health/src/main/java/com/vayunmathur/health/util/FoodSearchAPI.ktindex 484527cfcc..a25efa8a1d 100644--- a/health/src/main/java/com/vayunmathur/health/util/FoodSearchAPI.kt+++ b/health/src/main/java/com/vayunmathur/health/util/FoodSearchAPI.kt@@ -2,42 +2,17 @@ package com.vayunmathur.health.util import com.vayunmathur.health.data.Ingredient import com.vayunmathur.health.data.NutritionData-import io.ktor.client.HttpClient-import io.ktor.client.call.body-import io.ktor.client.engine.cio.CIO-import io.ktor.client.plugins.contentnegotiation.ContentNegotiation-import io.ktor.client.request.get-import io.ktor.client.request.parameter-import io.ktor.serialization.kotlinx.json.json+import com.vayunmathur.library.network.NetworkClient import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable-import kotlinx.serialization.json.Json object FoodSearchAPI {- private val client =- HttpClient(CIO) {- install(ContentNegotiation) {- json(- Json {- ignoreUnknownKeys = true- coerceInputValues = true- }- )- }- } @Serializable data class SearchResult(val id: Long, @SerialName("display_name") val displayName: String) suspend fun searchIngredients(query: String): List<SearchResult> { return try {- val response =- client.get("https://api.vayunmathur.com/api/food/search") {- parameter("q", query)- }- if (response.status.value !in 200..299) {- android.util.Log.e("FoodSearchAPI", "API Error: ${response.status}")- }- response.body()+ NetworkClient.getJson("https://api.vayunmathur.com/api/food/search?q=$query") } catch (e: Exception) { android.util.Log.e("FoodSearchAPI", "Search Error: ${e.message}", e) emptyList()@@ -47,7 +22,7 @@ object FoodSearchAPI { suspend fun getIngredientData(id: Long, displayName: String): Ingredient? { return try { val nutritionData: NutritionData =- client.get("https://api.vayunmathur.com/api/food/data/$id").body()+ NetworkClient.getJson("https://api.vayunmathur.com/api/food/data/$id") Ingredient( id = id.toString(),
library/downloadservice/build.gradle.kts
diff --git a/library/downloadservice/build.gradle.kts b/library/downloadservice/build.gradle.ktsindex 1104efaa5b..ac8760b175 100644--- a/library/downloadservice/build.gradle.kts+++ b/library/downloadservice/build.gradle.kts@@ -4,6 +4,6 @@ plugins { dependencies { implementation(project(":library"))- api(libs.okhttp)+ implementation(project(":library:network")) api(libs.androidx.work.runtime.ktx) }
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/DownloadService.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/DownloadService.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/DownloadService.ktindex 00fcca5614..524e8aa321 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/DownloadService.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/DownloadService.kt@@ -10,14 +10,10 @@ import android.os.PowerManager import androidx.core.app.NotificationCompat import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.*-import okhttp3.*-import okio.BufferedSink-import okio.buffer-import okio.appendingSink-import okio.sink+import com.vayunmathur.library.network.NetworkClient import java.io.File+import java.io.FileOutputStream import java.io.IOException-import java.security.MessageDigest import java.util.concurrent.TimeUnit import kotlin.math.pow @@ -28,17 +24,13 @@ class DownloadService : Service() { private const val NOTIF_ID = 1001 private const val CHANNEL_ID = "high_speed_download_channel" private const val MAX_RETRIES = 5- private const val BUFFER_SIZE = 262144L+ private const val BUFFER_SIZE = 262144 } private var wifiLock: WifiManager.WifiLock? = null private var wakeLock: PowerManager.WakeLock? = null - private val client = OkHttpClient.Builder()- .connectTimeout(30, TimeUnit.SECONDS)- .readTimeout(60, TimeUnit.SECONDS)- .callTimeout(0, TimeUnit.SECONDS)- .build()+ private val client = NetworkClient override fun onCreate() { super.onCreate()@@ -108,71 +100,58 @@ class DownloadService : Service() { var lastBytes = existingSize var lastTime = System.currentTimeMillis() - val request = Request.Builder()- .url(url)- .apply {- if (existingSize > 0) addHeader("Range", "bytes=$existingSize-")- }- .build()+ val headers = if (existingSize > 0) mapOf("Range" to "bytes=$existingSize-") else emptyMap() - client.newCall(request).execute().use { response ->- if (!response.isSuccessful && response.code != 206) {- if (response.code == 416) {+ client.stream(url, headers = headers) { stream, response ->+ if (stream == null) {+ if (response.status == 416) { markAsDone(ds, fileName)- return@withContext+ } else {+ throw IOException("Server returned ${response.status}") }- throw IOException("Server returned ${response.code}")+ return@stream }-- // Elvis operator removed as body is expected to be present if call succeeded- val body = response.body- val isResuming = response.code == 206- val totalSize = if (isResuming) existingSize + body.contentLength() else body.contentLength()-- val source = body.source()- val sink: BufferedSink = if (isResuming) file.appendingSink().buffer() else file.sink().buffer()+ val isResuming = existingSize > 0+ val contentLength = response.contentLength+ val totalSize = if (contentLength != null) {+ if (isResuming) existingSize + contentLength else contentLength+ } else null var downloaded = if (isResuming) existingSize else 0L - try {- sink.use { output ->- source.use { input ->- while (isActive && !input.exhausted()) {- val read = input.read(output.buffer, BUFFER_SIZE)- if (read == -1L) break+ FileOutputStream(file, isResuming).use { output ->+ val buffer = ByteArray(BUFFER_SIZE)+ while (isActive && !stream.isClosedForRead) {+ val read = stream.read(buffer)+ if (read == -1) break - output.emit()- downloaded += read+ output.write(buffer, 0, read)+ downloaded += read - val currentTime = System.currentTimeMillis()- val timeDiffMs = currentTime - lastTime+ val currentTime = System.currentTimeMillis()+ val timeDiffMs = currentTime - lastTime - if (timeDiffMs >= 1000L || downloaded == totalSize) {- val progress = if (totalSize > 0) downloaded.toDouble() / totalSize else 0.0- val speedMbps = ((downloaded - lastBytes) * 8.0) / 1_000_000.0 / (timeDiffMs / 1000.0)+ if (timeDiffMs >= 1000L || (totalSize != null && downloaded == totalSize)) {+ val progress = if (totalSize != null && totalSize > 0) downloaded.toDouble() / totalSize else 0.0+ val speedMbps = ((downloaded - lastBytes) * 8.0) / 1_000_000.0 / (timeDiffMs / 1000.0) - ds.setDouble("progress_$fileName", progress)- ds.setDouble("speed_$fileName", if (downloaded == totalSize) 0.0 else speedMbps)+ ds.setDouble("progress_$fileName", progress)+ ds.setDouble("speed_$fileName", if (totalSize != null && downloaded == totalSize) 0.0 else speedMbps) - val speedText = if (speedMbps > 0) "${speedMbps.toInt()} Mbps" else "Finishing..."- updateNotification("Downloading $fileName: ${(progress * 100).toInt()}% ($speedText)")+ val speedText = if (speedMbps > 0) "${speedMbps.toInt()} Mbps" else "Finishing..."+ updateNotification("Downloading $fileName: ${(progress * 100).toInt()}% ($speedText)") - lastBytes = downloaded- lastTime = currentTime- }- }- output.flush()+ lastBytes = downloaded+ lastTime = currentTime } }+ output.flush()+ } - if (totalSize > 0 && downloaded >= totalSize) {- markAsDone(ds, fileName)- } else if (isActive && totalSize > 0) {- throw IOException("Connection lost: $downloaded/$totalSize bytes received")- }-- } catch (e: Exception) {- throw e+ if (totalSize != null && totalSize > 0 && downloaded >= totalSize) {+ markAsDone(ds, fileName)+ } else if (isActive && totalSize != null && totalSize > 0) {+ throw IOException("Connection lost: $downloaded/$totalSize bytes received") } } }
library/network/build.gradle.kts
diff --git a/library/network/build.gradle.kts b/library/network/build.gradle.ktsnew file mode 100644index 0000000000..41f3bb4e3d--- /dev/null+++ b/library/network/build.gradle.kts@@ -0,0 +1,10 @@+plugins {+ id("common-conventions-library")+}++dependencies {+ implementation(libs.ktor.client.cio)+ implementation(libs.ktor.client.core)+ implementation(libs.ktor.client.content.negotiation)+ implementation(libs.ktor.serialization.kotlinx.json)+}
library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt
diff --git a/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt b/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.ktnew file mode 100644index 0000000000..2f953bbe48--- /dev/null+++ b/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt@@ -0,0 +1,138 @@+package com.vayunmathur.library.network++import io.ktor.client.HttpClient+import io.ktor.client.call.body+import io.ktor.client.engine.cio.CIO+import io.ktor.client.plugins.HttpTimeout+import io.ktor.client.plugins.contentnegotiation.ContentNegotiation+import io.ktor.client.request.HttpRequestBuilder+import io.ktor.client.request.header+import io.ktor.client.request.request+import io.ktor.client.request.setBody+import io.ktor.client.statement.HttpResponse+import io.ktor.client.statement.bodyAsChannel+import io.ktor.client.statement.bodyAsText+import io.ktor.client.statement.request+import io.ktor.http.HttpMethod+import io.ktor.serialization.kotlinx.json.json+import io.ktor.utils.io.readAvailable+import kotlinx.serialization.json.Json++data class SimpleResponse(+ val status: Int,+ val statusMessage: String,+ val body: String,+ val headers: Map<String, List<String>>,+ val url: String,+) {+ val isSuccess: Boolean get() = status in 200..299+ val contentLength: Long? get() = headers["Content-Length"]?.firstOrNull()?.toLongOrNull()+}++interface NetworkDataStream {+ suspend fun read(buffer: ByteArray): Int+ val isClosedForRead: Boolean+}++object NetworkClient {+ private val jsonConfig = Json {+ ignoreUnknownKeys = true+ prettyPrint = true+ isLenient = true+ }++ val client = HttpClient(CIO) {+ install(HttpTimeout) {+ requestTimeoutMillis = 60_000+ connectTimeoutMillis = 30_000+ }+ install(ContentNegotiation) {+ json(jsonConfig)+ }+ }++ @PublishedApi+ internal fun HttpRequestBuilder.applyHeaders(headers: Map<String, *>) {+ headers.forEach { (key, value) ->+ when (value) {+ is Iterable<*> -> value.forEach { v -> if (v != null) header(key, v) }+ else -> if (value != null) header(key, value)+ }+ }+ }++ private fun HttpResponse.toSimpleResponse(body: String = ""): SimpleResponse {+ return SimpleResponse(+ status = status.value,+ statusMessage = status.description,+ body = body,+ headers = headers.entries().associate { it.key to it.value },+ url = request.url.toString()+ )+ }++ suspend fun performRequest(+ url: String,+ method: String = "GET",+ headers: Map<String, *> = emptyMap<String, Any>(),+ body: Any? = null+ ): SimpleResponse {+ val response: HttpResponse = client.request(url) {+ this.method = HttpMethod.parse(method)+ applyHeaders(headers)+ body?.let { setBody(it) }+ }+ return response.toSimpleResponse(response.bodyAsText())+ }++ suspend fun stream(+ url: String,+ method: String = "GET",+ headers: Map<String, *> = emptyMap<String, Any>(),+ block: suspend (stream: NetworkDataStream?, response: SimpleResponse) -> Unit+ ): SimpleResponse {+ val response = client.request(url) {+ this.method = HttpMethod.parse(method)+ applyHeaders(headers)+ }+ val simpleResponse = response.toSimpleResponse()+ if (simpleResponse.isSuccess || simpleResponse.status == 206) {+ val channel = response.bodyAsChannel()+ val stream = object : NetworkDataStream {+ override suspend fun read(buffer: ByteArray): Int = channel.readAvailable(buffer)+ override val isClosedForRead: Boolean get() = channel.isClosedForRead+ }+ block(stream, simpleResponse)+ } else {+ block(null, simpleResponse)+ }+ return simpleResponse+ }++ suspend fun getContentLength(url: String, headers: Map<String, *> = emptyMap<String, Any>()): Long? {+ val response = client.request(url) {+ method = HttpMethod.Head+ applyHeaders(headers)+ }+ return response.headers["Content-Length"]?.toLongOrNull()+ ?: response.headers["Content-Range"]?.substringAfterLast("/")?.toLongOrNull()+ }++ suspend inline fun <reified T> callJson(+ url: String,+ method: String = "GET",+ headers: Map<String, *> = emptyMap<String, Any>(),+ body: Any? = null+ ): T {+ return client.request(url) {+ this.method = HttpMethod.parse(method)+ applyHeaders(headers)+ body?.let { setBody(it) }+ }.body()+ }++ suspend inline fun <reified T> getJson(+ url: String,+ headers: Map<String, *> = emptyMap<String, Any>()+ ): T = callJson(url, "GET", headers)+}
maps/build.gradle.kts
diff --git a/maps/build.gradle.kts b/maps/build.gradle.ktsindex c1a3f8deb6..204b11e7ec 100644--- a/maps/build.gradle.kts+++ b/maps/build.gradle.kts@@ -20,7 +20,7 @@ dependencies { implementation(libs.maplibre.compose) implementation(libs.coil.compose) - implementKtor(libs)+ implementation(project(":library:network")) implementation(libs.flatgeobuf)
maps/src/main/java/com/vayunmathur/maps/util/Reviews.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/Reviews.kt b/maps/src/main/java/com/vayunmathur/maps/util/Reviews.ktindex 462197002b..408911f151 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/Reviews.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/Reviews.kt@@ -1,14 +1,5 @@ package com.vayunmathur.maps.util-import io.ktor.client.HttpClient-import io.ktor.client.call.body-import io.ktor.client.engine.cio.CIO-import io.ktor.client.plugins.contentnegotiation.ContentNegotiation-import io.ktor.client.request.post-import io.ktor.client.request.setBody-import io.ktor.http.ContentType-import io.ktor.http.contentType-import io.ktor.serialization.kotlinx.json.json-import kotlinx.serialization.json.Json+import com.vayunmathur.library.network.NetworkClient import kotlinx.serialization.Serializable @Serializable@@ -29,33 +20,28 @@ data class FullPlaceInfo(val id: String, val rating: Float, val userRatingCount: object Reviews { private const val BASE_URL = "https://api.vayunmathur.com" - private val client = HttpClient(CIO) { // Using CIO engine- install(ContentNegotiation) {- json(Json {- ignoreUnknownKeys = true- encodeDefaults = true- })- }- }- /** * Chained call: 1. Match OSM data to Google ID -> 2. Get Stars from ID */ suspend fun getRatingForOsmLocation(name: String, lat: Double, lon: Double): FullPlaceInfo? { return try { // Step 1: Get the Google Place ID from your server- val idResponse: PlaceIdResponse = client.post("$BASE_URL/maps/place_match") {- contentType(ContentType.Application.Json)- setBody(PlaceMatchRequest(name, lat, lon))- }.body()+ val idResponse: PlaceIdResponse = NetworkClient.callJson(+ url = "$BASE_URL/maps/place_match",+ method = "POST",+ headers = mapOf("Content-Type" to "application/json"),+ body = PlaceMatchRequest(name, lat, lon)+ ) val placeId = idResponse.id // Step 2: Get the Rating using that ID- val ratingResponse: PlaceRatingResponse = client.post("$BASE_URL/maps/place_rating") {- contentType(ContentType.Application.Json)- setBody(PlaceRatingRequest(placeId))- }.body()+ val ratingResponse: PlaceRatingResponse = NetworkClient.callJson(+ url = "$BASE_URL/maps/place_rating",+ method = "POST",+ headers = mapOf("Content-Type" to "application/json"),+ body = PlaceRatingRequest(placeId)+ ) FullPlaceInfo( id = placeId,@@ -67,4 +53,4 @@ object Reviews { null // Handle errors or 404s gracefully } }-}\ No newline at end of file+}
maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt b/maps/src/main/java/com/vayunmathur/maps/util/RouteService.ktindex 461099203b..af937b06f6 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt@@ -1,30 +1,13 @@ package com.vayunmathur.maps.util import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.R-import io.ktor.client.HttpClient-import io.ktor.client.call.body-import io.ktor.client.plugins.contentnegotiation.ContentNegotiation-import io.ktor.client.request.post-import io.ktor.client.request.setBody-import io.ktor.http.ContentType-import io.ktor.http.contentType-import io.ktor.serialization.kotlinx.json.json+import com.vayunmathur.library.network.NetworkClient import kotlinx.serialization.Serializable-import kotlinx.serialization.json.Json import org.maplibre.spatialk.geojson.Position import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds object RouteService {- private val client = HttpClient {- install(ContentNegotiation) {- json(Json {- ignoreUnknownKeys = true- encodeDefaults = true- })- }- }- private const val ROUTES_URL = "https://api.vayunmathur.com/maps/route" suspend fun computeRoute(@@ -45,14 +28,12 @@ object RouteService { ) return try {- val response = client.post(ROUTES_URL) {- contentType(ContentType.Application.Json)- setBody(request)- }-- // The server now returns the transformed structure directly.- // We deserialize into a helper DTO to handle 'Position' conversion.- val serverRoute = response.body<ServerRouteResponse>()+ val serverRoute: ServerRouteResponse = NetworkClient.callJson(+ url = ROUTES_URL,+ method = "POST",+ headers = mapOf("Content-Type" to "application/json"),+ body = request+ ) return Route( duration = Duration.parse(serverRoute.duration),@@ -188,4 +169,4 @@ object RouteService { override val duration: Duration = 0.seconds override val distanceMeters: Double = 0.0 }-}\ No newline at end of file+}
maps/src/main/java/com/vayunmathur/maps/util/Wikidata.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/Wikidata.kt b/maps/src/main/java/com/vayunmathur/maps/util/Wikidata.ktindex 12e59d0bfb..5b0ec22372 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/Wikidata.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/Wikidata.kt@@ -1,26 +1,12 @@ package com.vayunmathur.maps.util-import io.ktor.client.HttpClient-import io.ktor.client.call.body-import io.ktor.client.plugins.contentnegotiation.ContentNegotiation-import io.ktor.client.request.get-import io.ktor.serialization.kotlinx.json.json+import com.vayunmathur.library.network.NetworkClient import kotlinx.serialization.Serializable-import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.jsonPrimitive object Wikidata { suspend fun get(wikidata: String): Wikidata {- val client = HttpClient {- install(ContentNegotiation) {- json(Json{- ignoreUnknownKeys = true- })- }- }- val wikidata = client.get("https://www.wikidata.org/w/rest.php/wikibase/v1/entities/items/${wikidata}").body<Wikidata>()- client.close()- return wikidata+ return NetworkClient.getJson("https://www.wikidata.org/w/rest.php/wikibase/v1/entities/items/${wikidata}") } @Serializable@@ -45,4 +31,4 @@ object Wikidata { val url: String, ) }-}\ No newline at end of file+}
openassistant/build.gradle.kts
diff --git a/openassistant/build.gradle.kts b/openassistant/build.gradle.ktsindex 6eb91db288..784f4face0 100644--- a/openassistant/build.gradle.kts+++ b/openassistant/build.gradle.kts@@ -36,8 +36,5 @@ dependencies { // ai implementation(libs.litertlm.android) - // markdown- implementation(libs.compose.markdown)- implementation(project(":library:downloadservice")) }\ No newline at end of file
passwords/build.gradle.kts
diff --git a/passwords/build.gradle.kts b/passwords/build.gradle.ktsindex c7d67db546..264331602a 100644--- a/passwords/build.gradle.kts+++ b/passwords/build.gradle.kts@@ -14,7 +14,4 @@ dependencies { implementation(project(":library:biometric")) implementRoom(libs) implementation(libs.androidx.fragment.ktx)-- // CSV parsing library for Bitwarden CSV imports- implementation(libs.kotlin.csv.jvm) }\ No newline at end of file
passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.ktindex dcbbd1fa04..0c3fdc0423 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/SettingsPage.kt@@ -31,8 +31,6 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import com.vayunmathur.passwords.R import androidx.compose.ui.unit.dp-import com.github.doyaaaaaken.kotlincsv.client.CsvReader-import com.github.doyaaaaaken.kotlincsv.dsl.context.CsvReaderContext import com.vayunmathur.library.ui.IconNavigation import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.passwords.data.Password@@ -123,9 +121,33 @@ private suspend fun importBitwardenCsvFromUri(contentResolver: ContentResolver, null } ?: throw Exception("Unable to open selected file") - val csvReader = CsvReader(CsvReaderContext()) val rows = try {- csvReader.readAll(inputStream)+ val reader = inputStream.bufferedReader()+ val list = mutableListOf<List<String>>()+ var line = reader.readLine()+ while (line != null) {+ val row = mutableListOf<String>()+ var current = StringBuilder()+ var inQuotes = false+ var i = 0+ while (i < line.length) {+ val c = line[i]+ if (c == '\"') {+ if (inQuotes && i + 1 < line.length && line[i+1] == '\"') {+ current.append('\"')+ i+++ } else inQuotes = !inQuotes+ } else if (c == ',' && !inQuotes) {+ row.add(current.toString())+ current = StringBuilder()+ } else current.append(c)+ i+++ }+ row.add(current.toString())+ list.add(row)+ line = reader.readLine()+ }+ list } catch (e: Exception) { Log.e("SettingsPage", "Error reading CSV from input stream", e) emptyList<List<String>>()
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 2ac0a0cb38..ed8e32999e 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -25,6 +25,7 @@ dependencyResolutionManagement { rootProject.name = "apps" include(":library")+include(":library:network") include(":library:biometric") include(":library:downloadservice") include(":library:widgets")
youpipe/build.gradle.kts
diff --git a/youpipe/build.gradle.kts b/youpipe/build.gradle.ktsindex 0aee23848c..08cb21671c 100644--- a/youpipe/build.gradle.kts+++ b/youpipe/build.gradle.kts@@ -12,7 +12,6 @@ android { dependencies { implementation(libs.coil.compose) implementation(libs.newpipeextractor)- implementation(libs.okhttp) implementRoom(libs) @@ -23,5 +22,5 @@ dependencies { implementation(libs.androidx.work.runtime.ktx) - implementKtor(libs)+ implementation(project(":library:network")) }\ No newline at end of file
youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.ktindex f93505c4ec..22cc3097ee 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/DownloadWorker.kt@@ -1,6 +1,7 @@ package com.vayunmathur.youpipe.util import android.content.Context+import android.util.Log import androidx.work.CoroutineWorker import androidx.work.Data import androidx.work.ExistingWorkPolicy@@ -11,9 +12,10 @@ import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.youpipe.data.DownloadedVideo import com.vayunmathur.youpipe.data.SubscriptionDatabase import com.vayunmathur.youpipe.ui.VideoInfo+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.NetworkDataStream import java.io.File import java.io.RandomAccessFile-import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicLong import kotlin.time.Clock import kotlin.time.Instant@@ -21,13 +23,11 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.withContext-import okhttp3.OkHttpClient-import okhttp3.Request-import okio.buffer-import okio.sink class DownloadWorker(context: Context, params: WorkerParameters) :- CoroutineWorker(context, params) {+ CoroutineWorker(context, params) {++ private val client = NetworkClient override suspend fun doWork(): Result = coroutineScope { val videoID = inputData.getLong("videoID", -1L)@@ -35,15 +35,15 @@ class DownloadWorker(context: Context, params: WorkerParameters) : val audioUrl = inputData.getString("audioUrl") val videoInfo =- VideoInfo(- name = inputData.getString("name") ?: "",- videoID = videoID,- duration = inputData.getLong("duration", 0L),- views = inputData.getLong("views", 0L),- uploadDate = Instant.fromEpochSeconds(inputData.getLong("uploadDate", 0L)),- thumbnailURL = inputData.getString("thumbnailURL") ?: "",- author = inputData.getString("author") ?: ""- )+ VideoInfo(+ name = inputData.getString("name") ?: "",+ videoID = videoID,+ duration = inputData.getLong("duration", 0L),+ views = inputData.getLong("views", 0L),+ uploadDate = Instant.fromEpochSeconds(inputData.getLong("uploadDate", 0L)),+ thumbnailURL = inputData.getString("thumbnailURL") ?: "",+ author = inputData.getString("author") ?: ""+ ) val db = applicationContext.buildDatabase<SubscriptionDatabase>() val dir = File(applicationContext.getExternalFilesDir(null), "downloads")@@ -64,40 +64,40 @@ class DownloadWorker(context: Context, params: WorkerParameters) : var audioP = 0.0 val vJob =- async(Dispatchers.IO) {- downloadFileChunked(videoUrl, videoFile) { p ->- videoP = p- DownloadManager.updateProgress(- videoID,- (videoP * videoWeight) + (audioP * (1.0 - videoWeight))- )- }+ async(Dispatchers.IO) {+ downloadFileChunked(videoUrl, videoFile) { p ->+ videoP = p+ DownloadManager.updateProgress(+ videoID,+ (videoP * videoWeight) + (audioP * (1.0 - videoWeight))+ ) }+ } val aJob =- audioUrl?.let { url ->- async(Dispatchers.IO) {- downloadFileChunked(url, audioFile!!) { p ->- audioP = p- DownloadManager.updateProgress(- videoID,- (videoP * videoWeight) + (audioP * (1.0 - videoWeight))- )- }+ audioUrl?.let { url ->+ async(Dispatchers.IO) {+ downloadFileChunked(url, audioFile!!) { p ->+ audioP = p+ DownloadManager.updateProgress(+ videoID,+ (videoP * videoWeight) + (audioP * (1.0 - videoWeight))+ ) } }+ } vJob.await() aJob?.await() val download =- DownloadedVideo(- id = videoID,- videoItem = videoInfo,- filePath = videoFile.absolutePath,- audioPath = audioFile?.absolutePath,- timestamp = Clock.System.now()- )+ DownloadedVideo(+ id = videoID,+ videoItem = videoInfo,+ filePath = videoFile.absolutePath,+ audioPath = audioFile?.absolutePath,+ timestamp = Clock.System.now()+ ) db.downloadedVideoDao().upsert(download) Result.success()@@ -114,142 +114,116 @@ class DownloadWorker(context: Context, params: WorkerParameters) : } private suspend fun downloadFileChunked(url: String, file: File, onProgress: (Double) -> Unit) =- coroutineScope {- val request = Request.Builder().url(url).head().build()- val totalBytes =- client.newCall(request).execute().use { response ->- if (!response.isSuccessful) {- // If HEAD fails, try GET with a small range to get content length- val getRequest =- Request.Builder()- .url(url)- .header("Range", "bytes=0-0")- .build()- client.newCall(getRequest).execute().use { getResponse ->- if (!getResponse.isSuccessful) return@coroutineScope- val contentRange = getResponse.header("Content-Range")- contentRange?.substringAfterLast("/")?.toLongOrNull()- ?: getResponse.body.contentLength()- }- } else {- response.body.contentLength()- }- }+ coroutineScope {+ var totalBytes = client.getContentLength(url) ?: 0L - if (totalBytes <= 0) {- // Fallback to simple download if size unknown- downloadFileSimple(url, file, onProgress)- return@coroutineScope- }+ if (totalBytes <= 0) {+ totalBytes =+ client.getContentLength(url, headers = mapOf("Range" to "bytes=0-0")) ?: 0L+ } - val numChunks = 4- val chunkSize = totalBytes / numChunks- val downloadedBytes = AtomicLong(0)+ if (totalBytes <= 0) {+ // Fallback to simple download if size unknown+ downloadFileSimple(url, file, onProgress)+ return@coroutineScope+ } - // Pre-allocate file- withContext(Dispatchers.IO) {- RandomAccessFile(file, "rw").use { raf -> raf.setLength(totalBytes) }- }+ val numChunks = 4+ val chunkSize = totalBytes / numChunks+ val downloadedBytes = AtomicLong(0)++ // Pre-allocate file+ withContext(Dispatchers.IO) {+ RandomAccessFile(file, "rw").use { raf -> raf.setLength(totalBytes) }+ } - val jobs =- (0 until numChunks).map { i ->- val start = i * chunkSize- val end =- if (i == numChunks - 1) totalBytes - 1- else (i + 1) * chunkSize - 1-- async(Dispatchers.IO) {- val chunkRequest =- Request.Builder()- .url(url)- .addHeader("Range", "bytes=$start-$end")- .build()-- client.newCall(chunkRequest).execute().use { response ->- if (!response.isSuccessful) return@async-- val source = response.body.source()- RandomAccessFile(file, "rw").use { raf ->- raf.seek(start)- val buffer = ByteArray(8192)- var bytesRead: Int- while (true) {- if (isStopped) return@async- bytesRead = source.read(buffer)- if (bytesRead == -1) break- raf.write(buffer, 0, bytesRead)- val total =- downloadedBytes.addAndGet(bytesRead.toLong())- onProgress(total.toDouble() / totalBytes.toDouble())- }+ val jobs =+ (0 until numChunks).map { i ->+ val start = i * chunkSize+ val end =+ if (i == numChunks - 1) totalBytes - 1+ else (i + 1) * chunkSize - 1++ async(Dispatchers.IO) {+ try {+ client.stream(+ url,+ headers = mapOf("Range" to "bytes=$start-$end")+ ) { stream, _ ->+ if (stream == null) return@stream+ RandomAccessFile(file, "rw").use { raf ->+ raf.seek(start)+ val buffer = ByteArray(8192)+ while (!stream.isClosedForRead) {+ if (isStopped) return@stream+ val bytesRead = stream.read(buffer)+ if (bytesRead == -1) break+ raf.write(buffer, 0, bytesRead)+ val total = downloadedBytes.addAndGet(bytesRead.toLong())+ onProgress(total.toDouble() / totalBytes.toDouble()) } } }+ } catch (e: Exception) {+ Log.e("DownloadWorker", "Error downloading chunk $i", e) }-- jobs.forEach { it.await() }- }-- private fun downloadFileSimple(url: String, file: File, onProgress: (Double) -> Unit) {- val request = Request.Builder().url(url).build()- client.newCall(request).execute().use { response ->- if (!response.isSuccessful) return- val totalBytes = response.body.contentLength()- var downloadedBytes = 0L-- val source = response.body.source()- val sink = file.sink().buffer()-- val buffer = okio.Buffer()- while (true) {- if (isStopped) {- sink.close()- file.delete()- return+ } }- val read = source.read(buffer, 8192)- if (read == -1L) break - sink.write(buffer, read)- downloadedBytes += read- if (totalBytes > 0) {- onProgress(downloadedBytes.toDouble() / totalBytes.toDouble())+ jobs.forEach { it.await() }+ }++ private suspend fun downloadFileSimple(url: String, file: File, onProgress: (Double) -> Unit) {+ try {+ client.stream(url) { stream, response ->+ if (stream == null) return@stream+ val totalBytes = response.contentLength+ var downloadedBytes = 0L+ file.outputStream().use { output ->+ val buffer = ByteArray(8192)+ while (!stream.isClosedForRead) {+ if (isStopped) {+ file.delete()+ return@stream+ }+ val read = stream.read(buffer)+ if (read == -1) break+ output.write(buffer, 0, read)+ downloadedBytes += read+ if (totalBytes != null && totalBytes > 0) {+ onProgress(downloadedBytes.toDouble() / totalBytes.toDouble())+ }+ } } }- sink.flush()- sink.close()+ } catch (e: Exception) {+ Log.e("DownloadWorker", "Error in simple download", e) } } companion object {- private val client =- OkHttpClient.Builder()- .connectTimeout(30, TimeUnit.SECONDS)- .readTimeout(30, TimeUnit.SECONDS)- .build()- fun enqueue(context: Context, videoInfo: VideoInfo, videoUrl: String, audioUrl: String?) { val data =- Data.Builder()- .putLong("videoID", videoInfo.videoID)- .putString("name", videoInfo.name)- .putLong("duration", videoInfo.duration)- .putLong("views", videoInfo.views)- .putLong("uploadDate", videoInfo.uploadDate.epochSeconds)- .putString("thumbnailURL", videoInfo.thumbnailURL)- .putString("author", videoInfo.author)- .putString("videoUrl", videoUrl)- .putString("audioUrl", audioUrl)- .build()+ Data.Builder()+ .putLong("videoID", videoInfo.videoID)+ .putString("name", videoInfo.name)+ .putLong("duration", videoInfo.duration)+ .putLong("views", videoInfo.views)+ .putLong("uploadDate", videoInfo.uploadDate.epochSeconds)+ .putString("thumbnailURL", videoInfo.thumbnailURL)+ .putString("author", videoInfo.author)+ .putString("videoUrl", videoUrl)+ .putString("audioUrl", audioUrl)+ .build() val request = OneTimeWorkRequestBuilder<DownloadWorker>().setInputData(data).build() WorkManager.getInstance(context)- .enqueueUniqueWork(- "download_${videoInfo.videoID}",- ExistingWorkPolicy.KEEP,- request- )+ .enqueueUniqueWork(+ "download_${videoInfo.videoID}",+ ExistingWorkPolicy.KEEP,+ request+ ) } } }
youpipe/src/main/java/com/vayunmathur/youpipe/util/MyDownloader.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/util/MyDownloader.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/util/MyDownloader.ktindex 3cd7f67adf..2046725190 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/util/MyDownloader.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/util/MyDownloader.kt@@ -1,49 +1,29 @@ package com.vayunmathur.youpipe.util-import okhttp3.Headers-import okhttp3.OkHttpClient-import okhttp3.RequestBody.Companion.toRequestBody+import com.vayunmathur.library.network.NetworkClient+import kotlinx.coroutines.runBlocking import org.schabi.newpipe.extractor.downloader.Downloader import org.schabi.newpipe.extractor.downloader.Request import org.schabi.newpipe.extractor.downloader.Response-import kotlin.time.Duration.Companion.seconds class MyDownloader : Downloader() {- // Build the client with reasonable timeouts- private val client: OkHttpClient = OkHttpClient.Builder()- .connectTimeout(15.seconds)- .readTimeout(15.seconds)- .build()-- override fun execute(request: Request): Response {+ override fun execute(request: Request): Response = runBlocking { val url = request.url() val method = request.httpMethod() val body = request.dataToSend()- val headersBuilder = Headers.Builder()- for (entry in request.headers().entries) {- for (value in entry.value) {- headersBuilder.add(entry.key, value)- }- }- val headers = headersBuilder.build() - // Construct the OkHttp Request- val okHttpRequest = okhttp3.Request.Builder()- .url(url)- .method(method, body?.toRequestBody())- .headers(headers)- .build()+ val response = NetworkClient.performRequest(+ url = url,+ method = method,+ headers = request.headers(),+ body = body+ ) - client.newCall(okHttpRequest).execute().use { okHttpResponse ->- val responseCode = okHttpResponse.code- val responseMessage = okHttpResponse.message- val responseBody = okHttpResponse.body.string()- return Response(- responseCode,- responseMessage,- okHttpResponse.headers.toMultimap(),- responseBody,- url- )- }+ Response(+ response.status,+ response.statusMessage,+ response.headers,+ response.body,+ response.url+ ) }-}\ No newline at end of file+}