package com.submetry import android.content.Context import android.os.Build import org.json.JSONArray import org.json.JSONObject import java.net.HttpURLConnection import java.net.URL import java.util.Locale import java.util.TimeZone import java.util.UUID import java.util.concurrent.Future import java.util.concurrent.ScheduledThreadPoolExecutor import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit import kotlin.math.min /** Source adapter. All storage/network work runs on a single background executor. */ class Submetry( context: Context, private val appId: String, private val publicKey: String, private val environment: String = "production", userId: String? = null, private val endpoint: String = "https://api.submetry.com/v1/events", private val extraContext: Map = emptyMap(), private val onError: (String) -> Unit = {}, private val transport: (String, String, String) -> Int = ::send ) { private val prefs = context.applicationContext.getSharedPreferences("submetry_$appId", Context.MODE_PRIVATE) private val executor = ScheduledThreadPoolExecutor(1) private var state: JSONObject private var session = id("sess_") private var failures = 0 private var nextAttempt = 0L private var timer: ScheduledFuture<*>? = null @Volatile private var stopped = false private val metadata = JSONObject(extraContext).put("platform", "android").put("environment", environment) .put("device_model", "${Build.MANUFACTURER} ${Build.MODEL}").put("os_version", Build.VERSION.RELEASE) .put("locale", Locale.getDefault().toLanguageTag()).put("timezone", TimeZone.getDefault().id) init { val url = URL(endpoint) require(appId.isNotEmpty() && appId.length <= 128 && publicKey.startsWith("sub_pk_") && environment in listOf("production", "debug", "sandbox", "testflight") && (url.protocol == "https" || url.host in listOf("localhost", "127.0.0.1"))) { "Invalid Submetry configuration" } require(extraContext.values.all { it.length <= 256 } && metadata.toString().toByteArray(Charsets.UTF_8).size <= 8192) { "Invalid context" } require(userId == null || userId.isNotEmpty() && userId.length <= 128) { "Invalid user ID" } // A corrupt queue aborts construction without overwriting app-private data. state = prefs.getString("queue", null)?.let { JSONObject(it) } ?: JSONObject().put("anonymousId", id("anon_")).put("firstOpenRecorded", false).put("events", JSONArray()) require(state.optString("anonymousId").isNotEmpty() && state.optJSONArray("events") != null) { "Invalid persisted queue; preserve for recovery" } if (userId != null) state.put("userId", userId) submit { if (!state.optBoolean("firstOpenRecorded")) record("first_open", JSONObject()); record("session_start", JSONObject()); record("app_open", JSONObject()); later(10000) } } private fun submit(action: () -> Unit): Future<*> = executor.submit { if (!stopped) try { action() } catch (e: Exception) { report(e.message ?: "Telemetry failed") } } private fun report(message: String) { try { onError(message) } catch (_: Exception) {} } private fun persist(next: JSONObject) { check(prefs.edit().putString("queue", next.toString()).commit()) { "Cannot persist telemetry queue" }; state = next } private fun record(name: String, properties: JSONObject) { require(Regex("^[a-z][a-z0-9_]{0,63}$").matches(name) && !name.startsWith("rc_") && properties.toString().toByteArray(Charsets.UTF_8).size <= 8192) { "Invalid SDK event/properties" } val next = JSONObject(state.toString()); val events = next.getJSONArray("events"); check(events.length() < 5000) { "Submetry queue full" } if (name == "first_open") next.put("firstOpenRecorded", true) val event = JSONObject().put("id", id("evt_")).put("ts", System.currentTimeMillis() / 1000.0).put("name", name).put("sid", session).put("aid", next.getString("anonymousId")).put("props", properties).put("context", metadata) if (next.has("userId")) event.put("uid", next.getString("userId")) events.put(event) persist(next) } fun track(name: String, properties: JSONObject = JSONObject()): Future<*> { val copy = JSONObject(properties.toString()); return submit { record(name, copy); later(maxOf(10000, nextAttempt - System.currentTimeMillis())) } } fun identify(userId: String): Future<*> = submit { require(userId.isNotEmpty() && userId.length <= 128); persist(JSONObject(state.toString()).put("userId", userId)); record("identify", JSONObject()) } fun startSession(): Future<*> = submit { session = id("sess_"); record("session_start", JSONObject()); record("app_open", JSONObject()); upload(true) } fun onboardingStep(index: Int, id: String): Future<*> = track("onboarding_step", JSONObject().put("index", index).put("id", id)) fun onboardingCompleted(): Future<*> = track("onboarding_completed") fun paywallShown(id: String): Future<*> = track("paywall_shown", JSONObject().put("paywall", id)) fun paywallDismissed(): Future<*> = track("paywall_dismissed") fun flush(): Future<*> = submit { upload(true) } private fun later(delay: Long) { if (stopped || failures >= 8) return; timer?.cancel(false); timer = executor.schedule({ if (!stopped) upload(false) }, maxOf(delay, 1000), TimeUnit.MILLISECONDS) } private fun upload(force: Boolean) { if (stopped || !force && (failures >= 8 || System.currentTimeMillis() < nextAttempt)) return val events = state.getJSONArray("events"); if (events.length() == 0) return timer?.cancel(false); val batch = JSONArray(); val ids = mutableSetOf() for (i in 0 until min(20, events.length())) { val item = events.getJSONObject(i); if (batch.length() > 0 && batch.toString().toByteArray(Charsets.UTF_8).size + item.toString().toByteArray(Charsets.UTF_8).size > 240000) break; batch.put(item); ids.add(item.getString("id")) } try { val status = transport(endpoint, publicKey, JSONObject().put("app_id", appId).put("events", batch).toString()); if (stopped) return if (status in 200..299 || status in listOf(400, 413, 422)) { if (status in listOf(400, 413, 422)) { val rejected = JSONArray(prefs.getString("rejected", "[]")); for (i in 0 until batch.length()) rejected.put(batch.getJSONObject(i)); check(prefs.edit().putString("rejected", rejected.toString()).commit()); report("Rejected batch archived ($status)") } val keep = JSONArray(); for (i in 0 until events.length()) if (events.getJSONObject(i).getString("id") !in ids) keep.put(events.getJSONObject(i)) persist(JSONObject(state.toString()).put("events", keep)); failures = 0 } else throw IllegalStateException("Upload failed ($status); queue retained") } catch (e: Exception) { failures++; nextAttempt = System.currentTimeMillis() + min(300000L, 1000L * (1L shl min(failures, 8))); report(e.message ?: "Upload failed; queue retained") } later(if (failures > 0) nextAttempt - System.currentTimeMillis() else 10000) } fun stop() { stopped = true; timer?.cancel(false); executor.shutdownNow() } companion object { private fun id(prefix: String) = prefix + UUID.randomUUID().toString() private fun send(endpoint: String, publicKey: String, body: String): Int { val connection = URL(endpoint).openConnection() as HttpURLConnection try { connection.requestMethod = "POST"; connection.connectTimeout = 20000; connection.readTimeout = 20000; connection.instanceFollowRedirects = false; connection.doOutput = true; connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Authorization", "Bearer $publicKey"); connection.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }; return connection.responseCode } finally { connection.disconnect() } } } }