All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.algolia.instantsearch.insights.internal.uploader.InsightsEventUploader.kt Maven / Gradle / Ivy

Go to download

InstantSearch Android is a library providing widgets and helpers to help you build the best instant-search experience on Android with Algolia. It is built on top of Algolia's Kotlin API Client to provide you a high-level solution to quickly build various search interfaces.

There is a newer version: 3.3.1
Show newest version
package com.algolia.instantsearch.insights.internal.uploader

import com.algolia.instantsearch.insights.internal.data.distant.InsightsDistantRepository
import com.algolia.instantsearch.insights.internal.data.local.InsightsLocalRepository
import com.algolia.instantsearch.insights.internal.event.EventResponse
import com.algolia.instantsearch.insights.internal.extension.currentTimeMillis
import com.algolia.instantsearch.insights.internal.logging.InsightsLogger
import com.algolia.search.configuration.Credentials
import com.algolia.search.model.insights.InsightsEvent

internal class InsightsEventUploader(
    private val localRepository: InsightsLocalRepository,
    private val distantRepository: InsightsDistantRepository,
) : InsightsUploader, Credentials by distantRepository {

    override suspend fun uploadAll(): List {
        val events = localRepository.read()
        InsightsLogger.log("Flushing remaining ${events.size} events.")
        val recentEvents = events.filter { insightsEvent ->
            insightsEvent.timestamp?.let { !isExpired(it) } ?: true
        }
        val failedEvents = sendEvents(recentEvents).filterEventsWhenException()
        localRepository.overwrite(failedEvents.map { it.event })
        return failedEvents
    }

    private suspend fun sendEvents(events: List): List {
        return events.map { event -> distantRepository.send(event) }
    }

    private fun List.filterEventsWhenException(): List {
        return this.filter { it.code == -1 }
    }

    private fun isExpired(timestampMillis: Long): Boolean {
        return currentTimeMillis - timestampMillis >= fourDaysMillis
    }

    companion object {
        const val fourDaysMillis = 4 * 24 * 60 * 60 * 1000 // 4 days in millis
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy