Files
androidapp/app/src/main/java/com/asio/tapremly/agent/SdkNixLink.kt
T

123 lines
4.5 KiB
Kotlin

package com.asio.tapremly.agent
import asia.asio.nixmsg.Client
import asia.asio.nixmsg.NixMsgException
import asia.asio.nixmsg.Types
import com.asio.tapremly.core.DEFAULT_MAX_SCHEDULE_SECONDS
import com.asio.tapremly.core.DEFAULT_MAX_TTL_SECONDS
import com.asio.tapremly.core.Limits
import com.asio.tapremly.core.WireOpt
import java.util.concurrent.CompletionException
/** 整台手机只在这里创建 NixMsg 连接。 */
class SdkNixLink : NixLink {
override var onMessage: (from: String, body: String) -> Unit = { _, _ -> }
override var onReceipt: (id: String, state: String, reason: String) -> Unit = { _, _, _ -> }
override var onPresence: (id: String, online: Boolean) -> Unit = { _, _ -> }
override var onConnection: (state: String, reason: String) -> Unit = { _, _ -> }
override var onSession: (token: String) -> Unit = {}
private var client: Client? = null
override fun connect(url: String, endpointId: String, password: String?, token: String?) {
client?.close()
val next = Client()
wire(next)
client = next
try {
next.connect(url, endpointId, password, token).join()
} catch (e: Exception) {
throw unwrap(e)
}
}
override fun send(to: String, body: String, messageId: String, opt: WireOpt): String {
val current = client ?: throw LinkException("not_connected", "没有连上")
val options = Types.SendOptions()
options.messageId = messageId
options.keep = opt.keep
options.receipt = true
if (opt.keep && opt.ttlSeconds != null) options.ttlSeconds = opt.ttlSeconds
if (opt.sendAtMs != null) options.sendAt = opt.sendAtMs
val payload = Types.Body(body)
payload.contentType = "application/json"
return try {
current.send(Types.Target("endpoint", to), payload, options).join().state
} catch (e: Exception) {
throw unwrap(e)
}
}
override fun presence(ids: List<String>): Map<String, Boolean> {
val current = client ?: return emptyMap()
val found = HashMap<String, Boolean>()
for (chunk in ids.chunked(200)) {
if (chunk.isEmpty()) continue
val data = try {
current.presence(chunk).join()
} catch (e: Exception) {
throw unwrap(e)
}
found.putAll(readPresence(data))
}
return found
}
override fun watch(ids: List<String>) {
val current = client ?: return
if (ids.isEmpty()) return
try {
current.watchPresence(ids.take(1000), false).join()
} catch (e: Exception) {
throw unwrap(e)
}
}
override fun limits(): Limits {
val hello = client?.limits ?: return Limits()
return Limits(
maxTtlSeconds = if (hello.maxTtlSeconds > 0) hello.maxTtlSeconds else DEFAULT_MAX_TTL_SECONDS,
maxScheduleSeconds = if (hello.maxScheduleSeconds > 0) hello.maxScheduleSeconds else DEFAULT_MAX_SCHEDULE_SECONDS,
)
}
override fun close() {
try {
client?.close()
} catch (_: Exception) {
}
client = null
}
private fun wire(next: Client) {
next.onMessage { msg -> onMessage(msg.from, msg.body?.data.orEmpty()) }
next.onReceipt { receipt -> onReceipt(receipt.id, receipt.state, receipt.reason) }
next.onPresence { event -> onPresence(event.id, event.online) }
next.onConnection { event -> onConnection(event.state.name, event.reason) }
next.onSession { token -> onSession(token) }
}
private fun readPresence(data: Map<String, Any>): Map<String, Boolean> {
val items = data["items"] as? List<*> ?: return emptyMap()
val out = HashMap<String, Boolean>()
for (item in items) {
val row = item as? Map<*, *> ?: continue
val id = row["id"]?.toString().orEmpty()
if (id.isBlank() || row["not_found"] == true) continue
out[id] = row["online"] == true
}
return out
}
private fun unwrap(error: Exception): LinkException {
var current: Throwable = error
while (current is CompletionException && current.cause != null) {
current = current.cause!!
}
val nix = current as? NixMsgException
if (nix != null) return LinkException(nix.code, nix.message ?: nix.code)
if (current is LinkException) return current
return LinkException("not_connected", "没有连上")
}
}