package com.vanta.smsgateway import okhttp3.* import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody import org.json.JSONObject import java.io.IOException import java.util.concurrent.TimeUnit data class SmsJob(val id: Long, val toNumber: String, val message: String) data class QueueResponse(val jobs: List, val delayMinSec: Long, val delayMaxSec: Long) class ApiClient(baseUrl: String, private val apiKey: String) { private val base = baseUrl.trimEnd('/') private val JSON = "application/json; charset=utf-8".toMediaType() private val http = OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(15, TimeUnit.SECONDS) .build() private fun req(path: String) = Request.Builder() .url("$base/$path") .header("X-API-Key", apiKey) fun fetchQueue(): QueueResponse { val resp = http.newCall(req("queue").get().build()).execute() if (!resp.isSuccessful) throw IOException("HTTP ${resp.code}") val body = resp.body?.string() ?: return QueueResponse(emptyList(), 30, 120) val json = JSONObject(body) val delayMin = json.optLong("delay_min", 30L) val delayMax = json.optLong("delay_max", 120L) val arr = json.optJSONArray("jobs") ?: return QueueResponse(emptyList(), delayMin, delayMax) val jobs = (0 until arr.length()).map { val j = arr.getJSONObject(it) SmsJob(j.getLong("id"), j.getString("to_number"), j.getString("message")) } return QueueResponse(jobs, delayMin, delayMax) } fun reportReceipt(id: Long, status: String, error: String? = null) { val obj = JSONObject().put("id", id).put("status", status) error?.let { obj.put("error", it) } val body = obj.toString().toRequestBody(JSON) try { http.newCall(req("receipt").post(body).build()).execute().close() } catch (_: Exception) {} } fun sendHeartbeat(deviceInfo: String) { val body = JSONObject().put("device", deviceInfo).toString().toRequestBody(JSON) try { http.newCall(req("heartbeat").post(body).build()).execute().close() } catch (_: Exception) {} } }