diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index f22ab4b2..6c60c191 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -9,8 +9,8 @@ android { applicationId = "tv.orbit.classic" minSdk = 26 targetSdk = 36 - versionCode = 211 - versionName = "0.108.51-settings-arcade" + versionCode = 212 + versionName = "0.108.52-multiroom" } buildFeatures { compose = true } // Android logging and the like do nothing in unit tests, so whole flows (a channel read from a fake server) can run. diff --git a/android/app/src/main/java/tv/orbit/classic/CreateChannel.kt b/android/app/src/main/java/tv/orbit/classic/CreateChannel.kt index c65d57c0..8681c4bd 100644 --- a/android/app/src/main/java/tv/orbit/classic/CreateChannel.kt +++ b/android/app/src/main/java/tv/orbit/classic/CreateChannel.kt @@ -159,7 +159,7 @@ internal fun CreateChannelFlow(maker: ChannelMaker, editing: CustomChannel?, onD } @Composable -private fun ChoiceCard(title: String, lines: List, modifier: Modifier, selected: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) { +internal fun ChoiceCard(title: String, lines: List, modifier: Modifier, selected: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) { var focused by remember { mutableStateOf(false) } val corner = RoundedCornerShape(12.dp) Column(modifier.onFocusChanged { focused = it.isFocused }.background(if (focused) Navy else Panel, corner) @@ -172,7 +172,7 @@ private fun ChoiceCard(title: String, lines: List, modifier: Modifier, s } @Composable -private fun OrbitField(value: String, onChange: (String) -> Unit, hint: String, modifier: Modifier) { +internal fun OrbitField(value: String, onChange: (String) -> Unit, hint: String, modifier: Modifier) { var focused by remember { mutableStateOf(false) } Box(modifier.onFocusChanged { focused = it.isFocused }.background(Panel, RoundedCornerShape(8.dp)).border(2.dp, if (focused) Yellow else Blue, RoundedCornerShape(8.dp)).padding(10.dp)) { if (value.isEmpty()) Text(hint, color = Muted, fontSize = 15.sp) diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt b/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt index 06f0aad0..6f546405 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt @@ -62,9 +62,9 @@ internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUI } /** The sign-in headers for this kind of server. */ internal fun authHeaders(token: String?): Map = when (kind) { - ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.51\"") + + ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.52\"") + (token?.let { mapOf("X-Emby-Token" to it) } ?: emptyMap()) - ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.51\"" + + ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.52\"" + (token?.let { ", Token=\"$it\"" } ?: "")) } /** One picture from the provider, or nothing. Same fixed origin and no redirects, and failures are never shown or logged. */ diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt index 253bdd28..d22caa99 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt @@ -329,6 +329,8 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea LaunchedEffect(scheduledChannels) { windingDown = scheduledChannels[TOTS_NUMBER]?.stepIn?.let { it.endMs > System.currentTimeMillis() } == true } fun smartLoop(programming: ChannelProgramming) = (extraChannels + listOfNotNull(channel, afterDarkChannel, toonamiChannel)).firstOrNull { it.number == programming.number } LaunchedEffect(session != null) { if (session != null) onSignedIn() } + // Joined from another room: its server, so this TV only needs to sign in. + LaunchedEffect(RoomArrival.server) { RoomArrival.server?.let { if (session == null) serverText = it } } // The first-launch flow's channels, one after another, as switching each on in Settings does. In the tour, it only counts. LaunchedEffect(ChannelSetup.wanted, session) { val active = session ?: return@LaunchedEffect diff --git a/android/app/src/main/java/tv/orbit/classic/MainActivity.kt b/android/app/src/main/java/tv/orbit/classic/MainActivity.kt index e444c094..be1bb432 100644 --- a/android/app/src/main/java/tv/orbit/classic/MainActivity.kt +++ b/android/app/src/main/java/tv/orbit/classic/MainActivity.kt @@ -60,6 +60,7 @@ class MainActivity : ComponentActivity() { AfterDarkLock.load(this) // Opening the saved sign-in takes seconds on the box: start it now, while the first screen is drawn. runCatching { Workspaces.current(this).connection.warm() } + Rooms.load(this) // The phone page's server runs only while Orbit is open (Create your own from a phone). PhoneLink.init(this) Profiles.load(this) diff --git a/android/app/src/main/java/tv/orbit/classic/Onboarding.kt b/android/app/src/main/java/tv/orbit/classic/Onboarding.kt index b9e33f79..c6ba1587 100644 --- a/android/app/src/main/java/tv/orbit/classic/Onboarding.kt +++ b/android/app/src/main/java/tv/orbit/classic/Onboarding.kt @@ -29,7 +29,9 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.tv.material3.Text +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext import kotlin.math.abs import kotlin.math.sin @@ -109,6 +111,8 @@ private fun clock(calm: Boolean): Long { internal fun OnboardingScreen(signedIn: Boolean, onDone: (tour: Boolean) -> Unit) { val step = Onboarding.step ?: return val context = LocalContext.current + // Multiroom: joining another room instead of setting up from scratch. + var joining by remember { mutableStateOf(false) } // A step back with Back, except from the first. BackHandler(step != OnboardStep.Welcome && step != OnboardStep.AllSet) { Onboarding.go(OnboardStep.entries[step.ordinal - 1].let { if (it == OnboardStep.SignIn && signedIn && !Onboarding.tour) OnboardStep.Server else it }) } Box(Modifier.fillMaxSize().then(if (step == OnboardStep.SignIn && !Onboarding.tour) Modifier else Modifier.background(Navy))) { @@ -116,7 +120,8 @@ internal fun OnboardingScreen(signedIn: Boolean, onDone: (tour: Boolean) -> Unit Steps(step, Modifier.align(Alignment.TopCenter).padding(top = 16.dp)) Box(Modifier.fillMaxSize().padding(top = 70.dp, bottom = 24.dp, start = 40.dp, end = 40.dp)) { when (step) { - OnboardStep.Welcome -> WelcomeStep { Onboarding.go(OnboardStep.Look) } + OnboardStep.Welcome -> if (joining) JoinRoomFlow(onJoined = { joining = false; Onboarding.go(if (signedIn) OnboardStep.Channels else OnboardStep.SignIn) }, onBack = { joining = false }) + else WelcomeStep(onJoin = if (Onboarding.tour) null else ({ joining = true })) { Onboarding.go(OnboardStep.Look) } OnboardStep.Look -> LookStep { Onboarding.go(OnboardStep.Server) } OnboardStep.Server -> ServerStep { Onboarding.go(OnboardStep.SignIn) } OnboardStep.SignIn -> if (Onboarding.tour) TourSignedIn { Onboarding.go(OnboardStep.Channels) } @@ -131,13 +136,13 @@ internal fun OnboardingScreen(signedIn: Boolean, onDone: (tour: Boolean) -> Unit } @Composable -private fun WelcomeStep(onNext: () -> Unit) { +private fun WelcomeStep(onJoin: (() -> Unit)? = null, onNext: () -> Unit) { val calm = reduceMotion(); val t = clock(calm) val go = remember { FocusRequester() } LaunchedEffect(Unit) { go.requestFocus() } Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { // Ollie rolls in from the left, settles with a bounce, then blinks every few seconds. - Canvas(Modifier.size(260.dp)) { + Canvas(Modifier.size(220.dp)) { val roll = if (calm) 1f else (t / 1_300f).coerceIn(0f, 1f) val eased = 1 - (1 - roll) * (1 - roll) val bounce = if (calm || t < 1_300) 0f else abs(sin((t - 1_300) / 180.0)).toFloat() * (1f - ((t - 1_300) / 700f).coerceIn(0f, 1f)) * size.height * .06f @@ -151,7 +156,12 @@ private fun WelcomeStep(onNext: () -> Unit) { Text("Welcome to Orbit", color = Ink, fontFamily = Anton, fontSize = 40.sp) Text("Proper TV channels, made from your own films and series.", color = Muted, fontSize = 18.sp, modifier = Modifier.padding(top = 8.dp)) Text("It takes about five minutes. I'm Ollie, and I'll show you round.", color = Muted, fontSize = 16.sp) - OrbitButton("Let's go", Modifier.padding(top = 24.dp).width(200.dp).focusRequester(go), centred = true, onClick = onNext) + // Multiroom (Paul, 6 November 2026): beside Let's go, for a TV joining one already set up. + Row(Modifier.padding(top = 24.dp), horizontalArrangement = Arrangement.spacedBy(16.dp)) { + OrbitButton("Let's go", Modifier.width(220.dp).focusRequester(go), centred = true, onClick = onNext) + if (onJoin != null) OrbitButton("Join another room", Modifier.width(220.dp), centred = true, onClick = onJoin) + } + if (onJoin != null) Text("Already have Orbit on another TV? Copy its channels and settings.", Modifier.padding(top = 8.dp), color = Muted, fontSize = 13.sp) } } @@ -219,6 +229,15 @@ private fun ChannelsStep(onNext: () -> Unit) { val setting = ChannelSetup.wanted.isNotEmpty() // Create your own from here (Paul, 6 November 2026): the same flow as Settings', then back to this step. In the tour // nothing is saved, so its last step only says what would have happened. + // Joined from another room: its channels and Director's Chair go into this server's workspace, and its line-up is set up. + val context = LocalContext.current + LaunchedEffect(RoomArrival.bundle) { + val arrived = RoomArrival.bundle ?: return@LaunchedEffect + if (Onboarding.tour) return@LaunchedEffect + val lineup = withContext(Dispatchers.IO) { runCatching { RoomBundle.applyToWorkspace(Workspaces.current(context).scheduleDir, arrived, RoomArrival.parts) }.getOrDefault(emptyList()) } + RoomArrival.done() + if (lineup.isNotEmpty()) ChannelSetup.begin(SmartChannels.map { it.number }.filter { it in lineup }) + } var creating by remember { mutableStateOf(false) } var made by remember { mutableStateOf(null) } val real = PhoneLink.handler?.maker diff --git a/android/app/src/main/java/tv/orbit/classic/PhoneLink.kt b/android/app/src/main/java/tv/orbit/classic/PhoneLink.kt index 0d5c06ed..7fe7b63f 100644 --- a/android/app/src/main/java/tv/orbit/classic/PhoneLink.kt +++ b/android/app/src/main/java/tv/orbit/classic/PhoneLink.kt @@ -61,6 +61,9 @@ internal object PhoneLink { @Volatile private var server: ServerSocket? = null private val workers = Executors.newFixedThreadPool(4) @Volatile var handler: PhoneHandler? = null + /** Multiroom: the room being added, answered at /room/ while Settings shows its code. */ + @Volatile var roomOffer: RoomOffer? = null + fun offerRoom(offer: RoomOffer?) { roomOffer = offer; if (offer != null) start() else if (phones.isEmpty() && pairing == null) stop() } /** Put in front of [handler] for a while: the Welcome Tour's, which saves nothing. */ @Volatile var standIn: PhoneHandler? = null var pairing by mutableStateOf(null) @@ -149,7 +152,7 @@ internal object PhoneLink { } private fun respond(out: OutputStream, status: Int, type: String, body: ByteArray, extra: List = emptyList()) { - val reason = mapOf(200 to "OK", 302 to "Found", 400 to "Bad Request", 403 to "Forbidden", 404 to "Not Found", 429 to "Too Many Requests")[status] ?: "OK" + val reason = mapOf(200 to "OK", 202 to "Accepted", 302 to "Found", 400 to "Bad Request", 403 to "Forbidden", 404 to "Not Found", 409 to "Conflict", 410 to "Gone", 413 to "Too Large", 429 to "Too Many Requests")[status] ?: "OK" val head = (listOf("HTTP/1.1 $status $reason", "Content-Type: $type", "Content-Length: ${body.size}", "Cache-Control: no-store", "X-Content-Type-Options: nosniff", "X-Frame-Options: DENY", "Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'", "Connection: close") + extra).joinToString("\r\n") + "\r\n\r\n" @@ -177,6 +180,11 @@ internal object PhoneLink { val input = BufferedInputStream(socket.getInputStream()); val out = socket.getOutputStream() val r = readRequest(input) ?: return if (!hostIsAnAddress(r.headers["host"])) return respond(out, 400, "text/plain", "Use the TV's address.".toByteArray()) + if (r.path.startsWith("/room/")) { + val offer = roomOffer ?: return json(out, 404, JSONObject().put("error", "That TV isn't adding a room right now.")) + val (status, reply) = runCatching { offer.handle(r.method, r.path, r.body) }.getOrElse { 400 to JSONObject() } + return json(out, status, reply) + } val phone = phoneOf(r) when { r.path == "/join" -> join(r, out, socket.inetAddress.hostAddress.orEmpty()) diff --git a/android/app/src/main/java/tv/orbit/classic/Rooms.kt b/android/app/src/main/java/tv/orbit/classic/Rooms.kt new file mode 100644 index 00000000..8d7783b7 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/Rooms.kt @@ -0,0 +1,250 @@ +package tv.orbit.classic + +import android.content.Context +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.security.KeyFactory +import java.security.KeyPair +import java.security.KeyPairGenerator +import java.security.MessageDigest +import java.security.SecureRandom +import java.security.spec.ECGenParameterSpec +import java.security.spec.X509EncodedKeySpec +import java.util.Base64 +import javax.crypto.Cipher +import javax.crypto.KeyAgreement +import javax.crypto.Mac +import javax.crypto.spec.GCMParameterSpec +import javax.crypto.spec.SecretKeySpec + +/** + * Orbit Multiroom, stage 1: Transfer my Orbit (Paul, 5 and 6 November 2026, from the approved design/multiroom). A new box + * joins one already set up on the home network; the existing TV shows a six-digit code and must allow it; the chosen set-up + * is copied once, encrypted, and nothing stays connected. The rules: + * - Only on the home network, through the phone link's server, and only while the existing TV is showing its code. + * - The two boxes agree a key (ECDH, P-256); the code proves neither is talking to someone in the middle. Three wrong proofs + * and the code is gone; a code lasts five minutes and works once. + * - The Emby or Jellyfin password and sign-in token never travel: the new box signs in for itself. The Adult PIN travels + * only as its salted hash. What comes across is shown, and ticked, before it's applied. + * - Schedules don't travel: each room plans its own week from the same channels. + */ +internal object RoomCrypto { + private val random = SecureRandom() + fun keyPair(): KeyPair = KeyPairGenerator.getInstance("EC").apply { initialize(ECGenParameterSpec("secp256r1")) }.generateKeyPair() + fun publicOf(pair: KeyPair): String = Base64.getEncoder().encodeToString(pair.public.encoded) + fun shared(mine: KeyPair, theirs: String): ByteArray = KeyAgreement.getInstance("ECDH").run { + init(mine.private); doPhase(KeyFactory.getInstance("EC").generatePublic(X509EncodedKeySpec(Base64.getDecoder().decode(theirs))), true); generateSecret() + } + private fun hmac(key: ByteArray, data: ByteArray): ByteArray = Mac.getInstance("HmacSHA256").run { init(SecretKeySpec(key, "HmacSHA256")); doFinal(data) } + /** Two keys from the agreed secret and the code: one to prove the code, one to seal what's copied. */ + fun keys(secret: ByteArray, code: String, transcript: String): Pair { + val prk = hmac(MessageDigest.getInstance("SHA-256").digest(transcript.toByteArray()), secret + code.toByteArray()) + return hmac(prk, "orbit-room-proof\u0001".toByteArray()) to hmac(prk, "orbit-room-seal\u0001".toByteArray()) + } + fun proof(key: ByteArray, who: String): String = Base64.getEncoder().encodeToString(hmac(key, who.toByteArray())) + fun matches(expected: String, given: String?) = given != null && MessageDigest.isEqual(expected.toByteArray(), given.toByteArray()) + fun seal(key: ByteArray, plain: ByteArray): String { + val nonce = ByteArray(12).also(random::nextBytes) + val sealed = Cipher.getInstance("AES/GCM/NoPadding").run { init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce)); doFinal(plain) } + return Base64.getEncoder().encodeToString(nonce + sealed) + } + fun open(key: ByteArray, sealed: String): ByteArray { + val bytes = Base64.getDecoder().decode(sealed) + return Cipher.getInstance("AES/GCM/NoPadding").run { init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, bytes, 0, 12)); doFinal(bytes, 12, bytes.size - 12) } + } + fun code(): String = "%06d".format(random.nextInt(1_000_000)) +} + +/** The parts of a set-up that can come across, each ticked on the new box before it's applied. */ +internal enum class RoomPart(val title: String, val line: String) { + Channels("Channels and your own channels", "Which channels are on, the channels you've made, and the titles chosen for them"), + Family("Profiles, Kids and the Adult PIN", "The PIN comes across scrambled, never as its digits"), + Look("Look and On screen settings", "The look, subtitles, the cast, motion and the rest"), + Director("Director's Chair decisions", "What you placed, dropped and taught it"), + Arcade("Arcade bests", "High scores and games won") +} + +/** On screen and Arcade settings that may travel; the sound output and anything about this box stay where they are. */ +private val LookKeys = listOf("look", "subtitles_on", "channel_logo", "idents", "ident_sound", "special_idents", "block_ident_sound", "squeeze_back", + "cast_on", "drive_in_intro", "reduce_motion") +private val ArcadeKeys = listOf("snake_best", "block_drop_best", "brick_break_best", "pairs_best", "patience_wins", "orb_man_best", "blast_best", "skydoku_solved", "snake_music") +private val DirectorFiles = listOf("director-decisions-0.json", "director-learning-0.json", "event-ideas-history-0.json") +private const val BUNDLE_LIMIT = 4 * 1024 * 1024 + +/** What one box sends another: plain settings and small files, read from the open workspace. Never a password or token. */ +internal object RoomBundle { + private fun prefsJson(context: Context, name: String, keys: List?): JSONObject { + val all = context.getSharedPreferences(name, Context.MODE_PRIVATE).all + return JSONObject().also { o -> all.filterKeys { keys == null || it in keys }.forEach { (k, v) -> o.put(k, JSONObject().put("t", v!!.javaClass.simpleName).put("v", v)) } } + } + private fun putPrefs(context: Context, name: String, o: JSONObject?, keys: List?) { + if (o == null) return + val edit = context.getSharedPreferences(name, Context.MODE_PRIVATE).edit() + o.keys().forEach { k -> + if (keys != null && k !in keys) return@forEach + val e = o.getJSONObject(k) + when (e.getString("t")) { + "Boolean" -> edit.putBoolean(k, e.getBoolean("v")); "Integer" -> edit.putInt(k, e.getInt("v")); "Long" -> edit.putLong(k, e.getLong("v")) + "String" -> edit.putString(k, e.getString("v").take(65_536)); "Float" -> edit.putFloat(k, e.getDouble("v").toFloat()) + } + } + edit.apply() + } + private fun files(dir: File, names: List) = JSONObject().also { o -> names.forEach { n -> File(dir, n).takeIf { it.isFile && it.length() < 1_000_000 }?.let { o.put(n, it.readText()) } } } + + /** This box's set-up, as the existing room sends it. */ + fun collect(context: Context, workspace: ServerWorkspace, room: String): JSONObject { + val dir = workspace.scheduleDir + // The channels that are on here; the new room plans its own schedules for them. + val lineup = SmartChannels.map { it.number }.filter { n -> runCatching { JSONObject(File(dir, "progress-$n.json").readText()).optBoolean("enabled") }.getOrDefault(false) } + val choices = dir.listFiles { f -> Regex("choices-\\d+\\.json").matches(f.name) }?.map { it.name }.orEmpty() + return JSONObject().put("version", 1).put("room", room).put("server", workspace.origin) + .put(RoomPart.Channels.name, JSONObject().put("lineup", JSONArray(lineup)).put("files", files(dir, choices + "yours.json"))) + .put(RoomPart.Family.name, JSONObject().put("profiles", prefsJson(context, "orbit_profiles", null)).put("lock", prefsJson(context, "orbit_lock", listOf("after_dark_salt", "after_dark_pin")))) + .put(RoomPart.Look.name, prefsJson(context, "orbit_settings", LookKeys)) + .put(RoomPart.Director.name, files(dir, DirectorFiles)) + .put(RoomPart.Arcade.name, prefsJson(context, "orbit_settings", ArcadeKeys)) + } + + /** What doesn't need a server: the look, the family and the arcade, straight away. */ + fun applyNow(context: Context, bundle: JSONObject, parts: Set) { + if (RoomPart.Look in parts) { putPrefs(context, "orbit_settings", bundle.optJSONObject(RoomPart.Look.name), LookKeys); OrbitTheme.load(context) } + if (RoomPart.Arcade in parts) putPrefs(context, "orbit_settings", bundle.optJSONObject(RoomPart.Arcade.name), ArcadeKeys) + if (RoomPart.Family in parts) bundle.optJSONObject(RoomPart.Family.name)?.let { f -> + putPrefs(context, "orbit_profiles", f.optJSONObject("profiles"), listOf("profiles", "kids_on")) + putPrefs(context, "orbit_lock", f.optJSONObject("lock"), listOf("after_dark_salt", "after_dark_pin")) + Profiles.load(context); AfterDarkLock.load(context) + } + } + + /** What belongs to a server's workspace, once this box has signed in to it. Returns the channels to set up. */ + fun applyToWorkspace(dir: File, bundle: JSONObject, parts: Set): List { + dir.mkdirs() + fun write(files: JSONObject?) = files?.keys()?.forEach { n -> + if (Regex("(choices-\\d+|yours|director-decisions-0|director-learning-0|event-ideas-history-0)\\.json").matches(n) && !File(dir, n).exists()) + File(dir, n).writeText(files.getString(n)) + } + var lineup = emptyList() + if (RoomPart.Channels in parts) bundle.optJSONObject(RoomPart.Channels.name)?.let { c -> + write(c.optJSONObject("files")); CustomChannels.load(dir) + lineup = c.optJSONArray("lineup")?.let { a -> (0 until minOf(a.length(), 200)).map { a.getInt(it) } }.orEmpty() + } + if (RoomPart.Director in parts) write(bundle.optJSONObject(RoomPart.Director.name)) + return lineup + } + + fun limit(text: String) = text.length <= BUNDLE_LIMIT +} + +/** This room's name, and the rooms that have copied it. Kept on this box only. */ +internal object Rooms { + var name by mutableStateOf("Living Room") + private set + var joined by mutableStateOf>>(emptyList()) + private set + private fun prefs(context: Context) = context.getSharedPreferences("orbit_rooms", Context.MODE_PRIVATE) + fun load(context: Context) { + name = prefs(context).getString("name", null) ?: "Living Room" + joined = runCatching { JSONArray(prefs(context).getString("joined", "[]")).let { a -> (0 until a.length()).map { a.getJSONObject(it).let { o -> o.getString("room") to o.getLong("at") } } } }.getOrDefault(emptyList()) + } + fun rename(context: Context, to: String) { name = to.trim().take(30).ifBlank { "Living Room" }; prefs(context).edit().putString("name", name).apply() } + fun recordJoined(context: Context, room: String, at: Long) { + joined = (joined.filter { it.first != room } + (room to at)).takeLast(12) + prefs(context).edit().putString("joined", JSONArray(joined.map { JSONObject().put("room", it.first).put("at", it.second) }).toString()).apply() + } +} + +/** + * The existing room's side: one offer at a time, while Settings › Rooms and phones › Add a room is showing its code. Answers + * the phone link's /room/ requests: hello (keys), proof (the code), and the copy once this TV has allowed it. + */ +internal class RoomOffer(val code: String, val untilMs: Long, private val room: String, private val bundle: () -> JSONObject) { + enum class State { Waiting, Asking, Allowed, Refused, Sent, Ended } + var state by mutableStateOf(State.Waiting) + var joining by mutableStateOf(null) + private val pair = RoomCrypto.keyPair() + private var transcript = "" + private var seal: ByteArray? = null + private var proofKey: ByteArray? = null + private var tries = 0 + + @Synchronized fun handle(method: String, path: String, body: String, now: Long = System.currentTimeMillis()): Pair { + if (now > untilMs && state != State.Sent) { state = State.Ended; return 410 to JSONObject().put("error", "That code has run out.") } + val o = runCatching { JSONObject(body.ifBlank { "{}" }) }.getOrElse { return 400 to JSONObject() } + return when ("$method $path") { + "POST /room/hello" -> { + if (state != State.Waiting || proofKey != null) return 409 to JSONObject().put("error", "Another room is already joining.") + val theirs = o.optString("pub").takeIf { it.length in 80..200 } ?: return 400 to JSONObject() + val name = o.optString("name").trim().take(30).ifBlank { "A new TV" } + val mine = RoomCrypto.publicOf(pair) + transcript = "$mine|$theirs" + val (proof, sealKey) = RoomCrypto.keys(runCatching { RoomCrypto.shared(pair, theirs) }.getOrElse { return 400 to JSONObject() }, code, transcript) + proofKey = proof; seal = sealKey; joining = name + 200 to JSONObject().put("pub", mine).put("room", room) + } + "POST /room/proof" -> { + val key = proofKey ?: return 409 to JSONObject() + if (state != State.Waiting) return 409 to JSONObject() + if (!RoomCrypto.matches(RoomCrypto.proof(key, "joiner"), o.optString("proof"))) { + if (++tries >= 3) state = State.Ended + return 403 to JSONObject().put("error", "That code didn't match.") + } + state = State.Asking + 200 to JSONObject().put("proof", RoomCrypto.proof(key, "existing")) + } + "GET /room/copy" -> when (state) { + State.Asking -> 202 to JSONObject().put("waiting", true) + State.Refused -> 403 to JSONObject().put("error", "The other TV said not now.") + State.Allowed -> { + val text = bundle().toString() + if (!RoomBundle.limit(text)) return 413 to JSONObject() + state = State.Sent + android.util.Log.i("OrbitRooms", "copy sent bytes=${text.length}") + 200 to JSONObject().put("sealed", RoomCrypto.seal(seal!!, text.toByteArray())) + } + else -> 409 to JSONObject() + } + else -> 404 to JSONObject() + } + } + fun allow() { if (state == State.Asking) state = State.Allowed } + fun refuse() { if (state == State.Asking) state = State.Refused } +} + +/** The new room's side, over any transport: the phone link on the home network, or a test's direct call. */ +internal class RoomJoin(private val call: (method: String, path: String, body: String) -> Pair) { + private val pair = RoomCrypto.keyPair() + private var proofKey: ByteArray? = null + private var seal: ByteArray? = null + var otherRoom: String? = null + private set + + /** Says hello and proves the code; true when the other TV must now allow it. */ + fun prove(code: String, name: String): Result = runCatching { + val mine = RoomCrypto.publicOf(pair) + val (status, text) = call("POST", "/room/hello", JSONObject().put("pub", mine).put("name", name).toString()) + val hello = JSONObject(text) + check(status == 200) { hello.optString("error").ifBlank { "That TV isn't adding a room right now." } } + val theirs = hello.getString("pub"); otherRoom = hello.optString("room").take(30) + val (proof, sealKey) = RoomCrypto.keys(RoomCrypto.shared(pair, theirs), code.filter(Char::isDigit), "$theirs|$mine") + proofKey = proof; seal = sealKey + val (ok, reply) = call("POST", "/room/proof", JSONObject().put("proof", RoomCrypto.proof(proof, "joiner")).toString()) + check(ok == 200) { JSONObject(reply).optString("error").ifBlank { "That code didn't match." } } + // The other TV proves the code too, so this box knows it's talking to the room it chose. + check(RoomCrypto.matches(RoomCrypto.proof(proof, "existing"), JSONObject(reply).optString("proof"))) { "That TV couldn't prove the code." } + } + + /** Null while the other TV hasn't decided; the copy once it has allowed it. */ + fun collect(): Result = runCatching { + val (status, text) = call("GET", "/room/copy", "") + when (status) { + 202 -> null + 200 -> JSONObject(String(RoomCrypto.open(seal!!, JSONObject(text).getString("sealed")))).also { check(it.getInt("version") == 1) } + else -> error(JSONObject(text).optString("error").ifBlank { "The copy didn't arrive." }) + } + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/RoomsUi.kt b/android/app/src/main/java/tv/orbit/classic/RoomsUi.kt new file mode 100644 index 00000000..a6e79545 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/RoomsUi.kt @@ -0,0 +1,265 @@ +package tv.orbit.classic + +import android.content.Context +import android.net.nsd.NsdManager +import android.net.nsd.NsdServiceInfo +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.tv.material3.Text +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.InetAddress +import java.net.URL + +private const val ROOM_SERVICE = "_orbitroom._tcp." +private const val OFFER_MS = 5 * 60_000L + +/** Calls the other room's phone link: only at an address on the home network, typed or found, never a name. */ +internal fun roomTransport(address: String, port: Int = PhoneLink.PORT): ((String, String, String) -> Pair)? { + val ip = address.trim().takeIf { Regex("^\\d{1,3}(\\.\\d{1,3}){3}$").matches(it) } ?: return null + if (!EmbyServer.isHomeAddress(InetAddress.getByName(ip))) return null + return { method, path, body -> + val c = URL("http://$ip:$port$path").openConnection() as HttpURLConnection + c.connectTimeout = 5_000; c.readTimeout = 15_000; c.requestMethod = method; c.instanceFollowRedirects = false + if (method == "POST") { c.doOutput = true; c.setRequestProperty("Content-Type", "application/json"); c.setRequestProperty("X-Orbit", "1"); c.outputStream.use { it.write(body.toByteArray()) } } + val status = c.responseCode + val text = (if (status < 400) c.inputStream else c.errorStream)?.use { it.readBytes().toString(Charsets.UTF_8) }.orEmpty() + c.disconnect(); status to text + } +} + +/** Other rooms on the Wi-Fi that are adding a room right now, by name and address. */ +internal class RoomFinder(context: Context) { + private val nsd = context.getSystemService(Context.NSD_SERVICE) as? NsdManager + var found by mutableStateOf>>(emptyList()) + private set + private var listener: NsdManager.DiscoveryListener? = null + @Suppress("DEPRECATION") + fun start() { + if (listener != null || nsd == null) return + listener = object : NsdManager.DiscoveryListener { + override fun onServiceFound(info: NsdServiceInfo) { + runCatching { nsd?.resolveService(info, object : NsdManager.ResolveListener { + override fun onResolveFailed(info: NsdServiceInfo, error: Int) {} + override fun onServiceResolved(info: NsdServiceInfo) { + val ip = info.host?.hostAddress ?: return + if (roomTransport(ip) == null) return + found = (found.filter { it.second != ip } + (info.serviceName.take(30) to ip)).sortedBy { it.first } + } + }) } + } + override fun onServiceLost(info: NsdServiceInfo) { found = found.filter { it.first != info.serviceName } } + override fun onDiscoveryStarted(type: String) {} + override fun onDiscoveryStopped(type: String) {} + override fun onStartDiscoveryFailed(type: String, error: Int) {} + override fun onStopDiscoveryFailed(type: String, error: Int) {} + } + runCatching { nsd?.discoverServices(ROOM_SERVICE, NsdManager.PROTOCOL_DNS_SD, listener) } + } + fun stop() { listener?.let { runCatching { nsd?.stopServiceDiscovery(it) } }; listener = null } +} + +/** What arrived from the other room, kept until this box has signed in and can put the rest in place. */ +internal object RoomArrival { + var bundle by mutableStateOf(null) + private set + var parts by mutableStateOf>(emptySet()) + private set + val server get() = bundle?.optString("server")?.takeIf { it.isNotBlank() } + fun keep(copy: JSONObject, chosen: Set) { bundle = copy; parts = chosen } + fun done() { bundle = null; parts = emptySet() } +} + +/** + * Settings › Rooms and phones › Add a room, on the TV already set up: a six-digit code for the new TV, found on the Wi-Fi by + * this room's name, then Allow (with the Adult PIN if one is set). The copy goes once; nothing stays connected. + */ +@Composable +internal fun AddRoomPanel(onClose: () -> Unit, modifier: Modifier = Modifier) { + val context = LocalContext.current + val workspace = remember { Workspaces.current(context) } + val offer = remember { RoomOffer(RoomCrypto.code(), System.currentTimeMillis() + OFFER_MS, Rooms.name) { RoomBundle.collect(context, workspace, Rooms.name) } } + var now by remember { mutableLongStateOf(System.currentTimeMillis()) } + var asking by remember { mutableStateOf(false) } + var problem by remember { mutableStateOf(null) } + LaunchedEffect(Unit) { while (true) { delay(1_000); now = System.currentTimeMillis() } } + // Found on the Wi-Fi by this room's name while the code shows; gone, with the offer, when it closes. + DisposableEffect(offer) { + PhoneLink.offerRoom(offer) + val nsd = context.getSystemService(Context.NSD_SERVICE) as? NsdManager + val registration = object : NsdManager.RegistrationListener { + override fun onServiceRegistered(info: NsdServiceInfo) {} + override fun onRegistrationFailed(info: NsdServiceInfo, error: Int) {} + override fun onServiceUnregistered(info: NsdServiceInfo) {} + override fun onUnregistrationFailed(info: NsdServiceInfo, error: Int) {} + } + runCatching { nsd?.registerService(NsdServiceInfo().apply { serviceName = Rooms.name; serviceType = ROOM_SERVICE; port = PhoneLink.PORT }, NsdManager.PROTOCOL_DNS_SD, registration) } + onDispose { runCatching { nsd?.unregisterService(registration) }; PhoneLink.offerRoom(null) } + } + LaunchedEffect(offer.state) { + if (offer.state == RoomOffer.State.Sent) { offer.joining?.let { Rooms.recordJoined(context, it, System.currentTimeMillis()) }; android.util.Log.i("OrbitRooms", "room joined") } + } + BackHandler { onClose() } + if (asking) { PinEntry("Enter the Adult PIN to allow it", problem, onDone = { pin -> + if (AfterDarkLock.check(context, pin)) { asking = false; offer.allow() } else problem = "That PIN didn't match." + }, onCancel = { asking = false }); return } + val first = remember { FocusRequester() } + Column(modifier, verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text("Add a room", color = Ink, fontFamily = Anton, fontSize = 26.sp) + when (offer.state) { + RoomOffer.State.Waiting, RoomOffer.State.Ended -> { + val left = ((offer.untilMs - now) / 1000).coerceAtLeast(0) + Text("On the new TV, open Orbit and choose Join another room. Pick ${Rooms.name}, or type this TV's address, then enter this code:", color = Muted, fontSize = 14.sp) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + offer.code.forEach { digit -> Box(Modifier.size(52.dp, 64.dp).background(Panel, RoundedCornerShape(8.dp)), contentAlignment = Alignment.Center) { + Text("$digit", color = Ink, fontFamily = Anton, fontSize = 34.sp) } } + } + PhoneLink.homeAddress()?.let { Text("This TV's address: $it", color = Ink, fontSize = 15.sp, fontWeight = FontWeight.SemiBold) } + Text(if (left > 0 && offer.state == RoomOffer.State.Waiting) "The code works once, for %d:%02d more.".format(left / 60, left % 60) else "That code has ended. Go back and add a room again.", + color = Muted, fontSize = 13.sp) + Text("Your Emby or Jellyfin password never travels: the new TV signs in for itself. Schedules stay with each room.", color = Muted, fontSize = 12.sp) + OrbitButton("Close", Modifier.width(160.dp).focusRequester(first), onClick = onClose) + LaunchedEffect(Unit) { runCatching { first.requestFocus() } } + } + RoomOffer.State.Asking -> { + Text("${offer.joining ?: "A new room"} wants to join", color = Yellow, fontSize = 20.sp, fontWeight = FontWeight.SemiBold) + Text("It has the right code. Allow it to copy this Orbit's set-up? Only allow it if you're setting up a TV in your home.", color = Muted, fontSize = 14.sp) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + OrbitButton("Allow", Modifier.width(160.dp).focusRequester(first), onClick = { if (AfterDarkLock.pinSet) { problem = null; asking = true } else offer.allow() }) + OrbitButton("Not now", Modifier.width(160.dp), onClick = { offer.refuse() }) + } + LaunchedEffect(Unit) { runCatching { first.requestFocus() } } + } + RoomOffer.State.Allowed -> Text("Sending the set-up…", color = Muted, fontSize = 15.sp) + RoomOffer.State.Sent, RoomOffer.State.Refused -> { + Text(if (offer.state == RoomOffer.State.Sent) "${offer.joining ?: "The new room"} has this Orbit's set-up. Nothing stays connected." else "Not now: nothing was copied.", + color = if (offer.state == RoomOffer.State.Sent) Mint else Muted, fontSize = 16.sp, fontWeight = FontWeight.SemiBold) + OrbitButton("Done", Modifier.width(160.dp).focusRequester(first), onClick = onClose) + LaunchedEffect(Unit) { runCatching { first.requestFocus() } } + } + } + } +} + +private enum class JoinPhase { Find, Code, Waiting, What, Name } + +/** + * Join another room, from Welcome on a new box: find the room (or type its address), enter its code, wait for it to allow, + * tick what comes across, name this room. The look, family and arcade apply straight away; channels and the Director's Chair + * wait for this box to sign in, which it does for itself. + */ +@Composable +internal fun JoinRoomFlow(onJoined: () -> Unit, onBack: () -> Unit) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val finder = remember { RoomFinder(context) } + DisposableEffect(finder) { finder.start(); onDispose { finder.stop() } } + var phase by remember { mutableStateOf(JoinPhase.Find) } + var address by remember { mutableStateOf("") } + var roomName by remember { mutableStateOf(null) } + var code by remember { mutableStateOf("") } + var note by remember { mutableStateOf(null) } + var join by remember { mutableStateOf(null) } + var copy by remember { mutableStateOf(null) } + var parts by remember { mutableStateOf(RoomPart.entries.toSet()) } + var name by remember { mutableStateOf("Bedroom") } + var working by remember { mutableStateOf(false) } + val first = remember { FocusRequester() } + LaunchedEffect(phase) { runCatching { first.requestFocus() } } + BackHandler { if (phase == JoinPhase.Find) onBack() else { phase = JoinPhase.Find; note = null; code = "" } } + LaunchedEffect(phase, join) { + val j = join ?: return@LaunchedEffect + if (phase != JoinPhase.Waiting) return@LaunchedEffect + // The other TV decides; ask every two seconds while it does. + while (true) { + val result = withContext(Dispatchers.IO) { j.collect() } + result.onSuccess { got -> if (got != null) { copy = got; phase = JoinPhase.What; return@LaunchedEffect } } + .onFailure { note = it.message ?: "The copy didn't arrive."; phase = JoinPhase.Code; return@LaunchedEffect } + delay(2_000) + } + } + Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(when (phase) { JoinPhase.Find -> "Bring Orbit to this room"; JoinPhase.Code -> "Enter the code"; JoinPhase.Waiting -> "Waiting for ${roomName ?: "the other TV"}" + JoinPhase.What -> "What comes across"; JoinPhase.Name -> "Name this room" }, color = Ink, fontFamily = Anton, fontSize = 32.sp) + note?.let { Text(it, color = Yellow, fontSize = 14.sp) } + when (phase) { + JoinPhase.Find -> { + Text("On the TV that already has Orbit, go to Settings › Rooms and phones › Add a room. It shows up here.", color = Muted, fontSize = 15.sp, textAlign = TextAlign.Center) + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + finder.found.forEachIndexed { i, (room, ip) -> + ChoiceCard(room, listOf("Found on your Wi-Fi", ip), Modifier.width(240.dp).then(if (i == 0) Modifier.focusRequester(first) else Modifier)) { + address = ip; roomName = room; note = null; phase = JoinPhase.Code } + } + } + if (finder.found.isEmpty()) Text("Looking on your Wi-Fi…", color = Muted, fontSize = 13.sp) + Text("Not listed? Type the address that TV shows, like 192.168.0.20:", color = Muted, fontSize = 13.sp) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { + OrbitField(address, { if (it.length <= 15) address = it.filter { c -> c.isDigit() || c == '.' } }, "192.168.0.20", Modifier.width(260.dp).then(if (finder.found.isEmpty()) Modifier.focusRequester(first) else Modifier)) + OrbitButton("Next", Modifier.width(140.dp), centred = true, enabled = roomTransport(address) != null) { roomName = null; note = null; phase = JoinPhase.Code } + } + } + JoinPhase.Code -> { + Text("Enter the six digits ${roomName ?: "the other TV"} is showing.", color = Muted, fontSize = 15.sp) + OrbitField(code, { if (it.length <= 6) code = it.filter(Char::isDigit) }, "6 digits", Modifier.width(220.dp).focusRequester(first)) + OrbitButton(if (working) "Checking…" else "Join", Modifier.width(200.dp), centred = true, enabled = code.length == 6 && !working) { + val transport = roomTransport(address) ?: return@OrbitButton + working = true + scope.launch { + val attempt = RoomJoin(transport) + val proved = withContext(Dispatchers.IO) { attempt.prove(code, "A new TV") } + working = false + proved.onSuccess { join = attempt; roomName = attempt.otherRoom ?: roomName; note = null; phase = JoinPhase.Waiting } + .onFailure { note = it.message ?: "That didn't work. Check the code and try again."; code = "" } + } + } + } + JoinPhase.Waiting -> Text("${roomName ?: "The other TV"} is asking whether to allow this. Choose Allow there.", color = Muted, fontSize = 15.sp) + JoinPhase.What -> { + Text("Ticked things are copied once. Nothing stays connected.", color = Muted, fontSize = 14.sp) + RoomPart.entries.forEachIndexed { i, part -> + Row(Modifier.width(620.dp).background(Panel, RoundedCornerShape(8.dp)).padding(horizontal = 12.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(part.title, color = Ink, fontSize = 15.sp, fontWeight = FontWeight.SemiBold) + Text(part.line, color = Muted, fontSize = 11.sp) + } + OnOff(part in parts, if (i == 0) Modifier.focusRequester(first) else Modifier) { parts = if (part in parts) parts - part else parts + part } + } + } + Text("Your sign-in doesn't come across: this TV signs in for itself next. Schedules are this room's own.", color = Muted, fontSize = 12.sp) + OrbitButton("Next", Modifier.width(200.dp), centred = true) { phase = JoinPhase.Name } + } + JoinPhase.Name -> { + Text("It shows in Settings › Rooms and phones.", color = Muted, fontSize = 14.sp) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + listOf("Bedroom", "Kids' room", "Kitchen", "Den").forEachIndexed { i, n -> + OrbitButton(n, Modifier.width(150.dp).then(if (i == 0) Modifier.focusRequester(first) else Modifier), selected = name == n, centred = true) { name = n } + } + } + OrbitButton("Start", Modifier.width(200.dp), centred = true) { + val got = copy ?: return@OrbitButton + Rooms.rename(context, name) + RoomBundle.applyNow(context, got, parts) + RoomArrival.keep(got, parts) + android.util.Log.i("OrbitRooms", "joined parts=${parts.size}") + onJoined() + } + } + } + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt b/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt index 71bdf17d..c798ee57 100644 --- a/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt +++ b/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt @@ -39,7 +39,7 @@ internal class SecureMediaDataSource(private val session: EmbySampleSession) : B next.instanceFollowRedirects = false next.connectTimeout = 10_000 next.readTimeout = 20_000 - next.setRequestProperty("User-Agent", "OrbitTV/0.108.51") + next.setRequestProperty("User-Agent", "OrbitTV/0.108.52") next.setRequestProperty("Accept-Encoding", "identity") session.mediaHeaders(address).forEach { (key, value) -> next.setRequestProperty(key, value) } if (dataSpec.position != 0L || dataSpec.length != C.LENGTH_UNSET.toLong()) { diff --git a/android/app/src/main/java/tv/orbit/classic/Settings.kt b/android/app/src/main/java/tv/orbit/classic/Settings.kt index 483e00ac..4e410121 100644 --- a/android/app/src/main/java/tv/orbit/classic/Settings.kt +++ b/android/app/src/main/java/tv/orbit/classic/Settings.kt @@ -320,13 +320,30 @@ private fun FamilyDetail(totsOn: Boolean, windingDown: Boolean, onWindDown: (Boo /** Rooms and phones: the phones that can make channels, and (with Multiroom) the other TVs in the home. */ @Composable private fun RoomsDetail(firstSwitch: FocusRequester, modifier: Modifier) { + val context = LocalContext.current + var adding by remember { mutableStateOf(false) } + var naming by remember { mutableStateOf(false) } + if (adding) { AddRoomPanel(onClose = { adding = false }, modifier = modifier); return } Column(modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Heading("This room") + SettingLine(Rooms.name, "What other TVs see when they join this one.") { + OrbitButton("Rename", Modifier.focusRequester(firstSwitch), onClick = { naming = !naming }) + } + if (naming) Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + listOf("Living Room", "Lounge", "Bedroom", "Kids' room", "Kitchen", "Den").forEach { n -> OrbitButton(n, selected = n == Rooms.name, onClick = { Rooms.rename(context, n); naming = false }) } + } + Heading("Other rooms") + SettingLine("Add a room", "Set up Orbit on another TV in your home by copying this one: channels, profiles, look and more. Your password never travels.") { + OrbitButton("Add a room", onClick = { adding = true }) + } + Rooms.joined.forEach { (room, at) -> + val day = java.time.Instant.ofEpochMilli(at).atZone(java.time.ZoneId.systemDefault()).toLocalDate() + SettingLine(room, "Copied this Orbit's set-up on ${day.dayOfMonth} ${day.month.getDisplayName(java.time.format.TextStyle.SHORT, java.util.Locale.UK)}. Not connected: it plans its own schedules.") {} + } Heading("Phones") if (PhoneLink.phones.isEmpty()) SettingLine("No phones yet", "Channels › Create your own › On your phone shows a code to scan.") {} else PhoneLink.phones.forEachIndexed { i, (id, name) -> SettingLine(name, "Can make and edit your channels, and tune this TV.") { OrbitButton("Remove", if (i == 0) Modifier.focusRequester(firstSwitch) else Modifier, onClick = { PhoneLink.forget(id) }) } } - Heading("Other rooms") - SettingLine("Multiroom is on its way", "Soon a TV in another room can join this one and copy its channels and settings. Your password never travels.") {} } } diff --git a/android/app/src/test/java/tv/orbit/classic/RoomsTest.kt b/android/app/src/test/java/tv/orbit/classic/RoomsTest.kt new file mode 100644 index 00000000..16468326 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/RoomsTest.kt @@ -0,0 +1,98 @@ +package tv.orbit.classic + +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.net.InetAddress + +/** Multiroom stage 1 (Paul, 6 November 2026): pairing by code, the existing TV's say, and the one-time copy. */ +class RoomsTest { + @get:Rule val folder = TemporaryFolder() + private val copy = JSONObject().put("version", 1).put("room", "Living Room").put("server", "https://emby.example.com") + .put(RoomPart.Channels.name, JSONObject().put("lineup", JSONArray(listOf(101, 605))).put("files", JSONObject() + .put("yours.json", """[{"number":701,"name":"90s Sci-Fi","style":"Standard","description":"","hours":null,"shows":[]}]""") + .put("../escape.json", "{}").put("choices-101.json", "{\"schema\":1}"))) + private fun offer(code: String = "123456", until: Long = System.currentTimeMillis() + 60_000) = RoomOffer(code, until, "Living Room") { copy } + private fun direct(o: RoomOffer): (String, String, String) -> Pair = { m, p, b -> o.handle(m, p, b).let { (s, j) -> s to j.toString() } } + @After fun reset() { CustomChannels.clear() } + + @Test fun theRightCodeAndTheTvsYesBringTheCopyAcrossSealed() { + val o = offer(); val join = RoomJoin(direct(o)) + assertTrue(join.prove("123456", "Bedroom").isSuccess) + assertEquals(RoomOffer.State.Asking, o.state); assertEquals("Bedroom", o.joining); assertEquals("Living Room", join.otherRoom) + assertNull(join.collect().getOrThrow()) // the TV hasn't said yet + o.allow() + assertEquals("https://emby.example.com", join.collect().getOrThrow()!!.getString("server")) + assertEquals(RoomOffer.State.Sent, o.state) + assertTrue(join.collect().isFailure) // once only + } + + @Test fun aWrongCodeFailsAndThreeEndTheOffer() { + val o = offer() + repeat(2) { assertTrue(RoomJoin(direct(o)).prove("000000", "x").isFailure); } + // Each attempt is a fresh hello, but only one joiner may say hello: the rest are turned away. + assertEquals(409, o.handle("POST", "/room/hello", JSONObject().put("pub", RoomCrypto.publicOf(RoomCrypto.keyPair())).toString()).first) + val fresh = offer(); val sneaky = RoomJoin(direct(fresh)) + assertTrue(sneaky.prove("111111", "x").isFailure) + repeat(2) { fresh.handle("POST", "/room/proof", JSONObject().put("proof", "nope").toString()) } + assertEquals(RoomOffer.State.Ended, fresh.state) + assertTrue(RoomJoin(direct(fresh)).prove("123456", "x").isFailure) + } + + @Test fun notNowAndTimeRunningOutSendNothing() { + val o = offer(); val join = RoomJoin(direct(o)) + join.prove("123456", "Den").getOrThrow(); o.refuse() + assertTrue(join.collect().isFailure); assertNotEquals(RoomOffer.State.Sent, o.state) + val late = offer(until = System.currentTimeMillis() - 1) + assertTrue(RoomJoin(direct(late)).prove("123456", "Den").isFailure) + } + + @Test fun someoneInTheMiddleWithoutTheCodeCantReadTheCopy() { + // A box that sees both keys but not the code has no seal key: the copy only opens with the code. + val o = offer(); RoomJoin(direct(o)).prove("123456", "Bedroom").getOrThrow(); o.allow() + val sealed = JSONObject(o.handle("GET", "/room/copy", "").second.toString()).getString("sealed") + assertTrue(runCatching { RoomCrypto.open(ByteArray(32), sealed) }.isFailure) + assertFalse(sealed.contains("emby.example.com")) + } + + @Test fun overTheHomeNetworkThroughThePhoneLink() { + PhoneLink.initForTest(object : PhoneStore { + override fun all() = emptyMap(); override fun get(id: String): String? = null + override fun put(id: String, value: String) {}; override fun remove(id: String) {} }) + PhoneLink.bindTo = InetAddress.getLoopbackAddress(); PhoneLink.port = 18_099; PhoneLink.allowed = { it.isLoopbackAddress } + try { + val o = offer(); PhoneLink.offerRoom(o) + val call: (String, String, String) -> Pair = { m, p, b -> + val c = java.net.URL("http://127.0.0.1:18099$p").openConnection() as java.net.HttpURLConnection + c.requestMethod = m + if (m == "POST") { c.doOutput = true; c.outputStream.use { it.write(b.toByteArray()) } } + val s = c.responseCode; s to ((if (s < 400) c.inputStream else c.errorStream)?.use { it.readBytes().toString(Charsets.UTF_8) }.orEmpty()) + } + val join = RoomJoin(call) + assertTrue(join.prove("123456", "Kitchen").isSuccess); o.allow() + assertEquals(1, join.collect().getOrThrow()!!.getInt("version")) + PhoneLink.offerRoom(null) + // With no offer and no phones, the server stops altogether. + assertTrue(runCatching { call("POST", "/room/hello", "{}") }.isFailure) + } finally { PhoneLink.stop(); PhoneLink.allowed = EmbyServer::isHomeAddress; PhoneLink.bindTo = null; PhoneLink.port = PhoneLink.PORT } + } + + @Test fun theCopyLandsInTheWorkspaceWithoutOverwritingOrEscaping() { + val dir = folder.newFolder() + java.io.File(dir, "choices-101.json").writeText("mine") + val lineup = RoomBundle.applyToWorkspace(dir, copy, setOf(RoomPart.Channels)) + assertEquals(listOf(101, 605), lineup) + assertEquals("mine", java.io.File(dir, "choices-101.json").readText()) // never overwritten + assertFalse(java.io.File(dir.parentFile, "escape.json").exists()) + assertEquals("90s Sci-Fi", CustomChannels.of(701)?.name) + assertTrue(RoomBundle.applyToWorkspace(folder.newFolder(), copy, emptySet()).isEmpty()) // not ticked: nothing + } + + @Test fun onlyHomeAddressesCanBeJoined() { + assertNotNull(roomTransport("192.168.0.20")); assertNull(roomTransport("8.8.8.8")); assertNull(roomTransport("living-room.example")) + } +}