Updates shared between rooms (0.108.57)

From the roadmap (Paul, 6 November 2026): while Orbit is open it shares its version and its
installed copy on the home network (/room/version, /room/orbit.apk). As it opens, Orbit
looks for a newer one in another room and asks Install? or Not now. The download must be
this app, newer, and signed by the same keys; this room's schedules are copied aside first;
Android's own installer then asks to confirm. Nothing installs silently.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-06 13:48:46 +00:00
co-authored by Claude Opus 5.5
parent cb93da6644
commit d4cdd7221d
9 changed files with 298 additions and 8 deletions
+2 -2
View File
@@ -9,8 +9,8 @@ android {
applicationId = "tv.orbit.classic"
minSdk = 26
targetSdk = 36
versionCode = 216
versionName = "0.108.56-kitchen-home-play"
versionCode = 217
versionName = "0.108.57-room-updates"
}
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.
+2
View File
@@ -1,5 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<!-- Updates shared between rooms: Android still asks the viewer to confirm every install. -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-feature android:name="android.software.leanback" android:required="true" />
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
<application android:label="Orbit TV" android:theme="@style/OrbitTheme" android:icon="@drawable/orbit_app_icon" android:banner="@drawable/orbit_banner" android:allowBackup="false" android:networkSecurityConfig="@xml/network_security_config" android:supportsRtl="true">
@@ -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<String, String> = when (kind) {
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.56\"") +
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.57\"") +
(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.56\"" +
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.57\"" +
(token?.let { ", Token=\"$it\"" } ?: ""))
}
/** One picture from the provider, or nothing. Same fixed origin and no redirects, and failures are never shown or logged. */
@@ -28,6 +28,8 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.tv.material3.MaterialTheme
@@ -47,7 +49,11 @@ class MainActivity : ComponentActivity() {
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)
if (Onboarding.done(this)) {
RoomBeacon.on(this)
// Updates shared between rooms: a newer Orbit in another room is offered, with Install? and Not now.
lifecycleScope.launch { runCatching { RoomUpdates.look(this@MainActivity) } }
}
}
override fun onStop() { RoomBeacon.off(this); PhoneLink.offerRoom(null); PhoneLink.stop(); super.onStop() }
override fun onCreate(savedInstanceState: Bundle?) {
@@ -215,8 +221,9 @@ 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.
// A new TV joining (Multiroom auto-scan), over everything else; and a newer Orbit from another room.
RoomKnockOverlay()
RoomUpdateCard()
}
}
}
@@ -67,6 +67,8 @@ internal object PhoneLink {
var offerShown by mutableStateOf<RoomOffer?>(null)
private set
fun offerRoom(offer: RoomOffer?) { roomOffer = offer; offerShown = offer; if (offer != null) start() else if (!needed()) stop() }
/** Updates shared between rooms: this Orbit's version and installed copy, while it's open and can be found. */
@Volatile var shared: SharedBuild? = null
/** 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
@@ -190,6 +192,19 @@ 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/version" && r.method == "GET") {
val build = shared ?: return json(out, 404, JSONObject())
return json(out, 200, JSONObject().put("code", build.code).put("name", build.name).put("room", Rooms.name))
}
if (r.path == "/room/orbit.apk" && r.method == "GET") {
// The installed copy, streamed: another room checks it's newer and signed as it is before Android installs it.
val build = shared?.takeIf { it.file.isFile } ?: return json(out, 404, JSONObject())
val head = listOf("HTTP/1.1 200 OK", "Content-Type: application/vnd.android.package-archive", "Content-Length: ${build.file.length()}", "Cache-Control: no-store",
"X-Content-Type-Options: nosniff", "Connection: close").joinToString("\r\n") + "\r\n\r\n"
out.write(head.toByteArray(Charsets.ISO_8859_1)); build.file.inputStream().use { it.copyTo(out, 64 * 1024) }; out.flush()
android.util.Log.i("OrbitRooms", "update shared bytes=${build.file.length()}")
return
}
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)) }
@@ -0,0 +1,209 @@
package tv.orbit.classic
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageInfo
import android.content.pm.PackageInstaller
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
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.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.io.File
import java.net.HttpURLConnection
import java.net.URL
/**
* Updates shared between rooms (Paul, 6 November 2026, roadmap): while Orbit is open, it offers its version and its own
* installed copy on the home network. Another Orbit that finds a newer one asks "Install?"; Android then asks too, as it
* always does for an app from outside the Play Store. Nothing installs silently. The rules:
* - Only a newer version of this same app, signed with the same key as the one installed, is accepted.
* - Before installing, this room's schedules are copied aside (schedule-rollback-<version>), as every install does.
* - Only on the home network, through the phone link, and only while the other Orbit is open.
*/
internal class SharedBuild(val code: Long, val name: String, val file: File)
internal class UpdateOffer(val room: String, val address: String, val code: Long, val name: String)
/** "0.108.57" from "0.108.57-kitchen-home-play". */
internal fun shortVersion(name: String) = name.substringBefore('-')
/** A version answer worth offering: newer than this box's, and not one already turned down this time. */
internal fun offerFrom(room: String, address: String, answer: JSONObject, mine: Long, declined: Set<Long>): UpdateOffer? {
val code = answer.optLong("code", -1)
val name = answer.optString("name").take(60)
if (code <= mine || code in declined || name.isBlank()) return null
return UpdateOffer(room.take(30), address, code, name)
}
/** The same package, newer, and signed by exactly the same keys as what's installed. */
internal fun acceptableUpdate(candidate: PackageInfo?, installed: PackageInfo, signers: (PackageInfo) -> Set<String>): String? = when {
candidate == null -> "The download isn't a complete Orbit."
candidate.packageName != installed.packageName -> "The download isn't Orbit."
versionCodeOf(candidate) <= versionCodeOf(installed) -> "The download isn't newer than this Orbit."
signers(candidate).isEmpty() || signers(candidate) != signers(installed) -> "The download isn't signed as this Orbit is, so it can't be installed."
else -> null
}
@Suppress("DEPRECATION")
internal fun versionCodeOf(info: PackageInfo): Long = if (Build.VERSION.SDK_INT >= 28) info.longVersionCode else info.versionCode.toLong()
internal object RoomUpdates {
var offer by mutableStateOf<UpdateOffer?>(null)
private set
var progress by mutableStateOf<String?>(null)
private set
private val declined = mutableSetOf<Long>()
private const val LIMIT = 200L * 1024 * 1024
fun mine(context: Context): PackageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
/** What this Orbit shares: its version, and the copy Android installed. */
fun shared(context: Context): SharedBuild? = runCatching {
val info = mine(context)
SharedBuild(versionCodeOf(info), info.versionName.orEmpty(), File(context.applicationInfo.sourceDir))
}.getOrNull()
/** Looks for a newer Orbit in another room for a few seconds, as Orbit opens. Quiet when there's none. */
suspend fun look(context: Context) {
val finder = withContext(Dispatchers.Main) { RoomFinder(context).also { it.start() } }
try {
delay(8_000)
val mine = versionCodeOf(mine(context))
for ((room, ip) in finder.found) {
val transport = roomTransport(ip) ?: continue
val answer = withContext(Dispatchers.IO) { runCatching { transport("GET", "/room/version", "").takeIf { it.first == 200 }?.let { JSONObject(it.second) } }.getOrNull() } ?: continue
offerFrom(room, ip, answer, mine, declined)?.let { offer = it; android.util.Log.i("OrbitRooms", "update offered code=${it.code}"); return }
}
} finally { withContext(Dispatchers.Main) { finder.stop() } }
}
fun notNow() { offer?.let { declined += it.code }; offer = null; progress = null }
/** Downloads, checks and hands the new Orbit to Android's installer, which asks the viewer to confirm. */
suspend fun install(context: Context, chosen: UpdateOffer) {
val pm = context.packageManager
if (Build.VERSION.SDK_INT >= 26 && !pm.canRequestPackageInstalls()) {
progress = "Allow Orbit to install updates on the next screen, then choose Install again."
runCatching { context.startActivity(Intent(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:${context.packageName}")).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
return
}
progress = "Copying Orbit ${shortVersion(chosen.name)} from ${chosen.room}…"
val file = File(context.cacheDir, "orbit-update.apk")
val fetched = withContext(Dispatchers.IO) { runCatching { download(chosen.address, file) } }
if (fetched.isFailure) { progress = "The copy from ${chosen.room} didn't finish. Check both TVs are on, then try again."; return }
val problem = withContext(Dispatchers.IO) {
@Suppress("DEPRECATION")
val candidate = pm.getPackageArchiveInfo(file.path, if (Build.VERSION.SDK_INT >= 28) PackageManager.GET_SIGNING_CERTIFICATES else PackageManager.GET_SIGNATURES)
@Suppress("DEPRECATION")
val installed = pm.getPackageInfo(context.packageName, if (Build.VERSION.SDK_INT >= 28) PackageManager.GET_SIGNING_CERTIFICATES else PackageManager.GET_SIGNATURES)
acceptableUpdate(candidate, installed, ::signersOf)
}
if (problem != null) { file.delete(); progress = problem; android.util.Log.w("OrbitRooms", "update refused"); return }
// As every install does: this room's schedules copied aside first, so a rollback has them.
withContext(Dispatchers.IO) { runCatching { snapshotSchedules(context) } }
progress = "Android will ask you to confirm the update."
withContext(Dispatchers.IO) { commit(context, file) }
}
private fun download(address: String, into: File) {
val c = URL("http://$address:${PhoneLink.PORT}/room/orbit.apk").openConnection() as HttpURLConnection
c.connectTimeout = 5_000; c.readTimeout = 30_000
try {
check(c.responseCode == 200)
val length = c.contentLengthLong
check(length in 1..LIMIT)
c.inputStream.use { input -> into.outputStream().use { out ->
val buffer = ByteArray(64 * 1024); var total = 0L
while (true) { val n = input.read(buffer); if (n < 0) break; total += n; check(total <= LIMIT); out.write(buffer, 0, n) }
check(total == length)
} }
} finally { c.disconnect() }
}
@Suppress("DEPRECATION")
private fun signersOf(info: PackageInfo): Set<String> {
val raw = if (Build.VERSION.SDK_INT >= 28) info.signingInfo?.let { if (it.hasMultipleSigners()) it.apkContentsSigners else it.signingCertificateHistory } else info.signatures
return raw.orEmpty().map { java.security.MessageDigest.getInstance("SHA-256").digest(it.toByteArray()).joinToString("") { b -> "%02x".format(b) } }.toSet()
}
private fun snapshotSchedules(context: Context) {
val dir = Workspaces.current(context).scheduleDir
val aside = File(dir.parentFile, "schedule-rollback-${shortVersion(mine(context).versionName.orEmpty())}")
aside.deleteRecursively(); dir.copyRecursively(aside, overwrite = true)
}
private fun commit(context: Context, apk: File) {
val installer = context.packageManager.packageInstaller
val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply { setAppPackageName(context.packageName) }
val id = installer.createSession(params)
installer.openSession(id).use { session ->
apk.inputStream().use { input -> session.openWrite("orbit.apk", 0, apk.length()).use { out -> input.copyTo(out); session.fsync(out) } }
val action = "${context.packageName}.ROOM_UPDATE"
context.applicationContext.registerReceiverCompat(object : BroadcastReceiver() {
override fun onReceive(c: Context, intent: Intent) {
when (intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) {
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
@Suppress("DEPRECATION")
(intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT))?.let { c.startActivity(it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
}
PackageInstaller.STATUS_SUCCESS -> { progress = null; offer = null }
else -> { progress = "Android didn't install the update. Nothing has changed."; runCatching { c.unregisterReceiver(this) } }
}
}
}, IntentFilter(action))
val pending = PendingIntent.getBroadcast(context, id, Intent(action).setPackage(context.packageName), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE)
session.commit(pending.intentSender)
}
}
private fun Context.registerReceiverCompat(receiver: BroadcastReceiver, filter: IntentFilter) {
if (Build.VERSION.SDK_INT >= 33) registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED) else @Suppress("UnspecifiedRegisterReceiverFlag") registerReceiver(receiver, filter)
}
}
/** "Orbit 0.108.57 is ready, from Living Room. Install it on this TV?" Not now hides it until Orbit next opens. */
@Composable
internal fun RoomUpdateCard() {
val offer = RoomUpdates.offer ?: return
val context = LocalContext.current
val scope = rememberCoroutineScope()
var working by remember(offer) { mutableStateOf(false) }
val first = remember { FocusRequester() }
LaunchedEffect(offer) { runCatching { first.requestFocus() } }
BackHandler { RoomUpdates.notNow() }
Box(Modifier.fillMaxSize().background(Navy.copy(alpha = .55f)), contentAlignment = Alignment.Center) {
Column(Modifier.width(560.dp).background(Panel, RoundedCornerShape(14.dp)).padding(22.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("Orbit ${shortVersion(offer.name)} is ready", color = Ink, fontFamily = Anton, fontSize = 26.sp)
Text("${offer.room} has a newer Orbit. Install it on this TV? Your channels, schedules and settings stay as they are.", color = Muted, fontSize = 14.sp)
RoomUpdates.progress?.let { Text(it, color = Yellow, fontSize = 13.sp, fontWeight = FontWeight.SemiBold) }
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
OrbitButton(if (working) "Installing…" else "Install", Modifier.width(180.dp).focusRequester(first), enabled = !working, centred = true) {
working = true
scope.launch { RoomUpdates.install(context, offer); working = false }
}
OrbitButton("Not now", Modifier.width(180.dp), centred = true) { RoomUpdates.notNow() }
}
}
}
}
@@ -84,6 +84,7 @@ internal object RoomBeacon {
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.shared = RoomUpdates.shared(app)
PhoneLink.listening = true
val nsd = app.getSystemService(Context.NSD_SERVICE) as? NsdManager ?: return
registration = object : NsdManager.RegistrationListener {
@@ -94,7 +95,7 @@ internal object RoomBeacon {
}.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
PhoneLink.knock = null; PhoneLink.shared = null; PhoneLink.listening = false
val nsd = context.applicationContext.getSystemService(Context.NSD_SERVICE) as? NsdManager
registration?.let { r -> runCatching { nsd?.unregisterService(r) } }; registration = null
}
@@ -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.56")
next.setRequestProperty("User-Agent", "OrbitTV/0.108.57")
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()) {
@@ -0,0 +1,56 @@
package tv.orbit.classic
import android.content.pm.PackageInfo
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.net.InetAddress
/** Updates shared between rooms (Paul, 6 November 2026): only a newer Orbit, signed as this one is, and only when asked. */
class RoomUpdatesTest {
@get:Rule val folder = TemporaryFolder()
@Test fun onlyANewerVersionIsOfferedAndNotNowSticks() {
val answer = JSONObject().put("code", 220).put("name", "0.108.60-x")
assertEquals(220L, offerFrom("Living Room", "192.168.0.252", answer, 216, emptySet())!!.code)
assertNull(offerFrom("Living Room", "192.168.0.252", answer, 220, emptySet())) // the same version
assertNull(offerFrom("Living Room", "192.168.0.252", answer, 230, emptySet())) // older than this one
assertNull(offerFrom("Living Room", "192.168.0.252", answer, 216, setOf(220L))) // turned down this time
assertEquals("0.108.60", shortVersion("0.108.60-x"))
}
@Suppress("DEPRECATION")
private fun info(name: String, code: Int) = PackageInfo().apply { packageName = name; versionCode = code }
@Test fun theDownloadMustBeNewerOrbitSignedTheSameWay() {
val installed = info("tv.orbit.classic", 216)
fun signers(same: Boolean): (PackageInfo) -> Set<String> = { p -> if (p === installed || same) setOf("abc") else setOf("xyz") }
assertNull(acceptableUpdate(info("tv.orbit.classic", 217), installed, signers(true)))
assertNotNull(acceptableUpdate(info("tv.orbit.classic", 217), installed, signers(false))) // another key: refused
assertNotNull(acceptableUpdate(info("tv.orbit.classic", 216), installed, signers(true))) // not newer
assertNotNull(acceptableUpdate(info("com.example.other", 300), installed, signers(true))) // another app
assertNotNull(acceptableUpdate(null, installed, signers(true)))
}
@Test fun theOtherRoomServesItsVersionAndCopyOnlyWhileShared() {
PhoneLink.initForTest(object : PhoneStore {
override fun all() = emptyMap<String, String>(); 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 }
val apk = folder.newFile("orbit.apk").apply { writeBytes(ByteArray(300_000) { (it % 251).toByte() }) }
fun get(path: String): Pair<Int, ByteArray> {
val c = java.net.URL("http://127.0.0.1:18099$path").openConnection() as java.net.HttpURLConnection
val s = c.responseCode; return s to ((if (s < 400) c.inputStream else c.errorStream)?.use { it.readBytes() } ?: ByteArray(0))
}
try {
PhoneLink.shared = SharedBuild(220, "0.108.60-x", apk); PhoneLink.listening = true
val (status, body) = get("/room/version")
assertEquals(200, status); assertEquals(220L, JSONObject(String(body)).getLong("code"))
assertArrayEquals(apk.readBytes(), get("/room/orbit.apk").second)
PhoneLink.shared = null
assertEquals(404, get("/room/version").first); assertEquals(404, get("/room/orbit.apk").first)
} finally { PhoneLink.listening = false; PhoneLink.stop(); PhoneLink.allowed = EmbyServer::isHomeAddress; PhoneLink.bindTo = null; PhoneLink.port = PhoneLink.PORT }
}
}