Skip to content
10 changes: 10 additions & 0 deletions sdk/src/main/java/cloud/mindbox/mobile_sdk/Extensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import cloud.mindbox.mobile_sdk.inapp.domain.models.InApp
import cloud.mindbox.mobile_sdk.inapp.domain.models.InAppType
import cloud.mindbox.mobile_sdk.inapp.domain.models.Layer
import cloud.mindbox.mobile_sdk.logger.MindboxLoggerImpl
import cloud.mindbox.mobile_sdk.logger.mindboxLogW
import cloud.mindbox.mobile_sdk.pushes.PushNotificationManager.EXTRA_UNIQ_PUSH_BUTTON_KEY
import cloud.mindbox.mobile_sdk.pushes.PushNotificationManager.EXTRA_UNIQ_PUSH_KEY
import cloud.mindbox.mobile_sdk.pushes.PushNotificationManager.IS_OPENED_FROM_PUSH_BUNDLE_KEY
Expand All @@ -40,6 +41,7 @@ import org.threeten.bp.LocalDateTime
import org.threeten.bp.ZoneOffset
import org.threeten.bp.ZonedDateTime
import org.threeten.bp.format.DateTimeFormatter
import java.net.URI
import java.net.URLEncoder
import java.nio.charset.Charset
import java.util.Collections
Expand All @@ -58,6 +60,14 @@ internal fun LinkedHashMap<String, String>.toUrlQueryString(): String = loggingR

internal fun String.encode(): String = URLEncoder.encode(this, "UTF-8")

internal fun String.isHttpsUrl(): Boolean = runCatching {
val uri = URI(this)
uri.scheme.equals("https", ignoreCase = true) && !uri.host.isNullOrBlank()
}.getOrElse { error ->
mindboxLogW("Url is not valid: ${error.message ?: this}")
false
}

internal fun ZonedDateTime.convertToString() = runCatching {
this.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"))
}.getOrElse {
Expand Down
12 changes: 10 additions & 2 deletions sdk/src/main/java/cloud/mindbox/mobile_sdk/Mindbox.kt
Original file line number Diff line number Diff line change
Expand Up @@ -449,9 +449,17 @@ public object Mindbox : MindboxLog {
* @param context used to initialize the main tools
* @param uniqKey - unique identifier of push notification
*/
public fun onPushReceived(context: Context, uniqKey: String): Unit = LoggingExceptionHandler.runCatching {
public fun onPushReceived(context: Context, uniqKey: String): Unit =
onPushReceived(context = context, uniqKey = uniqKey, deliveredUrl = null)

internal fun onPushReceived(
context: Context,
uniqKey: String,
deliveredUrl: DeliveredUrl?,
): Unit = LoggingExceptionHandler.runCatching {
initComponents(context)
MindboxLoggerImpl.d(this, "onPushReceived. uniqKey: $uniqKey")
mindboxLogD("onPushReceived. uniqKey: $uniqKey, hasDeliveredUrl: ${deliveredUrl != null}")
deliveredUrl?.let { MindboxEventManager.pushDelivered(context, it) }

if (!MindboxPreferences.isFirstInitialize) {
mindboxScope.launch {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,9 @@ internal fun DataModule(
override val deliveryPauseManager: DeliveryPauseManager by lazy {
DeliveryPauseManager(monotonicNow = timeProvider::monotonicMillis)
}
override val pushDeliveredManager: PushDeliveredManager by lazy {
PushDeliveredManager(mindboxServiceGenerator, timeProvider)
}

override val gson: Gson by lazy {
GsonBuilder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ internal interface DataModule : MindboxModule {
val migrationManager: MigrationManager
val timeProvider: SystemTimeProvider
val deliveryPauseManager: DeliveryPauseManager
val pushDeliveredManager: PushDeliveredManager
val slidingExpirationParametersValidator: TimeSpanPositiveValidator
val mobileConfigSettingsManager: MobileConfigSettingsManager
val integerPositiveValidator: IntegerPositiveValidator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ 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.TimeProvider
import cloud.mindbox.mobile_sdk.utils.loggingRunCatching
import com.android.volley.DefaultRetryPolicy
import com.android.volley.DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
Expand All @@ -38,6 +39,7 @@ import kotlin.coroutines.suspendCoroutine

internal class GatewayManager(
private val mindboxServiceGenerator: MindboxServiceGenerator,
private val timeProvider: () -> TimeProvider = { MindboxDI.appModule.timeProvider },
private val trackingIdsResolver: () -> TrackingIdsResolver = { MindboxDI.appModule.trackingIdsResolver },
) {

Expand All @@ -52,6 +54,7 @@ internal class GatewayManager(
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 const val PUSH_DELIVERED_IS_NOT_SENT_HERE = "Push delivered events are sent by PushDeliveredManager"
}

private val gson by lazy { Gson() }
Expand Down Expand Up @@ -148,19 +151,21 @@ internal class GatewayManager(
urlQueries[UrlQuery.OPERATION.value] = event.eventType.operation
urlQueries[UrlQuery.TRANSACTION_ID.value] = event.transactionId
urlQueries[UrlQuery.DATE_TIME_OFFSET.value] =
getTimeOffset(event.enqueueTimestamp, shouldCountOffset)
event.dateTimeOffset(shouldCountOffset, timeProvider().currentTimestamp()).interval.toString()
}

is EventType.TrackVisit -> {
urlQueries[UrlQuery.TRANSACTION_ID.value] = event.transactionId
urlQueries[UrlQuery.DATE_TIME_OFFSET.value] =
getTimeOffset(event.enqueueTimestamp, shouldCountOffset)
event.dateTimeOffset(shouldCountOffset, timeProvider().currentTimestamp()).interval.toString()
}

is EventType.SyncOperation -> {
urlQueries[UrlQuery.ENDPOINT_ID.value] = configuration.endpointId
urlQueries[UrlQuery.OPERATION.value] = event.eventType.operation
}

is EventType.PushDelivered -> error(PUSH_DELIVERED_IS_NOT_SENT_HERE)
}

val baseUrl = if (event.eventType is TrackingHostEvent) {
Expand Down Expand Up @@ -353,15 +358,8 @@ internal class GatewayManager(
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"
is EventType.PushDelivered -> error(PUSH_DELIVERED_IS_NOT_SENT_HERE)
}

private fun <T : OperationResponseBaseInternal> handleSuccessResponse(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ 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.pushes.DeliveredUrl
import cloud.mindbox.mobile_sdk.repository.MindboxPreferences
import cloud.mindbox.mobile_sdk.services.BackgroundWorkManager
import cloud.mindbox.mobile_sdk.utils.loggingRunCatching
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.flow.MutableSharedFlow
Expand Down Expand Up @@ -113,6 +115,36 @@ internal object MindboxEventManager {
)
}

fun pushDelivered(
context: Context,
deliveredUrl: DeliveredUrl,
): Unit = loggingRunCatching {
val event = Event(
eventType = EventType.PushDelivered,
additionalFields = hashMapOf(EventType.PushDelivered.FIELD_URL to deliveredUrl.value),
)
Mindbox.mindboxScope.launch(Dispatchers.IO) {
InitializeLock.await(InitializeLock.State.MIGRATION)
DbManager.addEventToQueue(context, event)
loggingRunCatching {
val configuration = DbManager.getConfigurations()
if (configuration == null) {
this@MindboxEventManager.mindboxLogW(
"Event ${event.eventType.operation} will be sent later, because configuration was not initialized"
)
} else {
WorkerDelegate().sendEventOrPostpone(
context = context,
configuration = configuration,
deviceUuid = MindboxPreferences.deviceUuid,
event = event,
parent = this@MindboxEventManager,
)
}
}
}
}

fun appStarted(
context: Context,
trackVisitData: TrackVisitData,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package cloud.mindbox.mobile_sdk.managers

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.AsyncEventSendResult
import cloud.mindbox.mobile_sdk.models.Configuration
import cloud.mindbox.mobile_sdk.models.Event
import cloud.mindbox.mobile_sdk.models.EventType
import cloud.mindbox.mobile_sdk.models.UrlQuery
import cloud.mindbox.mobile_sdk.models.dateTimeOffset
import cloud.mindbox.mobile_sdk.network.MindboxServiceGenerator
import cloud.mindbox.mobile_sdk.network.PushDeliveredRequest
import cloud.mindbox.mobile_sdk.pushes.DeliveredUrl
import cloud.mindbox.mobile_sdk.utils.TimeProvider
import com.android.volley.VolleyError

internal class PushDeliveredManager(
private val mindboxServiceGenerator: MindboxServiceGenerator,
private val timeProvider: TimeProvider,
) {

private companion object {
const val HTTP_TOO_MANY_REQUESTS = 429
val HTTP_SERVER_ERRORS = 500..599
}

fun send(
configuration: Configuration,
event: Event,
shouldCountOffset: Boolean,
onResult: (AsyncEventSendResult) -> Unit,
) {
val url = DeliveredUrl.of(event.additionalFields?.get(EventType.PushDelivered.FIELD_URL))
if (url == null) {
mindboxLogW("Event #${event.uid} has no delivered URL, dropping it")
onResult(AsyncEventSendResult.DISCARDED)
return
}
try {
val offset = event.dateTimeOffset(shouldCountOffset, timeProvider.currentTimestamp())
val request = PushDeliveredRequest(
url = url.withQueryParameter(UrlQuery.DATE_TIME_OFFSET.value, offset.interval.toString()),
configuration = configuration,
onDelivered = { onResult(AsyncEventSendResult.DELIVERED) },
errorListener = { volleyError -> onResult(resultOf(volleyError)) },
)
mindboxServiceGenerator.addToRequestQueue(request)
} catch (e: Exception) {
mindboxLogE("Sending push delivered event #${event.uid} failed", e)
onResult(AsyncEventSendResult.DISCARDED)
}
}

private fun resultOf(volleyError: VolleyError): AsyncEventSendResult {
val statusCode = volleyError.networkResponse?.statusCode
val result = when (statusCode) {
null -> AsyncEventSendResult.RETRY_LATER
HTTP_TOO_MANY_REQUESTS -> AsyncEventSendResult.THROTTLED
in HTTP_SERVER_ERRORS -> AsyncEventSendResult.RETRY_LATER
else -> AsyncEventSendResult.DISCARDED
}
val response = statusCode?.let { "HTTP $it" } ?: "no response"
val decision = if (result.isRemovedFromQueue) "delete" else "keep"
mindboxLogI("[GD] push delivered decision: $response → $decision")
return result
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import cloud.mindbox.mobile_sdk.logger.mindboxLogI
import cloud.mindbox.mobile_sdk.models.AsyncEventSendResult
import cloud.mindbox.mobile_sdk.models.Configuration
import cloud.mindbox.mobile_sdk.models.Event
import cloud.mindbox.mobile_sdk.models.EventType
import cloud.mindbox.mobile_sdk.models.Milliseconds
import cloud.mindbox.mobile_sdk.repository.MindboxPreferences
import cloud.mindbox.mobile_sdk.services.BackgroundWorkManager
Expand Down Expand Up @@ -164,12 +165,7 @@ internal class WorkerDelegate {
val countDownLatch = CountDownLatch(1)
var sendResult = AsyncEventSendResult.RETRY_LATER

MindboxDI.appModule.gatewayManager.sendAsyncEvent(
configuration = configuration,
deviceUuid = deviceUuid,
event = event,
shouldCountOffset = shouldCountOffset
) { result ->
val onResult: (AsyncEventSendResult) -> Unit = { result ->
Mindbox.mindboxScope.launch {
if (result.isRemovedFromQueue) {
DbManager.removeEventFromQueue(event)
Expand All @@ -186,6 +182,22 @@ internal class WorkerDelegate {
countDownLatch.countDown()
}
}
if (event.eventType is EventType.PushDelivered) {
MindboxDI.appModule.pushDeliveredManager.send(
configuration = configuration,
event = event,
shouldCountOffset = shouldCountOffset,
onResult = onResult,
)
} else {
MindboxDI.appModule.gatewayManager.sendAsyncEvent(
configuration = configuration,
deviceUuid = deviceUuid,
event = event,
shouldCountOffset = shouldCountOffset,
onResult = onResult,
)
}

try {
countDownLatch.await()
Expand Down
15 changes: 13 additions & 2 deletions sdk/src/main/java/cloud/mindbox/mobile_sdk/models/Event.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ internal data class Event(
val body: String? = null,
)

internal fun Event.dateTimeOffset(shouldCountOffset: Boolean, now: Timestamp): Milliseconds =
if (shouldCountOffset) {
Milliseconds((now.ms - enqueueTimestamp).coerceAtLeast(0L))
} else {
Milliseconds(0L)
}

internal sealed class EventType(
@SerializedName("operation") val operation: String,
@SerializedName("endpoint") val endpoint: String,
Expand All @@ -28,8 +35,6 @@ internal sealed class EventType(

private const val APP_INSTALLED_ORDINAL = 0
private const val APP_INFO_UPDATED_ORDINAL = 1

// use it when returning a delivered operation, it is not used now
private const val PUSH_DELIVERED_ORDINAL = 2
private const val PUSH_CLICKED_ORDINAL = 3
private const val TRACK_VISIT_ORDINAL = 4
Expand All @@ -47,6 +52,7 @@ internal sealed class EventType(
APP_KEEP_A_LIVE -> object : TypeToken<AppKeepalive>() {}
APP_TRACKING_IDS_UPDATED_ORDINAL -> object : TypeToken<AppTrackingIdsUpdated>() {}
APP_TRACKING_KEEP_A_LIVE_ORDINAL -> object : TypeToken<AppTrackingKeepalive>() {}
PUSH_DELIVERED_ORDINAL -> object : TypeToken<PushDelivered>() {}
PUSH_CLICKED_ORDINAL -> object : TypeToken<PushClicked>() {}
TRACK_VISIT_ORDINAL -> object : TypeToken<TrackVisit>() {}
ASYNC_OPERATION_ORDINAL -> object : TypeToken<AsyncOperation>() {}
Expand Down Expand Up @@ -76,6 +82,10 @@ internal sealed class EventType(

data object PushClicked : EventType("MobilePush.TrackClick", "/v3/operations/async")

data object PushDelivered : EventType("PushDelivered", "") {
const val FIELD_URL = "pushDeliveredUrl"
}

data object TrackVisit : EventType("TrackVisit", "/v1.1/customer/mobile-track-visit")

internal class AsyncOperation(operation: String) : EventType(operation, "/v3/operations/async")
Expand All @@ -89,6 +99,7 @@ internal sealed class EventType(
is AppKeepalive -> APP_KEEP_A_LIVE
is AppTrackingIdsUpdated -> APP_TRACKING_IDS_UPDATED_ORDINAL
is AppTrackingKeepalive -> APP_TRACKING_KEEP_A_LIVE_ORDINAL
is PushDelivered -> PUSH_DELIVERED_ORDINAL
is PushClicked -> PUSH_CLICKED_ORDINAL
is TrackVisit -> TRACK_VISIT_ORDINAL
is AsyncOperation -> ASYNC_OPERATION_ORDINAL
Expand Down
27 changes: 14 additions & 13 deletions sdk/src/main/java/cloud/mindbox/mobile_sdk/models/Requests.kt
Original file line number Diff line number Diff line change
Expand Up @@ -39,25 +39,26 @@ internal data class MindboxRequest(
private const val VALUE_ACCEPT = "application/json"

private const val DEFAULT_RESPONSE_CHARSET = "UTF-8"
}

override fun toString(): String = "MindboxRequest(methodType=$methodType, fullUrl=$fullUrl)"
fun buildHeaders(configuration: Configuration): MutableMap<String, String> {
val params: MutableMap<String, String> = HashMap()

// building headers
override fun getHeaders(): MutableMap<String, String> {
val params: MutableMap<String, String> = HashMap()
LoggingExceptionHandler.runCatching {
params[HEADER_CONTENT_TYPE] = VALUE_CONTENT_TYPE
params[HEADER_USER_AGENT] = configuration.getUserAgent()
params[HEADER_INTEGRATION] = VALUE_INTEGRATION
params[HEADER_INTEGRATION_VERSION] = BuildConfig.VERSION_NAME
params[HEADER_ACCEPT] = VALUE_ACCEPT
}

LoggingExceptionHandler.runCatching {
params[HEADER_CONTENT_TYPE] = VALUE_CONTENT_TYPE
params[HEADER_USER_AGENT] = configuration.getUserAgent()
params[HEADER_INTEGRATION] = VALUE_INTEGRATION
params[HEADER_INTEGRATION_VERSION] = BuildConfig.VERSION_NAME
params[HEADER_ACCEPT] = VALUE_ACCEPT
return params
}

return params
}

override fun toString(): String = "MindboxRequest(methodType=$methodType, fullUrl=$fullUrl)"

override fun getHeaders(): MutableMap<String, String> = buildHeaders(configuration)

// Logging responses
override fun parseNetworkResponse(response: NetworkResponse?): Response<JSONObject> {
return LoggingExceptionHandler.runCatching(
Expand Down
Loading
Loading