Household and Play editions, one version-code counter (build 40: 400 household, 402 Play)
Both editions are tv.orbit.classic. The Play edition has no room updater, no PackageInstaller, no REQUEST_INSTALL_PACKAGES, no adb install check and no adb test hooks; Google Play updates it. The household edition keeps all of them. Release builds and the Play bundle are unsigned until signing is approved. The release gate builds both editions and the bundle, tests both, and checks what was built: ids, codes above every earlier one (the reserved 390 included), Play isolation, household intact, nothing signed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -95,7 +95,7 @@ internal object CatalogueShadow {
|
||||
shouldStop = {
|
||||
when {
|
||||
cancel -> "cancelled"
|
||||
!InstallSnapshot.screenOpen -> "Orbit closed"
|
||||
!OrbitScreen.open -> "Orbit closed"
|
||||
PlaybackHealth.stalls - stallsAtStart >= MAX_STALLS -> "playback stalled $MAX_STALLS times"
|
||||
runtime.totalMemory() - runtime.freeMemory() > runtime.maxMemory() * 8 / 10 -> "memory above 80%"
|
||||
else -> null
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* What the two editions share (Paul, 10 November 2026). Each edition has its own `Edition` object in its source set:
|
||||
* src/household (updates between rooms, the adb install check and test hooks) and src/play (none of those; Google Play
|
||||
* updates it). Everything else, Rooms, profiles, Taste, Continue Watching, the Arcade and sync, is the same code in both.
|
||||
*/
|
||||
internal class SharedBuild(val code: Long, val name: String, val file: File)
|
||||
|
||||
/** Orbit's screen is open in this process (set by MainActivity): a restore waits until it isn't, and the shadow comparison stops. */
|
||||
internal object OrbitScreen { @Volatile var open = false }
|
||||
@@ -1,169 +0,0 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* The install check for a finished (non-debuggable) build (Paul, 6 November 2026), where adb's run-as can no longer read
|
||||
* Orbit's files. Sent only from adb (the receiver needs the DUMP permission, which apps can't hold):
|
||||
*
|
||||
* - `snapshot`: copies the schedules and settings into Orbit's own folder on shared storage, with the library's and
|
||||
* sign-in's checksums, for adb to pull and compare. Nothing is read out of them here.
|
||||
* - `rollback <version>`: copies the schedules aside as schedule-rollback-<version>, as every install does.
|
||||
* - `catalogue`: a read-only copy of the library catalogue beside it, for checking new channels' titles against the library.
|
||||
* - `clear`: removes the copy once it's been pulled.
|
||||
* - `restore` (8 November 2026, audit U12): puts a pulled snapshot back. See [InstallRestore]: only with `confirm RESTORE`,
|
||||
* only while Orbit's screen isn't open, only files a snapshot takes, each checked against its checksum first, and the
|
||||
* current data is kept aside before anything is replaced.
|
||||
*
|
||||
* Apart from `restore`, it only ever copies; it never changes the schedules, the library or the sign-in.
|
||||
*/
|
||||
class InstallSnapshotReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val result = runCatching {
|
||||
if (intent.getStringExtra("do") == "prepare-restore") {
|
||||
// adb can't make folders in Orbit's shared folder on Android 14, only put files in one Orbit made.
|
||||
File(context.getExternalFilesDir(null), "install-restore").run { deleteRecursively(); mkdirs(); "ready" }
|
||||
} else if (intent.getStringExtra("do") == "restore") {
|
||||
if (InstallSnapshot.screenOpen) "refused: Orbit is open; force-stop it first"
|
||||
else File(context.getExternalFilesDir(null), "install-restore").let { folder ->
|
||||
// The pushed copy goes once it's been used, restored or refused.
|
||||
try { InstallRestore.apply(context.filesDir.parentFile!!, folder, intent.getStringExtra("confirm"), System.currentTimeMillis()) }
|
||||
finally { if (intent.getStringExtra("confirm") == "RESTORE") folder.deleteRecursively() }
|
||||
}
|
||||
} else if (intent.getStringExtra("do") == "hive-household") {
|
||||
// BumbleHive's Household save from another TV, pushed into install-restore/ (see HiveLegacy.adoptCopy).
|
||||
val incoming = File(context.getExternalFilesDir(null), "install-restore/hive-household.json")
|
||||
try {
|
||||
tv.orbit.classic.arcade.hive.HiveLegacy.adoptCopy(File(context.filesDir, "arcade"), incoming, intent.getStringExtra("sha256"),
|
||||
intent.getStringExtra("confirm"), intent.getStringExtra("from"), System.currentTimeMillis())
|
||||
} finally { incoming.delete() }
|
||||
} else InstallSnapshot.handle(context, intent.getStringExtra("do").orEmpty(), intent.getStringExtra("version"))
|
||||
}
|
||||
resultData = result.fold({ it }, { "failed" })
|
||||
android.util.Log.i("OrbitInstall", "${intent.getStringExtra("do")}: $resultData")
|
||||
}
|
||||
}
|
||||
|
||||
internal object InstallSnapshot {
|
||||
/** Orbit's screen is open in this process (set by MainActivity); a restore waits until it isn't. */
|
||||
@Volatile var screenOpen = false
|
||||
// A plain version, or one with a short suffix (0.110.7-arcade1), so a trial build's name doesn't refuse the rollback copy.
|
||||
private val versionShape = Regex("""\d+\.\d+\.\d+(-[a-z0-9]+(-[a-z0-9]+)*)?""")
|
||||
|
||||
fun handle(context: Context, action: String, version: String?): String {
|
||||
val data = context.filesDir.parentFile ?: return "no data"
|
||||
val out = File(context.getExternalFilesDir(null), "install-snapshot")
|
||||
return when (action) {
|
||||
"snapshot" -> {
|
||||
out.deleteRecursively()
|
||||
val schedule = File(data, "no_backup/schedule")
|
||||
schedule.copyRecursively(File(out, "no_backup/schedule"), overwrite = true)
|
||||
File(data, "shared_prefs/orbit_settings.xml").takeIf { it.exists() }?.copyTo(File(out, "shared_prefs/orbit_settings.xml"), overwrite = true)
|
||||
// Profiles too (7 November 2026), so an install can be shown to keep everyone; names and channels only, no PIN.
|
||||
File(data, "shared_prefs/orbit_profiles.xml").takeIf { it.exists() }?.copyTo(File(out, "shared_prefs/orbit_profiles.xml"), overwrite = true)
|
||||
// The Arcade's saves and (BumbleHive native, 8 November 2026) the WebView's localStorage folder, copied only,
|
||||
// so an install can show the old BumbleHive save and every profile's scores came through untouched.
|
||||
File(data, "files/arcade").takeIf { it.isDirectory }?.copyRecursively(File(out, "files/arcade"), overwrite = true)
|
||||
File(data, "app_webview/Default/Local Storage").takeIf { it.isDirectory }?.copyRecursively(File(out, "app_webview/Default/Local Storage"), overwrite = true)
|
||||
File(out, "hashes.txt").writeText(listOf("no_backup/catalogue.db", "no_backup/orbit-connection.v1")
|
||||
.joinToString("\n") { "${sha256(File(data, it))} $it" } + "\n")
|
||||
"copied ${schedule.walk().count { it.isFile }}"
|
||||
}
|
||||
"rollback" -> {
|
||||
if (version == null || !versionShape.matches(version)) return "bad version"
|
||||
val schedule = File(data, "no_backup/schedule")
|
||||
val aside = File(data, "no_backup/schedule-rollback-$version")
|
||||
aside.deleteRecursively(); schedule.copyRecursively(aside, overwrite = true)
|
||||
"aside ${aside.walk().count { it.isFile }}"
|
||||
}
|
||||
"catalogue" -> {
|
||||
val db = File(data, "no_backup/catalogue.db")
|
||||
if (!db.exists()) return "no catalogue"
|
||||
db.copyTo(File(out, "catalogue.db"), overwrite = true)
|
||||
"copied catalogue"
|
||||
}
|
||||
"clear" -> { out.deleteRecursively(); "cleared" }
|
||||
else -> "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
private fun sha256(file: File): String = if (!file.exists()) "missing" else file.inputStream().use { input ->
|
||||
val digest = MessageDigest.getInstance("SHA-256"); val buffer = ByteArray(64 * 1024)
|
||||
while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) }
|
||||
digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Putting a snapshot back (8 November 2026, audit U12: Android won't install an older Orbit over a newer one, so without
|
||||
* this a bad install could only be fixed forward). adb pushes a pulled snapshot to Orbit's shared folder as
|
||||
* install-restore/, with restore.txt listing each file's SHA-256 (`sha256sum` format). Then, with Orbit force-stopped:
|
||||
*
|
||||
* - nothing happens without `confirm RESTORE`;
|
||||
* - only what a snapshot takes can come back: no_backup/schedule/... and the settings and profiles prefs. Never the
|
||||
* library catalogue, the sign-in or the PIN;
|
||||
* - every listed file is checked against its checksum before anything is touched, and any problem refuses the lot;
|
||||
* - the current schedules and prefs are kept aside as no_backup/before-restore-<time> (the last two are kept);
|
||||
* - the schedules are copied in beside the old ones and swapped in by renaming, so a failure leaves the old ones in place.
|
||||
*/
|
||||
internal object InstallRestore {
|
||||
private val allowed = Regex("""no_backup/schedule/[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)?|shared_prefs/orbit_(settings|profiles)\.xml""")
|
||||
|
||||
fun apply(data: File, folder: File, confirm: String?, nowMs: Long): String {
|
||||
if (confirm != "RESTORE") return "refused: needs confirm RESTORE"
|
||||
// The snapshot comes as one restore.zip (adb can only put files in a folder Orbit made): unpacked beside it, taking
|
||||
// only restore.txt and the names a snapshot can hold, so nothing can be written anywhere else.
|
||||
val zip = File(folder, "restore.zip")
|
||||
val source = if (!zip.isFile) folder else File(folder, "unpacked").also { out ->
|
||||
out.deleteRecursively(); out.mkdirs()
|
||||
java.util.zip.ZipInputStream(zip.inputStream().buffered()).use { z ->
|
||||
while (true) {
|
||||
val e = z.nextEntry ?: break
|
||||
if (e.isDirectory) continue
|
||||
val name = e.name
|
||||
if (name != "restore.txt" && (!allowed.matches(name) || name.split('/').any { it == ".." || it == "." || it.isEmpty() }))
|
||||
return "refused: not allowed in zip: ${name.take(80)}"
|
||||
File(out, name).apply { parentFile?.mkdirs() }.outputStream().use { z.copyTo(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
val manifest = File(source, "restore.txt").takeIf { it.isFile } ?: return "refused: no restore.txt"
|
||||
val listed = manifest.readLines().filter { it.isNotBlank() }.map { line ->
|
||||
val hash = line.substringBefore(' '); val path = line.substringAfter(' ').trimStart(' ', '*')
|
||||
if (!Regex("[0-9a-f]{64}").matches(hash) || !allowed.matches(path) || path.split('/').any { it == ".." || it == "." || it.isEmpty() })
|
||||
return "refused: not allowed: ${path.take(80)}"
|
||||
path to hash
|
||||
}
|
||||
if (listed.none { it.first.startsWith("no_backup/schedule/") }) return "refused: no schedules listed"
|
||||
for ((path, hash) in listed) {
|
||||
val f = File(source, path)
|
||||
if (!f.isFile || sha256(f) != hash) return "refused: checksum: ${path.take(80)}"
|
||||
}
|
||||
// Keep what's there now, before anything changes.
|
||||
val aside = File(data, "no_backup/before-restore-$nowMs")
|
||||
File(data, "no_backup/schedule").takeIf { it.isDirectory }?.copyRecursively(File(aside, "schedule"), overwrite = true)
|
||||
listOf("orbit_settings.xml", "orbit_profiles.xml").forEach { n -> File(data, "shared_prefs/$n").takeIf { it.isFile }?.copyTo(File(aside, "shared_prefs/$n"), overwrite = true) }
|
||||
File(data, "no_backup").listFiles { f -> f.name.startsWith("before-restore-") }.orEmpty().sortedBy { it.name }.dropLast(2).forEach { it.deleteRecursively() }
|
||||
// The schedules: built beside, then swapped in.
|
||||
val incoming = File(data, "no_backup/schedule.restoring").apply { deleteRecursively(); mkdirs() }
|
||||
for ((path, _) in listed.filter { it.first.startsWith("no_backup/schedule/") })
|
||||
File(source, path).copyTo(File(incoming, path.removePrefix("no_backup/schedule/")), overwrite = true)
|
||||
val live = File(data, "no_backup/schedule"); val old = File(data, "no_backup/schedule.replaced")
|
||||
old.deleteRecursively()
|
||||
if (live.exists() && !live.renameTo(old)) { incoming.deleteRecursively(); return "failed: couldn't move the current schedules" }
|
||||
if (!incoming.renameTo(live)) { old.renameTo(live); incoming.deleteRecursively(); return "failed: couldn't swap in; current schedules kept" }
|
||||
old.deleteRecursively()
|
||||
for ((path, _) in listed.filter { it.first.startsWith("shared_prefs/") }) writeSafely(File(data, path)) { out -> File(source, path).inputStream().use { it.copyTo(out) } }
|
||||
return "restored ${listed.size}; aside before-restore-$nowMs"
|
||||
}
|
||||
|
||||
private fun sha256(file: File): String = file.inputStream().use { input ->
|
||||
val digest = MessageDigest.getInstance("SHA-256"); val buffer = ByteArray(64 * 1024)
|
||||
while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) }
|
||||
digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
}
|
||||
@@ -53,35 +53,21 @@ class MainActivity : ComponentActivity() {
|
||||
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) } }
|
||||
lifecycleScope.launch { runCatching { Edition.lookForUpdate(this@MainActivity) } }
|
||||
}
|
||||
}
|
||||
// Phones stay connected while Orbit is in the background (Paul, 8 November 2026: the web app couldn't connect while the TV
|
||||
// was in another app), and paired rooms keep syncing; the phone says Orbit isn't on screen instead of failing to load.
|
||||
override fun onDestroy() { InstallSnapshot.screenOpen = false; super.onDestroy() }
|
||||
override fun onDestroy() { OrbitScreen.open = false; super.onDestroy() }
|
||||
override fun onStop() { WatchCheck.stopped(); OrbitCompanion.onTv = false; PhoneLink.offerRoom(null); if (PhoneLink.phones.isEmpty() && RoomLinks.links.none { it.on }) { RoomBeacon.off(this); PhoneLink.stop() }; super.onStop() }
|
||||
/**
|
||||
* The adb-only requests (inspection, evidence, the provider switch and shadow comparison). Read at start and, since Orbit
|
||||
* opens as one copy (singleTask, 8 November 2026), also when adb sends them to an Orbit already open.
|
||||
*/
|
||||
private fun readAdbRequests(intent: android.content.Intent?) {
|
||||
if (intent?.getBooleanExtra("orbit_intro_test", false) == true) IntroTrial.nextTune = true
|
||||
intent?.getStringExtra("orbit_inspect_series")?.take(120)?.let { SeriesInspection.title = it }
|
||||
if (intent?.getBooleanExtra("orbit_read_evidence", false) == true) EvidenceRequest.pending = true
|
||||
// Provider contract, step 3: the catalogue switch and the read-only shadow comparison.
|
||||
when (intent?.getStringExtra("orbit_provider_catalogue")) { "on" -> ProviderSwitches.setCatalogue(this, true); "off" -> ProviderSwitches.setCatalogue(this, false) }
|
||||
// Player improvements (9 November 2026): frame-rate matching and AVI, each off until switched on.
|
||||
when (intent?.getStringExtra("orbit_frame_rate")) { "on" -> PlayerSwitches.setFrameRate(this, true); "off" -> PlayerSwitches.setFrameRate(this, false) }
|
||||
intent?.getStringExtra("orbit_even_volume")?.let { PlayerSwitches.setEvenVolume(this, it) }
|
||||
when (intent?.getStringExtra("orbit_avi")) { "on" -> PlayerSwitches.setAvi(this, true); "off" -> PlayerSwitches.setAvi(this, false) }
|
||||
if (intent?.getBooleanExtra("orbit_shadow_catalogue_stop", false) == true) CatalogueShadow.cancel = true
|
||||
if (intent?.hasExtra("orbit_shadow_from") == true) CatalogueShadow.from = intent.getLongExtra("orbit_shadow_from", 0L).coerceAtLeast(0L)
|
||||
if (intent?.getBooleanExtra("orbit_shadow_resume", false) == true) CatalogueShadow.resume = true
|
||||
if (intent?.hasExtra("orbit_shadow_catalogue") == true) CatalogueShadow.pending = intent.getIntExtra("orbit_shadow_catalogue", 5)
|
||||
}
|
||||
private fun readAdbRequests(intent: android.content.Intent?) = Edition.readAdbRequests(this, intent)
|
||||
override fun onNewIntent(intent: android.content.Intent) { super.onNewIntent(intent); setIntent(intent); readAdbRequests(intent) }
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
InstallSnapshot.screenOpen = true
|
||||
OrbitScreen.open = true
|
||||
OrbitCompanion.activity = java.lang.ref.WeakReference(this)
|
||||
super.onCreate(savedInstanceState)
|
||||
tv.orbit.classic.ArcadeProgress.init(this)
|
||||
@@ -92,10 +78,7 @@ class MainActivity : ComponentActivity() {
|
||||
ProviderSwitches.load(this)
|
||||
PlayerSwitches.load(this)
|
||||
readAdbRequests(intent)
|
||||
// The hand-run playback test opens over Orbit, which stops in the background as it would for any other app, and comes back when it ends.
|
||||
intent?.getStringExtra("orbit_play_test")?.takeIf(EmbyClient::validId)?.let { item ->
|
||||
startActivity(android.content.Intent(this, PlaybackTestActivity::class.java).putExtra(PlaybackTestActivity.ITEM, item))
|
||||
}
|
||||
Edition.openPlaybackTest(this, intent)
|
||||
// Before anything is drawn, so a locked After Dark never shows for a moment.
|
||||
AfterDarkLock.load(this)
|
||||
// Opening the saved sign-in takes seconds on the box: start it now, while the first screen is drawn.
|
||||
@@ -266,7 +249,7 @@ private fun OrbitApp() {
|
||||
if (SleepTimer.goodnight && !FullScreen.active) LunaGoodnight()
|
||||
// A new TV joining (Multiroom auto-scan), over everything else; and a newer Orbit from another room.
|
||||
RoomKnockOverlay()
|
||||
RoomUpdateCard()
|
||||
Edition.UpdateCard()
|
||||
// Settings › Character cameos › Show one.
|
||||
CameoPreviewOverlay()
|
||||
}
|
||||
|
||||
@@ -213,19 +213,8 @@ 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
|
||||
}
|
||||
// Updates between rooms: the household edition answers these; the Play edition never shares itself.
|
||||
if (Edition.serveUpdate(r.path, r.method, out, shared) { status, body -> json(out, status, body) }) 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)) }
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.PlaybackException
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.common.Tracks
|
||||
import androidx.media3.common.text.CueGroup
|
||||
import androidx.tv.material3.MaterialTheme
|
||||
import androidx.tv.material3.Text
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* The hand-run playback test (approved by Paul on 4 November 2026 for Dragon Ball Super: Beerus): one episode, by its
|
||||
* Emby id, in Orbit's own player, opened with `--es orbit_play_test <id>` on MainActivity. Subtitles are chosen exactly as on
|
||||
* a channel, from the subtitles setting and [subtitleChoice]. It books nothing and never touches the scheduler, plans, cursors or
|
||||
* pools, reports nothing to Emby (so no progress or resume point is recorded there), and ends by itself after
|
||||
* [TEST_MS], or on Back, returning to Orbit as it was. It logs formats, languages and counts only (tag OrbitPlayTest),
|
||||
* never a title, path or address.
|
||||
*/
|
||||
class PlaybackTestActivity : ComponentActivity() {
|
||||
companion object {
|
||||
const val ITEM = "item"
|
||||
const val TEST_MS = 3 * 60_000L
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
val item = intent?.getStringExtra(ITEM)?.takeIf(EmbyClient::validId) ?: run { finish(); return }
|
||||
setContent { MaterialTheme { PlaybackTest(item) { finish() } } }
|
||||
}
|
||||
}
|
||||
|
||||
/** What the test saw, summed up at the end. Counts and formats only. */
|
||||
internal class PlaybackTestRecord {
|
||||
var ready = false
|
||||
var firstFrame = false
|
||||
var video = "none"
|
||||
var audio = "none"
|
||||
var subtitles = emptyList<String>()
|
||||
var subtitleSelected = "none"
|
||||
var cueUpdates = 0
|
||||
var firstCueMs: Long? = null
|
||||
var errors = 0
|
||||
fun summary() = "playtest result ready=$ready firstFrame=$firstFrame video=$video audio=$audio subtitles=${subtitles.size}[${subtitles.joinToString(", ")}]" +
|
||||
" subtitleSelected=$subtitleSelected cueUpdates=$cueUpdates firstCuePositionMs=${firstCueMs ?: "none"} errors=$errors"
|
||||
}
|
||||
|
||||
/** A short, safe label: a language code or a format's MIME type (one slash at most), else "unknown". */
|
||||
private val SafeLabel = Regex("""[A-Za-z0-9.+_-]{1,20}(/[A-Za-z0-9.+_-]{1,20})?""")
|
||||
internal fun playTestLabel(value: String?) = value?.trim()?.takeIf(SafeLabel::matches) ?: "unknown"
|
||||
|
||||
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
|
||||
@Composable
|
||||
private fun PlaybackTest(itemId: String, done: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
var session by remember { mutableStateOf<EmbySampleSession?>(null) }
|
||||
var plan by remember { mutableStateOf<EmbyPlaybackPlan?>(null) }
|
||||
var problem by remember { mutableStateOf<String?>(null) }
|
||||
val record = remember { PlaybackTestRecord() }
|
||||
// Starts from the subtitles setting exactly as a channel visit does, so the test shows what a viewer would get.
|
||||
val subtitles = remember { mutableStateOf(if (OrbitSettings(context).subtitlesOn) SUBTITLES_BY_DEFAULT else null) }
|
||||
val startedAt = remember { android.os.SystemClock.elapsedRealtime() }
|
||||
var ended by remember { mutableStateOf(false) }
|
||||
fun finish(reason: String) {
|
||||
if (ended) return
|
||||
ended = true
|
||||
Log.i("OrbitPlayTest", record.summary() + " ended=$reason")
|
||||
done()
|
||||
}
|
||||
LaunchedEffect(itemId) {
|
||||
Log.i("OrbitPlayTest", "playtest start item=$itemId")
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
val saved = RememberedConnectionStore.get(context).load() ?: throw EmbyCheckException("No saved connection.")
|
||||
EmbyServer.origin = saved.origin
|
||||
val active = EmbyClient(HttpsEmbyTransport(saved.identity.deviceId, saved.origin)).resume(saved)
|
||||
session = active
|
||||
val item = SampleItem("Playback test", "Episode", null, "", itemId)
|
||||
active.rememberScheduledItems(listOf(item))
|
||||
plan = active.prepare(item)
|
||||
}
|
||||
} catch (failure: Exception) {
|
||||
Log.w("OrbitPlayTest", "playtest failed=${failure.javaClass.simpleName} status=${(failure as? EmbyCheckException)?.httpStatus}")
|
||||
problem = "The playback test couldn't start."
|
||||
delay(5_000)
|
||||
finish("failed")
|
||||
}
|
||||
}
|
||||
// The test ends by itself, whatever happens.
|
||||
LaunchedEffect(plan) { if (plan != null) { delay(PlaybackTestActivity.TEST_MS); finish("time") } }
|
||||
// The test's own session ends without signing out, so Orbit's saved connection carries on.
|
||||
DisposableEffect(Unit) { onDispose { session?.let { active -> EmbyCleanup.run { active.detach() } } } }
|
||||
Box(Modifier.fillMaxSize().background(Color.Black), contentAlignment = Alignment.Center) {
|
||||
val ready = plan
|
||||
val active = session
|
||||
if (ready != null && active != null) {
|
||||
EmbyPlaybackDialog(active, ready, onClose = { finish("back") }, subtitlePreference = subtitles, announce = false, reportPlayback = false,
|
||||
onPlayer = { player ->
|
||||
player.addListener(object : Player.Listener {
|
||||
override fun onPlaybackStateChanged(state: Int) {
|
||||
if (state == Player.STATE_READY && !record.ready) { record.ready = true; Log.i("OrbitPlayTest", "playtest readyMs=${android.os.SystemClock.elapsedRealtime() - startedAt}") }
|
||||
if (state == Player.STATE_ENDED) finish("ended")
|
||||
}
|
||||
override fun onRenderedFirstFrame() { record.firstFrame = true }
|
||||
override fun onPlayerError(error: PlaybackException) { record.errors++; Log.w("OrbitPlayTest", "playtest error=${error.errorCodeName}") }
|
||||
override fun onTracksChanged(tracks: Tracks) {
|
||||
fun selected(type: Int) = tracks.groups.filter { it.type == type && it.isSelected }.mapNotNull { g -> (0 until g.length).firstOrNull(g::isTrackSelected)?.let(g::getTrackFormat) }.firstOrNull()
|
||||
selected(C.TRACK_TYPE_VIDEO)?.let { record.video = "${playTestLabel(it.sampleMimeType)} ${it.width}x${it.height}" }
|
||||
selected(C.TRACK_TYPE_AUDIO)?.let { record.audio = "${playTestLabel(it.sampleMimeType)} ${playTestLabel(it.language)} ${it.channelCount}ch" }
|
||||
val text = tracks.groups.filter { it.type == C.TRACK_TYPE_TEXT }
|
||||
record.subtitles = text.map { g -> g.getTrackFormat(0).let { "${playTestLabel(it.sampleMimeType ?: it.codecs)} ${playTestLabel(it.language)}" + (if (g.isSupported) "" else " unsupported") + (if (g.isSelected) " selected" else "") } }
|
||||
record.subtitleSelected = selected(C.TRACK_TYPE_TEXT)?.let { playTestLabel(it.language) } ?: "none"
|
||||
Log.i("OrbitPlayTest", "playtest tracks video=${record.video} audio=${record.audio} subtitles=${record.subtitles.joinToString(", ")}")
|
||||
}
|
||||
override fun onCues(cueGroup: CueGroup) {
|
||||
if (cueGroup.cues.isEmpty()) return
|
||||
record.cueUpdates++
|
||||
if (record.firstCueMs == null) { record.firstCueMs = player.currentPosition; Log.i("OrbitPlayTest", "playtest firstCuePositionMs=${record.firstCueMs}") }
|
||||
}
|
||||
})
|
||||
})
|
||||
} else Text(problem ?: "Playback test…", color = Muted, fontSize = 16.sp)
|
||||
}
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
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() }
|
||||
OverlayCard(Navy.copy(alpha = .55f)) {
|
||||
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,7 +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.shared = Edition.sharedBuild(app)
|
||||
PhoneLink.listening = true
|
||||
val nsd = app.getSystemService(Context.NSD_SERVICE) as? NsdManager ?: return
|
||||
registration = object : NsdManager.RegistrationListener {
|
||||
|
||||
Reference in New Issue
Block a user