/* * Viewthrough SDK for Android — one file, no dependencies. * * Drop this file into your app module (for example * app/src/main/java/app/viewthrough/sdk/Viewthrough.kt) and call * Viewthrough.init(this, key = "vts_…") in Application.onCreate(). Needs * android.permission.INTERNET, nothing else. * * Identity is the heart of it, not the events: a random device_id is made on * the first start and kept in SharedPreferences (survives logout, not * reinstall) — that is the install. After login, identify(userId) adds the * user id to everything from then on. Give RevenueCat the SAME id * (Purchases.sharedInstance.logIn(userId)), or Viewthrough cannot tie * purchases to installs. * * Only the money events exist (install, app_open, onboarding_started, * onboarding_completed, paywall_shown, checkout_started, trial_started, * purchase); anything else is rejected by the server on purpose. Trials and * purchases from the store come from the RevenueCat webhook; the two here * mean "what the app saw". * * Sending: events go to an on-device queue and leave in batches — after 20 * events or every 30 seconds, whichever comes first; flush() sends now and * the SDK flushes when the app goes to the background. Offline or server * error: the queue stays, retried with backoff (1 s → 5 min). A batch the * server rejects as malformed (400) is dropped; a wrong key (401) stops * sending until the next start, the queue is kept. Every event carries a * UUID, so a batch sent twice counts once. At most 5,000 events are kept * offline; beyond that the oldest go. * * Consent: with Options(requireConsent = true) nothing is written to * SharedPreferences and nothing is sent until optIn() — for apps whose consent * dialog decides whether attribution may run (ePrivacy Art. 5(3), German * TDDDG § 25). The choice is remembered; optOut() withdraws it. * * All work runs on one daemon thread; public methods never block. * Behaviour mirrors @viewthrough/sdk (packages/sdk/src/client.ts). */ package app.viewthrough.sdk import android.app.Activity import android.app.Application import android.content.Context import android.content.SharedPreferences import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.util.Log import org.json.JSONArray import org.json.JSONObject import java.io.IOException import java.net.HttpURLConnection import java.net.URL import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.TimeZone import java.util.UUID import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit class Viewthrough private constructor( private val key: String, private val options: Options, private val prefs: SharedPreferences?, private val noop: Boolean, ) { /** Defaults match @viewthrough/sdk. */ data class Options( /** Defaults to https://viewthrough.app/api/v1/events. */ val endpoint: String = DEFAULT_ENDPOINT, /** Send after this many queued events (default 20, server max 100). */ val flushAt: Int = 20, /** Send at least this often while something is queued (default 30 s). */ val flushIntervalMs: Long = 30_000L, /** Keep at most this many events offline (default 5,000); the oldest go first. */ val maxQueue: Int = 5_000, /** Send `app_open` on init (default true). */ val trackAppOpen: Boolean = true, /** Wait for consent (default false): store nothing and send nothing until optIn(). Remembered across starts. */ val requireConsent: Boolean = false, /** Log what the SDK does with Log.d. Warnings are always logged. */ val debug: Boolean = false, /** Your app's version; defaults to the versionName from the package manager. */ val appVersion: String? = null, /** Defaults to Build.VERSION.RELEASE. */ val osVersion: String? = null, /** e.g. "de-DE"; defaults to the device locale. */ val locale: String? = null, /** ios | android | web | unknown. */ val platform: String = "android", /** SharedPreferences file that holds the device id and the offline queue. */ val preferencesName: String = "viewthrough", ) companion object { const val SDK_NAME = "viewthrough-android" const val SDK_VERSION = "0.2.0" const val DEFAULT_ENDPOINT = "https://viewthrough.app/api/v1/events" private const val TAG = "Viewthrough" private const val HTTP_TIMEOUT_MS = 15_000 /** The instance made by init(); null before that. */ @Volatile @JvmStatic var shared: Viewthrough? = null private set /** * Create the client once, in Application.onCreate(). A key that is not * an SDK key (`vts_…` from Sources → SDK in Viewthrough) logs a warning * and returns an instance that does nothing — the app never crashes * over analytics. */ @JvmStatic @JvmOverloads fun init(context: Context, key: String, options: Options = Options()): Viewthrough { val appContext = context.applicationContext val instance = if (!ViewthroughCore.isValidKey(key)) { Log.w(TAG, "init: `key` must be the app's SDK key (vts_…) from Sources → SDK; the SDK is disabled") Viewthrough(key, options, null, noop = true) } else { val platform = if (options.platform in ViewthroughCore.PLATFORMS) options.platform else { Log.w(TAG, "init: platform \"${options.platform}\" is not ios|android|web; sending \"unknown\"") "unknown" } val resolved = options.copy( platform = platform, appVersion = options.appVersion ?: versionNameOf(appContext), osVersion = options.osVersion ?: Build.VERSION.RELEASE, locale = options.locale ?: Locale.getDefault().toLanguageTag(), ) val prefs = appContext.getSharedPreferences(resolved.preferencesName, Context.MODE_PRIVATE) Viewthrough(key, resolved, prefs, noop = false).also { it.start(appContext) } } shared = instance return instance } private fun versionNameOf(context: Context): String? = try { val pm = context.packageManager val info = if (Build.VERSION.SDK_INT >= 33) { pm.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(0)) } else { @Suppress("DEPRECATION") pm.getPackageInfo(context.packageName, 0) } info.versionName } catch (_: Exception) { null } } private val ns = if (noop) "" else ViewthroughCore.namespace(key) private val executor: ScheduledExecutorService? = if (noop) null else Executors.newSingleThreadScheduledExecutor { r -> Thread(r, "viewthrough").apply { isDaemon = true } } // Touched only on the executor thread, except the two volatile reads below. private var state: ViewthroughCore.State = ViewthroughCore.State(deviceId = "") private var queue: List = emptyList() private var attempt = 0 private var stopped = false private var nextAllowedAt = 0L private var timer: ScheduledFuture<*>? = null private var timerDueAt = Long.MAX_VALUE /** Whether `state` is in SharedPreferences. False only while a fresh install waits for consent. */ private var onDisk = false /** requireConsent and no optIn() yet (or consent withdrawn). Worker thread. */ private val pending: Boolean get() = options.requireConsent && !state.consent @Volatile private var deviceIdValue: String = "" @Volatile private var optedOutValue: Boolean = false /** The install id: made on the first start, kept until the app is uninstalled. Empty when the SDK is disabled. */ val deviceId: String get() = deviceIdValue val isOptedOut: Boolean get() = optedOutValue @Volatile private var collectingValue: Boolean = false /** Whether the SDK collects right now: not opted out and, with requireConsent, consented. */ val isCollecting: Boolean get() = collectingValue private fun updateFlags() { optedOutValue = state.optedOut collectingValue = !noop && !pending && !state.optedOut } // ------------------------------------------------------------------ start private fun start(app: Context) { val prefs = prefs ?: return // The state is tiny and read once, synchronously, so deviceId is // available right after init(); the queue is parsed on the worker. val loaded = ViewthroughCore.parseState(prefs.getString("$ns:state", null)) val firstStart = loaded == null val nowMs = System.currentTimeMillis() state = loaded ?: ViewthroughCore.State(deviceId = UUID.randomUUID().toString(), installedAt = ViewthroughCore.iso(nowMs)) deviceIdValue = state.deviceId onDisk = !firstStart updateFlags() if (firstStart) persistState() run { queue = ViewthroughCore.parseQueue(prefs.getString("$ns:queue", null)) if (firstStart && pending) { // Waiting for consent: the id lives in memory only, nothing is sent. debug("requireConsent: nothing is stored or sent until optIn()") } else { // First start on this device: that is the install. if (firstStart) enqueueNow("install", null, null, nowMs) if (pending) { // Stored by an earlier version without consent, or consent // withdrawn: only a pending opt-out still leaves the device. val before = queue.size queue = queue.filter { it.event == "opt_out" || it.event == "opt_in" } if (queue.size != before) persistQueue() } else if (options.trackAppOpen && !state.optedOut) { enqueueNow("app_open", null, null, nowMs) } schedule(0) } } (app as? Application)?.registerActivityLifecycleCallbacks(BackgroundFlush()) } /** Flush when the last activity stops — the app is going to the background. */ private inner class BackgroundFlush : Application.ActivityLifecycleCallbacks { private var started = 0 override fun onActivityStarted(activity: Activity) { started += 1 } override fun onActivityStopped(activity: Activity) { started = maxOf(0, started - 1) if (started == 0) flush() } 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) {} } // ----------------------------------------------------------------- events /** Record one of the money events. Unknown names are logged and ignored. */ @JvmOverloads fun track(event: String, props: Map? = null) { if (event !in ViewthroughCore.COUNT_EVENTS) { warn("track: \"$event\" is not a Viewthrough event; use one of ${ViewthroughCore.COUNT_EVENTS.joinToString(", ")}") return } enqueue(event, props) } @JvmOverloads fun onboardingStarted(props: Map? = null) = track("onboarding_started", props) @JvmOverloads fun onboardingCompleted(props: Map? = null) = track("onboarding_completed", props) /** e.g. surface = "onboarding" | "settings" | "feature_gate" */ @JvmOverloads fun paywallShown(surface: String? = null, props: Map? = null) = track("paywall_shown", merge(props, "surface" to surface)) @JvmOverloads fun checkoutStarted(productId: String? = null, plan: String? = null, props: Map? = null) = track("checkout_started", merge(props, "product_id" to productId, "plan" to plan)) /** What the app saw. The store's view comes from RevenueCat. */ @JvmOverloads fun trialStarted(productId: String? = null, props: Map? = null) = track("trial_started", merge(props, "product_id" to productId)) @JvmOverloads fun purchase(productId: String? = null, plan: String? = null, props: Map? = null) = track("purchase", merge(props, "product_id" to productId, "plan" to plan)) /** Call on foreground if you want app opens beyond cold starts. */ fun appOpened() = track("app_open") // --------------------------------------------------------------- identity /** After login. Use the same id for RevenueCat (`Purchases.logIn`). */ fun identify(userId: String) { val id = userId.trim() if (!ViewthroughCore.isValidUserId(id)) { warn("identify: user id must be a non-empty string without whitespace (max 128)") return } val atMs = System.currentTimeMillis() post { if (pending || state.userId == id) return@post state = state.copy(userId = id) persistState() enqueueNow("identify", null, id, atMs) } } /** * Where this install came from: the onboarding question * (acquisitionSource) and/or the tracking-link campaign * (installUtmCampaign from the Play Install Referrer). Stored on the * device, not counted as an event. `extra` takes further keys such as * install_utm_source, install_utm_medium, install_referrer. */ @JvmOverloads fun setAttribution( acquisitionSource: String? = null, installUtmCampaign: String? = null, extra: Map = emptyMap(), ) { val raw = LinkedHashMap() raw["acquisition_source"] = acquisitionSource raw["install_utm_campaign"] = installUtmCampaign raw.putAll(extra) val clean = ViewthroughCore.cleanAttribution(raw) { k -> warn("setAttribution: key \"${k.take(40)}\" ignored: letters, digits and _ only (max 64)") } if (clean.isEmpty()) return enqueue("set_attribution", clean) } /** On logout: forget the user id. The device id stays — it is still the same install. */ fun reset() = post { if (state.userId == null) return@post state = state.copy(userId = null) persistState() } /** * Stop collecting and tell the server to drop this device from every * count. Events still waiting on the device are discarded, not sent. * Before any consent (requireConsent, nothing stored yet) there is * nothing to undo. */ fun optOut() { val atMs = System.currentTimeMillis() post { if (state.optedOut || !onDisk) return@post queue = emptyList() state = state.copy(optedOut = true, consent = if (options.requireConsent) false else state.consent) updateFlags() enqueueNow("opt_out", null, null, atMs) persistState() drain() } } /** * Resume after optOut() — or, with requireConsent, the user's consent: * only from here on is the device id stored and anything sent. */ fun optIn() { val atMs = System.currentTimeMillis() post { val wasPending = pending val wasOptedOut = state.optedOut if (!wasPending && !wasOptedOut) return@post val fresh = !onDisk state = state.copy( optedOut = false, consent = options.requireConsent || state.consent, installedAt = if (fresh) ViewthroughCore.iso(atMs) else state.installedAt, ) updateFlags() persistState() // Consent on a fresh install: from here on it is the first start. if (fresh) enqueueNow("install", null, null, atMs) if (wasOptedOut) enqueueNow("opt_in", null, null, atMs) if (wasPending && options.trackAppOpen) enqueueNow("app_open", null, null, atMs) } } // ---------------------------------------------------------------- sending /** Send everything queued now, on the worker thread. Safe to call often. */ @JvmOverloads fun flush(onDone: (() -> Unit)? = null) { if (noop) { onDone?.invoke() return } post { drain() onDone?.invoke() } } /** Stop the timer (tests, process teardown). Queued events stay on disk. */ fun close() = post { timer?.cancel(false) timer = null timerDueAt = Long.MAX_VALUE } // --------------------------------------------------------------- internal private fun post(block: () -> Unit) { val ex = executor ?: return try { ex.execute { try { block() } catch (e: Exception) { warn("internal error: $e") } } } catch (_: Exception) { // executor shut down — nothing to do } } private fun enqueue(event: String, props: Map?, userId: String? = null) { val atMs = System.currentTimeMillis() post { if (pending) return@post if (state.optedOut && event != "opt_in" && event != "opt_out") return@post enqueueNow(event, props, userId, atMs) } } /** Worker thread only. */ private fun enqueueNow(event: String, props: Map?, userId: String?, atMs: Long) { val q = ViewthroughCore.Event( eventId = UUID.randomUUID().toString(), event = event, ts = ViewthroughCore.iso(atMs), userId = userId ?: state.userId, props = ViewthroughCore.cleanProps(props) { k -> warn("prop key \"${k.take(40)}\" ignored: letters, digits and _ only (max 64)") }, ) val pushed = ViewthroughCore.push(queue, q, options.maxQueue) queue = pushed.queue if (pushed.dropped > 0) warn("queue full (${options.maxQueue}), dropped ${pushed.dropped} oldest event(s)") persistQueue() debug("queued $event (${queue.size} waiting)") if (queue.size >= options.flushAt) schedule(0) else schedule(options.flushIntervalMs) } /** Worker thread only. */ private fun schedule(inMs: Long) { val ex = executor ?: return if (stopped || queue.isEmpty()) return val now = System.currentTimeMillis() val delay = maxOf(inMs, nextAllowedAt - now) val pending = timer if (pending != null) { // An earlier timer wins; a shorter one replaces it. if (delay >= timerDueAt - now) return pending.cancel(false) } timerDueAt = now + delay timer = ex.schedule({ timer = null timerDueAt = Long.MAX_VALUE drain() }, delay, TimeUnit.MILLISECONDS) } /** Worker thread only. Sends batch after batch until the queue is empty or a send fails. */ private fun drain() { while (queue.isNotEmpty() && !stopped) { val now = System.currentTimeMillis() if (now < nextAllowedAt) { schedule(nextAllowedAt - now) return } val batch = ViewthroughCore.nextBatch(queue, maxOf(options.flushAt, ViewthroughCore.SERVER_MAX_BATCH)) val status = send(batch) when (ViewthroughCore.outcomeFor(status)) { ViewthroughCore.Outcome.SENT -> { queue = ViewthroughCore.remove(queue, batch) attempt = 0 persistQueue() debug("sent ${batch.size} event(s)") } ViewthroughCore.Outcome.DROP -> { queue = ViewthroughCore.remove(queue, batch) persistQueue() warn("server rejected ${batch.size} event(s) with HTTP $status; dropped") } ViewthroughCore.Outcome.STOP -> { stopped = true warn("HTTP $status: the SDK key is unknown or revoked — events stay queued until the next start") return } ViewthroughCore.Outcome.RETRY -> { attempt += 1 val wait = ViewthroughCore.backoffMs(attempt) nextAllowedAt = System.currentTimeMillis() + wait debug("send failed (${status ?: "network"}), retry in ${wait / 1000} s") schedule(wait) return } } } } /** One HTTP POST; the status code, or null when the network failed. */ private fun send(batch: List): Int? { val body = ViewthroughCore.batchJson( deviceId = state.deviceId, userId = state.userId, platform = options.platform, appVersion = options.appVersion, osVersion = options.osVersion, locale = options.locale, sentAt = ViewthroughCore.iso(System.currentTimeMillis()), events = batch, ).toByteArray(Charsets.UTF_8) var conn: HttpURLConnection? = null return try { conn = (URL(options.endpoint).openConnection() as HttpURLConnection).apply { requestMethod = "POST" connectTimeout = HTTP_TIMEOUT_MS readTimeout = HTTP_TIMEOUT_MS doOutput = true setRequestProperty("Content-Type", "application/json") setRequestProperty("Authorization", "Bearer $key") setRequestProperty("Content-Length", body.size.toString()) setFixedLengthStreamingMode(body.size) } conn.outputStream.use { it.write(body) } val status = conn.responseCode // Read and discard so the connection can be reused. try { (if (status >= 400) conn.errorStream else conn.inputStream)?.use { s -> while (s.read() != -1) { /* drain */ } } } catch (_: IOException) { // body unreadable — the status is what matters } status } catch (_: Exception) { null } finally { conn?.disconnect() } } private fun persistState() { // Before consent on a fresh install nothing touches the device. if (!onDisk && pending) return onDisk = true prefs?.edit()?.putString("$ns:state", ViewthroughCore.stateJson(state))?.apply() } private fun persistQueue() { val p = prefs ?: return if (queue.isEmpty()) p.edit().remove("$ns:queue").apply() else p.edit().putString("$ns:queue", ViewthroughCore.queueJson(queue)).apply() } private fun merge(props: Map?, vararg named: Pair): Map? { val out = LinkedHashMap() for ((k, v) in named) if (v != null) out[k] = v if (props != null) out.putAll(props) return if (out.isEmpty()) null else out } private fun warn(msg: String) { Log.w(TAG, msg) } private fun debug(msg: String) { if (options.debug) Log.d(TAG, msg) } } /** * The pure part: queue arithmetic, validation, JSON writing. No Android * imports, so it runs — and is tested — on a plain JVM. */ internal object ViewthroughCore { val COUNT_EVENTS: List = listOf( "install", "app_open", "onboarding_started", "onboarding_completed", "paywall_shown", "checkout_started", "trial_started", "purchase", ) val CONTROL_EVENTS: List = listOf("identify", "set_attribution", "opt_out", "opt_in") val PLATFORMS: List = listOf("ios", "android", "web", "unknown") /** The server takes at most this many events per request. */ const val SERVER_MAX_BATCH = 100 private val KEY_RE = Regex("^vts_[A-Za-z0-9_-]{43}$") private val WHITESPACE = Regex("\\s") data class State( val deviceId: String, val userId: String? = null, val optedOut: Boolean = false, val installedAt: String? = null, /** Only meaningful with requireConsent: the user agreed via optIn(). */ val consent: Boolean = false, ) /** What goes over the wire, one per event. */ data class Event( val eventId: String, val event: String, val ts: String, val userId: String? = null, val props: Map? = null, ) data class Pushed(val queue: List, val dropped: Int) enum class Outcome { SENT, DROP, STOP, RETRY } fun isValidKey(key: String): Boolean = KEY_RE.matches(key) /** Storage namespace per key, so two keys on one device never share a queue. */ fun namespace(key: String): String = "vt:" + key.substring(4, 12) fun isValidUserId(id: String): Boolean = id.isNotEmpty() && id.length <= 128 && !WHITESPACE.containsMatchIn(id) /** Backoff after a failed send: 1 s, 2 s, 4 s … capped at 5 min. */ fun backoffMs(attempt: Int): Long { val exp = minOf(30, maxOf(0, attempt - 1)) return minOf(300_000L, 1000L * (1L shl exp)) } /** Append, dropping the oldest beyond `max` — the only place events are lost on purpose. */ fun push(queue: List, event: Event, max: Int): Pushed { val next = queue + event val dropped = maxOf(0, next.size - max) return Pushed(if (dropped > 0) next.drop(dropped) else next, dropped) } /** The next batch to send: the oldest events, at most what the server takes. */ fun nextBatch(queue: List, flushAt: Int): List = queue.take(minOf(SERVER_MAX_BATCH, maxOf(1, flushAt))) /** Remove the events of a sent batch (by id — the queue may have grown meanwhile). */ fun remove(queue: List, sent: List): List { val ids = sent.mapTo(HashSet()) { it.eventId } return queue.filter { it.eventId !in ids } } /** * What to do with an HTTP status: * SENT 202 — remove the batch * DROP 4xx that a retry won't fix (400, 413) — remove and warn * STOP 401/403 — key wrong: keep the queue, stop trying until next init * RETRY 429, 5xx, network — keep, back off */ fun outcomeFor(status: Int?): Outcome = when { status == null -> Outcome.RETRY status == 202 || status == 200 -> Outcome.SENT status == 401 || status == 403 -> Outcome.STOP status == 429 || status >= 500 -> Outcome.RETRY status >= 400 -> Outcome.DROP else -> Outcome.RETRY } /** * The server accepts only keys of letters, digits and `_` (max 64) — and * rejects the WHOLE batch (HTTP 400, install included) when one key is * off. So bad keys are dropped here, reported via [onDrop], instead of * taking the install down with them. */ val PROP_KEY = Regex("^[A-Za-z0-9_]{1,64}$") /** Strings cut to 256, numbers and booleans as they are, nothing else; null when nothing is left. */ fun cleanProps(props: Map?, onDrop: ((String) -> Unit)? = null): Map? { if (props == null) return null val out = LinkedHashMap() for ((k, v) in props) { if (!PROP_KEY.matches(k)) { onDrop?.invoke(k) continue } val c = cleanValue(v) ?: continue out[k] = c } return if (out.isEmpty()) null else out } /** Like cleanProps, but empty strings are skipped too (an unanswered question is no answer). */ fun cleanAttribution(attribution: Map, onDrop: ((String) -> Unit)? = null): Map { val out = LinkedHashMap() for ((k, v) in attribution) { if (!PROP_KEY.matches(k)) { onDrop?.invoke(k) continue } if (v is String && v.isEmpty()) continue val c = cleanValue(v) ?: continue out[k] = c } return out } private fun cleanValue(v: Any?): Any? = when (v) { null -> null is String -> v.take(256) is Boolean -> v is Double -> if (v.isFinite()) v else null is Float -> if (v.isFinite()) v else null is Number -> v else -> null } /** ISO 8601 in UTC with milliseconds, e.g. 2026-11-05T17:02:16.805Z. */ fun iso(ms: Long): String { val f = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US) f.timeZone = TimeZone.getTimeZone("UTC") return f.format(Date(ms)) } // ------------------------------------------------------------- JSON out fun quote(s: String): String { val sb = StringBuilder(s.length + 2).append('"') for (c in s) { when (c) { '"' -> sb.append("\\\"") '\\' -> sb.append("\\\\") '\n' -> sb.append("\\n") '\r' -> sb.append("\\r") '\t' -> sb.append("\\t") '\b' -> sb.append("\\b") '\u000C' -> sb.append("\\f") else -> if (c < ' ') sb.append(String.format(Locale.US, "\\u%04x", c.code)) else sb.append(c) } } return sb.append('"').toString() } fun value(v: Any?): String = when (v) { null -> "null" is String -> quote(v) is Boolean -> v.toString() is Double -> if (v.isFinite()) v.toString() else "null" is Float -> if (v.isFinite()) v.toString() else "null" is Number -> v.toString() is Map<*, *> -> v.entries.joinToString(",", "{", "}") { (k, x) -> quote(k.toString()) + ":" + value(x) } is List<*> -> v.joinToString(",", "[", "]") { value(it) } else -> quote(v.toString()) } private fun obj(fields: List>): String = fields.filter { it.second != null }.joinToString(",", "{", "}") { (k, v) -> quote(k) + ":" + value(v) } fun eventJson(e: Event): String = obj( listOf("event_id" to e.eventId, "event" to e.event, "ts" to e.ts, "user_id" to e.userId, "props" to e.props), ) fun queueJson(queue: List): String = queue.joinToString(",", "[", "]") { eventJson(it) } fun stateJson(state: State): String = obj( listOf( "device_id" to state.deviceId, "user_id" to state.userId, "opted_out" to (if (state.optedOut) true else null), "installed_at" to state.installedAt, "consent" to (if (state.consent) true else null), ), ) fun batchJson( deviceId: String, userId: String?, platform: String, appVersion: String?, osVersion: String?, locale: String?, sentAt: String, events: List, ): String { val head = obj( listOf( "device_id" to deviceId, "user_id" to userId, "platform" to platform, "app_version" to appVersion, "os_version" to osVersion, "locale" to locale, "sdk" to mapOf("name" to Viewthrough.SDK_NAME, "version" to Viewthrough.SDK_VERSION), "sent_at" to sentAt, ), ) return head.dropLast(1) + ",\"events\":" + queueJson(events) + "}" } // -------------------------------------------------------------- JSON in // Parsing uses org.json from the Android SDK (not available on a plain // JVM) — kept here so the whole persistence format lives in one place. fun parseState(raw: String?): State? { if (raw.isNullOrEmpty()) return null return try { val o = JSONObject(raw) val id = o.optString("device_id", "") if (id.length < 8) return null State( deviceId = id, userId = o.optString("user_id", "").ifEmpty { null }, optedOut = o.optBoolean("opted_out", false), installedAt = o.optString("installed_at", "").ifEmpty { null }, consent = o.optBoolean("consent", false), ) } catch (_: Exception) { null } } fun parseQueue(raw: String?): List { if (raw.isNullOrEmpty()) return emptyList() return try { val arr = JSONArray(raw) val out = ArrayList(arr.length()) for (i in 0 until arr.length()) { val o = arr.optJSONObject(i) ?: continue val id = o.optString("event_id", "") val event = o.optString("event", "") if (id.isEmpty() || event.isEmpty()) continue var props: Map? = null val p = o.optJSONObject("props") if (p != null) { val m = LinkedHashMap() val keys = p.keys() while (keys.hasNext()) { val k = keys.next() when (val v = p.opt(k)) { is String, is Boolean, is Number -> m[k] = v } } if (m.isNotEmpty()) props = m } out.add(Event(id, event, o.optString("ts", ""), o.optString("user_id", "").ifEmpty { null }, props)) } out } catch (_: Exception) { emptyList() } } }