Recently Written · git

subrep-android

Subrep on Android: live captions of the sound of the phone, made on the phone by Whisper, shared by link.

git clone https://github.com/equwal/subrep-android

Log | Files | Refs


app/src/main/kotlin/com/honjimaku/subrep/Messages.kt (1690 bytes)

1 package com.honjimaku.subrep
2 
3 import org.json.JSONObject
4 
5 /** A caption: `final` when the sentence is done, `partial` while it goes on, or `clear`. */
6 data class Caption(val type: String, val text: String)
7 
8 /**
9  * The messages of the relay protocol, the same as the desktop app sends them: a hello with
10  * the room secret, then the captions, then a status when something about the stream changes.
11  */
12 object Messages {
13 
14     fun relayHello(secret: String, lang: String, title: String): String =
15         JSONObject().put("secret", secret).put("lang", lang).put("title", title).toString()
16 
17     /** A caption as the viewer page reads it. */
18     fun caption(caption: Caption, nowSeconds: Double = System.currentTimeMillis() / 1000.0): String =
19         JSONObject().put("type", caption.type).put("text", caption.text).put("tr", "").put("ts", nowSeconds).toString()
20 
21     /** The stream is [live] in [lang], named [title]: sent when the language is found. */
22     fun status(live: Boolean, lang: String, title: String): String =
23         JSONObject().put("type", "status").put("live", live).put("lang", lang).put("title", title).toString()
24 
25     /** The reason in an error message of the relay; null for another message. */
26     fun error(json: String): String? {
27         val message = parse(json) ?: return null
28         if (message.optString("type") != "error") return null
29         return message.optString("error").ifEmpty { "error" }
30     }
31 
32     /** True for the ready message that the relay sends after the hello. */
33     fun isReady(json: String): Boolean = parse(json)?.optString("type") == "ready"
34 
35     private fun parse(json: String): JSONObject? = runCatching { JSONObject(json) }.getOrNull()
36 }