1 // Copyright 2015-present 650 Industries. All rights reserved. 2 package host.exp.exponent.network 3 4 import android.content.Context 5 import android.net.ConnectivityManager 6 import host.exp.exponent.storage.ExponentSharedPreferences 7 import host.exp.expoview.ExpoViewBuildConfig 8 import okhttp3.Cache 9 import okhttp3.OkHttpClient 10 import java.io.File 11 import java.io.IOException 12 import java.util.concurrent.TimeUnit 13 import javax.inject.Singleton 14 15 @Singleton 16 class ExponentNetwork constructor( 17 contextArg: Context, 18 val exponentSharedPreferences: ExponentSharedPreferences 19 ) { 20 val context: Context = contextArg.applicationContext 21 val client = ExponentHttpClient( 22 context, 23 object : OkHttpClientFactory { getNewClientnull24 override fun getNewClient(): OkHttpClient = createHttpClientBuilder().build() 25 } 26 ) 27 val longTimeoutClient = ExponentHttpClient( 28 context, 29 object : OkHttpClientFactory { 30 override fun getNewClient(): OkHttpClient = createHttpClientBuilder() 31 .readTimeout(2, TimeUnit.MINUTES) 32 .build() 33 } 34 ) 35 36 // Warning: this doesn't WRITE to the cache either. Don't use this to populate the cache in the background. 37 val noCacheClient: OkHttpClient = OkHttpClient.Builder().build() 38 39 interface OkHttpClientFactory { getNewClientnull40 fun getNewClient(): OkHttpClient 41 } 42 43 private fun createHttpClientBuilder(): OkHttpClient.Builder { 44 val clientBuilder = OkHttpClient.Builder() 45 .cache(cache) 46 if (ExpoViewBuildConfig.DEBUG) { 47 // FIXME: 8/9/17 48 // clientBuilder.addNetworkInterceptor(new StethoInterceptor()); 49 } 50 return clientBuilder 51 } 52 53 val cache: Cache 54 get() { 55 val cacheSize = 50 * 1024 * 1024 // 50 MiB 56 val directory = File(context.cacheDir, CACHE_DIR) 57 return Cache(directory, cacheSize.toLong()) 58 } 59 60 companion object { 61 private val TAG = ExponentNetwork::class.java.simpleName 62 63 const val IGNORE_INTERCEPTORS_HEADER = "exponentignoreinterceptors" 64 65 private const val CACHE_DIR = "http-cache" 66 private const val LEGACY_CACHE_DIR = "okhttp" 67 68 // This fixes OkHttp bug where if you don't read a response, it'll never cache that request in the future 69 @Throws(IOException::class) flushResponsenull70 fun flushResponse(response: ExpoResponse) { 71 response.body().bytes() 72 } 73 isNetworkAvailablenull74 fun isNetworkAvailable(context: Context): Boolean { 75 val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager 76 val activeNetworkInfo = connectivityManager.activeNetworkInfo 77 return activeNetworkInfo != null && activeNetworkInfo.isConnected 78 } 79 } 80 } 81