Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: When ApiError the context field throws an exception #193

Merged
merged 4 commits into from
Jun 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 62 additions & 46 deletions src/main/java/com/infomaniak/lib/core/api/ApiController.kt
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ import com.infomaniak.lib.core.networking.HttpUtils
import com.infomaniak.lib.core.utils.CustomDateTypeAdapter
import com.infomaniak.lib.core.utils.isNetworkException
import com.infomaniak.lib.login.ApiToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
Expand Down Expand Up @@ -110,41 +108,50 @@ object ApiController {

if (InfomaniakCore.accessType == null) formBuilder.addFormDataPart("duration", "infinite")

return withContext(Dispatchers.IO) {
val request = Request.Builder()
.url("${LOGIN_ENDPOINT_URL}token")
.post(formBuilder.build())
.build()
val request = Request.Builder()
.url("${LOGIN_ENDPOINT_URL}token")
.post(formBuilder.build())
.build()

val response = HttpClient.okHttpClientNoTokenInterceptor.newCall(request).execute()
response.use {
val bodyResponse = it.body?.string()
val apiToken = HttpClient.okHttpClientNoTokenInterceptor.newCall(request).execute().use {
val bodyResponse = it.body?.string()

when {
it.isSuccessful -> {
val apiToken = gson.fromJson(bodyResponse, ApiToken::class.java)
apiToken.expiresAt = System.currentTimeMillis() + (apiToken.expiresIn * 1_000)
tokenInterceptorListener.onRefreshTokenSuccess(apiToken)
return@withContext apiToken
}
else -> {
var invalidGrant = false
runCatching {
invalidGrant = JsonParser.parseString(bodyResponse)
.asJsonObject
.getAsJsonPrimitive("error")
.asString == "invalid_grant"
}

if (invalidGrant) {
tokenInterceptorListener.onRefreshTokenError()
throw RefreshTokenException()
}
throw Exception(bodyResponse)
}
when {
it.isSuccessful -> {
getApiToken(bodyResponse, tokenInterceptorListener)
}
else -> {
handleInvalidGrant(bodyResponse, tokenInterceptorListener)
throw Exception(bodyResponse)
}
}
}

return apiToken
}

private suspend fun handleInvalidGrant(bodyResponse: String?, tokenInterceptorListener: TokenInterceptorListener) {
val invalidGrant = runCatching {
JsonParser.parseString(bodyResponse)
.asJsonObject
.getAsJsonPrimitive("error")
.asString == "invalid_grant"
}.getOrDefault(false)

if (invalidGrant) {
tokenInterceptorListener.onRefreshTokenError()
throw RefreshTokenException()
}
}

private suspend fun getApiToken(
bodyResponse: String?,
tokenInterceptorListener: TokenInterceptorListener,
): ApiToken {
val apiToken = gson.fromJson(bodyResponse, ApiToken::class.java)
apiToken.expiresAt = System.currentTimeMillis() + (apiToken.expiresIn * 1_000L)
tokenInterceptorListener.onRefreshTokenSuccess(apiToken)
return apiToken
}

class RefreshTokenException : Exception()
Expand Down Expand Up @@ -178,23 +185,13 @@ object ApiController {
return when {
response.code >= 500 -> {
createErrorResponse(
apiError = ApiError(context = bodyResponse.bodyResponseToJson(), exception = ServerErrorException()),
apiError = createApiError(useKotlinxSerialization, bodyResponse, ServerErrorException()),
translatedError = R.string.serverError,
buildErrorResult = buildErrorResult,
)
}
bodyResponse.isBlank() -> createInternetErrorResponse(buildErrorResult = buildErrorResult)
else -> {
val decodedApiResponse = if (useKotlinxSerialization) {
json.decodeFromString<T>(bodyResponse)
} else {
gson.fromJson(bodyResponse, object : TypeToken<T>() {}.type)
}
decodedApiResponse.apply {
val apiResponse = this as? ApiResponse<*>
if (apiResponse?.result == ERROR) apiResponse.translatedError = R.string.anErrorHasOccurred
}
}
else -> createApiResponse<T>(useKotlinxSerialization, bodyResponse)
}
}
} catch (refreshTokenException: RefreshTokenException) {
Expand All @@ -208,15 +205,28 @@ object ApiController {
} else {
createErrorResponse(
translatedError = R.string.anErrorHasOccurred,
apiError = ApiError(context = bodyResponse.bodyResponseToJson(), exception = exception),
apiError = createApiError(useKotlinxSerialization, bodyResponse, exception = exception),
buildErrorResult = buildErrorResult,
)
}

}
}

fun String.bodyResponseToJson(): JsonObject {
inline fun <reified T> createApiResponse(useKotlinxSerialization: Boolean, bodyResponse: String): T {
val apiResponse = when {
useKotlinxSerialization -> json.decodeFromString<T>(bodyResponse)
else -> gson.fromJson(bodyResponse, object : TypeToken<T>() {}.type)
}

if (apiResponse is ApiResponse<*> && apiResponse.result == ERROR) {
apiResponse.translatedError = R.string.anErrorHasOccurred
}

return apiResponse
}

private fun String.bodyResponseToJson(): JsonObject {
return JsonObject(mapOf("bodyResponse" to JsonPrimitive(this)))
}

Expand All @@ -229,6 +239,12 @@ object ApiController {
buildErrorResult = buildErrorResult,
)

fun createApiError(useKotlinxSerialization: Boolean, bodyResponse: String, exception: Exception) = ApiError(
contextJson = if (useKotlinxSerialization) bodyResponse.bodyResponseToJson() else null,
contextGson = if (useKotlinxSerialization) JsonParser.parseString(bodyResponse).asJsonObject else null,
exception = exception
)

inline fun <reified T> createErrorResponse(
@StringRes translatedError: Int,
apiError: ApiError? = null,
Expand Down
9 changes: 8 additions & 1 deletion src/main/java/com/infomaniak/lib/core/models/ApiError.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,23 @@
*/
package com.infomaniak.lib.core.models

import com.google.gson.annotations.SerializedName
import kotlinx.serialization.Contextual
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
import com.google.gson.JsonObject as GsonObject

@Serializable
class ApiError(
val code: String? = null,
val description: String? = null,
@Contextual
val context: JsonObject? = null,
@SerializedName("context")
var contextGson: GsonObject? = null,
@Contextual
@SerialName("context")
var contextJson: JsonObject? = null,
val errors: Array<ApiError>? = null,
@Contextual
val exception: Exception? = null
Expand Down
Loading