package eu.friedcutlet.yokan.services.together import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.hubWebSocketBase import eu.friedcutlet.yokan.util.nowMillis import eu.friedcutlet.yokan.util.PlatformLock import io.ktor.client.HttpClient import io.ktor.client.engine.HttpClientEngine import io.ktor.client.plugins.websocket.DefaultClientWebSocketSession import io.ktor.client.plugins.websocket.WebSockets import io.ktor.client.plugins.websocket.webSocket import io.ktor.client.request.header import io.ktor.http.HttpHeaders import io.ktor.websocket.Frame import io.ktor.websocket.readText import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.withContext import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlin.concurrent.Volatile import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.longOrNull import kotlinx.serialization.json.put /** Credentials for one hub; the same ones the sync service stores in `sync_preference`. */ data class HubSession(val server: String, val token: String, val deviceId: String) { val wsBase: String get() = hubWebSocketBase(server) val headers: Map get() = mapOf("Authorization" to "Bearer $token", "X-Device" to deviceId) } /** REST side of rooms: create, look up, close. */ class RoomApi( private val http: HttpService, private val isSessionCurrent: () -> Boolean = { true }, ) { data class Created(val code: String, val joinUrl: String) suspend fun create( session: HubSession, media: RoomMedia, policy: String = "approve", playlistPolicy: String = "suggest", maxParticipants: Int? = null, ): Result = catchingNonCancellation { ensureCurrent() val body = buildJsonObject { put("media", RoomJson.encodeToJsonElement(RoomMedia.serializer(), media)) put("policy", policy) put("playlist_policy", playlistPolicy) if (maxParticipants != null) put("max_participants", maxParticipants) } ensureCurrent() val r = http.request(HttpRequest("${session.server}/api/v1/rooms", "POST", session.headers + ("Content-Type" to "application/json"), body.toString())) ensureCurrent() check(r.statusCode in 200..299) { errorOf(r.body) ?: "Hub returned HTTP ${r.statusCode}" } val o = RoomJson.parseToJsonElement(r.body).jsonObject val code = requireNotNull(o["code"]?.jsonPrimitive?.contentOrNull) { "Hub response has no room code." } Created(code, o["join_url"]?.jsonPrimitive?.contentOrNull.orEmpty()).also { ensureCurrent() } } suspend fun info(session: HubSession, code: String): Result = catchingNonCancellation { ensureCurrent() val r = http.request(HttpRequest("${session.server}/api/v1/rooms/${code.uppercase()}", "GET", session.headers)) ensureCurrent() check(r.statusCode in 200..299) { if (r.statusCode == 404) "No room with code ${code.uppercase()}." else errorOf(r.body) ?: "Hub returned HTTP ${r.statusCode}" } RoomJson.decodeFromString(RoomSummary.serializer(), r.body).also { ensureCurrent() } } suspend fun close(session: HubSession, code: String): Result = catchingNonCancellation { ensureCurrent() val r = http.request(HttpRequest("${session.server}/api/v1/rooms/${code.uppercase()}", "DELETE", session.headers)) ensureCurrent() check(r.statusCode in 200..299) { errorOf(r.body) ?: "Hub returned HTTP ${r.statusCode}" } ensureCurrent() } private suspend fun ensureCurrent() { currentCoroutineContext().ensureActive() if (!isSessionCurrent()) throw CancellationException("Together account changed during room request.") } private fun errorOf(body: String): String? = runCatching { RoomJson.parseToJsonElement(body).jsonObject["error"]?.jsonPrimitive?.contentOrNull }.getOrNull() } /** * One WebSocket into one room. [state] is the reduced view for the UI, [bursts] the live emoji * stream. Reconnects with backoff until [close] or the hub says the room is gone. Owns [engine]: * [close] releases it. * * Every command is fire-and-forget; the hub answers with a state message (or `error`, surfaced as * `RoomState.lastError`). The player/reader hooks call [sendState] and read [RoomState.position]. */ class RoomClient( engine: HttpClientEngine, private val session: HubSession, code: String, scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default), private val isSessionCurrent: () -> Boolean = { true }, ) { private val ownerJob = requireNotNull(scope.coroutineContext[Job]) { "Room client requires an owner job" } private val lifecycleJob = SupervisorJob(ownerJob) private val scope = CoroutineScope(scope.coroutineContext + lifecycleJob) private val lock = PlatformLock() private val engine = eu.friedcutlet.yokan.services.http.ProfileHttpEngine(engine, lifecycleJob) { isAvailable } private val retirementLock = Mutex() private var released = false val code: String = code.uppercase() private val client = HttpClient(this.engine) { expectSuccess = false install(WebSockets) } private val _state = MutableStateFlow(RoomState(code = this.code)) val state: StateFlow = _state.asStateFlow() private val _bursts = MutableSharedFlow(extraBufferCapacity = 64) val bursts: SharedFlow = _bursts.asSharedFlow() @Volatile private var ws: DefaultClientWebSocketSession? = null private var job: Job? = null /** Checking a revoked account permanently ends this client, even if its credentials return. */ internal val isAvailable: Boolean get() { if (!lifecycleJob.isActive || !ownerJob.isActive) return false // The guard may read the database. Keep it outside room/engine locks. if (!isSessionCurrent()) { lifecycleJob.cancel() return false } return lifecycleJob.isActive && ownerJob.isActive } /** Stop admission immediately; transport release remains in awaited cleanup. */ internal fun revoke() { lifecycleJob.cancel() } fun connect() { if (!isAvailable) return val pending = lock.withLock { if (!lifecycleJob.isActive || !ownerJob.isActive || job?.isCompleted == false) return@withLock null // Start outside the lock even with an immediate owner dispatcher. scope.launch(start = CoroutineStart.LAZY) { run() }.also { job = it } } pending?.start() } fun close() { lifecycleJob.cancel() release() } /** Leaves socket/pinger/send finalizers joined before releasing the captured transport. */ suspend fun closeAndJoin() = retirementLock.withLock { withContext(NonCancellable) { lifecycleJob.cancelAndJoin() // Engine call coroutines can finish outside the room's caller scope. val clientJob = client.coroutineContext[Job] clientJob?.cancel() engine.closeAndJoin() clientJob?.join() release() } } private fun release() = lock.withLock { if (!released) { client.close() // Ktor leaves an engine it was handed open; this client is its only user. engine.close() released = true } } private suspend fun run() { var backoff = 1_000L while (scope.isActive && isAvailable) { val terminal = _state.value.connection if (terminal is RoomConnection.Denied || terminal is RoomConnection.Closed) return try { client.webSocket( urlString = "${session.wsBase}/api/v1/rooms/$code/ws", request = { if (!isAvailable) throw CancellationException("Together account changed") header(HttpHeaders.Authorization, "Bearer ${session.token}") header("X-Device", session.deviceId) }, ) { if (!isAvailable) throw CancellationException("Together account changed") ws = this backoff = 1_000L val pinger = launch { while (isActive) { ping() delay(15_000L) } } try { for (frame in incoming) { val text = (frame as? Frame.Text)?.readText() ?: continue val msg = runCatching { RoomJson.parseToJsonElement(text).jsonObject }.getOrNull() ?: continue handle(msg) } } finally { pinger.cancel() ws = null } } } catch (cancelled: CancellationException) { throw cancelled } catch (_: Throwable) { // fall through to reconnect } val after = _state.value.connection if (after is RoomConnection.Denied || after is RoomConnection.Closed || !isAvailable) return _state.update { it.copy(connection = RoomConnection.Connecting) } delay(backoff) backoff = (backoff * 2).coerceAtMost(30_000L) } } private fun handle(msg: JsonObject) { if (!isAvailable) return when (msg["type"]?.jsonPrimitive?.contentOrNull) { "burst" -> { val emoji = msg["emoji"]?.jsonPrimitive?.contentOrNull ?: return _bursts.tryEmit(RoomBurst(emoji, msg["from"]?.jsonPrimitive?.contentOrNull.orEmpty())) } "pong" -> { val t = msg["t"]?.jsonPrimitive?.longOrNull ?: return val serverMs = msg["server_ms"]?.jsonPrimitive?.longOrNull ?: return // The hub echoes our send time, so no per-ping bookkeeping is shared with the pinger. val sent = t val now = nowMillis() val offset = serverMs - (sent + (now - sent) / 2) _state.update { it.copy(clockOffsetMs = offset) } } else -> _state.update { RoomReducer.reduce(it, msg) } } } // ── commands ──────────────────────────────────────────────────────────── private fun send(type: String, build: kotlinx.serialization.json.JsonObjectBuilder.() -> Unit = {}) { if (!isAvailable) return val msg = buildJsonObject { put("type", type) build() } val socket = ws ?: return scope.launch { if (isAvailable) catchingNonCancellation { socket.send(Frame.Text(msg.toString())) } } } private fun ping() = send("ping") { put("t", nowMillis()) } /** Host/co-host: authoritative position. Pass the shape for the item type (see `RoomState.position`). */ fun sendState(fields: Map) = send("state") { fields.forEach { (k, v) -> put(k, v) } } fun sendPlayback(positionMs: Long, playing: Boolean, rate: Double = 1.0) = sendState(mapOf("positionMs" to JsonPrimitive(positionMs), "playing" to JsonPrimitive(playing), "rate" to JsonPrimitive(rate))) fun sendPage(page: Int, pages: Int) = sendState(mapOf("page" to JsonPrimitive(page), "pages" to JsonPrimitive(pages))) fun sendProgress(progress: Double) = sendState(mapOf("progress" to JsonPrimitive(progress))) fun setMedia(media: RoomMedia) = send("media") { RoomJson.encodeToJsonElement(RoomMedia.serializer(), media).jsonObject.forEach { (k, v) -> put(k, v) } } fun approve(userId: String) = send("approve") { put("user", userId) } fun deny(userId: String) = send("deny") { put("user", userId) } fun kick(userId: String) = send("kick") { put("user", userId) } fun ban(userId: String) = send("ban") { put("user", userId) } fun promote(userId: String) = send("promote") { put("user", userId) } fun demote(userId: String) = send("demote") { put("user", userId) } fun setPolicy(policy: String? = null, playlistPolicy: String? = null) = send("set_policy") { policy?.let { put("policy", it) } playlistPolicy?.let { put("playlist_policy", it) } } fun playlistAdd(media: RoomMedia, at: Int? = null) = send("pl_add") { put("media", RoomJson.encodeToJsonElement(RoomMedia.serializer(), media)) at?.let { put("at", it) } } fun playlistSuggest(media: RoomMedia, note: String? = null) = send("pl_suggest") { put("media", RoomJson.encodeToJsonElement(RoomMedia.serializer(), media)) note?.takeIf { it.isNotBlank() }?.let { put("note", it) } } fun playlistAccept(id: Long) = send("pl_accept") { put("id", id) } fun playlistReject(id: Long) = send("pl_reject") { put("id", id) } fun playlistRemove(id: Long) = send("pl_remove") { put("id", id) } fun playlistMove(id: Long, to: Int) = send("pl_move") { put("id", id); put("to", to) } fun playlistPlay(id: Long) = send("pl_play") { put("id", id) } fun playlistNext() = send("pl_next") fun chat(text: String, replyTo: Long? = null) = send("chat") { put("text", text) replyTo?.let { put("reply_to", it) } } fun react(messageId: Long, emoji: String) = send("react") { put("msg_id", messageId); put("emoji", emoji) } fun burst(emoji: String) = send("burst") { put("emoji", emoji) } fun presence(detached: Boolean, position: JsonElement? = null) = send("presence") { put("detached", detached) position?.let { put("position", it) } } companion object { /** The fixed quick-reaction row; the OS emoji keyboard covers everything else. */ val QUICK_REACTIONS = listOf("👍", "❤️", "😂", "😮", "😢", "🔥", "👏", "💀") } }