package com.asio.tapremly.data import com.asio.tapremly.core.Account import com.asio.tapremly.core.ApiJson import com.asio.tapremly.core.Device import com.asio.tapremly.core.Group import com.asio.tapremly.core.LogEntry import com.asio.tapremly.core.Provision import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import java.io.IOException import java.util.concurrent.TimeUnit class ApiException(message: String) : Exception(message) class TapApi(private val prefs: Prefs) { private val json = "application/json; charset=utf-8".toMediaType() private val http = OkHttpClient.Builder() .connectTimeout(20, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .build() fun login(username: String, password: String): Account = account("login", username, password) fun register(username: String, password: String): Account = account("register", username, password) fun logout() { call("POST", listOf("api", "logout"), "{}", bearer = null) } fun directory(): Pair, List> = ApiJson.directory(call("GET", listOf("api", "devices"), null, bearer = null)) fun createGroup(name: String) { call("POST", listOf("api", "groups"), """{"name":${quote(name)}}""", bearer = null) } fun renameGroup(id: String, name: String) { call("PATCH", listOf("api", "groups", id), """{"name":${quote(name)}}""", bearer = null) } fun deleteGroup(id: String) { call("DELETE", listOf("api", "groups", id), null, bearer = null) } fun addDevice(name: String, endpointId: String) { call( "POST", listOf("api", "devices"), """{"name":${quote(name)},"endpoint_id":${quote(endpointId)}}""", bearer = null, ) } fun provisionSelf(name: String): Provision { val raw = call( "POST", listOf("api", "devices"), """{"name":${quote(name)},"endpoint_id":""}""", bearer = null, ) return ApiJson.provision(raw) ?: throw ApiException("没有拿到本机的连接信息") } fun moveDevice(recordId: Long, groupId: String) { val group = if (groupId.isBlank()) "null" else groupId call( "PATCH", listOf("api", "devices", recordId.toString()), """{"group_id":$group}""", bearer = null, ) } fun removeDevice(recordId: Long) { call("DELETE", listOf("api", "devices", recordId.toString()), null, bearer = null) } fun putLogs(endpointId: String, password: String, items: List) { if (password.isBlank() || items.isEmpty()) return call("PUT", listOf("api", "command-logs"), ApiJson.logsBody(endpointId, items), bearer = password) } private fun account(path: String, username: String, password: String): Account { val raw = call( "POST", listOf("api", path), """{"username":${quote(username)},"password":${quote(password)}}""", bearer = null, ) val account = ApiJson.account(raw, username) ?: throw ApiException("没有登录成功") prefs.saveAccount(account.username) return account } private fun call(method: String, path: List, body: String?, bearer: String?): String { val base = prefs.serverUrl.trim().trimEnd('/').let { if (it.startsWith("http://") || it.startsWith("https://")) it else throw ApiException("服务器地址不对") } val url = base.toHttpUrlOrNull()?.newBuilder()?.apply { path.forEach { addPathSegment(it) } }?.build() ?: throw ApiException("服务器地址不对") val builder = Request.Builder().url(url).header("Accept", "application/json") if (method != "GET") builder.header("X-Tapremly-Request", "1") val cookie = prefs.cookieHeader if (cookie.isNotBlank()) builder.header("Cookie", cookie) if (!bearer.isNullOrBlank()) builder.header("Authorization", "Bearer $bearer") val request = when (method) { "GET" -> builder.get().build() "DELETE" -> builder.delete().build() else -> builder.method(method, (body ?: "{}").toRequestBody(json)).build() } try { http.newCall(request).execute().use { response -> absorbCookies(response.headers("Set-Cookie")) val text = response.body?.string().orEmpty() if (!response.isSuccessful) { throw ApiException(ApiJson.errorMessage(text) ?: "没有完成操作") } return text } } catch (e: ApiException) { throw e } catch (_: IOException) { throw ApiException("暂时连不上服务器") } } private fun absorbCookies(setCookies: List) { if (setCookies.isEmpty()) return val map = linkedMapOf() prefs.cookieHeader.split(';').forEach { part -> val piece = part.trim() val name = piece.substringBefore('=', "") if (name.isNotBlank() && piece.contains('=')) map[name] = piece.substringAfter('=') } for (header in setCookies) { val pair = header.substringBefore(';').trim() val name = pair.substringBefore('=', "") if (name.isBlank()) continue val value = pair.substringAfter('=', "") if (value.isEmpty()) map.remove(name) else map[name] = value } prefs.cookieHeader = map.entries.joinToString("; ") { "${it.key}=${it.value}" } } private fun quote(value: String): String = buildString { append('"') for (ch in value) { when (ch) { '\\' -> append("\\\\") '"' -> append("\\\"") '\n' -> append("\\n") '\r' -> append("\\r") else -> append(ch) } } append('"') } }