diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 6c60c191..003ee7a0 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 = 212 - versionName = "0.108.52-multiroom" + versionCode = 213 + versionName = "0.108.53-autoscan" } 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/ChannelScheduler.kt b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt index 6039167b..a0be22fa 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -243,6 +243,9 @@ internal class ChannelScheduler(private val store: ScheduleStore, /** Starts a channel that has no loop yet: reads its pool, then gives it a small fallback made from that pool. */ fun seedLoop(session: EmbySampleSession, userId: String, programming: ChannelProgramming, checkActive: () -> Unit = {}): SampleChannel { val choices = store.loadChoices(userId, programming.number) + // A fresh pool already on the box (from another room, or turned on before) needs no reading of the library. + store.loadPool(userId, programming.number)?.takeIf { clock() - it.fetchedAtMs < POOL_REFRESH_MS && it.signature == "${programming.signature}#${choices.tag}" } + ?.let { cached -> loopFromPool(cached.series, programming)?.let { return it } } val read = session.readChannelPool(programming, null, choices, checkActive) val loop = loopFromPool(read.series, programming) ?: throw EmbyCheckException("None of ${programming.name}'s shows were found with episodes to schedule.") store.savePool(userId, programming.number, ScheduleStore.SavedPool(read.series, clock(), "${programming.signature}#${choices.tag}")) 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 6f546405..5a2d0ab2 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.52\"") + + ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.53\"") + (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.52\"" + + ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.53\"" + (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/MainActivity.kt b/android/app/src/main/java/tv/orbit/classic/MainActivity.kt index be1bb432..41c481c7 100644 --- a/android/app/src/main/java/tv/orbit/classic/MainActivity.kt +++ b/android/app/src/main/java/tv/orbit/classic/MainActivity.kt @@ -44,8 +44,12 @@ internal val Barlow = FontFamily(Font(R.font.barlow_regular), Font(R.font.barlow internal fun clock(time: Long) = SimpleDateFormat("HH:mm", Locale.UK).format(Date(time)) class MainActivity : ComponentActivity() { - override fun onStart() { super.onStart(); if (PhoneLink.phones.isNotEmpty()) PhoneLink.start() } - override fun onStop() { PhoneLink.stop(); super.onStop() } + override fun onStart() { + super.onStart(); if (PhoneLink.phones.isNotEmpty()) PhoneLink.start() + // Multiroom auto-scan: a set-up Orbit can be found by a new TV while it's open. + if (Onboarding.done(this)) RoomBeacon.on(this) + } + override fun onStop() { RoomBeacon.off(this); PhoneLink.offerRoom(null); PhoneLink.stop(); super.onStop() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) @@ -211,6 +215,8 @@ private fun OrbitApp() { // Full screen draws its own, over the programme. if (SleepTimer.warning && !FullScreen.active) SleepWarning(Modifier.align(Alignment.TopCenter).padding(top = 64.dp)) if (SleepTimer.goodnight && !FullScreen.active) LunaGoodnight() + // A new TV joining (Multiroom auto-scan), over everything else. + RoomKnockOverlay() } } } 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 7fe7b63f..0be03ee8 100644 --- a/android/app/src/main/java/tv/orbit/classic/PhoneLink.kt +++ b/android/app/src/main/java/tv/orbit/classic/PhoneLink.kt @@ -63,7 +63,17 @@ internal object PhoneLink { @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() } + /** The same offer, for the screen to follow. */ + var offerShown by mutableStateOf(null) + private set + fun offerRoom(offer: RoomOffer?) { roomOffer = offer; offerShown = offer; if (offer != null) start() else if (!needed()) stop() } + /** Multiroom auto-scan: while Orbit is open and signed in, a new TV may knock, and this one shows a code. */ + @Volatile var knock: ((String) -> RoomOffer?)? = null + @Volatile private var lastKnockMs = 0L + /** Kept running while Orbit is open and can be found by a new room. */ + @Volatile var listening = false + set(value) { field = value; if (value) start() else if (!needed()) stop() } + private fun needed() = phones.isNotEmpty() || pairing != null || roomOffer != null || listening /** 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) @@ -114,7 +124,7 @@ internal object PhoneLink { } fun pairingUrl(p: Pairing): String? = homeAddress()?.let { "http://$it:$PORT/join?k=${p.secret}" } - fun forget(id: String) { prefs().remove(id); loadPhones(); if (phones.isEmpty() && pairing == null) stop() } + fun forget(id: String) { prefs().remove(id); loadPhones(); if (!needed()) stop() } @Synchronized fun start() { if (server != null || store == null) return @@ -180,6 +190,18 @@ 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 == "/room/knock" && r.method == "POST") { + // A new TV asks to join: this one shows a code, or the one it's already showing. One knock every 20 seconds. + roomOffer?.takeIf { it.state == RoomOffer.State.Waiting && System.currentTimeMillis() < it.untilMs }?.let { return json(out, 200, JSONObject().put("room", Rooms.name)) } + val now = System.currentTimeMillis() + val make = knock ?: return json(out, 404, JSONObject().put("error", "That TV isn't ready to add a room.")) + if (now - lastKnockMs < 20_000) return json(out, 429, JSONObject().put("error", "Wait a moment, then try again.")) + lastKnockMs = now + val name = runCatching { JSONObject(r.body).optString("name") }.getOrDefault("").trim().take(30).ifBlank { "A new TV" } + val offer = make(name) ?: return json(out, 404, JSONObject().put("error", "That TV isn't ready to add a room.")) + offerRoom(offer) + return json(out, 200, JSONObject().put("room", Rooms.name)) + } 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() } diff --git a/android/app/src/main/java/tv/orbit/classic/Rooms.kt b/android/app/src/main/java/tv/orbit/classic/Rooms.kt index 8d7783b7..6d6136cb 100644 --- a/android/app/src/main/java/tv/orbit/classic/Rooms.kt +++ b/android/app/src/main/java/tv/orbit/classic/Rooms.kt @@ -73,7 +73,7 @@ private val LookKeys = listOf("look", "subtitles_on", "channel_logo", "idents", "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 +private const val BUNDLE_LIMIT = 12 * 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 { @@ -94,7 +94,14 @@ internal object RoomBundle { } 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()) } } } + private fun files(dir: File, names: List) = JSONObject().also { o -> names.forEach { n -> File(dir, n).takeIf { it.isFile && it.length() < 3_000_000 }?.let { o.put(n, it.readText()) } } } + internal fun gzip(text: String): String = java.io.ByteArrayOutputStream().also { b -> java.util.zip.GZIPOutputStream(b).use { it.write(text.toByteArray()) } } + .toByteArray().let { java.util.Base64.getEncoder().encodeToString(it) } + private fun gunzip(text: String): String = java.util.zip.GZIPInputStream(java.util.Base64.getDecoder().decode(text).inputStream()).use { input -> + val out = java.io.ByteArrayOutputStream(); val buffer = ByteArray(16_384); var total = 0 + while (true) { val n = input.read(buffer); if (n < 0) break; total += n; require(total <= 32 * 1024 * 1024); out.write(buffer, 0, n) } + out.toString(Charsets.UTF_8.name()) + } /** This box's set-up, as the existing room sends it. */ fun collect(context: Context, workspace: ServerWorkspace, room: String): JSONObject { @@ -102,8 +109,11 @@ internal object RoomBundle { // 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() + // "Here's where everything goes": each channel's matched shows, so the new room plans straight away instead of + // reading the library again. Compressed; the same account's own, checked by the store as it reads them. + val pools = files(dir, lineup.map { "episodes-$it.json" }) 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.Channels.name, JSONObject().put("lineup", JSONArray(lineup)).put("files", files(dir, choices + "yours.json")).put("pools", gzip(pools.toString()))) .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)) @@ -125,12 +135,13 @@ internal object RoomBundle { 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()) + if (Regex("(choices-\\d+|episodes-\\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) + c.optString("pools").takeIf { it.isNotBlank() }?.let { packed -> runCatching { write(JSONObject(gunzip(packed))) } } 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)) @@ -162,7 +173,7 @@ internal object Rooms { * 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) { +internal class RoomOffer(val code: String, val untilMs: Long, private val room: String, val knocked: Boolean = false, private val bundle: () -> JSONObject) { enum class State { Waiting, Asking, Allowed, Refused, Sent, Ended } var state by mutableStateOf(State.Waiting) var joining by mutableStateOf(null) @@ -223,6 +234,14 @@ internal class RoomJoin(private val call: (method: String, path: String, body: S var otherRoom: String? = null private set + /** Asks the other TV to show a code (auto-scan): the room it's in, or why not. */ + fun knock(name: String): Result = runCatching { + val (status, text) = call("POST", "/room/knock", JSONObject().put("name", name).toString()) + val reply = JSONObject(text) + check(status == 200) { reply.optString("error").ifBlank { "That TV couldn't show a code." } } + reply.optString("room").take(30).also { otherRoom = it } + } + /** 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) diff --git a/android/app/src/main/java/tv/orbit/classic/RoomsUi.kt b/android/app/src/main/java/tv/orbit/classic/RoomsUi.kt index a6e79545..0a14fb9b 100644 --- a/android/app/src/main/java/tv/orbit/classic/RoomsUi.kt +++ b/android/app/src/main/java/tv/orbit/classic/RoomsUi.kt @@ -75,6 +75,84 @@ internal class RoomFinder(context: Context) { fun stop() { listener?.let { runCatching { nsd?.stopServiceDiscovery(it) } }; listener = null } } +/** This room, findable on the Wi-Fi by its name while Orbit is open (auto-scan), and ready to show a code when a new TV knocks. */ +internal object RoomBeacon { + private var registration: NsdManager.RegistrationListener? = null + fun on(context: Context) { + if (registration != null) return + val app = context.applicationContext + PhoneLink.knock = { joining -> RoomOffer(RoomCrypto.code(), System.currentTimeMillis() + OFFER_MS, Rooms.name, knocked = true) { RoomBundle.collect(app, Workspaces.current(app), Rooms.name) }.also { it.joining = joining } } + PhoneLink.listening = true + val nsd = app.getSystemService(Context.NSD_SERVICE) as? NsdManager ?: return + 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) {} + }.also { runCatching { nsd.registerService(NsdServiceInfo().apply { serviceName = Rooms.name; serviceType = ROOM_SERVICE; port = PhoneLink.PORT }, NsdManager.PROTOCOL_DNS_SD, it) } } + } + fun off(context: Context) { + PhoneLink.knock = null; PhoneLink.listening = false + val nsd = context.applicationContext.getSystemService(Context.NSD_SERVICE) as? NsdManager + registration?.let { r -> runCatching { nsd?.unregisterService(r) } }; registration = null + } +} + +/** + * A new TV knocked (auto-scan): wherever this TV is, a card shows the code to enter there, then Allow, with the Adult PIN + * if one is set. Not now, Back or five minutes passing ends it, and nothing is copied. + */ +@Composable +internal fun RoomKnockOverlay() { + val offer = PhoneLink.offerShown?.takeIf { it.knocked } ?: return + val context = LocalContext.current + var asking by remember(offer) { mutableStateOf(false) } + var problem by remember(offer) { mutableStateOf(null) } + var now by remember { mutableLongStateOf(System.currentTimeMillis()) } + LaunchedEffect(offer) { while (true) { delay(1_000); now = System.currentTimeMillis() + if (offer.state == RoomOffer.State.Waiting && now > offer.untilMs) { PhoneLink.offerRoom(null); return@LaunchedEffect } } } + LaunchedEffect(offer.state) { + when (offer.state) { + RoomOffer.State.Sent -> { offer.joining?.let { Rooms.recordJoined(context, it, System.currentTimeMillis()) }; delay(6_000); PhoneLink.offerRoom(null) } + RoomOffer.State.Refused, RoomOffer.State.Ended -> { delay(3_000); PhoneLink.offerRoom(null) } + else -> {} + } + } + BackHandler { if (asking) asking = false else { offer.refuse(); PhoneLink.offerRoom(null) } } + Box(Modifier.fillMaxSize().background(Navy.copy(alpha = .55f)), contentAlignment = Alignment.Center) { + 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@Box } + val first = remember { FocusRequester() } + Column(Modifier.width(560.dp).background(Panel, RoundedCornerShape(14.dp)).padding(22.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text("${offer.joining ?: "A new TV"} wants to join", color = Ink, fontFamily = Anton, fontSize = 26.sp) + when (offer.state) { + RoomOffer.State.Waiting -> { + Text("To copy this Orbit's set-up, enter this code on the new TV:", color = Muted, fontSize = 14.sp) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + offer.code.forEach { digit -> Box(Modifier.size(50.dp, 62.dp).background(Navy, RoundedCornerShape(8.dp)), contentAlignment = Alignment.Center) { + Text("$digit", color = Yellow, fontFamily = Anton, fontSize = 32.sp) } } + } + val left = ((offer.untilMs - now) / 1000).coerceAtLeast(0) + Text("Works once, for %d:%02d more. Not expecting this? Choose Not now.".format(left / 60, left % 60), color = Muted, fontSize = 12.sp) + OrbitButton("Not now", Modifier.width(180.dp).focusRequester(first), centred = true) { offer.refuse(); PhoneLink.offerRoom(null) } + } + RoomOffer.State.Asking -> { + Text("It entered the right code. Allow it to copy this Orbit's set-up? Your password never travels.", color = Muted, fontSize = 14.sp, textAlign = TextAlign.Center) + Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { + OrbitButton("Allow", Modifier.width(160.dp).focusRequester(first), centred = true) { if (AfterDarkLock.pinSet) { problem = null; asking = true } else offer.allow() } + OrbitButton("Not now", Modifier.width(160.dp), centred = true) { offer.refuse() } + } + } + RoomOffer.State.Allowed -> Text("Sending the set-up…", color = Muted, fontSize = 14.sp) + RoomOffer.State.Sent -> Text("Done: it has this Orbit's set-up. Nothing stays connected.", color = Mint, fontSize = 15.sp, fontWeight = FontWeight.SemiBold) + RoomOffer.State.Refused, RoomOffer.State.Ended -> Text("Nothing was copied.", color = Muted, fontSize = 14.sp) + } + } + LaunchedEffect(offer.state, asking) { runCatching { first.requestFocus() } } + } +} + /** 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) @@ -182,6 +260,16 @@ internal fun JoinRoomFlow(onJoined: () -> Unit, onBack: () -> Unit) { var working by remember { mutableStateOf(false) } val first = remember { FocusRequester() } LaunchedEffect(phase) { runCatching { first.requestFocus() } } + // Auto-scan: asks the chosen TV to show its code, wherever it is in Orbit. + fun knock() { + val transport = roomTransport(address) ?: return + working = true; note = null + scope.launch { + val answer = withContext(Dispatchers.IO) { RoomJoin(transport).knock("A new TV") } + working = false + answer.onSuccess { room -> roomName = room.ifBlank { roomName }; code = ""; phase = JoinPhase.Code }.onFailure { note = it.message } + } + } BackHandler { if (phase == JoinPhase.Find) onBack() else { phase = JoinPhase.Find; note = null; code = "" } } LaunchedEffect(phase, join) { val j = join ?: return@LaunchedEffect @@ -200,22 +288,22 @@ internal fun JoinRoomFlow(onJoined: () -> Unit, onBack: () -> Unit) { 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) + Text("Choose the TV to copy. It shows a code to enter here, then asks to allow it.", 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 } + address = ip; roomName = room; knock() } } } - if (finder.found.isEmpty()) Text("Looking on your Wi-Fi…", color = Muted, fontSize = 13.sp) + if (finder.found.isEmpty()) Text("Looking for Orbit on your Wi-Fi… Make sure Orbit is open on the other TV.", 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 } + OrbitButton(if (working) "Asking…" else "Next", Modifier.width(140.dp), centred = true, enabled = roomTransport(address) != null && !working) { roomName = null; knock() } } } JoinPhase.Code -> { - Text("Enter the six digits ${roomName ?: "the other TV"} is showing.", color = Muted, fontSize = 15.sp) + Text("${roomName ?: "The other TV"} is showing a code now. Enter its six digits.", 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 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 c798ee57..0ccb62f6 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.52") + next.setRequestProperty("User-Agent", "OrbitTV/0.108.53") 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/test/java/tv/orbit/classic/RoomsTest.kt b/android/app/src/test/java/tv/orbit/classic/RoomsTest.kt index 16468326..856d0979 100644 --- a/android/app/src/test/java/tv/orbit/classic/RoomsTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/RoomsTest.kt @@ -92,6 +92,42 @@ class RoomsTest { assertTrue(RoomBundle.applyToWorkspace(folder.newFolder(), copy, emptySet()).isEmpty()) // not ticked: nothing } + @Test fun aNewTvKnocksAndTheOtherShowsItsCode() { + 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 { + var made: RoomOffer? = null + PhoneLink.knock = { name -> offer().also { it.joining = name; made = it } } + PhoneLink.listening = true + val join = RoomJoin(roomTransport("127.0.0.1", 18_099) ?: { 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()) + }) + assertTrue(join.knock("Bedroom").isSuccess) + assertEquals("Bedroom", made!!.joining); assertSame(made, PhoneLink.offerShown) + assertTrue(join.knock("Bedroom").isSuccess) // knocking again shows the same code + assertTrue(join.prove("123456", "Bedroom").isSuccess); made!!.allow() + assertNotNull(join.collect().getOrThrow()) + PhoneLink.offerRoom(null); PhoneLink.knock = null + assertTrue(join.knock("Bedroom").isFailure) // not open to knocks any more + } finally { PhoneLink.listening = false; PhoneLink.stop(); PhoneLink.allowed = EmbyServer::isHomeAddress; PhoneLink.bindTo = null; PhoneLink.port = PhoneLink.PORT } + } + + @Test fun theChannelMatchingComesAcrossCompressed() { + val pool = "{\"schema\":1,\"series\":[" + (1..400).joinToString(",") { "{\"id\":\"s$it\"}" } + "]}" + val packed = RoomBundle.gzip(JSONObject().put("episodes-101.json", pool).put("../../evil.json", "x").toString()) + assertTrue(packed.length < pool.length / 4) + val bundle = JSONObject().put("version", 1).put(RoomPart.Channels.name, JSONObject().put("lineup", JSONArray(listOf(101))).put("pools", packed)) + val dir = folder.newFolder() + RoomBundle.applyToWorkspace(dir, bundle, setOf(RoomPart.Channels)) + assertEquals(pool, java.io.File(dir, "episodes-101.json").readText()) + assertEquals(listOf("episodes-101.json"), dir.list()!!.toList()) + } + @Test fun onlyHomeAddressesCanBeJoined() { assertNotNull(roomTransport("192.168.0.20")); assertNull(roomTransport("8.8.8.8")); assertNull(roomTransport("living-room.example")) }