Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @file:Suppress("EXPERIMENTAL_API_USAGE_FUTURE_ERROR")
- package bz.lement.pro.di
- import android.content.Context
- import android.util.Log
- import bz.lement.pro.data.http.*
- import io.ktor.client.*
- import io.ktor.client.engine.okhttp.*
- import io.ktor.client.features.*
- import io.ktor.client.features.cookies.*
- import io.ktor.client.features.json.*
- import io.ktor.client.features.logging.*
- import io.ktor.client.request.*
- import io.ktor.http.*
- import io.ktor.http.Cookie
- import okhttp3.*
- import org.koin.android.ext.koin.androidContext
- import org.koin.dsl.module
- import java.io.File
- import java.util.*
- private const val TIME_OUT = 60_000
- val networkModule = module {
- val connectionSpec = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).apply {
- tlsVersions(TlsVersion.TLS_1_2)
- cipherSuites(
- CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
- CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
- CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
- )
- }.build()
- fun initKTorClient(
- context: Context,
- connectivityInterceptor: ConnectivityInterceptor,
- errorCodeInterceptor: ErrorCodeInterceptor
- ) = HttpClient(OkHttp) {
- val cacheSize = (10 * 1024 * 1024).toLong()
- val httpCacheDirectory = File(context.cacheDir, "offlineCache")
- val httpCache = Cache(httpCacheDirectory, cacheSize)
- var cookieAuth: String? = null
- install(JsonFeature) {
- // serializer = KotlinxSerializer(
- // kotlinx.serialization.json.Json {
- // prettyPrint = true
- // isLenient = true
- // ignoreUnknownKeys = true
- // }
- // )
- serializer = GsonSerializer() {
- setPrettyPrinting()
- disableHtmlEscaping()
- }
- engine {
- config {
- followRedirects(true)
- cache(httpCache)
- connectionSpecs(Collections.singletonList(connectionSpec))
- }
- addInterceptor(offlineCacheInterceptor(context))
- addInterceptor(connectivityInterceptor)
- addInterceptor(errorCodeInterceptor)
- addNetworkInterceptor(cacheInterceptor())
- clientCacheSize = (10 * 1024 * 1024)
- }
- }
- install(Logging) {
- logger = object : Logger {
- override fun log(message: String) {
- Log.v("KTor", "Logger Ktor => $message")
- }
- }
- level = LogLevel.ALL
- }
- install(DefaultRequest) {
- headers {
- append(HttpHeaders.Accept, "application/json")
- }
- }
- install(HttpCookies) {
- storage = AcceptAllCookiesStorage()
- storage = ConstantCookiesStorage(
- Cookie("set-cookie", cookieAuth ?: "")
- )
- }
- HttpResponseValidator {
- validateResponse { response ->
- cookieAuth = response.headers["set-cookie"]
- Log.v("HTTPClient ->", "set-cookie auth => $cookieAuth}")
- }
- }
- }
- factory { ConnectivityInterceptor(context = androidContext()) }
- factory { ErrorCodeInterceptor() }
- single {
- initKTorClient(
- context = androidContext(),
- connectivityInterceptor = get(),
- errorCodeInterceptor = get()
- )
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement