2018-10-04 13:19:03 +00:00
|
|
|
package im.vector.matrix.android.internal.network
|
2018-10-03 15:56:33 +00:00
|
|
|
|
2018-11-06 15:35:06 +00:00
|
|
|
import arrow.core.Try
|
|
|
|
import arrow.core.failure
|
|
|
|
import arrow.core.recoverWith
|
|
|
|
import arrow.effects.IO
|
|
|
|
import arrow.effects.fix
|
|
|
|
import arrow.effects.instances.io.async.async
|
|
|
|
import arrow.integrations.retrofit.adapter.runAsync
|
2018-10-03 15:56:33 +00:00
|
|
|
import com.squareup.moshi.Moshi
|
2018-10-04 13:19:03 +00:00
|
|
|
import im.vector.matrix.android.api.failure.Failure
|
|
|
|
import im.vector.matrix.android.api.failure.MatrixError
|
2018-10-13 09:18:49 +00:00
|
|
|
import im.vector.matrix.android.internal.di.MoshiProvider
|
2018-10-03 15:56:33 +00:00
|
|
|
import okhttp3.ResponseBody
|
2018-11-06 15:35:06 +00:00
|
|
|
import retrofit2.Call
|
2018-10-03 15:56:33 +00:00
|
|
|
import java.io.IOException
|
|
|
|
|
2018-11-08 10:04:40 +00:00
|
|
|
internal inline fun <DATA> executeRequest(block: Request<DATA>.() -> Unit) = Request<DATA>().apply(block).execute()
|
2018-10-03 15:56:33 +00:00
|
|
|
|
2018-11-08 10:04:40 +00:00
|
|
|
internal class Request<DATA> {
|
2018-10-03 15:56:33 +00:00
|
|
|
|
2018-11-08 12:56:07 +00:00
|
|
|
private val moshi: Moshi = MoshiProvider.providesMoshi()
|
2018-11-06 15:35:06 +00:00
|
|
|
lateinit var apiCall: Call<DATA>
|
2018-10-10 17:46:43 +00:00
|
|
|
|
2018-11-06 15:35:06 +00:00
|
|
|
fun execute(): Try<DATA> {
|
|
|
|
return Try {
|
|
|
|
val response = apiCall.runAsync(IO.async()).fix().unsafeRunSync()
|
2018-10-03 15:56:33 +00:00
|
|
|
if (response.isSuccessful) {
|
2018-11-06 15:35:06 +00:00
|
|
|
response.body() ?: throw IllegalStateException("The request returned a null body")
|
2018-10-03 15:56:33 +00:00
|
|
|
} else {
|
2018-11-06 15:35:06 +00:00
|
|
|
throw manageFailure(response.errorBody())
|
2018-10-03 15:56:33 +00:00
|
|
|
}
|
2018-11-06 15:35:06 +00:00
|
|
|
}.recoverWith {
|
|
|
|
when (it) {
|
|
|
|
is IOException -> Failure.NetworkConnection(it)
|
|
|
|
is Failure.ServerError -> it
|
|
|
|
else -> Failure.Unknown(it)
|
|
|
|
}.failure()
|
2018-10-03 15:56:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-06 15:35:06 +00:00
|
|
|
private fun manageFailure(errorBody: ResponseBody?): Throwable {
|
|
|
|
val matrixError = errorBody?.let {
|
|
|
|
val matrixErrorAdapter = moshi.adapter(MatrixError::class.java)
|
|
|
|
matrixErrorAdapter.fromJson(errorBody.source())
|
|
|
|
} ?: return RuntimeException("Matrix error should not be null")
|
|
|
|
return Failure.ServerError(matrixError)
|
2018-10-03 15:56:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|