From e58fa190d5b05462009c2a87232a2c4d85cbc055 Mon Sep 17 00:00:00 2001 From: Pauljd Date: Tue, 10 Nov 2026 15:42:25 +0000 Subject: [PATCH] Back up Orbit to my phone: sealed on the TV, previewed and restored safely, with undo (0.128.0) Companion More > Back up and restore, in both editions. The file is sealed on the TV (AES-256-GCM, key from the TV's backup code with PBKDF2) and the code is shown and typed only on the TV. No sign-in, token, PIN, phones, room keys or box switches. Versioned header bound into the seal, checksums outside and in. Restore: TV preview, this TV's data kept aside, a journal, then put in place first thing on restart; three failed starts put the old data back. Undo in Settings > Rooms and phones. Also fixes two remote-focus bugs found on the emulator: Right from Emby on the first-launch server step escaped into the hidden sign-in form, and Connect, Add a room and Bring in jumped to Settings > Channels. Report: docs/PHONE-BACKUP-2026-11-10.md (incl. the password-field accessibility finding). Co-Authored-By: Claude Opus 5.5 --- android/app/build.gradle.kts | 4 +- .../app/src/main/assets/phone/companion.html | 41 ++ .../java/tv/orbit/classic/MainActivity.kt | 10 +- .../main/java/tv/orbit/classic/PhoneBackup.kt | 433 ++++++++++++++++++ .../java/tv/orbit/classic/PhoneBackupFlow.kt | 359 +++++++++++++++ .../main/java/tv/orbit/classic/PhoneLink.kt | 31 +- .../main/java/tv/orbit/classic/Settings.kt | 41 +- .../java/tv/orbit/classic/PhoneBackupTest.kt | 259 +++++++++++ .../java/tv/orbit/classic/PhoneLinkTest.kt | 14 + docs/EDITIONS-EMULATOR-2026-11-10.md | 6 +- docs/PHONE-BACKUP-2026-11-10.md | 170 +++++++ 11 files changed, 1354 insertions(+), 14 deletions(-) create mode 100644 android/app/src/main/java/tv/orbit/classic/PhoneBackup.kt create mode 100644 android/app/src/main/java/tv/orbit/classic/PhoneBackupFlow.kt create mode 100644 android/app/src/test/java/tv/orbit/classic/PhoneBackupTest.kt create mode 100644 docs/PHONE-BACKUP-2026-11-10.md diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 5462e2c1..10b0ec8a 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -3,7 +3,7 @@ plugins { id("org.jetbrains.kotlin.plugin.compose") } /** The release's build number: versionCode is this x 10 plus the edition's channel. */ -val ORBIT_BUILD = 40 +val ORBIT_BUILD = 41 android { namespace = "tv.orbit.classic" compileSdk = 36 @@ -11,7 +11,7 @@ android { applicationId = "tv.orbit.classic" minSdk = 26 targetSdk = 36 - versionName = "0.127.0" + versionName = "0.128.0" } // Two editions of the same app (Paul, 10 November 2026): the household build, which updates itself between rooms, and the // Play build, which only Google Play updates. Both are tv.orbit.classic, so a TV can move between them keeping its data. diff --git a/android/app/src/main/assets/phone/companion.html b/android/app/src/main/assets/phone/companion.html index f7de604e..a488c584 100644 --- a/android/app/src/main/assets/phone/companion.html +++ b/android/app/src/main/assets/phone/companion.html @@ -263,6 +263,44 @@ function rooms() { if (!r.online.length && !r.asleep.length) h += '
No other rooms yet. Add one from Settings › Rooms and phones on the TV.
'; return h; } +// Back up and restore (Paul, 10 November 2026): the TV makes the file, sealed with its backup code, which only the TV shows; +// this page only carries the sealed file to the phone and back. Opening it and the choice to restore happen on the TV. +function backupSheet() { + const b = state.backup || {}; + return `
Back up and restore
+
A backup holds this TV's channels, schedules, profiles, what Orbit has learnt, Continue watching, Drive-In tickets, the Arcade's records and settings. Never your sign-in, PIN or phones. It's locked with the TV's backup code, which only the TV shows.
+ + ${b.download ? `Save it again` : ''} + + ${state.bnote ? `
${esc(state.bnote)}
` : ''}`; +} +function backupNote(j) { + return {waiting: 'Now go to the TV and type the backup code there, to see what\'s in it. Nothing changes until you choose Restore on the TV.', + preview: 'The TV is showing what\'s in the backup. Choose there whether to restore it.', restoring: 'The TV is restoring and restarting Orbit.', + done: j.ok ? 'Done: see the TV.' : 'The restore didn\'t finish: see the TV.', problem: j.message || 'See the TV.'}[j.state] || ''; +} +function watchBackup() { + clearTimeout(watchBackup.t); + watchBackup.t = setTimeout(() => api('/api/backup').then(j => { state.backup = j; const n = j.state === 'idle' ? 'Not restored: it was cancelled on the TV. Nothing changed.' : backupNote(j); if (n) state.bnote = n; + if ($('#bsheet')) openSheet(backupSheet()); if (['waiting', 'preview', 'restoring'].includes(j.state)) watchBackup(); }).catch(() => watchBackup()), 2500); +} +function makeBackup() { + state.bbusy = 'make'; state.bnote = ''; openSheet(backupSheet()); + api('/api/backup/make', {}).then(j => { + const a = document.createElement('a'); a.href = '/api/backup/file?id=' + encodeURIComponent(j.id); a.download = j.name; document.body.appendChild(a); a.click(); a.remove(); + state.backup = {...(state.backup || {}), download: j}; + state.bnote = `Saving ${j.name} to this phone. The TV is showing its backup code: write it down or take a photo, and keep it apart from the phone. You'll type it on the TV to restore.`; + }).catch(e => state.bnote = e.message).finally(() => { state.bbusy = ''; if ($('#bsheet')) openSheet(backupSheet()); }); +} +document.addEventListener('change', e => { + if (!e.target.dataset?.bfile) return; + const f = e.target.files?.[0]; if (!f) return; + if (!/\.orbitbackup$/i.test(f.name)) { state.bnote = 'That isn\'t an Orbit backup: they end in .orbitbackup.'; openSheet(backupSheet()); return; } + state.bbusy = 'send'; state.bnote = ''; openSheet(backupSheet()); + f.text().then(text => fetch('/api/backup/upload', {method: 'POST', headers: {'Content-Type': 'text/plain', 'X-Orbit': '1'}, body: text})) + .then(r => r.json().catch(() => ({})).then(j => { if (!r.ok) throw new Error(j.error || 'The TV couldn\'t take it.'); state.bnote = backupNote({state: 'waiting'}); watchBackup(); })) + .catch(e => state.bnote = e.message).finally(() => { state.bbusy = ''; if ($('#bsheet')) openSheet(backupSheet()); }); +}); function more() { // More, reorganised (design/companion/build-create-v3.py): who's watching as faces, what needs you with a count, your // channels as tiles, and settings as a short list. @@ -291,6 +329,7 @@ function more() { h += `
Settings
${line('Look', keptLook() ? esc(keptLook()) : 'Follows the TV', 'data-klook="1"', true)} ${standalone() ? '' : line('Add to home screen', '', 'data-home="1"')} + ${line('Back up and restore', '', 'data-kbackup="1"')} ${line('About Orbit Companion', '', 'data-kabout="1"')}
`; return h; } @@ -766,6 +805,8 @@ document.addEventListener('click', e => { if (d.klook) { openSheet(`
Look
Following the TV, each room's remote wears that room's look. Pick one to keep it on this phone instead.
${(state.looks || []).map(l => ``).join('')}
`); return; } + if (d.kbackup) { state.bnote = ''; openSheet(backupSheet()); api('/api/backup').then(j => { state.backup = j; if ($('#bsheet')) openSheet(backupSheet()); }).catch(() => {}); return; } + if (d.bmake) { makeBackup(); return; } if (d.kabout) { openSheet(`
Orbit Companion
It runs on the TV itself, over your home Wi-Fi: nothing to install, no account. It works while Orbit is open on the TV. To stop this phone, remove it in Settings › Rooms and phones on the TV.
`); return; } if (d.kquick) { quickBuild(); return; } if (d.ktry) { $('#kdesc').value = d.ktry; quickBuild(); return; } 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 1c95e571..31e9c772 100644 --- a/android/app/src/main/java/tv/orbit/classic/MainActivity.kt +++ b/android/app/src/main/java/tv/orbit/classic/MainActivity.kt @@ -15,6 +15,7 @@ import androidx.compose.foundation.layout.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.foundation.focusGroup import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusProperties import androidx.compose.ui.focus.focusRequester @@ -67,6 +68,8 @@ class MainActivity : ComponentActivity() { 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?) { + // A restore confirmed on the phone's backup is put in place first, before anything here reads the data. + PhoneBackups.finishAtStart(this) OrbitScreen.open = true OrbitCompanion.activity = java.lang.ref.WeakReference(this) super.onCreate(savedInstanceState) @@ -195,7 +198,11 @@ private fun OrbitApp() { val fullBleed = section == "Drive-In" || playingGame // Sections change at once (Paul, 6 November 2026: the slide stuttered on the box while the new screen was // being built, between the guide, the channels and the Arcade). - Column(if (fullBleed) Modifier.fillMaxSize() else Modifier.fillMaxSize().padding(start = 36.dp, end = 36.dp, top = 56.dp, bottom = 16.dp)) { + // While a first-launch step covers the sign-in form (any step but Sign in), the remote can't wander into it behind + // the step (10 November 2026: Right from a server card landed in the hidden address field and raised the keyboard). + val formHidden = onboarding && Onboarding.step != OnboardStep.SignIn + Column((if (fullBleed) Modifier.fillMaxSize() else Modifier.fillMaxSize().padding(start = 36.dp, end = 36.dp, top = 56.dp, bottom = 16.dp)) + .then(if (formHidden) Modifier.focusProperties { onEnter = { cancelFocusChange() } }.focusGroup() else Modifier)) { if (section == "Arcade" && realChannelAvailable && chosen) OrbitArcade(Modifier.weight(1f), onPlaying = { playingGame = it }, onExit = { section = "Home" }) EmbyConnectionScreen(if (section == "Arcade") Modifier else Modifier.weight(1f), visible = section == "Connect Emby", onboarding = onboarding, onSignedIn = { if (Onboarding.step == OnboardStep.SignIn) Onboarding.go(OnboardStep.Channels) }, @@ -249,6 +256,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() + PhoneBackupOverlay() Edition.UpdateCard() // Settings › Character cameos › Show one. CameoPreviewOverlay() diff --git a/android/app/src/main/java/tv/orbit/classic/PhoneBackup.kt b/android/app/src/main/java/tv/orbit/classic/PhoneBackup.kt new file mode 100644 index 00000000..944d8080 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/PhoneBackup.kt @@ -0,0 +1,433 @@ +package tv.orbit.classic + +import android.content.Context +import org.json.JSONArray +import org.json.JSONObject +import java.io.ByteArrayOutputStream +import java.io.File +import java.security.MessageDigest +import java.security.SecureRandom +import java.util.Base64 +import java.util.zip.ZipEntry +import java.util.zip.ZipInputStream +import java.util.zip.ZipOutputStream +import javax.crypto.AEADBadTagException +import javax.crypto.Cipher +import javax.crypto.SecretKeyFactory +import javax.crypto.spec.GCMParameterSpec +import javax.crypto.spec.PBEKeySpec +import javax.crypto.spec.SecretKeySpec + +/** + * Back up Orbit to my phone (Paul, 10 November 2026): a household's set-up, saved as one file on a phone through the + * Companion, and put back on this TV or another, in either edition. The rules: + * + * - **Encrypted on the TV, with a code that never travels.** The file is sealed (AES-256-GCM) with a key made from this TV's + * backup code, which is shown only on the TV's screen and typed only on the TV's remote. The phone carries a sealed file in + * both directions, so nothing readable crosses the Wi-Fi and nothing readable sits on the phone. A phone has to have joined + * (the Companion's code, and the Adult PIN when one is set), and the backup routes are for Adult only. + * - **No secrets in it.** Never the Emby or Jellyfin sign-in or token, the library copy, the Adult PIN, joined phones or the + * rooms' sync keys. Each file is also checked for anything shaped like a token before it goes in, and left out if so. + * - **Versioned and checked.** A plain first line and header (format, when, which Orbit) are bound into the seal, so they + * can't be changed either; the header carries the sealed part's size and checksum, so a file cut short in a download, or + * damaged, is caught before the code is asked for. Inside, every file is listed with its checksum and checked again. + * - **Shown before it's used, never silently.** A restore says what the backup holds and what it replaces here, and asks. + * This TV's data is kept aside first (see [PhoneRestore]), so a restore can be undone. + */ +internal object BackupFormat { + const val FORMAT = 1 + private const val FIRST_LINE = "ORBIT-BACKUP $FORMAT" + private const val LAST_LINE = "END ORBIT-BACKUP" + const val ITERATIONS = 210_000 + /** The largest sealed file a TV takes, and the most a backup may unpack to. */ + const val MAX_TEXT = 64 * 1024 * 1024 + private const val MAX_UNPACKED = 400L * 1024 * 1024 + private const val MAX_ENTRIES = 20_000 + private val random = SecureRandom() + + /** What's in a backup's plain header: enough to say what it is and to check it arrived whole, never what's inside it. */ + class Header(val json: JSONObject, val line: String) { + val format get() = json.optInt("format") + val madeMs get() = json.optLong("made") + val app get() = json.optString("app") + val build get() = json.optLong("build") + val edition get() = json.optString("edition") + } + + /** Why a file can't be opened, in words for the TV and phone. */ + class Refused(message: String) : Exception(message) + + /** Paths a backup may hold: its list, the three settings files, and files under schedule/ and arcade/ only. */ + private val allowedPath = Regex("""manifest\.json|prefs/orbit_(settings|profiles|rooms)\.json|(schedule|arcade)/[A-Za-z0-9._-]{1,120}(/[A-Za-z0-9._-]{1,120}){0,2}""") + fun allowed(path: String) = allowedPath.matches(path) && path.split('/').none { it == "." || it == ".." } + + private fun key(code: String, salt: ByteArray, iterations: Int): SecretKeySpec = + SecretKeySpec(SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(PBEKeySpec(code.toCharArray(), salt, iterations, 256)).encoded, "AES") + + fun sha256(bytes: ByteArray): String = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } + + /** Seals [plain] (a zip, see [BackupContents]) with [code] into the file's text. */ + fun seal(plain: ByteArray, code: String, madeMs: Long, app: String, build: Long, edition: String, iterations: Int = ITERATIONS): String { + val salt = ByteArray(16).also(random::nextBytes); val nonce = ByteArray(12).also(random::nextBytes) + // The header's size and checksum are of the sealed part, so they're worked out before the header is fixed: GCM's + // output is the same length whatever the additional data, so the seal is made once the header is known. + val length = plain.size + 16 + val stub = JSONObject().put("format", FORMAT).put("made", madeMs).put("app", app).put("build", build).put("edition", edition) + .put("kdf", "PBKDF2-HMAC-SHA256").put("iterations", iterations).put("salt", b64(salt)).put("cipher", "AES-256-GCM").put("nonce", b64(nonce)) + .put("bytes", length) + // The checksum can't be in the data it covers, so it's kept beside the header line, on a line of its own, and checked + // before anything else. Tampering with it gains nothing: the seal covers everything else. + val line = stub.toString() + val sealed = Cipher.getInstance("AES/GCM/NoPadding").run { + init(Cipher.ENCRYPT_MODE, key(code, salt, iterations), GCMParameterSpec(128, nonce)); updateAAD((FIRST_LINE + "\n" + line).toByteArray(Charsets.UTF_8)); doFinal(plain) + } + check(sealed.size == length) + val body = Base64.getMimeEncoder(76, "\n".toByteArray()).encodeToString(sealed) + return "$FIRST_LINE\n$line\nsha256 ${sha256(sealed)}\n$body\n$LAST_LINE\n" + } + + /** The parts of a file's text, checked whole: the header, and the sealed bytes. Refused with a reason otherwise. */ + fun parse(text: String): Pair { + if (text.length > MAX_TEXT) throw Refused("That file is too big to be an Orbit backup.") + val lines = text.replace("\r\n", "\n").trimEnd('\n').split('\n') + val first = lines.firstOrNull().orEmpty() + if (!first.startsWith("ORBIT-BACKUP ")) throw Refused("That isn't an Orbit backup.") + if (first != FIRST_LINE) { + val n = first.removePrefix("ORBIT-BACKUP ").toIntOrNull() + throw Refused(if (n != null && n > FORMAT) "This backup was made by a newer Orbit. Update Orbit on this TV, then try again." else "That isn't an Orbit backup.") + } + if (lines.size < 4) throw Refused("This backup is incomplete: it may not have finished saving on the phone. Make a new backup.") + val header = runCatching { Header(JSONObject(lines[1]), lines[1]) }.getOrElse { throw Refused("This backup is damaged and can't be read.") } + if (header.format != FORMAT) throw Refused("This backup was made by a newer Orbit. Update Orbit on this TV, then try again.") + val sum = lines[2].takeIf { it.startsWith("sha256 ") }?.removePrefix("sha256 ") ?: throw Refused("This backup is damaged and can't be read.") + if (lines.last() != LAST_LINE) throw Refused("This backup is incomplete: it may not have finished saving on the phone. Make a new backup.") + val sealed = runCatching { Base64.getMimeDecoder().decode(lines.subList(3, lines.size - 1).joinToString("")) } + .getOrElse { throw Refused("This backup is damaged and can't be read.") } + val expected = header.json.optLong("bytes", -1) + if (sealed.size.toLong() != expected) throw Refused(if (sealed.size < expected) "This backup is incomplete: part of it is missing. Make a new backup." else "This backup is damaged and can't be read.") + if (sha256(sealed) != sum) throw Refused("This backup is damaged: its checksum doesn't match. Make a new backup.") + if (header.json.optInt("iterations") !in 100_000..5_000_000 || header.json.optString("cipher") != "AES-256-GCM") throw Refused("This backup is damaged and can't be read.") + return header to sealed + } + + /** Opens [sealed] with [code]; null when the code doesn't open it. */ + fun open(header: Header, sealed: ByteArray, code: String): ByteArray? = try { + val salt = Base64.getDecoder().decode(header.json.getString("salt")); val nonce = Base64.getDecoder().decode(header.json.getString("nonce")) + Cipher.getInstance("AES/GCM/NoPadding").run { + init(Cipher.DECRYPT_MODE, key(code, salt, header.json.getInt("iterations")), GCMParameterSpec(128, nonce)) + updateAAD((FIRST_LINE + "\n" + header.line).toByteArray(Charsets.UTF_8)); doFinal(sealed) + } + } catch (_: AEADBadTagException) { null } + + /** + * Unpacks an opened backup's zip into [into] (which must be empty), checking every name against [allowed], the sizes, and + * every file against the list's checksum, with nothing extra and nothing missing. Returns the list. Refused otherwise, + * and [into] is emptied. + */ + fun unpack(zip: ByteArray, into: File): JSONObject { + into.deleteRecursively(); into.mkdirs() + try { + var total = 0L; var count = 0; val seen = HashMap() + ZipInputStream(zip.inputStream()).use { z -> + while (true) { + val e = z.nextEntry ?: break + if (e.isDirectory) continue + if (++count > MAX_ENTRIES) throw Refused("This backup holds too many files.") + if (!allowed(e.name) || e.name in seen) throw Refused("This backup holds something Orbit doesn't restore.") + val target = File(into, e.name).apply { parentFile?.mkdirs() } + val digest = MessageDigest.getInstance("SHA-256") + target.outputStream().use { out -> + val buffer = ByteArray(64 * 1024) + while (true) { val n = z.read(buffer); if (n < 0) break; total += n; if (total > MAX_UNPACKED) throw Refused("This backup is too big to restore."); digest.update(buffer, 0, n); out.write(buffer, 0, n) } + } + seen[e.name] = digest.digest().joinToString("") { "%02x".format(it) } + } + } + val manifest = runCatching { JSONObject(File(into, "manifest.json").readText()) }.getOrElse { throw Refused("This backup is damaged: its list of files is missing.") } + if (manifest.optInt("format") != FORMAT) throw Refused("This backup was made by a newer Orbit. Update Orbit on this TV, then try again.") + val listed = manifest.getJSONArray("files").let { a -> (0 until a.length()).associate { a.getJSONObject(it).let { f -> f.getString("path") to f.getString("sha256") } } } + if (listed.keys != seen.keys - "manifest.json") throw Refused("This backup is damaged: its files don't match its list.") + listed.forEach { (path, sum) -> if (seen[path] != sum) throw Refused("This backup is damaged: ${path.substringAfterLast('/').take(60)} doesn't match its checksum.") } + return manifest + } catch (failure: Throwable) { into.deleteRecursively(); throw if (failure is Refused) failure else Refused("This backup is damaged and can't be read.") } + } + + private fun b64(bytes: ByteArray) = Base64.getEncoder().encodeToString(bytes) +} + +/** This TV's backup code: sixteen characters, shown on the screen in fours, and typed back on the remote to restore. */ +internal object BackupCode { + /** Crockford's base 32: no I, L, O or U, so it reads and types without mix-ups. 80 bits. */ + private const val ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" + private val random = SecureRandom() + fun make(): String = (1..16).map { ALPHABET[random.nextInt(ALPHABET.length)] }.joinToString("") + /** What was typed, tidied: case, spaces and dashes don't matter, and O, I and L read as 0, 1 and 1. Null if it can't be a code. */ + fun normalise(typed: String): String? = typed.uppercase().filter { !it.isWhitespace() && it != '-' } + .map { when (it) { 'O' -> '0'; 'I', 'L' -> '1'; else -> it } }.joinToString("").takeIf { s -> s.length == 16 && s.all { it in ALPHABET } } + fun shown(code: String) = code.chunked(4).joinToString("-") + + private fun file(noBackup: File) = File(noBackup, "backup-code") + fun existing(noBackup: File): String? = runCatching { file(noBackup).takeIf { it.isFile }?.readText()?.trim()?.let(::normalise) }.getOrNull() + /** This TV's code, made the first time it's needed. */ + fun ofThisTv(noBackup: File): Pair = existing(noBackup)?.let { it to false } ?: make().also { writeSafely(file(noBackup), it) }.let { it to true } + /** A restored backup's code becomes this TV's own, when it hasn't one, so a household keeps one code. */ + fun adopt(noBackup: File, code: String) { if (existing(noBackup) == null) writeSafely(file(noBackup), code) } +} + +/** Shared settings, read and written whole: Android's own in the app, a map in tests. */ +internal interface PrefsBox { + fun read(name: String): Map + /** Replaces everything in [name] with [values], saved before it returns. */ + fun write(name: String, values: Map) +} + +internal class AndroidPrefsBox(private val context: Context) : PrefsBox { + override fun read(name: String): Map = context.getSharedPreferences(name, Context.MODE_PRIVATE).all + override fun write(name: String, values: Map) { + val edit = context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear() + values.forEach { (k, v) -> when (v) { is Boolean -> edit.putBoolean(k, v); is Int -> edit.putInt(k, v); is Long -> edit.putLong(k, v); is Float -> edit.putFloat(k, v); is String -> edit.putString(k, v) + is Set<*> -> edit.putStringSet(k, v.filterIsInstance().toSet()) } } + check(edit.commit()) { "Couldn't save $name." } + } +} + +/** + * What goes in a backup and what a restore puts back. Everything here works on folders and a [PrefsBox], so it's the same + * on the TV and in tests. + */ +internal object BackupContents { + /** The settings files that travel, and which of their keys. */ + val prefsFiles = listOf("orbit_settings", "orbit_profiles", "orbit_rooms") + /** + * Settings about this box, not the household, which stay as they are on the TV a backup goes to: the sound output, the + * library-reading and player switches (which stay off unless set on that TV), and anything only adb sets. + */ + private val boxKeys = setOf("surround_to_amplifier", "surround_to_amplifier_v2", "provider_catalogue", "player_frame_rate", "player_avi", "player_even_volume") + fun travels(file: String, key: String): Boolean = when (file) { + "orbit_settings" -> key !in boxKeys && !key.startsWith("adb_") && !key.startsWith("shadow") + "orbit_profiles" -> true + "orbit_rooms" -> key == "name" + else -> false + } + + /** Left in the schedule folder: copies kept for safety while saving, older copies kept by upgrades, and diagnostics. */ + private val leftBehind = Regex(""".*\.(prev|tmp|part|bak|writing|moving|replaced|restoring|wav)$|.*\.before-.*|.*\.schema\d+$|.*\.empty-\d+$|playback-notes\.txt""") + /** Shapes that would mean a sign-in had found its way into a file. A file holding one is left out, not sent. */ + private val secretShapes = Regex("""api_key=[A-Za-z0-9]|X-(Emby|MediaBrowser)-Token|"AccessToken"\s*:|after_dark_pin|orbit-connection""", RegexOption.IGNORE_CASE) + + private fun files(dir: File, prefix: String): List> = if (!dir.isDirectory) emptyList() else + dir.walkTopDown().maxDepth(3).filter { it.isFile }.map { "$prefix/" + it.relativeTo(dir).invariantSeparatorsPath to it } + .filter { (path, f) -> !leftBehind.matches(f.name) && BackupFormat.allowed(path) }.sortedBy { it.first }.toList() + + private fun prefsJson(values: Map, file: String) = JSONObject().also { o -> + values.toSortedMap().forEach { (k, v) -> if (travels(file, k) && v != null) { + val type = when (v) { is Boolean -> "Boolean"; is Int -> "Integer"; is Long -> "Long"; is Float -> "Float"; is String -> "String" + is Set<*> -> "Set"; else -> null } ?: return@forEach + o.put(k, JSONObject().put("t", type).put("v", if (v is Set<*>) JSONArray(v.toList()) else v)) + } } + } + fun prefsFrom(o: JSONObject): Map = o.keys().asSequence().mapNotNull { k -> runCatching { val e = o.getJSONObject(k); k to when (e.getString("t")) { + "Boolean" -> e.getBoolean("v"); "Integer" -> e.getInt("v"); "Long" -> e.getLong("v"); "Float" -> e.getDouble("v").toFloat() + "String" -> e.getString("v").take(262_144); "Set" -> e.getJSONArray("v").let { a -> (0 until a.length()).map { a.getString(it) }.toSet() } + else -> null } }.getOrNull()?.takeIf { it.second != null } }.toMap() + + /** The backup's zip: its list first, then the files. */ + fun zip(scheduleDir: File, arcadeDir: File, prefs: PrefsBox, madeMs: Long, app: String, build: Long, edition: String, room: String, server: String): ByteArray { + val bytes = ByteArrayOutputStream() + val listed = JSONArray(); val leftOut = JSONArray() + val entries = LinkedHashMap() + (files(scheduleDir, "schedule") + files(arcadeDir, "arcade")).forEach { (path, f) -> + val data = f.readBytes() + if (secretShapes.containsMatchIn(String(data, Charsets.ISO_8859_1))) leftOut.put(path) else entries[path] = data + } + prefsFiles.forEach { name -> entries["prefs/$name.json"] = prefsJson(prefs.read(name), name).toString().toByteArray() } + entries.forEach { (path, data) -> listed.put(JSONObject().put("path", path).put("bytes", data.size).put("sha256", BackupFormat.sha256(data))) } + val manifest = JSONObject().put("format", BackupFormat.FORMAT).put("made", madeMs).put("app", app).put("build", build).put("edition", edition) + .put("room", room).put("server", server).put("files", listed).put("leftOut", leftOut) + ZipOutputStream(bytes).use { z -> + z.setLevel(9) + z.putNextEntry(ZipEntry("manifest.json")); z.write(manifest.toString().toByteArray()); z.closeEntry() + entries.forEach { (path, data) -> z.putNextEntry(ZipEntry(path)); z.write(data); z.closeEntry() } + } + return bytes.toByteArray() + } + + /** One household's data, counted for a preview: in an unpacked backup, or on this TV now. */ + class Summary(val profiles: List, val channelsOn: Int, val yourChannels: List, val scheduleFiles: Int, val tasteEvents: Map, + val continueEntries: Int, val tickets: Int, val arcadeFiles: Int, val arcadeBests: Int, val settings: Int, val room: String?, val user: String?) { + fun lines(): List = listOf( + "Profiles: " + (if (profiles.isEmpty()) "none" else profiles.joinToString(", ")), + "Channels on: $channelsOn" + if (yourChannels.isEmpty()) "" else ", including your own: " + yourChannels.take(6).joinToString(", ") + if (yourChannels.size > 6) " and ${yourChannels.size - 6} more" else "", + "Schedules: " + if (scheduleFiles == 1) "1 channel's plan" else "$scheduleFiles channels' plans", + "What Orbit has learnt: " + (if (tasteEvents.isEmpty()) "nothing yet" else tasteEvents.entries.joinToString(", ") { "${it.value} for ${it.key}" }), + "Continue watching: $continueEntries", + "Drive-In tickets: $tickets", + "Arcade: $arcadeFiles save${if (arcadeFiles == 1) "" else "s"}" + if (arcadeBests > 0) " and $arcadeBests best score${if (arcadeBests == 1) "" else "s"}" else "", + "Settings: $settings") + } + + private fun count(file: File, block: (String) -> Int): Int = runCatching { if (file.isFile) block(file.readText()) else 0 }.getOrDefault(0) + + fun summarise(scheduleDir: File, arcadeDir: File, prefs: Map>): Summary { + // No profiles saved yet means Orbit's own two (Adult and Kids), as on a new TV. + val profileList = (prefs["orbit_profiles"]?.get("profiles") as? String)?.let { runCatching { Profiles.decode(it) }.getOrNull() } ?: DefaultProfiles + val names = profileList.associate { it.id to it.name } + val files = scheduleDir.listFiles().orEmpty() + val on = files.count { Regex("progress-\\d+\\.json").matches(it.name) && count(it) { t -> if (JSONObject(t).optBoolean("enabled")) 1 else 0 } == 1 } + val yours = runCatching { JSONArray(File(scheduleDir, "yours.json").readText()).let { a -> (0 until a.length()).map { a.getJSONObject(it).optString("name") } } }.getOrDefault(emptyList()) + val taste = File(scheduleDir, "taste").listFiles { f -> f.name.endsWith(".events.jsonl") }.orEmpty().associate { f -> + val id = f.name.removeSuffix(".events.jsonl"); (names[id] ?: names.entries.firstOrNull { it.key.filter(Char::isLetterOrDigit) == id }?.value ?: id) to f.readLines().count { it.isNotBlank() } } + .filterValues { it > 0 } + val cont = files.filter { Regex("continue-[A-Za-z0-9]{1,40}\\.json").matches(it.name) }.sumOf { f -> count(f) { JSONArray(it).length() } } + val tickets = count(File(scheduleDir, "tickets-0.json")) { JSONObject(it).optJSONObject("tickets")?.length() ?: 0 } + val user = files.filter { Regex("(progress|schedule)-\\d+\\.json").matches(it.name) }.firstNotNullOfOrNull { f -> runCatching { JSONObject(f.readText()).optString("user").takeIf { it.isNotBlank() } }.getOrNull() } + val settings = prefs["orbit_settings"].orEmpty() + val bests = settings.count { (k, v) -> (k.endsWith("_best") || k.endsWith("_wins") || k.endsWith("_solved")) && (v as? Int ?: 0) > 0 } + return Summary(profileList.map { it.name }, on, yours, files.count { Regex("schedule-\\d+\\.json").matches(it.name) }, taste, cont, tickets, + arcadeDir.walkTopDown().count { it.isFile && it.name.endsWith(".json") }, bests, settings.count { (k, _) -> travels("orbit_settings", k) }, + prefs["orbit_rooms"]?.get("name") as? String, user) + } +} + +/** + * Putting a backup back, and undoing it (Paul, 10 November 2026). Kept in no_backup/phone-restore: + * + * - `incoming/`: a backup that has been opened, checked and shown, waiting for Restore. + * - `aside-