/
Api.kt
82 lines (71 loc) · 3.07 KB
/
Api.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.fireblocks.sdkdemo.bl.core.server
import androidx.annotation.Keep
import androidx.annotation.VisibleForTesting
import com.fireblocks.sdkdemo.bl.core.environment.environment
import com.fireblocks.sdkdemo.bl.core.extensions.isDebugLog
import com.fireblocks.sdkdemo.log.HttpLoggingInterceptor
import com.fireblocks.sdkdemo.log.TimberLogTree
import okhttp3.ConnectionPool
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.concurrent.TimeUnit
/**
* Created by Fireblocks Ltd. on 18/09/2023
*/
object Api {
@VisibleForTesting
@Keep
var test_Interceptor: Interceptor? = null
private var connectionPool = ConnectionPool(4, 15, TimeUnit.SECONDS)
private val services = hashMapOf<String, MobileBackendService>()
fun with(headerProvider: HeaderProvider): MobileBackendService {
val host = headerProvider.environment().host()
return getService(headerProvider, host)
}
fun with(headerProvider: HeaderProvider, host: String): MobileBackendService {
return getService(headerProvider, host)
}
private fun getService(headerProvider: HeaderProvider, host: String): MobileBackendService {
if (host.isEmpty()) {
throw RuntimeException("Missing Host url")
}
val deviceId = headerProvider.deviceId()
var mobileBackendService = services[deviceId]
if (mobileBackendService != null) {
return mobileBackendService
}
val clientBuilder = OkHttpClient.Builder() //
clientBuilder.apply {
connectTimeout(30, TimeUnit.SECONDS) //
readTimeout(30, TimeUnit.SECONDS) //
// retryOnConnectionFailure(true) //
// addInterceptor(TimeoutInterceptor())
// addInterceptor(HeaderInterceptor(headerProvider)) //
if (test_Interceptor == null) {
if (isDebugLog()) {
val loggingInterceptor = HttpLoggingInterceptor(headerProvider.deviceId(), TimberLogTree())
addInterceptor(loggingInterceptor) //
addInterceptor(ResponseInterceptor())
}
} else {
addNetworkInterceptor(test_Interceptor!!)
addInterceptor(test_Interceptor!!)
}
}
clientBuilder.connectionPool(connectionPool)
val sSLSocketFactoryTcpNoDelay = SSLSocketFactoryTcpNoDelay()
clientBuilder.sslSocketFactory(sSLSocketFactoryTcpNoDelay.sslSocketFactory, sSLSocketFactoryTcpNoDelay.trustManager)
val client = clientBuilder.build()
val retrofit = Retrofit.Builder().baseUrl(host) //
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
mobileBackendService = retrofit.create(MobileBackendService::class.java)
services[deviceId] = mobileBackendService
return mobileBackendService
}
}