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

main.com.wisetrack.sdk.WiseTrack.kt Maven / Gradle / Ivy

There is a newer version: 1.5.3
Show newest version
package com.wisetrack.sdk

import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.util.Log
import com.wisetrack.VerifyLibrary
import com.wisetrack.sdk.network.IActivityPackageSender
import com.wisetrack.sdk.network.parser.JsonObjectDecoder
import org.json.JSONObject
import java.io.File
import java.security.MessageDigest

/**
 * The main interface to WiseTrack.
 * Use the methods of this class to tell WiseTrack about the usage of your app.
 * See the README for details.
 *
@author hamed (@hamed-hsb)
 * @since 17th October 2021
 */

public class WiseTrack private constructor() {
    companion object {
        private val TRACK_EVENT = "track_event"
        private val ON_RESUME = "on_resume"
        private val ON_PAUSE = "on_pause"
        private val SET_ENABLED = "set_enabled"
        private val APP_WILL_OPEN_URL = "app_will_open_url"
        private val SET_REFERRER = "set_referrer"
        private val SET_OFFLINE_MODE = "set_offline_mode"
        private val SEND_FIRST_PACKAGES = "send_first_packages"
        private val SESSION_CALLBACK_PARAMETER = "session_callback_parameter"
        private val SESSION_PARTNER_PARAMETER = "session_partner_parameter"
        private val REMOVE_SESSION_CALLBACK_PARAMETER = "remove_session_callback_parameter"
        private val REMOVE_SESSION_PARTNER_PARAMETER = "remove_session_partner_parameter"
        private val RESET_SESSION_CALLBACK_PARAMETERS = "reset_session_callback_parameters"
        private val RESET_SESSION_PARTNER_PARAMETERS = "reset_session_partner_parameters"
        private val PUSH_TOKEN = "push_token"
        private val GDPR_FORGET_ME = "gdpr_forget_me"
        private val DISABLE_THIRD_PARTY_SHARING = "disable_Third_party_sharing"
        private val TRACK_THIRD_PARTY_SHARING = "track_third_party_sharing"
        private val TRACK_MEASUREMENT_CONSENT = "track_measurement_consent"
        private val TRACK_AD_REVENUE_JSON = "track_ad_revenue_json"
        private val TRACK_AD_REVENUE = "track_ad_revenue"
        private val TRACK_PLAY_STORE_SUBSCRIPTION = "track_play_store_subscription"
        private val GOOGLE_AD_ID = "google_ad_id"
        private val AMAZON_AD_ID = "amazon_ad_id"
        private val TEST_OPTIONS = "test_options"

        private var isCallConfigApi = false

        private var status_sdk = false


        var cacheJob = mutableMapOf>()

        /**
         * Singleton WiseTrack SDK instance.
         */
        private var defaultInstance: WiseTrackInstance? = null

        /**
         * Method used to obtain WiseTrack SDK singleton instance.
         *
         * @return WiseTrack SDK singleton instance.
         */
        @Synchronized
        fun getDefaultInstance(): WiseTrackInstance {
            val VERSION = "!SDK-VERSION-STRING!:com.wisetrack.sdk:track-android:"

            if (defaultInstance == null) {
                defaultInstance = WiseTrackInstance()
            }
            return defaultInstance as WiseTrackInstance
        }



        /**
         * Called upon SDK initialisation.
         *
         * @param wiseTrackConfig WiseTrackConfig object used for SDK initialisation
         */
        fun onCreate(wiseTrackConfig: WiseTrackConfig,context: Context) {

            var logger: ILogger?  = null
            logger = WiseTrackFactory.getLogger()
            logger!!.lockLogLevel()

            var sdkConfig = SDKConfig(wiseTrackConfig!!)
            sdkConfig.start()
            sdkConfig.callback =
                object : IActivityPackageSender.ResponseConfigDataCallbackSubscriber {
                    override fun onResponseConfigDataCallback(response: String) {

                        val parseJson = JsonObjectDecoder(response)
                        val configResponse = parseJson.getConfigModel()


                        if (!configResponse.success) {
                            logger.info("The SDK has been disabled because it has been hacked, edited, or cracked. Please reinstall the official version.")
                            return
                        }

                        if (configResponse.force_update!!) {
                            logger.info("The SDK needs to be updated to the latest version. Please update to continue using the official latest version.")
                            return
                        }

                        if (!configResponse.sdk_enabled!!) {
                            logger.info("The SDK is currently disabled due to ongoing updates to the server infrastructure. Please try again later.")
                            return
                        }

                        if (!configResponse.sdk_secure!!) {
                            logger.info("The SDK has been disabled because it has been hacked, edited, or cracked. Please reinstall the official version.")
                            return
                        }


                        val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                        wiseTrackInstance.onCreate(wiseTrackConfig)


                        Constants.END_POINT_EVENT = configResponse.events!!
                        Constants.END_POINT_SESSION = configResponse.sessions!!
                        Constants.END_POINT_SDK_CLICK = configResponse.sdk_clicks!!
                        Constants.END_POINT_SDK_INFO = configResponse.sdk_infos!!
                        Constants.END_POINT_ATTRIBUTION = configResponse.attributions!!
                        Constants.END_POINT_PACKAGE_INFO = configResponse.pkg_info!!
                        // todo for test "/api/v2/page" remove it
                        Constants.END_POINT_PAGE = configResponse.page ?: "/api/v2/page"

                        Constants.BASE_URL = configResponse.base_url!!

                        Constants.SDK_ENABLED = configResponse.sdk_enabled!!
                        Constants.FORCE_UPDATE = configResponse.force_update!!
                        Constants.SDK_UPDATE = configResponse.sdk_update!!
                        Constants.SDK_SECURE = configResponse.sdk_secure!!
                        Constants.SENTRY_ENABLED = configResponse.sentry_enabled!!

                        isCallConfigApi = true


                        val entry: MutableSet>> =
                            cacheJob.entries
                        entry.forEach {
                            when (it.key) {
                                "track_event" -> {
                                    trackEvent(it.value.values.single() as WiseTrackEvent)
                                }

                                "on_resume" -> {
                                    onResume()
                                }

                                "on_pause" -> {
                                    onPause()
                                }

                                "set_enabled" -> {
                                    setEnabled(it.value.values.single() as Boolean)
                                }

                                "app_will_open_url" -> {
                                    if (it.value.values.single() == null) {
                                        appWillOpenUrl(null,context)
                                    } else appWillOpenUrl(it.value.values.single() as Uri,context)
                                }

                                "set_referrer" -> {
                                    setReferrer(it.value.values.single() as String, context)
                                }

                                "set_offline_mode" -> {
                                    setOfflineMode(it.value.values.single() as Boolean)
                                }

                                "send_first_packages" -> {
                                    sendFirstPackages()
                                }

                                "session_callback_parameter" -> {
                                    addSessionCallbackParameter(
                                        it.value.keys.toString(),
                                        it.value.values.single() as String
                                    )
                                }

                                "session_partner_parameter" -> {
                                    addSessionPartnerParameter(
                                        it.value.keys.toString(),
                                        it.value.values.single() as String
                                    )
                                }

                                "remove_session_callback_parameter" -> {
                                    removeSessionCallbackParameter(it.value.keys.toString())
                                }

                                "remove_session_partner_parameter" -> {
                                    removeSessionPartnerParameter(it.value.keys.toString())
                                }

                                "reset_session_callback_parameters" -> {
                                    resetSessionCallbackParameters()
                                }

                                "reset_session_partner_parameters" -> {
                                    resetSessionPartnerParameters()
                                }

                                "push_token" -> {
                                    println("push token : ${it.value.values.single() as String}")
                                    setPushToken(it.value.values.single() as String, context)
                                }

                                "gdpr_forget_me" -> {
                                    gdprForgetMe(it.value.values.single() as Context)
                                }

                                "disable_Third_party_sharing" -> {
                                    disableThirdPartySharing(it.value.values.single() as Context)
                                }

                                "track_third_party_sharing" -> {
                                    trackThirdPartySharing(it.value.values.single() as WiseTrackThirdPartySharing)
                                }

                                "track_measurement_consent" -> {
                                    trackMeasurementConsent(it.value.values.single() as Boolean)
                                }

                                "track_ad_revenue_json" -> {
                                    trackAdRevenue(
                                        it.value.keys.toString(),
                                        it.value.values.single() as JSONObject
                                    )
                                }

                                "track_ad_revenue" -> {
                                    trackAdRevenue(it.value.values.single() as WiseTrackAdRevenue)
                                }

                                "track_play_store_subscription" -> {
                                    trackPlayStoreSubscription(it.value.values.single() as WiseTrackPlayStoreSubscription)
                                }

                                "google_ad_id" -> {
                                    getGoogleAdId(null, it.value.values.single() as OnDeviceIdsRead)
                                }

                                "amazon_ad_id" -> {
                                    getAmazonAdId(it.value.values.single() as Context)
                                }

                                "test_options" -> {
                                    setTestOptions(it.value.values.single() as WiseTrackTestOptions)
                                }
                            }
                        }
                    }
                }
        }



        /**
         * Called to track event.
         *
         * @param event WiseTrackEvent object to be tracked
         */
        fun trackEvent(event: WiseTrackEvent) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.trackEvent(event)
            } else {
                val key: String? = "event"
                val trackEvent = mapOf(key to event)
                cacheJob[TRACK_EVENT] = trackEvent
            }
        }

        /**
         * Called upon each Activity's onResume() method call.
         */
        fun onResume() {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.onResume()
            } else {
                val key: String? = "resume"
                val onResume = mapOf(key to null)
                cacheJob[ON_RESUME] = onResume
            }

        }

        /**
         * Called upon each Activity's onPause() method call.
         */
        fun onPause() {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.onPause()
            } else {
                val key: String? = "pause"
                val onPause = mapOf(key to null)
                cacheJob[ON_PAUSE] = onPause
            }
        }

        /**
         * Called to disable/enable SDK.
         *
         * @param enabled boolean indicating whether SDK should be enabled or disabled
         */
        fun setEnabled(enabled: Boolean) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.setEnabled(enabled)
            } else {
                val key: String? = "enabled"
                val setEnabled = mapOf(key to enabled)
                cacheJob[SET_ENABLED] = setEnabled

                status_sdk = enabled
            }

        }

        /**
         * Get information if SDK is enabled or not.
         *
         * @return boolean indicating whether SDK is enabled or not
         */
        fun isEnabled(): Boolean {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                return wiseTrackInstance.isEnabled()
            }
            return status_sdk
        }


        /**
         * Called to process deep link.
         *
         * @param url Deep link URL to process
         * @param context Application context
         */
        fun appWillOpenUrl(url: Uri?, context: Context?) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.appWillOpenUrl(url, extractApplicationContext(context))
            } else {

                val key: String? = "appWillOpenUrl"
                val appWillOpenUrl = mapOf(key to url)
                cacheJob[APP_WILL_OPEN_URL] = appWillOpenUrl
            }
        }

        /**
         * Called to process referrer information sent with INSTALL_REFERRER intent.
         *
         * @param referrer Referrer content
         * @param context  Application context
         */
        fun setReferrer(referrer: String?, context: Context?) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.sendReferrer(referrer, extractApplicationContext(context))
            } else {
                val key: String? = "setReferrer"
                val setReferrer = mapOf(key to referrer)
                cacheJob[SET_REFERRER] = setReferrer
            }
        }

        /**
         * Called to set SDK to offline or online mode.
         *
         * @param enabled boolean indicating should SDK be in offline mode (true) or not (false)
         */
        fun setOfflineMode(enabled: Boolean) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.setOfflineMode(enabled)
            } else {
                val key: String? = "setOfflineMode"
                val setOfflineMode = mapOf(key to enabled)
                cacheJob[SET_OFFLINE_MODE] = setOfflineMode

            }
        }

        /**
         * Called if SDK initialisation was delayed and you would like to stop waiting for timer.
         */
        fun sendFirstPackages() {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.sendFirstPackages()
            } else {
                val key: String? = "sendFirstPackages"
                val sendFirstPackages = mapOf(key to null)
                cacheJob[SEND_FIRST_PACKAGES] = sendFirstPackages
            }
        }

        /**
         * Called to add global callback parameter that will be sent with each session and event.
         *
         * @param key   Global callback parameter key
         * @param value Global callback parameter value
         */
        fun addSessionCallbackParameter(key: String?, value: String?) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.addSessionCallbackParameter(key, value)
            } else {
                val callback = mapOf(key to value)
                cacheJob[SESSION_CALLBACK_PARAMETER] = callback
            }
        }

        /**
         * Called to add global partner parameter that will be sent with each session and event.
         *
         * @param key   Global partner parameter key
         * @param value Global partner parameter value
         */
        fun addSessionPartnerParameter(key: String?, value: String?) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.addSessionPartnerParameter(key, value)
            } else {
                val partner = mapOf(key to value)
                cacheJob[SESSION_PARTNER_PARAMETER] = partner
            }
        }

        /**
         * Called to remove global callback parameter from session and event packages.
         *
         * @param key Global callback parameter key
         */
        fun removeSessionCallbackParameter(key: String?) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.removeSessionCallbackParameter(key)
            } else {
                val callback = mapOf(key to "")
                cacheJob[REMOVE_SESSION_CALLBACK_PARAMETER] = callback
            }
        }

        /**
         * Called to remove global partner parameter from session and event packages.
         *
         * @param key Global partner parameter key
         */
        fun removeSessionPartnerParameter(key: String?) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.removeSessionPartnerParameter(key)
            } else {
                val partner = mapOf(key to "")
                cacheJob[REMOVE_SESSION_PARTNER_PARAMETER] = partner
            }
        }

        /**
         * Called to remove all added global callback parameters.
         */
        fun resetSessionCallbackParameters() {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.resetSessionCallbackParameters()
            } else {
                val key: String? = null
                val callback = mapOf(key to "null")
                cacheJob[RESET_SESSION_CALLBACK_PARAMETERS] = callback
            }
        }

        /**
         * Called to remove all added global partner parameters.
         */
        fun resetSessionPartnerParameters() {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.resetSessionPartnerParameters()
            } else {
                val key: String? = null
                val partner = mapOf(key to "null")
                cacheJob[RESET_SESSION_PARTNER_PARAMETERS] = partner
            }
        }


        /**
         * Called to set user's push notifications token.
         *
         * @param token   Push notifications token
         * @param context Application context
         */
        fun setPushToken(token: String, context: Context?) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                extractApplicationContext(context)?.let {
                    wiseTrackInstance.setPushToken(
                        token, it
                    )
                }
            } else {
                val key: String? = "token"
                val pushToken = mapOf(key to token)
                cacheJob[PUSH_TOKEN] = pushToken
            }
        }

        /**
         * Called to forget the user in accordance with GDPR law.
         *
         * @param context Application context
         */
        fun gdprForgetMe(context: Context?) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                extractApplicationContext(context)?.let { wiseTrackInstance.gdprForgetMe(it) }
            } else {
                val key: String? = "context"
                val forgetMe = mapOf(key to context)
                cacheJob[GDPR_FORGET_ME] = forgetMe
            }
        }

        /**
         * Called to disable the third party sharing.
         *
         * @param context Application context
         */
        fun disableThirdPartySharing(context: Context?) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                extractApplicationContext(context)?.let {
                    wiseTrackInstance.disableThirdPartySharing(
                        it
                    )
                }
            } else {
                val key: String? = "disableThirdPartySharing"
                val disableThirdPartySharing = mapOf(key to context)
                cacheJob[DISABLE_THIRD_PARTY_SHARING] = disableThirdPartySharing
            }

        }

        fun trackThirdPartySharing(wiseTrackThirdPartySharing: WiseTrackThirdPartySharing) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.trackThirdPartySharing(wiseTrackThirdPartySharing)
            } else {
                val key: String? = "trackThirdPartySharing"
                val trackThirdPartySharing = mapOf(key to wiseTrackThirdPartySharing)
                cacheJob[TRACK_THIRD_PARTY_SHARING] = trackThirdPartySharing
            }

        }

        fun trackMeasurementConsent(consentMeasurement: Boolean) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.trackMeasurementConsent(consentMeasurement)
            } else {
                val key: String? = "trackMeasurementConsent"
                val trackMeasurementConsent = mapOf(key to consentMeasurement)
                cacheJob[TRACK_MEASUREMENT_CONSENT] = trackMeasurementConsent
            }
        }

        /**
         * Track ad revenue from a source provider
         *
         * @param source Source of ad revenue information, see WiseTrackConfig.AD_REVENUE_* for some possible sources
         * @param payload JsonObject content of the ad revenue information
         */
        fun trackAdRevenue(source: String?, payload: JSONObject?) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.trackAdRevenue(source, payload)
            } else {
                val trackAdRevenue = mapOf(source to payload)
                cacheJob[TRACK_AD_REVENUE_JSON] = trackAdRevenue
            }
        }

        /**
         * Track ad revenue from a source provider
         *
         * @param wiseTrackAdRevenue WiseTrack ad revenue information like source, revenue, currency etc
         */
        fun trackAdRevenue(wiseTrackAdRevenue: WiseTrackAdRevenue) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.trackAdRevenue(wiseTrackAdRevenue)
            } else {
                val key: String? = "trackAdRevenue"
                val trackAdRevenue = mapOf(key to wiseTrackAdRevenue)
                cacheJob[TRACK_AD_REVENUE] = trackAdRevenue
            }
        }

        /**
         * Track subscription from Google Play.
         *
         * @param subscription WiseTrackPlayStoreSubscription object to be tracked
         */
        fun trackPlayStoreSubscription(subscription: WiseTrackPlayStoreSubscription) {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.trackPlayStoreSubscription(subscription)
            } else {
                val key: String? = "subscription"
                val trackPlayStoreSubscription = mapOf(key to subscription)
                cacheJob[TRACK_PLAY_STORE_SUBSCRIPTION] = trackPlayStoreSubscription
            }
        }


        /**
         * Called to get value of Google Play Advertising Identifier.
         *
         * @param context        Application context
         * @param onDeviceIdRead Callback to get triggered once identifier is obtained
         */
        fun getGoogleAdId(context: Context?, onDeviceIdRead: OnDeviceIdsRead) {
            if (isCallConfigApi) {
                var appContext: Context? = null
                context?.let { appContext = context.applicationContext }
                appContext?.let { AndroidUtil.getGoogleAdId(it, onDeviceIdRead) }
            } else {
                val key: String? = "getGoogleAdId"
                val getGoogleAdId = mapOf(key to onDeviceIdRead)
                cacheJob[GOOGLE_AD_ID] = getGoogleAdId
            }
        }

        /**
         * Called to get value of Amazon Advertising Identifier.
         *
         * @param context Application context
         * @return Amazon Advertising Identifier
         */
        fun getAmazonAdId(context: Context?): String? {
            if (isCallConfigApi) {
                val appContext: Context? = extractApplicationContext(context)
                return if (appContext != null) {
                    AndroidUtil.getFireAdvertisingId(appContext.contentResolver)
                } else null
            } else {
                val key: String? = "getAmazonAdId"
                val getAmazonAdId = mapOf(key to context)
                cacheJob[AMAZON_AD_ID] = getAmazonAdId
            }


            return null
        }

        /**
         * Called to get value of unique WiseTrack device identifier.
         *
         * @return Unique WiseTrack device identifier
         */
        fun getAdid(): String? {
            if (isCallConfigApi) {
                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                return wiseTrackInstance.getAdid()
            }

            return null
        }

        /**
         * Called to get user's current attribution value.
         *
         * @return WiseTrackAttribution object with current attribution value
         */
        fun getAttribution(): WiseTrackAttribution? {
            if (isCallConfigApi) {
                    val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                    return wiseTrackInstance.getAttribution()
            }
            return null
        }

        /**
         * Called to get native SDK version string.
         *
         * @return Native SDK version string.
         */
        fun getSdkVersion(): String {
            if (isCallConfigApi) {
                    val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                    return wiseTrackInstance.getSdkVersion()
            }
            return ""
        }

        /**
         * Used for testing purposes only. Do NOT use this method.
         *
         * @param testOptions WiseTrack integration tests options
         */
        fun setTestOptions(testOptions: WiseTrackTestOptions) {
            if (isCallConfigApi) {
                testOptions.teardown?.let {
                    if (it) {
                        defaultInstance?.teardown()
                        defaultInstance = null
                        WiseTrackFactory.teardown(testOptions.context)
                    }
                }

                val wiseTrackInstance: WiseTrackInstance = getDefaultInstance()
                wiseTrackInstance.setTestOptions(testOptions)

            } else {
                val key: String? = "setTestOptions"
                val setTestOptions = mapOf(key to testOptions)
                cacheJob[TEST_OPTIONS] = setTestOptions
            }

        }

        private fun extractApplicationContext(context: Context?): Context? {
            return context?.applicationContext
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy