diff --git a/dependencies.gradle b/dependencies.gradle index fedd3035..1b42169f 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -51,6 +51,8 @@ ext.versions = [ ] ext.libs = [ + android: "org.robolectric:android-all:10-robolectric-5803371", + appCompat: "androidx.appcompat:appcompat:$versions.appCompat", material: "com.google.android.material:material:$versions.material", multiDex: "androidx.multidex:multidex:$versions.multiDex", diff --git a/scarlet-websocket-okhttp/build.gradle b/scarlet-websocket-okhttp/build.gradle index e8ed314c..1704c09b 100644 --- a/scarlet-websocket-okhttp/build.gradle +++ b/scarlet-websocket-okhttp/build.gradle @@ -9,6 +9,7 @@ dependencies { implementation project(':scarlet-core-internal') implementation libs.rxJava implementation libs.kotlin.stdlib + compileOnly libs.android testImplementation project(':scarlet') testImplementation project(':scarlet-websocket-mockwebserver') diff --git a/scarlet-websocket-okhttp/src/main/java/com/tinder/scarlet/websocket/okhttp/OkHttpClientUtils.kt b/scarlet-websocket-okhttp/src/main/java/com/tinder/scarlet/websocket/okhttp/OkHttpClientUtils.kt index c28d7c8a..a7ce4d87 100644 --- a/scarlet-websocket-okhttp/src/main/java/com/tinder/scarlet/websocket/okhttp/OkHttpClientUtils.kt +++ b/scarlet-websocket-okhttp/src/main/java/com/tinder/scarlet/websocket/okhttp/OkHttpClientUtils.kt @@ -6,15 +6,34 @@ package com.tinder.scarlet.websocket.okhttp +import android.os.Build +import android.security.NetworkSecurityPolicy import com.tinder.scarlet.WebSocket import com.tinder.scarlet.websocket.okhttp.request.RequestFactory import com.tinder.scarlet.websocket.okhttp.request.StaticUrlRequestFactory +import okhttp3.HttpUrl import okhttp3.OkHttpClient +import java.net.UnknownServiceException fun OkHttpClient.newWebSocketFactory(requestFactory: RequestFactory): WebSocket.Factory { return OkHttpWebSocket.Factory(OkHttpClientWebSocketConnectionEstablisher(this, requestFactory)) } fun OkHttpClient.newWebSocketFactory(url: String): WebSocket.Factory { + if (url.startsWith("ws:", ignoreCase = true)) { + try { + if ((Build.VERSION.SDK_INT > 23 && + !NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted( + HttpUrl.parse("http:${url.substring(3)}")?.host())) || + (Build.VERSION.SDK_INT == 23 && + !NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted)) { + throw UnknownServiceException( + "CLEARTEXT communication to $url not permitted by network security policy") + } + } catch (_: ClassNotFoundException) { + // Not running on Android + } + } + return newWebSocketFactory(StaticUrlRequestFactory(url)) }