Coverage Summary for Class: GatewayManager (cloud.mindbox.mobile_sdk.managers)
| Class |
Method, %
|
Branch, %
|
Line, %
|
Instruction, %
|
| GatewayManager |
75%
(27/36)
|
82%
(82/100)
|
75.8%
(169/223)
|
74.6%
(879/1178)
|
| GatewayManager$1 |
0%
(0/1)
|
|
0%
(0/1)
|
0%
(0/3)
|
| GatewayManager$checkCustomerSegmentations$2$1 |
100%
(1/1)
|
|
100%
(1/1)
|
100%
(3/3)
|
| GatewayManager$checkCustomerSegmentations$2$request$1 |
0%
(0/1)
|
|
0%
(0/2)
|
0%
(0/16)
|
| GatewayManager$checkCustomerSegmentations$2$request$1$onResponse$$inlined$resumeFromJson$1 |
0%
(0/1)
|
|
| GatewayManager$checkCustomerSegmentations$2$request$1$onResponse$$inlined$resumeFromJson$1$1 |
0%
(0/1)
|
|
| GatewayManager$checkCustomerSegmentations$2$request$2 |
0%
(0/1)
|
|
0%
(0/1)
|
0%
(0/15)
|
| GatewayManager$checkGeoTargeting$2$1 |
100%
(1/1)
|
|
100%
(1/1)
|
100%
(3/3)
|
| GatewayManager$checkGeoTargeting$2$request$1 |
0%
(0/1)
|
|
0%
(0/2)
|
0%
(0/16)
|
| GatewayManager$checkGeoTargeting$2$request$1$onResponse$$inlined$resumeFromJson$1 |
0%
(0/1)
|
|
| GatewayManager$checkGeoTargeting$2$request$1$onResponse$$inlined$resumeFromJson$1$1 |
0%
(0/1)
|
|
| GatewayManager$checkGeoTargeting$2$request$2 |
0%
(0/1)
|
|
0%
(0/1)
|
0%
(0/15)
|
| GatewayManager$checkProductSegmentation$2$1 |
0%
(0/1)
|
|
0%
(0/2)
|
0%
(0/15)
|
| GatewayManager$checkProductSegmentation$2$1$onResponse$$inlined$resumeFromJson$1 |
0%
(0/1)
|
|
| GatewayManager$checkProductSegmentation$2$1$onResponse$$inlined$resumeFromJson$1$1 |
0%
(0/1)
|
|
| GatewayManager$checkProductSegmentation$2$2 |
0%
(0/1)
|
|
0%
(0/1)
|
0%
(0/14)
|
| GatewayManager$Companion |
|
| GatewayManager$convertJsonToBody$2 |
100%
(1/1)
|
|
100%
(1/1)
|
100%
(13/13)
|
| GatewayManager$fetchMobileConfig$2$1 |
0%
(0/1)
|
|
0%
(0/1)
|
0%
(0/8)
|
| GatewayManager$fetchMobileConfig$2$2 |
0%
(0/1)
|
|
0%
(0/1)
|
0%
(0/11)
|
| GatewayManager$fetchWebViewContent$2$1 |
100%
(1/1)
|
|
100%
(1/1)
|
100%
(3/3)
|
| GatewayManager$fetchWebViewContent$2$request$1 |
100%
(1/1)
|
|
100%
(1/1)
|
100%
(8/8)
|
| GatewayManager$fetchWebViewContent$2$request$2 |
100%
(1/1)
|
|
100%
(1/1)
|
100%
(12/12)
|
| GatewayManager$gatewayScope$2 |
100%
(1/1)
|
|
100%
(1/1)
|
100%
(14/14)
|
| GatewayManager$gson$2 |
100%
(1/1)
|
|
100%
(1/1)
|
100%
(3/3)
|
| GatewayManager$handleAsyncError$1 |
100%
(1/1)
|
|
100%
(2/2)
|
100%
(11/11)
|
| GatewayManager$handleAsyncError$2 |
100%
(1/1)
|
100%
(4/4)
|
100%
(6/6)
|
100%
(29/29)
|
| GatewayManager$handleError$1 |
100%
(1/1)
|
66.7%
(10/15)
|
78.9%
(30/38)
|
82%
(159/194)
|
| GatewayManager$handleSuccessResponse$1 |
0%
(0/1)
|
0%
(0/4)
|
0%
(0/6)
|
0%
(0/76)
|
| GatewayManager$resumeFromJson$1 |
0%
(0/1)
|
|
0%
(0/1)
|
0%
(0/9)
|
| GatewayManager$resumeFromJson$1$invoke$$inlined$fromJsonTyped$1 |
0%
(0/1)
|
|
| GatewayManager$sendAsyncEvent$1 |
100%
(1/1)
|
|
100%
(1/1)
|
100%
(5/5)
|
| GatewayManager$sendAsyncEvent$2 |
100%
(1/1)
|
|
100%
(1/1)
|
100%
(5/5)
|
| GatewayManager$sendAsyncEvent$3 |
100%
(1/1)
|
100%
(2/2)
|
100%
(3/3)
|
100%
(15/15)
|
| GatewayManager$sendAsyncEvent$outgoing$1 |
100%
(1/1)
|
|
100%
(1/1)
|
100%
(7/7)
|
| GatewayManager$sendAsyncEvent$report$1 |
100%
(1/1)
|
100%
(2/2)
|
100%
(2/2)
|
100%
(16/16)
|
| GatewayManager$sendEvent$1 |
0%
(0/1)
|
|
0%
(0/1)
|
0%
(0/11)
|
| GatewayManager$sendEvent$2 |
100%
(1/1)
|
|
100%
(1/1)
|
100%
(9/9)
|
| Total |
61.1%
(44/72)
|
78.7%
(100/127)
|
73.2%
(224/306)
|
68.7%
(1194/1737)
|
package cloud.mindbox.mobile_sdk.managers
import android.util.Log
import androidx.annotation.VisibleForTesting
import cloud.mindbox.mobile_sdk.SdkValidation
import cloud.mindbox.mobile_sdk.di.MindboxDI
import cloud.mindbox.mobile_sdk.fromJsonTyped
import cloud.mindbox.mobile_sdk.inapp.data.dto.GeoTargetingDto
import cloud.mindbox.mobile_sdk.inapp.domain.models.*
import cloud.mindbox.mobile_sdk.logger.MindboxLoggerImpl
import cloud.mindbox.mobile_sdk.logger.mindboxLogE
import cloud.mindbox.mobile_sdk.logger.mindboxLogI
import cloud.mindbox.mobile_sdk.logger.mindboxLogW
import cloud.mindbox.mobile_sdk.models.*
import cloud.mindbox.mobile_sdk.models.operation.OperationResponseBaseInternal
import cloud.mindbox.mobile_sdk.models.operation.request.LogResponseDto
import cloud.mindbox.mobile_sdk.models.operation.request.SegmentationCheckRequest
import cloud.mindbox.mobile_sdk.models.operation.response.SegmentationCheckResponse
import cloud.mindbox.mobile_sdk.network.MindboxServiceGenerator
import cloud.mindbox.mobile_sdk.network.WebViewContentRequest
import cloud.mindbox.mobile_sdk.repository.MindboxPreferences
import cloud.mindbox.mobile_sdk.toUrlQueryString
import cloud.mindbox.mobile_sdk.utils.loggingRunCatching
import com.android.volley.DefaultRetryPolicy
import com.android.volley.DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
import com.android.volley.ParseError
import com.android.volley.Request
import com.android.volley.VolleyError
import com.google.gson.Gson
import kotlinx.coroutines.*
import org.json.JSONException
import org.json.JSONObject
import java.util.Collections
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
internal class GatewayManager(
private val mindboxServiceGenerator: MindboxServiceGenerator,
private val trackingIdsResolver: () -> TrackingIdsResolver = { MindboxDI.appModule.trackingIdsResolver },
) {
companion object {
private const val TIMEOUT_DELAY = 60000
private const val TRACKING_HOST_TIMEOUT_DELAY = 10000
private const val MAX_RETRIES = 0
private const val MONITORING_DELAY = 5000
private const val HTTP_TOO_MANY_REQUESTS = 429
private val HTTP_SERVER_ERRORS = 500..599
private const val OPERATION_MOBILE_SDK_LOGS = "MobileSdk.Logs"
private const val OPERATION_CHECK_PRODUCT_SEGMENTS = "Tracker.CheckProductSegments"
private const val OPERATION_CHECK_CUSTOMER_SEGMENTS = "Tracker.CheckCustomerSegments"
}
private val gson by lazy { Gson() }
private val gatewayScope by lazy { CoroutineScope(SupervisorJob() + Dispatchers.Main + Job()) }
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun getCustomerSegmentationsUrl(configuration: Configuration): String {
return buildEventUrl(
configuration = configuration,
deviceUuid = MindboxPreferences.deviceUuid,
shouldCountOffset = false,
event = Event(
eventType = EventType.SyncOperation(OPERATION_CHECK_CUSTOMER_SEGMENTS)
)
)
}
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun getProductSegmentationUrl(configuration: Configuration): String {
return buildEventUrl(
configuration = configuration,
deviceUuid = MindboxPreferences.deviceUuid,
shouldCountOffset = false,
event = Event(
eventType = EventType.SyncOperation(OPERATION_CHECK_PRODUCT_SEGMENTS)
)
)
}
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun getLogsUrl(configuration: Configuration): String {
return buildEventUrl(
configuration = configuration,
deviceUuid = MindboxPreferences.deviceUuid,
shouldCountOffset = false,
event = Event(
eventType = EventType.AsyncOperation(OPERATION_MOBILE_SDK_LOGS)
)
)
}
private fun getConfigUrl(configuration: Configuration): String {
return "${SdkValidation.toBaseUrl(configuration.domain)}/mobile/byendpoint/${configuration.endpointId}.json"
}
/**
* Resolves the host to use for operations endpoints using the priority:
* 1. operationsDomainFromConfig — settings.baseAddresses.operations from the remote mobile config
* 2. operationsDomain from Mindbox.init configuration
* 3. domain from Mindbox.init configuration (fallback, preserves backward compatibility)
*/
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun resolveOperationsDomain(
configuration: Configuration,
operationsDomainFromConfig: String?,
): String = anonymizer(configuration, operationsDomainFromConfig) ?: configuration.domain
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun resolveTrackingHost(
configuration: Configuration,
operationsDomainFromConfig: String? = MindboxPreferences.operationsDomainFromConfig,
): String? =
if (anonymizer(configuration, operationsDomainFromConfig) != null) {
null
} else {
SdkValidation.deriveTrackingHost(configuration.domain)
}
private fun anonymizer(configuration: Configuration, operationsDomainFromConfig: String?): String? =
operationsDomainFromConfig?.takeIf { it.isNotBlank() }
?: configuration.operationsDomain?.takeIf { it.isNotBlank() }
private fun buildEventUrl(
configuration: Configuration,
deviceUuid: String,
shouldCountOffset: Boolean,
event: Event,
): String {
val urlQueries: LinkedHashMap<String, String> = linkedMapOf(
UrlQuery.DEVICE_UUID.value to deviceUuid,
)
when (event.eventType) {
is EventType.AppInstalled,
is EventType.AppInstalledWithoutCustomer,
is EventType.AppInfoUpdated,
is EventType.AppKeepalive,
is EventType.AppTrackingIdsUpdated,
is EventType.AppTrackingKeepalive,
is EventType.PushClicked,
is EventType.AsyncOperation,
-> {
urlQueries[UrlQuery.ENDPOINT_ID.value] = configuration.endpointId
urlQueries[UrlQuery.OPERATION.value] = event.eventType.operation
urlQueries[UrlQuery.TRANSACTION_ID.value] = event.transactionId
urlQueries[UrlQuery.DATE_TIME_OFFSET.value] =
getTimeOffset(event.enqueueTimestamp, shouldCountOffset)
}
is EventType.TrackVisit -> {
urlQueries[UrlQuery.TRANSACTION_ID.value] = event.transactionId
urlQueries[UrlQuery.DATE_TIME_OFFSET.value] =
getTimeOffset(event.enqueueTimestamp, shouldCountOffset)
}
is EventType.SyncOperation -> {
urlQueries[UrlQuery.ENDPOINT_ID.value] = configuration.endpointId
urlQueries[UrlQuery.OPERATION.value] = event.eventType.operation
}
}
val baseUrl = if (event.eventType is TrackingHostEvent) {
val trackingHost = checkNotNull(resolveTrackingHost(configuration)) { "No tracking host for the tracking event #${event.uid}" }
SdkValidation.toTrackingBaseUrl(trackingHost)
} else {
SdkValidation.toBaseUrl(resolveOperationsDomain(configuration, MindboxPreferences.operationsDomainFromConfig))
}
return "$baseUrl${event.eventType.endpoint}${urlQueries.toUrlQueryString()}"
}
private val refusedByTrackingHost: MutableSet<String> = Collections.synchronizedSet(mutableSetOf())
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal fun Event.forCurrentHosts(configuration: Configuration): Event {
val trackingEvent = eventType as? TrackingHostEvent ?: return this
when {
resolveTrackingHost(configuration) == null ->
this@GatewayManager.mindboxLogW("No tracking host for event #$uid, sending it to the main host without ids")
transactionId in refusedByTrackingHost ->
this@GatewayManager.mindboxLogW("Event #$uid did not reach the tracking host, retrying on the main host without ids")
else -> return this
}
trackingIdsResolver().invalidateSent()
return onMainHost(trackingEvent)
}
private fun Event.onMainHost(trackingEvent: TrackingHostEvent): Event = copy(
eventType = trackingEvent.mainHostCounterpart,
body = body?.withoutTrackingIds(),
)
fun sendAsyncEvent(
configuration: Configuration,
deviceUuid: String,
event: Event,
shouldCountOffset: Boolean,
onResult: (AsyncEventSendResult) -> Unit,
) {
val outgoing = loggingRunCatching(defaultValue = null) { event.forCurrentHosts(configuration) }
if (outgoing == null) {
onResult(AsyncEventSendResult.RETRY_LATER)
return
}
val isOnTrackingHost = outgoing.eventType is TrackingHostEvent
val report: (AsyncEventSendResult) -> Unit = { result ->
if (result.isRemovedFromQueue) refusedByTrackingHost.remove(event.transactionId)
onResult(result)
}
enqueueEventRequest(
configuration = configuration,
deviceUuid = deviceUuid,
event = outgoing,
shouldCountOffset = shouldCountOffset,
onSuccess = { report(AsyncEventSendResult.DELIVERED) },
onFailure = { report(AsyncEventSendResult.RETRY_LATER) },
onVolleyError = { volleyError ->
if (isOnTrackingHost) {
report(AsyncEventSendResult.RETRY_LATER)
} else {
handleAsyncError(volleyError, report)
}
},
)
}
fun <T : OperationResponseBaseInternal> sendEvent(
configuration: Configuration,
deviceUuid: String,
event: Event,
classOfT: Class<T>,
shouldCountOffset: Boolean,
onSuccess: (T) -> Unit,
onError: (MindboxError) -> Unit,
) = sendEvent(
configuration = configuration,
deviceUuid = deviceUuid,
event = event,
shouldCountOffset = shouldCountOffset,
onSuccess = { body -> handleSuccessResponse(body, onSuccess, onError, classOfT) },
onError = onError,
)
fun sendEvent(
configuration: Configuration,
deviceUuid: String,
event: Event,
shouldCountOffset: Boolean,
onSuccess: (String) -> Unit,
onError: (MindboxError) -> Unit,
) = enqueueEventRequest(
configuration = configuration,
deviceUuid = deviceUuid,
event = event,
shouldCountOffset = shouldCountOffset,
onSuccess = onSuccess,
onFailure = onError,
onVolleyError = { volleyError -> handleError(volleyError, onSuccess, onError) },
)
private fun enqueueEventRequest(
configuration: Configuration,
deviceUuid: String,
event: Event,
shouldCountOffset: Boolean,
onSuccess: (String) -> Unit,
onFailure: (MindboxError) -> Unit,
onVolleyError: (VolleyError) -> Unit,
) {
try {
val isOnTrackingHost = event.eventType is TrackingHostEvent
val requestType: Int = getRequestType(event.eventType)
val url: String = buildEventUrl(configuration, deviceUuid, shouldCountOffset, event)
val jsonRequest: JSONObject? = convertBodyToJson(event.body)
val request = MindboxRequest(
methodType = requestType,
fullUrl = url,
configuration = configuration,
jsonRequest = jsonRequest,
listener = {
MindboxLoggerImpl.d(this, "Event from background successful sent")
onSuccess.invoke(it.toString())
},
errorsListener = { volleyError ->
if (isOnTrackingHost) refusedByTrackingHost.add(event.transactionId)
onVolleyError(volleyError)
},
).apply {
setShouldCache(false)
val timeout = if (isOnTrackingHost) TRACKING_HOST_TIMEOUT_DELAY else TIMEOUT_DELAY
retryPolicy = DefaultRetryPolicy(timeout, MAX_RETRIES, DEFAULT_BACKOFF_MULT)
}
mindboxServiceGenerator.addToRequestQueue(request)
} catch (e: Exception) {
MindboxLoggerImpl.e(this, "Sending event was failure with exception", e)
onFailure.invoke(MindboxError.Unknown(e))
}
}
private fun handleAsyncError(
volleyError: VolleyError,
onResult: (AsyncEventSendResult) -> Unit,
) {
when (val statusCode = volleyError.networkResponse?.statusCode) {
null -> {
mindboxLogI("[GD] decision: no response → keep")
onResult(AsyncEventSendResult.RETRY_LATER)
}
HTTP_TOO_MANY_REQUESTS -> {
mindboxLogI("[GD] decision: HTTP $statusCode → keep")
onResult(AsyncEventSendResult.THROTTLED)
}
in HTTP_SERVER_ERRORS -> {
mindboxLogI("[GD] decision: HTTP $statusCode → keep")
onResult(AsyncEventSendResult.RETRY_LATER)
}
else -> handleError(
volleyError = volleyError,
onSuccess = {
mindboxLogI("[GD] decision: HTTP $statusCode → delete")
onResult(AsyncEventSendResult.DELIVERED)
},
onError = { error ->
val result = if (isAsyncSent(error.statusCode)) {
AsyncEventSendResult.DISCARDED
} else {
AsyncEventSendResult.RETRY_LATER
}
val decision = if (result.isRemovedFromQueue) "delete" else "keep"
mindboxLogI("[GD] decision: HTTP $statusCode → $decision")
onResult(result)
},
)
}
}
private fun getRequestType(eventType: EventType): Int = when (eventType) {
is EventType.AppInstalled,
is EventType.AppInstalledWithoutCustomer,
is EventType.AppInfoUpdated,
is EventType.AppKeepalive,
is EventType.AppTrackingIdsUpdated,
is EventType.AppTrackingKeepalive,
is EventType.PushClicked,
is EventType.TrackVisit,
is EventType.AsyncOperation,
is EventType.SyncOperation,
-> Request.Method.POST
}
private fun getTimeOffset(
timeMls: Long,
shouldCountOffset: Boolean,
): String = if (shouldCountOffset) {
(System.currentTimeMillis() - timeMls).coerceAtLeast(0L).toString()
} else {
"0"
}
private fun <T : OperationResponseBaseInternal> handleSuccessResponse(
data: String,
onSuccess: (T) -> Unit,
onError: (MindboxError) -> Unit,
classOfT: Class<T>,
) = gatewayScope.launch {
try {
val body = convertJsonToBody(data, MindboxResponse::class.java)
if (body.status != MindboxResponse.STATUS_VALIDATION_ERROR) {
onSuccess.invoke(convertJsonToBody(data, classOfT))
} else {
val validationMessages = body.validationMessages ?: emptyList()
onError.invoke(MindboxError.Validation(200, body.status, validationMessages))
}
} catch (e: Exception) {
onError.invoke(MindboxError.Unknown(e))
}
}
private fun handleError(
volleyError: VolleyError,
onSuccess: (String) -> Unit,
onError: (MindboxError) -> Unit,
) = gatewayScope.launch {
try {
val error = volleyError.networkResponse
if (error == null) {
onError.invoke(MindboxError.UnknownServer())
return@launch
}
val code = error.statusCode
val errorData = error.data
val errorBody: MindboxResponse? = errorData?.let { data ->
convertJsonToBody(String(data), MindboxResponse::class.java)
}
when (val status = errorBody?.status) {
null -> onError.invoke(MindboxError.UnknownServer())
MindboxResponse.STATUS_SUCCESS,
MindboxResponse.STATUS_TRANSACTION_ALREADY_PROCESSED,
-> {
onSuccess.invoke(String(errorData))
}
MindboxResponse.STATUS_VALIDATION_ERROR -> onError.invoke(
MindboxError.Validation(
statusCode = code,
status = status,
validationMessages = errorBody.validationMessages ?: emptyList(),
)
)
MindboxResponse.STATUS_PROTOCOL_ERROR -> onError.invoke(
MindboxError.Protocol(
statusCode = code,
status = status,
errorMessage = errorBody.errorMessage,
errorId = errorBody.errorId,
httpStatusCode = errorBody.httpStatusCode,
)
)
MindboxResponse.STATUS_INTERNAL_SERVER_ERROR -> onError.invoke(
MindboxError.InternalServer(
statusCode = code,
status = status,
errorMessage = errorBody.errorMessage,
errorId = errorBody.errorId,
httpStatusCode = errorBody.httpStatusCode,
)
)
else -> onError.invoke(
MindboxError.UnknownServer(
statusCode = code,
status = status,
errorMessage = errorBody.errorMessage,
errorId = errorBody.errorId,
httpStatusCode = errorBody.httpStatusCode,
)
)
}
} catch (e: Exception) {
MindboxLoggerImpl.e(this, "Parsing server response was failure", e)
onError.invoke(MindboxError.Unknown(e))
}
}
private fun convertBodyToJson(body: String?): JSONObject? =
if (body == null) {
null
} else {
try {
JSONObject(body)
} catch (_: JSONException) {
null
}
}
private suspend fun <T> convertJsonToBody(
data: String,
classOfT: Class<T>,
) = withContext(Dispatchers.Default) { gson.fromJson(data, classOfT) }
private fun isAsyncSent(statusCode: Int?) = statusCode?.let { code ->
code < 300 || code in 400..499
} ?: false
suspend fun checkGeoTargeting(configuration: Configuration): GeoTargetingDto {
return suspendCancellableCoroutine { continuation ->
val request = MindboxRequest(
Request.Method.GET,
"${SdkValidation.toBaseUrl(configuration.domain)}/geo",
configuration,
null,
{ response ->
continuation.resumeFromJson<GeoTargetingDto>(
json = response.toString()
)
},
{ error ->
continuation.resumeWithException(GeoError(error))
}
)
continuation.invokeOnCancellation { request.cancel() }
mindboxServiceGenerator.addToRequestQueue(request)
}
}
suspend fun checkProductSegmentation(
configuration: Configuration,
segmentation: ProductSegmentationRequestDto,
): ProductSegmentationResponseDto {
return suspendCoroutine { continuation ->
mindboxServiceGenerator.addToRequestQueue(
MindboxRequest(
Request.Method.POST,
getProductSegmentationUrl(configuration),
configuration,
convertBodyToJson(
gson.toJson(
segmentation,
ProductSegmentationRequestDto::class.java
)
)!!,
{ response ->
continuation.resumeFromJson<ProductSegmentationResponseDto>(
json = response.toString()
)
},
{ error ->
continuation.resumeWithException(ProductSegmentationError(error))
}
)
)
}
}
suspend fun checkCustomerSegmentations(
configuration: Configuration,
segmentationCheckRequest: SegmentationCheckRequest,
): SegmentationCheckResponse {
return suspendCancellableCoroutine { continuation ->
val request = MindboxRequest(
Request.Method.POST,
getCustomerSegmentationsUrl(configuration),
configuration,
convertBodyToJson(
gson.toJson(
segmentationCheckRequest,
SegmentationCheckRequest::class.java
)
)!!,
{ response ->
continuation.resumeFromJson<SegmentationCheckResponse>(
json = response.toString()
)
},
{ error ->
continuation.resumeWithException(CustomerSegmentationError(error))
}
)
continuation.invokeOnCancellation { request.cancel() }
mindboxServiceGenerator.addToRequestQueue(request)
}
}
fun sendLogEvent(logs: LogResponseDto, configuration: Configuration) {
try {
val url = getLogsUrl(configuration)
val jsonRequest: JSONObject? = convertBodyToJson(gson.toJson(logs))
val request = MindboxRequest(
methodType = Request.Method.POST,
fullUrl = url,
configuration = configuration,
jsonRequest = jsonRequest,
listener = {
Log.d("Success", "Sending logs success")
},
errorsListener = { volleyError ->
Log.e("Error", "Sending logs was failure with exception", volleyError)
}
).apply {
setShouldCache(false)
retryPolicy =
DefaultRetryPolicy(MONITORING_DELAY, MAX_RETRIES, DEFAULT_BACKOFF_MULT)
}
mindboxServiceGenerator.addToRequestQueue(request)
} catch (e: Exception) {
Log.e("Error", "Sending event was failure with exception", e)
}
}
suspend fun fetchMobileConfig(configuration: Configuration): String {
return suspendCoroutine { continuation ->
mindboxServiceGenerator.addToRequestQueue(
MindboxRequest(
methodType = Request.Method.GET,
fullUrl = getConfigUrl(configuration),
configuration = configuration,
jsonRequest = null,
listener = { response ->
continuation.resume(response.toString())
},
errorsListener = { error ->
continuation.resumeWithException(error)
},
)
)
}
}
suspend fun fetchWebViewContent(contentUrl: String): String {
return suspendCancellableCoroutine { continuation ->
try {
val request = WebViewContentRequest(
url = contentUrl,
listener = { response -> continuation.resume(response) },
errorListener = { error -> continuation.resumeWithException(error) },
)
continuation.invokeOnCancellation { request.cancel() }
mindboxServiceGenerator.addToRequestQueue(request)
} catch (e: Exception) {
mindboxLogE("Failed to fetch WebView content", e)
continuation.resumeWithException(e)
}
}
}
private inline fun <reified T> Continuation<T>.resumeFromJson(json: String) {
loggingRunCatching(null) {
gson.fromJsonTyped<T>(json)
}?.let { dto ->
resume(dto)
} ?: run {
resumeWithException(
ParseError(JSONException("Could not parse JSON: $json"))
)
}
}
}