package com.crispstats.sdk import android.app.Activity import android.app.Application import android.content.Context import android.content.SharedPreferences import android.content.pm.ApplicationInfo import android.os.Build import android.os.Bundle import android.os.SystemClock import android.util.Log import org.json.JSONArray import org.json.JSONObject import java.net.HttpURLConnection import java.net.URL import java.nio.ByteBuffer import java.nio.charset.CodingErrorAction import java.util.Locale import java.util.TimeZone import java.util.TreeMap import java.util.UUID import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.ScheduledFuture import java.util.concurrent.ThreadFactory import java.util.concurrent.TimeUnit /** * App analytics for CrispStats, version 1.1.0. One file, no dependencies. * * Screen views are pageviews on the same site as the website. A random * install id is kept on the device and hashed by the collector before it is * stored. No advertising id is read. * * Calls never throw and never block the calling thread: storage and network * run on one background thread. Time on screen pauses while no activity is * started. Call [screen] from each destination, and [track], [identify], * [revenue] and [recordError] from anywhere. * * If the site key, app id or app version can never produce a valid event, * the client does nothing and says why once in Logcat (debuggable builds). */ class CrispStats @JvmOverloads constructor( context: Context, site: String, appId: String, appVersion: String, osVersion: String = Build.VERSION.RELEASE ?: "", appBuild: String? = null, device: Device? = null, sdk: Sdk = Sdk.ANDROID, api: String = DEFAULT_API, ) : Application.ActivityLifecycleCallbacks { /** Phone or tablet. Detected from the smallest screen width when not given. */ enum class Device(val wire: String) { PHONE("phone"), TABLET("tablet") } /** The SDK name the collector stores. Wrappers built on this file set their own. */ enum class Sdk(val wire: String) { ANDROID("android"), REACT_NATIVE("react-native"), FLUTTER("flutter") } private enum class Outcome { OK, DROP, RETRY } private val appContext: Context = context.applicationContext ?: context private val debug: Boolean = isDebuggable(appContext) private val siteKey: String = site.trim() private val bundleId: String = appId.trim() private val host: String = bundleId.lowercase(Locale.US) private val appVersionText: String = appVersion.trim().take(32) private val appBuildText: String? = cleanBuild(appBuild) private val osVersionText: String = cleanOsVersion(osVersion) private val deviceWire: String = (device ?: detectDevice(appContext)).wire private val sdkWire: String = sdk.wire private val endpoint: String = api.trim().trimEnd('/') + "/e" private val problem: String? = configProblem(siteKey, bundleId, appVersionText) private val disabled: Boolean = problem != null // Opened on the background thread on first use: it can throw before the user unlocks the device. private val prefs: SharedPreferences by lazy { appContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) } private val executor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor( ThreadFactory { runnable -> val thread = Thread(runnable, "CrispStats") thread.isDaemon = true thread }, ) // Main thread only. private var startedActivities = 0 // Background thread only. Every task runs on the one executor thread, in order. private var loaded = false private var installId: String? = null private val queue = ArrayList() private var optedOut = false private var screenName: String? = null private var screenUrl: String? = null private var shownAt: Long? = null private var accumulatedMs = 0L private var leftAt: Long? = null private var pumping = false private var retryTask: ScheduledFuture<*>? = null private var backoffMs = INITIAL_BACKOFF_MS init { val reason = problem if (reason != null) { log("CrispStats is off: $reason") } else { try { val application = appContext as? Application application?.registerActivityLifecycleCallbacks(this) } catch (e: Exception) { log("Could not listen for activity changes.", e) } // Loads the stored state, then sends anything a previous launch left queued. submit { load() pump() } } } /** * Counts a screen. The previous screen's visible time is sent first. * [campaign] pairs (for example from [campaignFrom]) and [referrer] apply * to this one screen view only. */ @JvmOverloads fun screen( name: String, campaign: Map? = null, referrer: String? = null, props: Map? = null, ) { if (disabled) return try { val now = SystemClock.elapsedRealtime() val path = screenPath(name) if (path == null) { log("Screen name \"$name\" is not valid. Nothing was sent.") return } val label = if (name.length <= MAX_SCREEN) name else path.substring(1) val base = "app://$host$path" val url = withQuery(base, campaignPairs(campaign)) val ref = cleanReferrer(referrer) val properties = cleanProps(props) submit { openScreen(label, base, url, ref, properties, now) } } catch (e: Exception) { log("screen failed.", e) } } /** A custom event on the current screen. */ @JvmOverloads fun track(name: String, props: Map? = null) { if (disabled) return try { val trimmed = name.trim().take(120) if (trimmed.isEmpty()) return val properties = cleanProps(props) submit { val body = payload("event", currentUrl(), screenName, trimmed, properties) if (body != null) enqueue(body) } } catch (e: Exception) { log("track failed.", e) } } /** Ties this install to your own user id. */ @JvmOverloads fun identify(userId: String, traits: Map? = null) { if (disabled) return try { val trimmed = userId.trim().take(200) if (trimmed.isEmpty()) return val properties = cleanProps(traits) submit { val body = payload("identify", currentUrl(), screenName, null, properties) if (body != null) { body.put("i", trimmed) enqueue(body) } } } catch (e: Exception) { log("identify failed.", e) } } /** Revenue in minor units (cents) with an ISO currency code. A negative amount is ignored. */ @JvmOverloads fun revenue(amount: Int, currency: String, props: Map? = null) { if (disabled) return try { if (amount < 0) return val code = currency.trim().uppercase(Locale.US) if (!CURRENCY.matches(code)) return val properties = cleanProps(props) submit { val body = payload("revenue", currentUrl(), screenName, null, properties) if (body != null) { body.put("a", amount) body.put("c", code) enqueue(body) } } } catch (e: Exception) { log("revenue failed.", e) } } /** An app error. The message is grouped on the Errors page. */ @JvmOverloads fun recordError(message: String, source: String? = null) { if (disabled) return try { val text = message.trim().take(1000) if (text.isEmpty()) return val origin = source?.take(500) submit { val body = payload("error", currentUrl(), screenName, null, null) if (body != null) { val error = JSONObject() error.put("message", text) if (origin != null && origin.isNotEmpty()) error.put("source", origin) body.put("e", error) enqueue(body) } } } catch (e: Exception) { log("recordError failed.", e) } } /** The app left the foreground. Visible time so far is sent and the clock stops. Runs on its own from activity callbacks. */ fun leave() { if (disabled) return val now = SystemClock.elapsedRealtime() submit { emitPause(now) if (leftAt == null) leftAt = now } } /** * The app came back. After 30 minutes or more away the current screen is * counted again, because the collector has started a new session. Otherwise * its time keeps adding up. Runs on its own from activity callbacks. */ fun resume() { if (disabled) return val now = SystemClock.elapsedRealtime() submit { val left = leftAt leftAt = null val url = screenUrl val name = screenName if (canSend() && url != null && name != null) { if (left != null && now - left >= SESSION_GAP_MS) { accumulatedMs = 0L shownAt = now val body = payload("pageview", url, name, null, null) if (body != null) enqueue(body) } else if (shownAt == null) { shownAt = now } } pump() } } /** Stops sending and drops anything still queued. Kept across launches. */ fun optOut() { if (disabled) return submit { setOptOut(true) } } /** Starts sending again after [optOut]. */ fun optIn() { if (disabled) return submit { setOptOut(false) } } // Background thread from here on. private fun load() { if (loaded) return loaded = true optedOut = prefs.getString(KEY_OPT_OUT, "0") == "1" val saved = prefs.getString(KEY_INSTALL, null) if (saved != null && INSTALL.matches(saved)) { installId = saved } else if (!optedOut) { installId = createInstallId() } val raw = prefs.getString(KEY_QUEUE, null) if (raw != null && !optedOut) { try { val array = JSONArray(raw) for (index in 0 until array.length()) { val item = array.optJSONObject(index) if (item != null) queue.add(item) } while (queue.size > QUEUE_LIMIT) queue.removeAt(0) } catch (e: Exception) { queue.clear() } } } private fun createInstallId(): String { val created = UUID.randomUUID().toString().replace("-", "").lowercase(Locale.US) prefs.edit().putString(KEY_INSTALL, created).apply() return created } private fun canSend(): Boolean = loaded && !optedOut && installId != null private fun openScreen(label: String, base: String, url: String, referrer: String?, props: JSONObject?, now: Long) { if (!canSend()) return emitPause(now) screenName = label screenUrl = base accumulatedMs = 0L shownAt = now leftAt = null val body = payload("pageview", url, label, null, props) ?: return if (referrer != null) body.put("r", referrer) enqueue(body) } private fun emitPause(now: Long) { val url = screenUrl val name = screenName val started = shownAt if (!canSend() || url == null || name == null || started == null) return shownAt = null // Whole seconds per visible stretch, as the reference client counts them. val deltaSeconds = ((now - started) / 1000L).coerceAtLeast(0L) accumulatedMs = (accumulatedMs + deltaSeconds * 1000L).coerceAtMost(MAX_SECONDS * 1000L) val seconds = (accumulatedMs / 1000L).toInt() if (seconds <= 0) return val body = payload("ping", url, name, null, null) ?: return body.put("d", seconds) enqueue(body) } private fun currentUrl(): String = screenUrl ?: "app://$host/" private fun payload(type: String, url: String, screen: String?, name: String?, props: JSONObject?): JSONObject? { val id = installId if (id == null || optedOut) return null val app = JSONObject() app.put("os", "android") app.put("id", bundleId) app.put("v", appVersionText) app.put("ov", osVersionText) app.put("d", deviceWire) app.put("sdk", sdkWire) app.put("sv", VERSION) val build = appBuildText if (build != null) app.put("b", build) if (screen != null) app.put("sn", screen) val body = JSONObject() body.put("k", siteKey) body.put("t", type) body.put("u", url) body.put("vid", id) body.put("m", app) if (name != null) body.put("n", name) val language = languageTag() if (language != null) body.put("l", language) val zone = timeZoneId() if (zone != null) body.put("z", zone) if (props != null) body.put("p", props) return body } private fun enqueue(body: JSONObject) { queue.add(body) while (queue.size > QUEUE_LIMIT) queue.removeAt(0) persist() pump() } /** Starts sending the queue, one event per task, unless a send is already under way. */ private fun pump() { if (pumping || !canSend() || queue.isEmpty()) return pumping = true submit { sendOne() } } private fun sendOne() { var more = false try { if (!canSend() || queue.isEmpty()) return val event = queue[0] val outcome = post(event) if (outcome == Outcome.RETRY) { scheduleRetry() return } removeEvent(event) if (outcome == Outcome.OK) resetBackoff() persist() more = canSend() && queue.isNotEmpty() } finally { if (more) { submit { sendOne() } } else { pumping = false } } } private fun removeEvent(event: JSONObject) { for (index in queue.indices) { if (queue[index] === event) { queue.removeAt(index) return } } } private fun scheduleRetry() { if (retryTask != null || !canSend()) return val delay = backoffMs backoffMs = minOf(backoffMs * 2L, MAX_BACKOFF_MS) try { retryTask = executor.schedule( Runnable { retryTask = null try { pump() } catch (e: Throwable) { log("Retry failed.", e) } }, delay, TimeUnit.MILLISECONDS, ) } catch (e: Exception) { retryTask = null } } private fun resetBackoff() { backoffMs = INITIAL_BACKOFF_MS val task = retryTask retryTask = null if (task != null) task.cancel(false) } private fun post(body: JSONObject): Outcome { var connection: HttpURLConnection? = null try { val bytes = body.toString().toByteArray(Charsets.UTF_8) val opened = URL(endpoint).openConnection() as HttpURLConnection connection = opened opened.requestMethod = "POST" opened.connectTimeout = TIMEOUT_MS opened.readTimeout = TIMEOUT_MS opened.doOutput = true opened.useCaches = false opened.setFixedLengthStreamingMode(bytes.size) opened.setRequestProperty("Content-Type", "application/json") opened.setRequestProperty("User-Agent", "CrispStats-Mobile/$VERSION") val output = opened.outputStream try { output.write(bytes) } finally { output.close() } return outcomeFor(opened.responseCode) } catch (e: Exception) { return Outcome.RETRY } finally { try { connection?.disconnect() } catch (e: Exception) { // Nothing to clean up. } } } private fun outcomeFor(status: Int): Outcome { if (status in 200..299) return Outcome.OK if (status == 408 || status == 429) return Outcome.RETRY if (status in 400..499) return Outcome.DROP return Outcome.RETRY } private fun persist() { val array = JSONArray() for (event in queue) array.put(event) prefs.edit().putString(KEY_QUEUE, array.toString()).apply() } private fun setOptOut(out: Boolean) { load() optedOut = out if (out) { queue.clear() screenName = null screenUrl = null shownAt = null accumulatedMs = 0L leftAt = null resetBackoff() persist() } else if (installId == null) { installId = createInstallId() } prefs.edit().putString(KEY_OPT_OUT, if (out) "1" else "0").apply() if (!out) pump() } private fun submit(block: () -> Unit) { try { executor.execute( Runnable { try { block() } catch (e: Throwable) { log("A background task failed.", e) } }, ) } catch (e: Exception) { log("Could not schedule work.", e) } } private fun log(message: String, error: Throwable? = null) { if (!debug) return try { if (error == null) Log.w(TAG, message) else Log.w(TAG, message, error) } catch (e: Exception) { // Logging is best effort. } } // Activity callbacks, main thread. override fun onActivityStarted(activity: Activity) { startedActivities += 1 if (startedActivities == 1) resume() } override fun onActivityStopped(activity: Activity) { startedActivities = (startedActivities - 1).coerceAtLeast(0) if (startedActivities == 0) leave() } override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {} override fun onActivityResumed(activity: Activity) {} override fun onActivityPaused(activity: Activity) {} override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} override fun onActivityDestroyed(activity: Activity) {} companion object { /** Sent as the SDK version on every event. */ const val VERSION = "1.1.0" /** The production collector. */ const val DEFAULT_API = "https://in.crispstats.com" private const val TAG = "CrispStats" private const val PREFS_NAME = "crispstats" private const val KEY_INSTALL = "cs.install" private const val KEY_QUEUE = "cs.queue" private const val KEY_OPT_OUT = "cs.optout" private const val QUEUE_LIMIT = 100 private const val TIMEOUT_MS = 10_000 private const val INITIAL_BACKOFF_MS = 1_000L private const val MAX_BACKOFF_MS = 60_000L private const val SESSION_GAP_MS = 1_800_000L private const val MAX_SECONDS = 86_400L private const val MAX_SCREEN = 200 private const val MAX_URL = 2_048 private const val MAX_CAMPAIGN_PAIRS = 10 private const val MAX_CAMPAIGN_VALUE = 200 private const val MAX_REFERRER = 2_000 private const val HEX = "0123456789ABCDEF" private val INSTALL = Regex("^[a-f0-9]{32}$") private val CURRENCY = Regex("^[A-Z]{3}$") private val PART = Regex("^[A-Za-z0-9][A-Za-z0-9 ._-]*$") private val APP_ID = Regex("^[A-Za-z0-9][A-Za-z0-9._-]*$") private val CAMPAIGN_KEY = Regex("^[a-z0-9_]{1,32}$") private val RESERVED = setOf("app_version", "app_build", "os_version", "sdk", "sdk_version") /** * The campaign pairs in a deep link's query string, under the same * rules [screen] applies: lower-case keys of letters, digits and `_` * up to 32 characters, trimmed values of 1 to 200 characters, at most * 10 pairs, sorted by key. Never throws. */ @JvmStatic fun campaignFrom(url: String): Map { try { var rest = url val hash = rest.indexOf('#') if (hash >= 0) rest = rest.substring(0, hash) val question = rest.indexOf('?') if (question < 0) return emptyMap() val found = LinkedHashMap() for (part in rest.substring(question + 1).split("&")) { if (part.isEmpty()) continue val equals = part.indexOf('=') val rawKey = if (equals >= 0) part.substring(0, equals) else part val rawValue = if (equals >= 0) part.substring(equals + 1) else "" val key = decode(rawKey) ?: continue val value = decode(rawValue) ?: continue val lower = key.lowercase(Locale.US) if (found.containsKey(lower) || !CAMPAIGN_KEY.matches(lower)) continue // An empty or oversized value does not claim the key, so a later repeat can. val trimmed = value.trim() if (trimmed.isNotEmpty() && trimmed.length <= MAX_CAMPAIGN_VALUE) found.put(lower, trimmed) } return campaignPairs(found) } catch (e: Exception) { return emptyMap() } } /** Same as JavaScript's decodeURIComponent after `+` becomes a space: null on a bad escape or invalid UTF-8. */ private fun decode(raw: String): String? { try { val text = raw.replace('+', ' ') val out = StringBuilder(text.length) var index = 0 while (index < text.length) { if (text[index] != '%') { out.append(text[index]) index += 1 continue } val bytes = ArrayList() while (index < text.length && text[index] == '%') { if (index + 2 >= text.length) return null val high = Character.digit(text[index + 1], 16) val low = Character.digit(text[index + 2], 16) if (high < 0 || low < 0) return null bytes.add((high * 16 + low).toByte()) index += 3 } val decoder = Charsets.UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT) out.append(decoder.decode(ByteBuffer.wrap(bytes.toByteArray())).toString()) } return out.toString() } catch (e: Exception) { return null } } /** The bytes URLSearchParams writes: letters, digits and `*-._` kept, space as `+`, the rest as UTF-8 `%XX`. */ private fun encode(raw: String): String { val out = StringBuilder(raw.length) for (byte in wellFormed(raw).toByteArray(Charsets.UTF_8)) { val code = byte.toInt() and 0xFF val kept = (code in 0x61..0x7A) || (code in 0x41..0x5A) || (code in 0x30..0x39) || code == 0x2A || code == 0x2D || code == 0x2E || code == 0x5F if (kept) { out.appendCodePoint(code) } else if (code == 0x20) { out.append('+') } else { out.append('%') out.append(HEX[code shr 4]) out.append(HEX[code and 0x0F]) } } return out.toString() } /** Lone surrogates become U+FFFD, as in the reference client. */ private fun wellFormed(text: String): String { val out = StringBuilder(text.length) var index = 0 while (index < text.length) { val char = text[index] if (Character.isHighSurrogate(char) && index + 1 < text.length && Character.isLowSurrogate(text[index + 1])) { out.append(char) out.append(text[index + 1]) index += 2 } else { out.append(if (Character.isSurrogate(char)) '\uFFFD' else char) index += 1 } } return out.toString() } private fun campaignPairs(raw: Map?): Map { val sorted = TreeMap() if (raw == null) return sorted // The original keys in sorted order, so of two keys that differ only in case the first sorted wins. val keys = ArrayList() for (rawKey in raw.keys) { val candidate: Any? = rawKey if (candidate is String) keys.add(candidate) } for (rawKey in keys.sorted()) { val rawValue: Any? = raw[rawKey] if (rawValue !is String) continue val key = rawKey.lowercase(Locale.US) val value = rawValue.trim() if (!CAMPAIGN_KEY.matches(key)) continue if (value.isEmpty() || value.length > MAX_CAMPAIGN_VALUE) continue if (!sorted.containsKey(key)) sorted.put(key, value) } val out = LinkedHashMap() for (entry in sorted.entries) { if (out.size >= MAX_CAMPAIGN_PAIRS) break out.put(entry.key, entry.value) } return out } /** Adds the pairs as a query string. Drops pairs from the end if the URL would pass 2,048 characters. */ private fun withQuery(base: String, pairs: Map): String { val parts = ArrayList() for (entry in pairs.entries) parts.add(entry.key + "=" + encode(entry.value)) while (parts.isNotEmpty()) { val url = base + "?" + parts.joinToString("&") if (url.length <= MAX_URL) return url parts.removeAt(parts.size - 1) } return base } private fun cleanReferrer(raw: String?): String? { if (raw == null) return null val trimmed = raw.trim() if (trimmed.isEmpty() || trimmed.length > MAX_REFERRER) return null return trimmed } /** Same rules as `screenPath` in the shared package. */ private fun screenPath(name: String): String? { val parts = ArrayList() for (piece in name.split("/")) { val trimmed = piece.trim() if (trimmed.isNotEmpty()) parts.add(trimmed) } if (parts.isEmpty() || parts.size > 8) return null for (part in parts) { if (part == "." || part == ".." || part.length > 80 || !PART.matches(part)) return null } val path = "/" + parts.joinToString("/") return if (path.length <= MAX_SCREEN) path else null } private fun cleanProps(raw: Map?): JSONObject? { if (raw == null) return null val out = JSONObject() for (entry in raw.entries) { if (out.length() >= 30) break val key = entry.key.trim().take(60) if (key.isEmpty() || RESERVED.contains(key)) continue val value = entry.value if (value == null) { out.put(key, JSONObject.NULL) } else if (value is String) { out.put(key, value.take(500)) } else if (value is Boolean) { out.put(key, value) } else if (value is Int) { out.put(key, value) } else if (value is Long) { out.put(key, value) } else if (value is Double) { if (!value.isNaN() && !value.isInfinite()) out.put(key, value) } else if (value is Float) { if (!value.isNaN() && !value.isInfinite()) out.put(key, value.toDouble()) } else { out.put(key, value.toString().take(500)) } } return if (out.length() == 0) null else out } private fun configProblem(site: String, appId: String, appVersion: String): String? { if (!site.startsWith("cs_pk_") || site.length > 64) { return "the site key must be the site's public key, which starts with cs_pk_." } if (appId.length > 200 || !APP_ID.matches(appId)) { return "appId \"$appId\" must start with a letter or digit and use only letters, digits, '.', '_' and '-'." } if (appVersion.isEmpty()) return "appVersion is empty." return null } private fun cleanBuild(raw: String?): String? { if (raw == null) return null val trimmed = raw.trim().take(32) return if (trimmed.isEmpty()) null else trimmed } private fun cleanOsVersion(raw: String): String { val trimmed = raw.trim().take(32) return if (trimmed.isEmpty()) "unknown" else trimmed } private fun detectDevice(context: Context): Device { return try { if (context.resources.configuration.smallestScreenWidthDp >= 600) Device.TABLET else Device.PHONE } catch (e: Exception) { Device.PHONE } } private fun isDebuggable(context: Context): Boolean { return try { (context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0 } catch (e: Exception) { false } } private fun languageTag(): String? { return try { val tag = Locale.getDefault().toLanguageTag().take(35) if (tag.isEmpty()) null else tag } catch (e: Exception) { null } } private fun timeZoneId(): String? { return try { val id = TimeZone.getDefault().id.take(64) if (id.isEmpty()) null else id } catch (e: Exception) { null } } } }