RoomClient.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomClient.kt
1package eu.friedcutlet.yokan.services.together23import eu.friedcutlet.yokan.services.catchingNonCancellation4import eu.friedcutlet.yokan.services.http.HttpRequest5import eu.friedcutlet.yokan.services.http.HttpService6import eu.friedcutlet.yokan.services.http.hubWebSocketBase7import eu.friedcutlet.yokan.util.nowMillis8import eu.friedcutlet.yokan.util.PlatformLock9import io.ktor.client.HttpClient10import io.ktor.client.engine.HttpClientEngine11import io.ktor.client.plugins.websocket.DefaultClientWebSocketSession12import io.ktor.client.plugins.websocket.WebSockets13import io.ktor.client.plugins.websocket.webSocket14import io.ktor.client.request.header15import io.ktor.http.HttpHeaders16import io.ktor.websocket.Frame17import io.ktor.websocket.readText18import kotlinx.coroutines.CancellationException19import kotlinx.coroutines.CoroutineScope20import kotlinx.coroutines.currentCoroutineContext21import kotlinx.coroutines.ensureActive22import kotlinx.coroutines.CoroutineStart23import kotlinx.coroutines.Dispatchers24import kotlinx.coroutines.Job25import kotlinx.coroutines.SupervisorJob26import kotlinx.coroutines.cancel27import kotlinx.coroutines.cancelAndJoin28import kotlinx.coroutines.NonCancellable29import kotlinx.coroutines.withContext30import kotlinx.coroutines.sync.Mutex31import kotlinx.coroutines.sync.withLock32import kotlinx.coroutines.delay33import kotlinx.coroutines.flow.MutableSharedFlow34import kotlinx.coroutines.flow.MutableStateFlow35import kotlinx.coroutines.flow.SharedFlow36import kotlinx.coroutines.flow.StateFlow37import kotlinx.coroutines.flow.asSharedFlow38import kotlinx.coroutines.flow.asStateFlow39import kotlinx.coroutines.flow.update40import kotlinx.coroutines.isActive41import kotlinx.coroutines.launch42import kotlin.concurrent.Volatile43import kotlinx.serialization.json.JsonElement44import kotlinx.serialization.json.JsonObject45import kotlinx.serialization.json.JsonPrimitive46import kotlinx.serialization.json.buildJsonObject47import kotlinx.serialization.json.contentOrNull48import kotlinx.serialization.json.jsonObject49import kotlinx.serialization.json.jsonPrimitive50import kotlinx.serialization.json.longOrNull51import kotlinx.serialization.json.put5253/** Credentials for one hub; the same ones the sync service stores in `sync_preference`. */54data class HubSession(val server: String, val token: String, val deviceId: String) {55 val wsBase: String get() = hubWebSocketBase(server)56 val headers: Map<String, String> get() = mapOf("Authorization" to "Bearer $token", "X-Device" to deviceId)57}5859/** REST side of rooms: create, look up, close. */60class RoomApi(61 private val http: HttpService,62 private val isSessionCurrent: () -> Boolean = { true },63) {64 data class Created(val code: String, val joinUrl: String)6566 suspend fun create(67 session: HubSession,68 media: RoomMedia,69 policy: String = "approve",70 playlistPolicy: String = "suggest",71 maxParticipants: Int? = null,72 ): Result<Created> = catchingNonCancellation {73 ensureCurrent()74 val body = buildJsonObject {75 put("media", RoomJson.encodeToJsonElement(RoomMedia.serializer(), media))76 put("policy", policy)77 put("playlist_policy", playlistPolicy)78 if (maxParticipants != null) put("max_participants", maxParticipants)79 }80 ensureCurrent()81 val r = http.request(HttpRequest("${session.server}/api/v1/rooms", "POST", session.headers + ("Content-Type" to "application/json"), body.toString()))82 ensureCurrent()83 check(r.statusCode in 200..299) { errorOf(r.body) ?: "Hub returned HTTP ${r.statusCode}" }84 val o = RoomJson.parseToJsonElement(r.body).jsonObject85 val code = requireNotNull(o["code"]?.jsonPrimitive?.contentOrNull) { "Hub response has no room code." }86 Created(code, o["join_url"]?.jsonPrimitive?.contentOrNull.orEmpty()).also { ensureCurrent() }87 }8889 suspend fun info(session: HubSession, code: String): Result<RoomSummary> = catchingNonCancellation {90 ensureCurrent()91 val r = http.request(HttpRequest("${session.server}/api/v1/rooms/${code.uppercase()}", "GET", session.headers))92 ensureCurrent()93 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}" }94 RoomJson.decodeFromString(RoomSummary.serializer(), r.body).also { ensureCurrent() }95 }9697 suspend fun close(session: HubSession, code: String): Result<Unit> = catchingNonCancellation {98 ensureCurrent()99 val r = http.request(HttpRequest("${session.server}/api/v1/rooms/${code.uppercase()}", "DELETE", session.headers))100 ensureCurrent()101 check(r.statusCode in 200..299) { errorOf(r.body) ?: "Hub returned HTTP ${r.statusCode}" }102 ensureCurrent()103 }104105 private suspend fun ensureCurrent() {106 currentCoroutineContext().ensureActive()107 if (!isSessionCurrent()) throw CancellationException("Together account changed during room request.")108 }109110 private fun errorOf(body: String): String? =111 runCatching { RoomJson.parseToJsonElement(body).jsonObject["error"]?.jsonPrimitive?.contentOrNull }.getOrNull()112}113114/**115 * One WebSocket into one room. [state] is the reduced view for the UI, [bursts] the live emoji116 * stream. Reconnects with backoff until [close] or the hub says the room is gone. Owns [engine]:117 * [close] releases it.118 *119 * Every command is fire-and-forget; the hub answers with a state message (or `error`, surfaced as120 * `RoomState.lastError`). The player/reader hooks call [sendState] and read [RoomState.position].121 */122class RoomClient(123 engine: HttpClientEngine,124 private val session: HubSession,125 code: String,126 scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default),127 private val isSessionCurrent: () -> Boolean = { true },128) {129 private val ownerJob = requireNotNull(scope.coroutineContext[Job]) { "Room client requires an owner job" }130 private val lifecycleJob = SupervisorJob(ownerJob)131 private val scope = CoroutineScope(scope.coroutineContext + lifecycleJob)132 private val lock = PlatformLock()133 private val engine = eu.friedcutlet.yokan.services.http.ProfileHttpEngine(engine, lifecycleJob) { isAvailable }134 private val retirementLock = Mutex()135 private var released = false136 val code: String = code.uppercase()137 private val client = HttpClient(this.engine) {138 expectSuccess = false139 install(WebSockets)140 }141 private val _state = MutableStateFlow(RoomState(code = this.code))142 val state: StateFlow<RoomState> = _state.asStateFlow()143 private val _bursts = MutableSharedFlow<RoomBurst>(extraBufferCapacity = 64)144 val bursts: SharedFlow<RoomBurst> = _bursts.asSharedFlow()145146 @Volatile147 private var ws: DefaultClientWebSocketSession? = null148 private var job: Job? = null149150 /** Checking a revoked account permanently ends this client, even if its credentials return. */151 internal val isAvailable: Boolean152 get() {153 if (!lifecycleJob.isActive || !ownerJob.isActive) return false154 // The guard may read the database. Keep it outside room/engine locks.155 if (!isSessionCurrent()) {156 lifecycleJob.cancel()157 return false158 }159 return lifecycleJob.isActive && ownerJob.isActive160 }161162 /** Stop admission immediately; transport release remains in awaited cleanup. */163 internal fun revoke() { lifecycleJob.cancel() }164165 fun connect() {166 if (!isAvailable) return167 val pending = lock.withLock {168 if (!lifecycleJob.isActive || !ownerJob.isActive || job?.isCompleted == false) return@withLock null169 // Start outside the lock even with an immediate owner dispatcher.170 scope.launch(start = CoroutineStart.LAZY) { run() }.also { job = it }171 }172 pending?.start()173 }174175 fun close() {176 lifecycleJob.cancel()177 release()178 }179180 /** Leaves socket/pinger/send finalizers joined before releasing the captured transport. */181 suspend fun closeAndJoin() = retirementLock.withLock {182 withContext(NonCancellable) {183 lifecycleJob.cancelAndJoin()184 // Engine call coroutines can finish outside the room's caller scope.185 val clientJob = client.coroutineContext[Job]186 clientJob?.cancel()187 engine.closeAndJoin()188 clientJob?.join()189 release()190 }191 }192193 private fun release() = lock.withLock {194 if (!released) {195 client.close()196 // Ktor leaves an engine it was handed open; this client is its only user.197 engine.close()198 released = true199 }200 }201202 private suspend fun run() {203 var backoff = 1_000L204 while (scope.isActive && isAvailable) {205 val terminal = _state.value.connection206 if (terminal is RoomConnection.Denied || terminal is RoomConnection.Closed) return207 try {208 client.webSocket(209 urlString = "${session.wsBase}/api/v1/rooms/$code/ws",210 request = {211 if (!isAvailable) throw CancellationException("Together account changed")212 header(HttpHeaders.Authorization, "Bearer ${session.token}")213 header("X-Device", session.deviceId)214 },215 ) {216 if (!isAvailable) throw CancellationException("Together account changed")217 ws = this218 backoff = 1_000L219 val pinger = launch {220 while (isActive) {221 ping()222 delay(15_000L)223 }224 }225 try {226 for (frame in incoming) {227 val text = (frame as? Frame.Text)?.readText() ?: continue228 val msg = runCatching { RoomJson.parseToJsonElement(text).jsonObject }.getOrNull() ?: continue229 handle(msg)230 }231 } finally {232 pinger.cancel()233 ws = null234 }235 }236 } catch (cancelled: CancellationException) {237 throw cancelled238 } catch (_: Throwable) {239 // fall through to reconnect240 }241 val after = _state.value.connection242 if (after is RoomConnection.Denied || after is RoomConnection.Closed || !isAvailable) return243 _state.update { it.copy(connection = RoomConnection.Connecting) }244 delay(backoff)245 backoff = (backoff * 2).coerceAtMost(30_000L)246 }247 }248249 private fun handle(msg: JsonObject) {250 if (!isAvailable) return251 when (msg["type"]?.jsonPrimitive?.contentOrNull) {252 "burst" -> {253 val emoji = msg["emoji"]?.jsonPrimitive?.contentOrNull ?: return254 _bursts.tryEmit(RoomBurst(emoji, msg["from"]?.jsonPrimitive?.contentOrNull.orEmpty()))255 }256 "pong" -> {257 val t = msg["t"]?.jsonPrimitive?.longOrNull ?: return258 val serverMs = msg["server_ms"]?.jsonPrimitive?.longOrNull ?: return259 // The hub echoes our send time, so no per-ping bookkeeping is shared with the pinger.260 val sent = t261 val now = nowMillis()262 val offset = serverMs - (sent + (now - sent) / 2)263 _state.update { it.copy(clockOffsetMs = offset) }264 }265 else -> _state.update { RoomReducer.reduce(it, msg) }266 }267 }268269 // ── commands ────────────────────────────────────────────────────────────270271 private fun send(type: String, build: kotlinx.serialization.json.JsonObjectBuilder.() -> Unit = {}) {272 if (!isAvailable) return273 val msg = buildJsonObject {274 put("type", type)275 build()276 }277 val socket = ws ?: return278 scope.launch {279 if (isAvailable) catchingNonCancellation { socket.send(Frame.Text(msg.toString())) }280 }281 }282283 private fun ping() = send("ping") { put("t", nowMillis()) }284285 /** Host/co-host: authoritative position. Pass the shape for the item type (see `RoomState.position`). */286 fun sendState(fields: Map<String, JsonElement>) = send("state") { fields.forEach { (k, v) -> put(k, v) } }287288 fun sendPlayback(positionMs: Long, playing: Boolean, rate: Double = 1.0) =289 sendState(mapOf("positionMs" to JsonPrimitive(positionMs), "playing" to JsonPrimitive(playing), "rate" to JsonPrimitive(rate)))290291 fun sendPage(page: Int, pages: Int) = sendState(mapOf("page" to JsonPrimitive(page), "pages" to JsonPrimitive(pages)))292293 fun sendProgress(progress: Double) = sendState(mapOf("progress" to JsonPrimitive(progress)))294295 fun setMedia(media: RoomMedia) = send("media") {296 RoomJson.encodeToJsonElement(RoomMedia.serializer(), media).jsonObject.forEach { (k, v) -> put(k, v) }297 }298299 fun approve(userId: String) = send("approve") { put("user", userId) }300 fun deny(userId: String) = send("deny") { put("user", userId) }301 fun kick(userId: String) = send("kick") { put("user", userId) }302 fun ban(userId: String) = send("ban") { put("user", userId) }303 fun promote(userId: String) = send("promote") { put("user", userId) }304 fun demote(userId: String) = send("demote") { put("user", userId) }305 fun setPolicy(policy: String? = null, playlistPolicy: String? = null) = send("set_policy") {306 policy?.let { put("policy", it) }307 playlistPolicy?.let { put("playlist_policy", it) }308 }309310 fun playlistAdd(media: RoomMedia, at: Int? = null) = send("pl_add") {311 put("media", RoomJson.encodeToJsonElement(RoomMedia.serializer(), media))312 at?.let { put("at", it) }313 }314 fun playlistSuggest(media: RoomMedia, note: String? = null) = send("pl_suggest") {315 put("media", RoomJson.encodeToJsonElement(RoomMedia.serializer(), media))316 note?.takeIf { it.isNotBlank() }?.let { put("note", it) }317 }318 fun playlistAccept(id: Long) = send("pl_accept") { put("id", id) }319 fun playlistReject(id: Long) = send("pl_reject") { put("id", id) }320 fun playlistRemove(id: Long) = send("pl_remove") { put("id", id) }321 fun playlistMove(id: Long, to: Int) = send("pl_move") { put("id", id); put("to", to) }322 fun playlistPlay(id: Long) = send("pl_play") { put("id", id) }323 fun playlistNext() = send("pl_next")324325 fun chat(text: String, replyTo: Long? = null) = send("chat") {326 put("text", text)327 replyTo?.let { put("reply_to", it) }328 }329 fun react(messageId: Long, emoji: String) = send("react") { put("msg_id", messageId); put("emoji", emoji) }330 fun burst(emoji: String) = send("burst") { put("emoji", emoji) }331 fun presence(detached: Boolean, position: JsonElement? = null) = send("presence") {332 put("detached", detached)333 position?.let { put("position", it) }334 }335336 companion object {337 /** The fixed quick-reaction row; the OS emoji keyboard covers everything else. */338 val QUICK_REACTIONS = listOf("👍", "❤️", "😂", "😮", "😢", "🔥", "👏", "💀")339 }340}341