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

com.deque.networking.analytics.AnalyticsService.kt Maven / Gradle / Ivy

The newest version!
package com.deque.networking.analytics

import com.deque.axe.android.constants.AxeBuildEnv
import com.deque.axe.android.constants.Config
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

object AnalyticsService {
    private const val BASE_URL: String = "https://api2.amplitude.com/"
    private val amplitudeClient: AmplitudeClient = AmplitudeClient(AMPLITUDE_API_KEY, BASE_URL)
    private val scope = MainScope()
    private var eventInfoProps: AmplitudeEventInfoProps? = null
    private var ruleErrorLog: MutableList = mutableListOf()
    internal var userId: String = ""

    @JvmStatic
    @JvmOverloads
    fun sendEvent(
        eventType: AmplitudeEventType,
        eventProps: AmplitudeEventProps? = null
    ): Job? {
        return if (notAuthorizedUser()
            || skipDuringTestInProduction()
        ) {
            null
        } else {
            scope.launch(Dispatchers.IO) {
                amplitudeClient.sendEvent(eventType, eventInfoProps, eventProps)
            }
        }
    }

    @JvmStatic
    fun addRuleError(msg: String) {
        if (notAuthorizedUser()
            || skipDuringTestInProduction()
        ) return

        ruleErrorLog.add(msg)
    }

    @JvmStatic
    fun sendRuleErrorLog(scanType: String?) {
        if (ruleErrorLog.isEmpty()) return

        sendEvent(
            AmplitudeEventType.SCAN_CREATE_ERROR,
            AmplitudeEventProps(
                scan_type = scanType,
                logs = ruleErrorLog
            )
        )?.invokeOnCompletion {
            ruleErrorLog.clear()
        }
    }

    @JvmStatic
    fun setDeviceInfo(
        osName: String?,
        osVersion: String?,
        deviceBrand: String?,
        deviceManufacturer: String?,
        deviceModel: String?,
    ) {
        eventInfoProps = AmplitudeEventInfoProps(
            os_name = osName,
            os_version = osVersion,
            device_brand = deviceBrand,
            device_manufacturer = deviceManufacturer,
            device_model = deviceModel
        )
    }

    private fun notAuthorizedUser(): Boolean {
        return userId.isEmpty()
    }

    private fun skipDuringTestInProduction(): Boolean {
        return Config.UNDER_TEST
                && AXE_DEVTOOLS_BUILD_ENV == AxeBuildEnv.PROD
    }

    @JvmStatic
    fun setUserInfo(userId: String) {
        this.userId = userId
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy