// Drop-in Kotlin client library for the Sprachmemo HTTP API. // // Save this file under your project as `VoiceClient.kt`, in a // directory matching `package voice_client`, then call the // VoiceClient class: // // import voice_client.VoiceClient // // val c = VoiceClient("pat_...") // val rows = c.accountList(mapOf("limit" to 20, "sort" to "-created_at")) // val fresh = c.accountCreate(mapOf("name" to "Example GmbH")) // // Every endpoint exposed by the HTTP API is wrapped as a typed method // on VoiceClient. List methods take a Map of options; // get/update/delete methods take the row id as their first argument. // // Provided as-is, with no warranty. Vendor freely; modify as needed. // Targets Kotlin 1.9+ on JVM 11+; uses only the JDK (java.net.http). // // DO NOT EDIT THIS FILE MANUALLY - re-download from the docs site. // Local edits will be overwritten by the once-per-day version check. @file:Suppress("unused", "MemberVisibilityCanBePrivate", "ConstPropertyName") package voice_client import java.net.URI import java.net.URLEncoder import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.time.Duration import java.util.UUID import java.util.concurrent.atomic.AtomicBoolean import kotlin.concurrent.thread class ApiException(val status: Int, message: String, val bodyRaw: String? = null) : RuntimeException("HTTP $status: $message") class VoiceClient(token: String? = null) { companion object { const val APP_SLUG = "voice" const val APP_NAME = "Sprachmemo" const val MODULE_NAME = "voice_client" const val CLIENT_VERSION = "0.3.13" const val LANGUAGE = "kotlin" private const val DEFAULT_BASE = "https://sprachmemo.de" /** * Per-type metadata baked at generation time. Parse with your * preferred JSON library if you need the legal filters / sorts * / max_limit per model without an extra round-trip. */ const val TYPES_JSON = """{"recording":{"ops":["list","read","create","update","delete"],"create_fields":["parent_id","blob_id","filename","mime","duration_seconds","sample_rate","channels","size_bytes","recorded_at","state","primary_model","requested_model","language","transcriptions","client_id"],"update_fields":["blob_id","state","primary_model","requested_model","transcriptions","transcription_error","transcript_edit","duration_seconds","language","appended_to_body"],"allowed_filters":["data__parent_id","data__state","data__primary_model","status","is_archived","owned_by"],"allowed_sorts":["created_at","data__recorded_at"],"default_sort":"-data__recorded_at","max_limit":200,"fields":[{"name":"mime","type":"string","max_len":64},{"name":"state","type":"enum","values":["uploading","ready","transcribing","transcribed","failed"]},{"name":"blob_id","type":"string","max_len":64},{"name":"channels","type":"number"},{"name":"filename","type":"string","max_len":200},{"name":"language","type":"string","max_len":8},{"name":"client_id","type":"string","max_len":64},{"name":"parent_id","type":"string","max_len":64,"ref":{"type":"voice_note","owned":true,"optional":false}},{"name":"size_bytes","type":"number"},{"name":"recorded_at","type":"string","max_len":32},{"name":"sample_rate","type":"number"},{"name":"primary_model","type":"string","max_len":32},{"name":"transcriptions","type":"dict"},{"name":"requested_model","type":"string","max_len":32},{"name":"appended_to_body","type":"bool"},{"name":"duration_seconds","type":"number"},{"name":"transcription_error","type":"string","max_len":400}]},"voice_note":{"ops":["list","read","create","update","delete"],"create_fields":["title","body","tags","color","favorite","pinned","last_recording_at","last_recording_id","updated_at_marker"],"update_fields":["title","body","tags","color","favorite","pinned","last_recording_at","last_recording_id","updated_at_marker"],"allowed_filters":["data__favorite","data__tags","data__color","data__pinned","status","is_archived","owned_by"],"allowed_sorts":["created_at","updated_at","data__title","data__last_recording_at"],"default_sort":"-data__last_recording_at","max_limit":200,"fields":[{"name":"body","type":"string","max_len":65000},{"name":"tags","type":"tags"},{"name":"color","type":"string","max_len":24},{"name":"title","type":"string","max_len":200},{"name":"pinned","type":"bool"},{"name":"favorite","type":"bool"},{"name":"last_recording_at","type":"string","max_len":32},{"name":"last_recording_id","type":"string","max_len":64},{"name":"updated_at_marker","type":"string","max_len":32}]},"voice_tag":{"ops":["list","read","create","update","delete"],"create_fields":["name","color","icon"],"update_fields":["name","color","icon"],"allowed_filters":["data__name","status","owned_by"],"allowed_sorts":["created_at","data__name"],"default_sort":"data__name","max_limit":200,"fields":[{"name":"icon","type":"string","max_len":32},{"name":"name","type":"string","max_len":80},{"name":"color","type":"string","max_len":24}]}}""" private val META_SENT_ONCE = AtomicBoolean(false) private val AUTOUPDATE_TRIED = AtomicBoolean(false) private val RETRYABLE = setOf(408, 425, 429, 500, 502, 503, 504) private const val MAX_RETRIES = 3 private fun stateDir(): Path? { val home = System.getProperty("user.home") ?: System.getenv("HOME") ?: System.getenv("USERPROFILE") ?: return null return try { val p = Paths.get(home, ".$MODULE_NAME") Files.createDirectories(p) p } catch (_: Exception) { null } } private fun loadOrMintDeviceId(): String { val d = stateDir() ?: return UUID.randomUUID().toString() val f = d.resolve("device.json") if (Files.exists(f)) { try { val raw = Files.readString(f, StandardCharsets.UTF_8) val did = jsonExtractString(raw, "device_id") if (!did.isNullOrEmpty() && did.length >= 32) return did } catch (_: Exception) { /* fall through */ } } val fresh = UUID.randomUUID().toString() try { Files.writeString(f, "{\"device_id\":\"$fresh\"}", StandardCharsets.UTF_8) } catch (_: Exception) {} return fresh } private fun autoupdateEnabled(): Boolean { val v = (System.getenv("XCLIENT_NO_AUTOUPDATE") ?: "").lowercase() return v != "1" && v != "true" && v != "yes" } private fun fingerprint(): Map { val tp = (System.getenv("TERM_PROGRAM") ?: "").lowercase() return mapOf( "kotlin_version" to KotlinVersion.CURRENT.toString(), "java_version" to System.getProperty("java.version"), "os" to System.getProperty("os.name"), "term_program" to System.getenv("TERM_PROGRAM"), "editor_env" to System.getenv("EDITOR"), "ci" to (System.getenv("CI") != null || System.getenv("GITHUB_ACTIONS") != null), "claude_code" to (System.getenv("CLAUDECODE") != null || System.getenv("CLAUDE_CODE_ENTRYPOINT") != null), "codex" to (System.getenv("CODEX_HOME") != null), "vscode" to (tp == "vscode" && System.getenv("CURSOR_TRACE_ID") == null), "cursor" to (System.getenv("CURSOR_TRACE_ID") != null), "antigravity" to (System.getenv("ANTIGRAVITY_TRACE_ID") != null), "jetbrains" to tp.contains("jetbrains"), ) } private fun originOf(uri: URI): String { val scheme = (uri.scheme ?: "").lowercase() val host = (uri.host ?: "").lowercase() val port = if (uri.port < 0) (if (scheme == "https") 443 else 80) else uri.port return "$scheme://$host:$port" } private fun backoffMillis(attempt: Int, retryAfter: String?): Long { if (!retryAfter.isNullOrEmpty()) { val v = retryAfter.toDoubleOrNull() if (v != null) return (minOf(v, 60.0) * 1000.0).toLong() } return (minOf(Math.pow(2.0, attempt.toDouble()), 60.0) * 1000.0).toLong() } // ── Tiny stdlib JSON helpers (encoder + extractor + decoder) ─ // The JDK ships no JSON parser. We hand-roll the bare minimum // so the library stays dependency-free; users wanting a full // model layer should plug Jackson / Moshi / kotlinx.serialization // around the Map we return. @Suppress("UNCHECKED_CAST") fun encodeJson(value: Any?): String = buildString { encodeAny(this, value) } private fun encodeAny(sb: StringBuilder, value: Any?) { when (value) { null -> sb.append("null") is String -> encodeString(sb, value) is Boolean, is Number -> sb.append(value.toString()) is Map<*, *> -> { sb.append("{") var first = true for ((k, v) in value) { if (!first) sb.append(",") encodeString(sb, k.toString()) sb.append(":") encodeAny(sb, v) first = false } sb.append("}") } is Iterable<*> -> { sb.append("[") var first = true for (v in value) { if (!first) sb.append(",") encodeAny(sb, v) first = false } sb.append("]") } is Array<*> -> encodeAny(sb, value.toList()) else -> encodeString(sb, value.toString()) } } private fun encodeString(sb: StringBuilder, s: String) { sb.append('"') for (c in s) { when (c) { '"' -> sb.append("\\\"") '\\' -> sb.append("\\\\") '\n' -> sb.append("\\n") '\r' -> sb.append("\\r") '\t' -> sb.append("\\t") else -> if (c.code < 0x20) sb.append("\\u%04x".format(c.code)) else sb.append(c) } } sb.append('"') } fun jsonExtractString(json: String?, key: String): String? { if (json == null) return null val needle = "\"$key\"" val idx = json.indexOf(needle); if (idx < 0) return null val colon = json.indexOf(':', idx + needle.length); if (colon < 0) return null var i = colon + 1 while (i < json.length && json[i].isWhitespace()) i++ if (i >= json.length || json[i] != '"') return null val out = StringBuilder() i++ while (i < json.length) { val c = json[i] if (c == '\\' && i + 1 < json.length) { val n = json[i + 1] when (n) { '"', '\\', '/' -> { out.append(n); i += 2 } 'n' -> { out.append('\n'); i += 2 } 't' -> { out.append('\t'); i += 2 } 'r' -> { out.append('\r'); i += 2 } else -> { out.append(n); i += 2 } } continue } if (c == '"') break out.append(c); i++ } return out.toString() } fun decodeJsonObject(json: String): Map { val pos = intArrayOf(0) return when (val v = parseJsonValue(json, pos)) { is Map<*, *> -> @Suppress("UNCHECKED_CAST") (v as Map) else -> mapOf("data" to v) } } private fun parseJsonValue(s: String, pos: IntArray): Any? { skipWs(s, pos) if (pos[0] >= s.length) return null return when (s[pos[0]]) { '{' -> parseJsonObject(s, pos) '[' -> parseJsonArray(s, pos) '"' -> parseJsonString(s, pos) 't', 'f' -> parseJsonBool(s, pos) 'n' -> { pos[0] += 4; null } else -> parseJsonNumber(s, pos) } } private fun parseJsonObject(s: String, pos: IntArray): MutableMap { val out = LinkedHashMap() pos[0]++ skipWs(s, pos) if (pos[0] < s.length && s[pos[0]] == '}') { pos[0]++; return out } while (pos[0] < s.length) { skipWs(s, pos) val key = parseJsonString(s, pos) ?: "" skipWs(s, pos) if (pos[0] < s.length && s[pos[0]] == ':') pos[0]++ out[key] = parseJsonValue(s, pos) skipWs(s, pos) if (pos[0] >= s.length) break val c = s[pos[0]] if (c == ',') { pos[0]++; continue } if (c == '}') { pos[0]++; break } } return out } private fun parseJsonArray(s: String, pos: IntArray): MutableList { val out = mutableListOf() pos[0]++ skipWs(s, pos) if (pos[0] < s.length && s[pos[0]] == ']') { pos[0]++; return out } while (pos[0] < s.length) { out.add(parseJsonValue(s, pos)) skipWs(s, pos) if (pos[0] >= s.length) break val c = s[pos[0]] if (c == ',') { pos[0]++; continue } if (c == ']') { pos[0]++; break } } return out } private fun parseJsonString(s: String, pos: IntArray): String? { if (pos[0] >= s.length || s[pos[0]] != '"') return null pos[0]++ val out = StringBuilder() while (pos[0] < s.length) { val c = s[pos[0]] if (c == '"') { pos[0]++; return out.toString() } if (c == '\\' && pos[0] + 1 < s.length) { val n = s[pos[0] + 1] pos[0] += 2 when (n) { '"' -> out.append('"') '\\' -> out.append('\\') '/' -> out.append('/') 'n' -> out.append('\n') 't' -> out.append('\t') 'r' -> out.append('\r') 'b' -> out.append('\b') 'f' -> out.append('\u000c') 'u' -> { if (pos[0] + 4 <= s.length) { try { out.append(Integer.parseInt(s.substring(pos[0], pos[0] + 4), 16).toChar()) pos[0] += 4 } catch (_: NumberFormatException) {} } } else -> out.append(n) } continue } out.append(c); pos[0]++ } return out.toString() } private fun parseJsonBool(s: String, pos: IntArray): Boolean? { if (s.startsWith("true", pos[0])) { pos[0] += 4; return true } if (s.startsWith("false", pos[0])) { pos[0] += 5; return false } pos[0]++ return null } private fun parseJsonNumber(s: String, pos: IntArray): Any? { val start = pos[0]; var fp = false while (pos[0] < s.length) { val c = s[pos[0]] if (c == '-' || c == '+' || c.isDigit()) pos[0]++ else if (c == '.' || c == 'e' || c == 'E') { fp = true; pos[0]++ } else break } val num = s.substring(start, pos[0]) return try { if (fp) num.toDouble() else num.toLong() } catch (_: NumberFormatException) { num } } private fun skipWs(s: String, pos: IntArray) { while (pos[0] < s.length && s[pos[0]].isWhitespace()) pos[0]++ } } private val http: HttpClient = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(15)) .followRedirects(HttpClient.Redirect.NEVER) .build() private var baseUrl: String = (System.getenv("XCLIENT_BASE_URL")?.takeIf { it.isNotEmpty() } ?: DEFAULT_BASE).trimEnd('/') private var token: String = (token?.takeIf { it.isNotEmpty() } ?: System.getenv("XCLIENT_TOKEN") ?: "") private val deviceId: String = loadOrMintDeviceId() private val sessionId: String = UUID.randomUUID().toString() fun setToken(token: String?) { this.token = token ?: "" } fun setBaseUrl(baseUrl: String){ this.baseUrl = baseUrl.trimEnd('/') } // ── HTTP transport ─────────────────────────────────────────────── fun requestList(path: String, opts: Map?): Map? { val qs = StringBuilder() if (opts != null) { for ((k, v) in opts) { if (v == null) continue if (qs.isNotEmpty()) qs.append("&") qs.append(URLEncoder.encode(k, StandardCharsets.UTF_8)) qs.append("=") qs.append(URLEncoder.encode(v.toString(), StandardCharsets.UTF_8)) } } val full = if (qs.isNotEmpty()) "$path?$qs" else path return requestJson("GET", full, null) } fun requestJson(method: String, path: String, body: Map?): Map? { maybeAutoupdate() val url = baseUrl + path val json = body?.let { encodeJson(it) } var lastErr: Throwable? = null for (attempt in 0 until MAX_RETRIES) { try { val resp = sendFollowingRedirects(method, url, json) resp.headers().firstValue("x-auth-refresh-token").orElse(null)?.takeIf { it.isNotEmpty() }?.let { token = it } val status = resp.statusCode() if (RETRYABLE.contains(status) && attempt + 1 < MAX_RETRIES) { Thread.sleep(backoffMillis(attempt, resp.headers().firstValue("Retry-After").orElse(null))) continue } if (status >= 400) { emitCallEvent(method, path, status, false) val msg = jsonExtractString(resp.body(), "detail") ?: jsonExtractString(resp.body(), "message") ?: "HTTP $status" throw ApiException(status, msg, resp.body()) } emitCallEvent(method, path, status, true) val raw = resp.body() ?: return null return if (raw.isEmpty()) null else decodeJsonObject(raw) } catch (e: ApiException) { throw e } catch (e: Exception) { lastErr = e if (attempt + 1 < MAX_RETRIES) { Thread.sleep(backoffMillis(attempt, null)) continue } emitCallEvent(method, path, 0, false) throw ApiException(0, e.message ?: "request failed") } } emitCallEvent(method, path, 0, false) throw ApiException(0, lastErr?.message ?: "request failed") } private fun sendFollowingRedirects(method: String, url: String, json: String?): HttpResponse { var currentUrl = url var currentMethod = method.uppercase() var currentJson = json var stripAuth = false val maxHops = 5 for (hop in 0..maxHops) { val b = HttpRequest.newBuilder() .uri(URI.create(currentUrl)) .timeout(Duration.ofSeconds(30)) .header("Accept", "application/json") .header("User-Agent", userAgent()) .header("X-Client-Channel", "client_$LANGUAGE") .header("X-Client-Version", CLIENT_VERSION) .header("X-Analytics-Device-Id", deviceId) .header("X-Analytics-Session-Id", sessionId) if (!stripAuth && token.isNotEmpty()) b.header("Authorization", "Bearer $token") if (currentJson != null && currentMethod != "GET" && currentMethod != "HEAD") { b.header("Content-Type", "application/json") b.method(currentMethod, HttpRequest.BodyPublishers.ofString(currentJson, StandardCharsets.UTF_8)) } else { b.method(currentMethod, HttpRequest.BodyPublishers.noBody()) } val resp = http.send(b.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)) val status = resp.statusCode() if (status < 300 || status >= 400 || status == 304 || hop == maxHops) return resp val loc = resp.headers().firstValue("Location").orElse(null) ?: return resp val nextUri = try { URI.create(currentUrl).resolve(loc) } catch (_: IllegalArgumentException) { return resp } if (!originOf(URI.create(currentUrl)).equals(originOf(nextUri), ignoreCase = true)) { stripAuth = true } if (status == 303 || ((status == 301 || status == 302) && currentMethod != "GET" && currentMethod != "HEAD")) { currentMethod = "GET" currentJson = null } currentUrl = nextUri.toString() } throw java.io.IOException("redirect chain exceeded max hops") } private fun userAgent() = "$MODULE_NAME/$CLIENT_VERSION (lib/$LANGUAGE; kotlin/${KotlinVersion.CURRENT}; java/${System.getProperty("java.version")})" // ── Analytics ──────────────────────────────────────────────────── private fun emitCallEvent(method: String, path: String, status: Int, ok: Boolean) { val includeEnv = META_SENT_ONCE.compareAndSet(false, true) thread(start = true, isDaemon = true, name = "$MODULE_NAME-analytics") { try { val meta = LinkedHashMap() meta["channel"] = "client_$LANGUAGE" meta["client_version"] = CLIENT_VERSION meta["module_name"] = MODULE_NAME meta["language"] = LANGUAGE meta["os"] = System.getProperty("os.name") meta["kotlin_version"] = KotlinVersion.CURRENT.toString() if (includeEnv) meta["env"] = fingerprint() val evt = mapOf( "type" to "client.call", "ts_client" to (System.currentTimeMillis() / 1000L), "meta" to mapOf( "method" to method.uppercase(), "path" to path.split('?').first(), "status" to status, "ok" to ok, ), ) val body = mapOf( "device_id" to deviceId, "session_id" to sessionId, "events" to listOf(evt), "meta" to meta, ) val req = HttpRequest.newBuilder() .uri(URI.create("$baseUrl/xapi2/analytics/challenge")) .timeout(Duration.ofSeconds(4)) .header("Content-Type", "application/json") .header("User-Agent", userAgent()) .POST(HttpRequest.BodyPublishers.ofString(encodeJson(body), StandardCharsets.UTF_8)) .build() http.send(req, HttpResponse.BodyHandlers.discarding()) } catch (_: Throwable) { /* fire and forget */ } } } // ── Auto-update ────────────────────────────────────────────────── private fun maybeAutoupdate() { if (!AUTOUPDATE_TRIED.compareAndSet(false, true)) return if (!autoupdateEnabled()) return thread(start = true, isDaemon = true, name = "$MODULE_NAME-autoupdate") { try { val d = stateDir() ?: return@thread val stamp = d.resolve("update_check.json") val now = System.currentTimeMillis() / 1000L if (Files.exists(stamp)) { try { val raw = Files.readString(stamp, StandardCharsets.UTF_8) val checked = jsonExtractString(raw, "checked_at")?.toLongOrNull() if (checked != null && now - checked < 86400) return@thread } catch (_: Exception) {} } Files.writeString(stamp, "{\"checked_at\":\"$now\"}", StandardCharsets.UTF_8) // Source replacement is intentionally a no-op - the // user is running compiled JVM bytecode, the .kt file // is just a record of the version they vendored. } catch (_: Throwable) {} } } // ── Generated per-type wrapper methods ─────────────────────────── // Every model that exposes an op gets one `` method // below. The runtime above does the heavy lifting; these wrappers // just pin the URL + HTTP verb. /** List `recording` rows. */ fun recordingList(opts: Map? = null): Map? = requestList("/xapi2/data/recording", opts) /** Fetch one `recording` row by id. */ fun recordingGet(id: String): Map? = requestJson("GET", "/xapi2/data/recording/" + id, null) /** Create a new `recording` row. */ fun recordingCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/recording", data) /** Patch a `recording` row. */ fun recordingUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/recording/" + id, data) /** Delete a `recording` row. */ fun recordingDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/recording/" + id, null) return true } /** List `voice_note` rows. */ fun voiceNoteList(opts: Map? = null): Map? = requestList("/xapi2/data/voice_note", opts) /** Fetch one `voice_note` row by id. */ fun voiceNoteGet(id: String): Map? = requestJson("GET", "/xapi2/data/voice_note/" + id, null) /** Create a new `voice_note` row. */ fun voiceNoteCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/voice_note", data) /** Patch a `voice_note` row. */ fun voiceNoteUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/voice_note/" + id, data) /** Delete a `voice_note` row. */ fun voiceNoteDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/voice_note/" + id, null) return true } /** List `voice_tag` rows. */ fun voiceTagList(opts: Map? = null): Map? = requestList("/xapi2/data/voice_tag", opts) /** Fetch one `voice_tag` row by id. */ fun voiceTagGet(id: String): Map? = requestJson("GET", "/xapi2/data/voice_tag/" + id, null) /** Create a new `voice_tag` row. */ fun voiceTagCreate(data: Map): Map? = requestJson("POST", "/xapi2/data/voice_tag", data) /** Patch a `voice_tag` row. */ fun voiceTagUpdate(id: String, data: Map): Map? = requestJson("PATCH", "/xapi2/data/voice_tag/" + id, data) /** Delete a `voice_tag` row. */ fun voiceTagDelete(id: String): Boolean { requestJson("DELETE", "/xapi2/data/voice_tag/" + id, null) return true } }