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 <noreply@anthropic.com>
This commit is contained in:
@@ -263,6 +263,44 @@ function rooms() {
|
||||
if (!r.online.length && !r.asleep.length) h += '<div class="empty">No other rooms yet. Add one from Settings › Rooms and phones on the TV.</div>';
|
||||
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 `<div id="bsheet" class="title">Back up and restore</div>
|
||||
<div class="small" style="margin:8px 0 12px">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.</div>
|
||||
<button class="btn gold" data-bmake="1"${state.bbusy ? ' disabled' : ''}>${state.bbusy === 'make' ? 'Making the backup…' : 'Back up this TV'}</button>
|
||||
${b.download ? `<a class="btn" style="margin-top:8px;display:block;text-align:center" href="/api/backup/file?id=${esc(b.download.id)}" download="${esc(b.download.name)}">Save it again</a>` : ''}
|
||||
<label class="btn" style="margin-top:8px;display:block;text-align:center">${state.bbusy === 'send' ? 'Sending to the TV…' : 'Restore from a backup'}<input type="file" accept=".orbitbackup" data-bfile="1" style="display:none"></label>
|
||||
${state.bnote ? `<div class="small" style="margin-top:12px;color:var(--accent)">${esc(state.bnote)}</div>` : ''}`;
|
||||
}
|
||||
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 += `<div class="label">Settings</div><div style="background:var(--surface);border-radius:16px;overflow:hidden">
|
||||
${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"')}</div>`;
|
||||
return h;
|
||||
}
|
||||
@@ -766,6 +805,8 @@ document.addEventListener('click', e => {
|
||||
if (d.klook) { openSheet(`<div class="title">Look</div><div class="small" style="margin:6px 0 12px">Following the TV, each room's remote wears that room's look. Pick one to keep it on this phone instead.</div>
|
||||
<div class="chips" style="flex-wrap:wrap"><button class="${keptLook() ? '' : 'on'}" data-look="">Follow this TV${state.now?.look ? ' (' + esc(state.now.look.name) + ')' : ''}</button>
|
||||
${(state.looks || []).map(l => `<button class="${keptLook() === l.name ? 'on' : ''}" data-look="${esc(l.name)}">${esc(l.name)}</button>`).join('')}</div>`); 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(`<div class="title">Orbit Companion</div><div class="small" style="margin-top:8px">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.</div>`); return; }
|
||||
if (d.kquick) { quickBuild(); return; }
|
||||
if (d.ktry) { $('#kdesc').value = d.ktry; quickBuild(); return; }
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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<Header, ByteArray> {
|
||||
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<String, String>()
|
||||
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<String, Boolean> = 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<String, Any?>
|
||||
/** Replaces everything in [name] with [values], saved before it returns. */
|
||||
fun write(name: String, values: Map<String, Any?>)
|
||||
}
|
||||
|
||||
internal class AndroidPrefsBox(private val context: Context) : PrefsBox {
|
||||
override fun read(name: String): Map<String, Any?> = context.getSharedPreferences(name, Context.MODE_PRIVATE).all
|
||||
override fun write(name: String, values: Map<String, Any?>) {
|
||||
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<String>().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<Pair<String, File>> = 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<String, Any?>, 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<String, Any?> = 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<String, ByteArray>()
|
||||
(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<String>, val channelsOn: Int, val yourChannels: List<String>, val scheduleFiles: Int, val tasteEvents: Map<String, Int>,
|
||||
val continueEntries: Int, val tickets: Int, val arcadeFiles: Int, val arcadeBests: Int, val settings: Int, val room: String?, val user: String?) {
|
||||
fun lines(): List<String> = 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<String, Map<String, Any?>>): 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-<time>/`: this TV's data as it was just before a restore, in the same shape, for Undo. The last two are kept.
|
||||
* - `journal.json`: written, whole, only once everything above is complete. While it's there, the next start of Orbit puts
|
||||
* its source in place before anything else reads the data, so a restore never happens under a running Orbit.
|
||||
*
|
||||
* Interrupted at any point, it ends in one of two states, never between: before the journal, nothing has changed and the
|
||||
* part-made folders are cleared away; after it, each start carries on until it's done (each step can be run again), and if a
|
||||
* start fails three times the data kept aside goes back.
|
||||
*/
|
||||
/** For tests: stops a restore part-way, as a power cut would, without the clean-up a failure gets. */
|
||||
internal class PowerCut : Error()
|
||||
|
||||
internal class PhoneRestore(private val root: File, private val scheduleDir: File, private val arcadeDir: File, private val prefs: PrefsBox) {
|
||||
val incoming get() = File(root, "incoming")
|
||||
private val journal get() = File(root, "journal.json")
|
||||
private val last get() = File(root, "last.json")
|
||||
/** For tests: called between the steps of putting data in place, to stop part-way as a power cut would. */
|
||||
internal var step: (String) -> Unit = {}
|
||||
|
||||
private fun asides() = root.listFiles { f -> f.isDirectory && Regex("aside-\\d+").matches(f.name) && File(f, "complete").exists() }.orEmpty().sortedBy { it.name.removePrefix("aside-").toLong() }
|
||||
/** The newest data kept aside, for Undo; null when there's none. */
|
||||
fun undoable(): JSONObject? = asides().lastOrNull()?.let { a -> runCatching { JSONObject(File(a, "info.json").readText()).put("aside", a.name) }.getOrNull() }
|
||||
fun lastOutcome(): JSONObject? = runCatching { JSONObject(last.readText()) }.getOrNull()
|
||||
fun clearLastOutcome() { last.delete() }
|
||||
fun pending() = journal.isFile
|
||||
|
||||
/** Reads [dir]'s three settings files as a backup holds them. */
|
||||
fun prefsIn(dir: File): Map<String, Map<String, Any?>> = BackupContents.prefsFiles.associateWith { n ->
|
||||
runCatching { BackupContents.prefsFrom(JSONObject(File(dir, "prefs/$n.json").readText())) }.getOrDefault(emptyMap()) }
|
||||
|
||||
/** This TV now, counted. */
|
||||
fun summariseHere() = BackupContents.summarise(scheduleDir, arcadeDir, BackupContents.prefsFiles.associateWith { prefs.read(it) })
|
||||
|
||||
/** Copies this TV's data into [into], complete or not at all. */
|
||||
private fun keepAside(into: File, info: JSONObject) {
|
||||
val part = File(into.parentFile, into.name + ".part").apply { deleteRecursively(); mkdirs() }
|
||||
if (scheduleDir.isDirectory) scheduleDir.copyRecursively(File(part, "schedule"), overwrite = true) else File(part, "schedule").mkdirs()
|
||||
if (arcadeDir.isDirectory) arcadeDir.copyRecursively(File(part, "arcade"), overwrite = true) else File(part, "arcade").mkdirs()
|
||||
BackupContents.prefsFiles.forEach { n ->
|
||||
// Everything, box settings too, so Undo puts back exactly what was here.
|
||||
val all = prefs.read(n)
|
||||
val o = JSONObject().also { j -> all.toSortedMap().forEach { (k, v) -> val t = when (v) { is Boolean -> "Boolean"; is Int -> "Integer"; is Long -> "Long"; is Float -> "Float"; is String -> "String"; is Set<*> -> "Set"; else -> null }
|
||||
if (t != null) j.put(k, JSONObject().put("t", t).put("v", if (v is Set<*>) JSONArray(v.toList()) else v)) } }
|
||||
writeSafely(File(part, "prefs/$n.json"), o.toString())
|
||||
}
|
||||
writeSafely(File(part, "info.json"), info.toString())
|
||||
writeSafely(File(part, "complete"), "")
|
||||
if (!part.renameTo(into)) throw java.io.IOException("Couldn't keep this TV's data aside.")
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore, once it's been shown and confirmed: keeps this TV's data aside, then writes the journal. Nothing here is changed
|
||||
* yet; the next start of Orbit puts the backup in place ([finish]). Returns the aside folder's name.
|
||||
*/
|
||||
fun prepare(nowMs: Long, made: Long, from: String): String {
|
||||
check(File(incoming, "manifest.json").isFile) { "No backup is waiting." }
|
||||
check(!journal.exists()) { "A restore is already waiting to finish." }
|
||||
val aside = File(root, "aside-$nowMs")
|
||||
keepAside(aside, JSONObject().put("at", nowMs).put("before", "restore").put("made", made).put("from", from).put("schedule", scheduleDir.absolutePath))
|
||||
writeSafely(journal, JSONObject().put("schedule", scheduleDir.absolutePath).put("source", "incoming").put("aside", aside.name).put("kind", "restore").put("made", made).put("tries", 0).toString())
|
||||
return aside.name
|
||||
}
|
||||
|
||||
/** Undo: what was kept aside goes back. What's here now is kept aside in turn, so Undo can itself be undone. */
|
||||
fun prepareUndo(nowMs: Long): String {
|
||||
check(!journal.exists()) { "A restore is already waiting to finish." }
|
||||
val back = asides().lastOrNull() ?: throw IllegalStateException("There's nothing to undo.")
|
||||
val info = runCatching { JSONObject(File(back, "info.json").readText()) }.getOrDefault(JSONObject())
|
||||
// Kept aside while another server was signed in: it goes back only to that server's folder.
|
||||
check(info.optString("schedule", scheduleDir.absolutePath) == scheduleDir.absolutePath) { "It was kept aside while another server was signed in. Sign in to that server to undo it." }
|
||||
val made = info.optLong("made")
|
||||
val aside = File(root, "aside-$nowMs")
|
||||
keepAside(aside, JSONObject().put("at", nowMs).put("before", "undo").put("made", made).put("from", "undo").put("schedule", scheduleDir.absolutePath))
|
||||
writeSafely(journal, JSONObject().put("schedule", scheduleDir.absolutePath).put("source", back.name).put("aside", aside.name).put("kind", "undo").put("made", made).put("tries", 0).toString())
|
||||
return aside.name
|
||||
}
|
||||
|
||||
/**
|
||||
* At start, before anything reads the data: finishes a restore or undo that's waiting. Returns what happened (also kept in
|
||||
* last.json for the TV to say), or null when nothing was waiting. Part-made folders from an interrupted [prepare] go.
|
||||
*/
|
||||
fun finish(nowMs: Long): JSONObject? {
|
||||
if (!journal.isFile) {
|
||||
root.listFiles { f -> f.name.endsWith(".part") }.orEmpty().forEach { it.deleteRecursively() }
|
||||
// An opened backup that was never confirmed (Orbit closed while it was shown) doesn't stay on the TV.
|
||||
incoming.deleteRecursively()
|
||||
return null
|
||||
}
|
||||
val j = runCatching { JSONObject(journal.readText()) }.getOrNull() ?: run { journal.delete(); return null }
|
||||
val tries = j.optInt("tries") + 1
|
||||
writeSafely(journal, j.put("tries", tries).toString())
|
||||
val kind = j.optString("kind"); val aside = File(root, j.optString("aside"))
|
||||
val outcome = JSONObject().put("kind", kind).put("at", nowMs).put("made", j.optLong("made")).put("aside", aside.name)
|
||||
val result = runCatching {
|
||||
if (tries > 3) throw IllegalStateException("It stopped part-way three times.")
|
||||
place(File(root, j.getString("source")))
|
||||
outcome.put("ok", true)
|
||||
}.getOrElse { failure ->
|
||||
if (failure is PowerCut) throw failure
|
||||
// Back to how it was, from the copy kept aside a moment before.
|
||||
val back = runCatching { if (File(aside, "complete").exists()) place(aside) }.isSuccess
|
||||
outcome.put("ok", false).put("message", failure.message ?: "It didn't finish.").put("putBack", back)
|
||||
}
|
||||
if (result.optBoolean("ok") && j.optString("source") == "incoming") incoming.deleteRecursively()
|
||||
asides().dropLast(2).forEach { it.deleteRecursively() }
|
||||
writeSafely(last, result.toString())
|
||||
journal.delete()
|
||||
return result
|
||||
}
|
||||
|
||||
/** Puts [source]'s data in place of this TV's: the two folders swapped in whole, then the settings. Safe to run again. */
|
||||
private fun place(source: File) {
|
||||
swapIn(File(source, "schedule"), scheduleDir)
|
||||
step("schedule")
|
||||
swapIn(File(source, "arcade"), arcadeDir)
|
||||
step("arcade")
|
||||
BackupContents.prefsFiles.forEach { n ->
|
||||
val incomingValues = runCatching { BackupContents.prefsFrom(JSONObject(File(source, "prefs/$n.json").readText())) }.getOrDefault(emptyMap())
|
||||
val here = prefs.read(n)
|
||||
// The household's settings from the source; this box's own (sound output, player switches) as they are here.
|
||||
prefs.write(n, here.filterKeys { !BackupContents.travels(n, it) } + incomingValues.filterKeys { BackupContents.travels(n, it) })
|
||||
step("prefs/$n")
|
||||
}
|
||||
}
|
||||
|
||||
/** Replaces [target] with a copy of [source]: built beside it, then two renames. A run stopped part-way is put right here. */
|
||||
private fun swapIn(source: File, target: File) {
|
||||
val building = File(target.parentFile, target.name + ".restoring"); val replaced = File(target.parentFile, target.name + ".replaced")
|
||||
// A run that stopped between the two renames left the old data under .replaced: it goes back first.
|
||||
if (!target.exists() && replaced.exists()) check(replaced.renameTo(target)) { "Couldn't put the data back." }
|
||||
building.deleteRecursively(); replaced.deleteRecursively()
|
||||
if (source.isDirectory) source.copyRecursively(building, overwrite = true) else building.mkdirs()
|
||||
step("copied ${target.name}")
|
||||
if (target.exists() && !target.renameTo(replaced)) { building.deleteRecursively(); throw java.io.IOException("Couldn't move the current data.") }
|
||||
step("moved ${target.name}")
|
||||
if (!building.renameTo(target)) { replaced.renameTo(target); building.deleteRecursively(); throw java.io.IOException("Couldn't put the backup in place.") }
|
||||
replaced.deleteRecursively()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.view.KeyEvent
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
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.focus.onFocusChanged
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.tv.material3.Text
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* The TV's side of Back up Orbit to my phone (see [BackupFormat] and [PhoneRestore]): what the Companion asks for, what the
|
||||
* TV shows, and finishing a restore when Orbit starts. A backup is made when the phone asks and shows its code here; a
|
||||
* restore arrives from the phone, and everything after that happens on the TV: the code, the preview and the choice.
|
||||
*/
|
||||
internal object PhoneBackups {
|
||||
sealed interface Screen
|
||||
/** A backup was made for [phone]: the code is shown here, and only here. */
|
||||
class Made(val phone: String?, val code: String, val first: Boolean, val name: String, val bytes: Int, val leftOut: Int) : Screen
|
||||
/** A backup arrived from [phone] and is waiting for its code, typed on the remote. */
|
||||
class Arrived(val phone: String?, val header: BackupFormat.Header, val sealed: ByteArray) : Screen
|
||||
/** Opened and checked: what it holds, what's here now, and anything to know first. */
|
||||
class Preview(val phone: String?, val made: Long, val app: String, val code: String, val theirs: BackupContents.Summary,
|
||||
val here: BackupContents.Summary, val notes: List<String>) : Screen
|
||||
object Restarting : Screen
|
||||
class Done(val outcome: JSONObject) : Screen
|
||||
class Problem(val message: String) : Screen
|
||||
|
||||
var screen by mutableStateOf<Screen?>(null)
|
||||
/** Opening a backup takes a moment (the code is stretched on purpose), so the screen says so. */
|
||||
var busy by mutableStateOf(false)
|
||||
var codeProblem by mutableStateOf<String?>(null)
|
||||
private var tries = 0
|
||||
/** The made file, for the phone to fetch, for ten minutes. */
|
||||
private class Download(val id: String, val name: String, val text: String, val untilMs: Long)
|
||||
@Volatile private var download: Download? = null
|
||||
@Volatile private var started = false
|
||||
private val random = SecureRandom()
|
||||
|
||||
private fun root(context: Context) = File(context.noBackupFilesDir, "phone-restore")
|
||||
private fun arcade(context: Context) = File(context.filesDir, "arcade")
|
||||
fun restorer(context: Context, scheduleDir: File) = PhoneRestore(root(context), scheduleDir, arcade(context), AndroidPrefsBox(context))
|
||||
private fun version(context: Context): Pair<String, Long> = context.packageManager.getPackageInfo(context.packageName, 0).let {
|
||||
(it.versionName ?: "") to if (android.os.Build.VERSION.SDK_INT >= 28) it.longVersionCode else @Suppress("DEPRECATION") it.versionCode.toLong() }
|
||||
|
||||
/**
|
||||
* First thing when Orbit starts, before anything reads the data: finishes a restore or undo that was confirmed. If this
|
||||
* process had already started (Orbit's screen reopened in a living process), it starts again fresh instead.
|
||||
*/
|
||||
fun finishAtStart(activity: Activity) {
|
||||
val journal = File(root(activity), "journal.json")
|
||||
if (started && journal.isFile) { relaunch(activity); return }
|
||||
started = true
|
||||
val schedule = runCatching { JSONObject(journal.readText()).optString("schedule") }.getOrNull()?.takeIf { it.isNotBlank() }?.let(::File)
|
||||
val outcome = runCatching { PhoneRestore(root(activity), schedule ?: File(activity.noBackupFilesDir, "schedule"), arcade(activity), AndroidPrefsBox(activity)).finish(System.currentTimeMillis()) }.getOrNull()
|
||||
if (outcome != null) { screen = Done(outcome); android.util.Log.i("OrbitBackup", "restore finished kind=${outcome.optString("kind")} ok=${outcome.optBoolean("ok")}") }
|
||||
}
|
||||
|
||||
/** Orbit, started again in a new process, so a confirmed restore is put in place before anything has read the data. */
|
||||
fun relaunch(activity: Activity) {
|
||||
activity.startActivity(Intent.makeRestartActivityTask(ComponentName(activity, MainActivity::class.java)))
|
||||
Runtime.getRuntime().exit(0)
|
||||
}
|
||||
|
||||
private fun fileName(madeMs: Long): String {
|
||||
val t = java.time.Instant.ofEpochMilli(madeMs).atZone(java.time.ZoneId.systemDefault())
|
||||
return "orbit-backup-${Rooms.name.filter { it.isLetterOrDigit() }.take(20).lowercase().ifEmpty { "tv" }}-%04d%02d%02d-%02d%02d.orbitbackup".format(t.year, t.monthValue, t.dayOfMonth, t.hour, t.minute)
|
||||
}
|
||||
|
||||
// --- What the Companion asks for. Adults only, from a joined phone (checked by PhoneLink before it gets here). ---
|
||||
|
||||
/** The state for the phone to follow. */
|
||||
fun status(context: Context): JSONObject {
|
||||
val s = screen
|
||||
val o = JSONObject().put("state", when (s) { null -> "idle"; is Made -> "made"; is Arrived -> "waiting"; is Preview -> "preview"; Restarting -> "restoring"; is Done -> "done"; is Problem -> "problem" })
|
||||
if (s is Problem) o.put("message", s.message)
|
||||
if (s is Done) o.put("ok", s.outcome.optBoolean("ok"))
|
||||
download?.takeIf { System.currentTimeMillis() < it.untilMs }?.let { o.put("download", JSONObject().put("id", it.id).put("name", it.name).put("bytes", it.text.length)) }
|
||||
runCatching { o.put("undo", PhoneRestore(root(context), Workspaces.current(context).scheduleDir, arcade(context), AndroidPrefsBox(context)).undoable() != null) }
|
||||
return o
|
||||
}
|
||||
|
||||
/** Makes a backup of this TV for [phone]. Returns (status, reply). */
|
||||
fun make(context: Context, phone: String?): Pair<Int, JSONObject> {
|
||||
if (screen is Arrived || screen is Preview || screen == Restarting) return 409 to JSONObject().put("error", "A restore is in progress on the TV.")
|
||||
val workspace = Workspaces.current(context)
|
||||
if (workspace.origin.isEmpty()) return 409 to JSONObject().put("error", "Sign in on the TV first.")
|
||||
val now = System.currentTimeMillis(); val (app, build) = version(context)
|
||||
val (code, first) = BackupCode.ofThisTv(context.noBackupFilesDir)
|
||||
val zip = BackupContents.zip(workspace.scheduleDir, arcade(context), AndroidPrefsBox(context), now, app, build, Edition.NAME, Rooms.name, Workspaces.keyOf(workspace.origin))
|
||||
val leftOut = runCatching { java.util.zip.ZipInputStream(zip.inputStream()).use { z -> z.nextEntry; JSONObject(z.readBytes().toString(Charsets.UTF_8)).getJSONArray("leftOut").length() } }.getOrDefault(0)
|
||||
val text = BackupFormat.seal(zip, code, now, app, build, Edition.NAME)
|
||||
val id = ByteArray(16).also(random::nextBytes).joinToString("") { "%02x".format(it) }
|
||||
val made = Download(id, fileName(now), text, now + 10 * 60_000L)
|
||||
download = made
|
||||
screen = Made(phone, code, first, made.name, text.length, leftOut)
|
||||
android.util.Log.i("OrbitBackup", "backup made bytes=${text.length} files=${zip.size} leftOut=$leftOut")
|
||||
return 200 to JSONObject().put("id", id).put("name", made.name).put("bytes", text.length)
|
||||
}
|
||||
|
||||
/** The made file, by its id, while it's still there: (file name, text), or null. */
|
||||
fun file(id: String?): Pair<String, String>? = download?.takeIf { it.id == id && System.currentTimeMillis() < it.untilMs }?.let { it.name to it.text }
|
||||
|
||||
/** A backup the phone sent: checked whole, then waiting on the TV for its code. */
|
||||
fun receive(context: Context, phone: String?, text: String): Pair<Int, JSONObject> {
|
||||
if (screen is Arrived || screen is Preview || screen == Restarting) return 409 to JSONObject().put("error", "Another restore is already on the TV.")
|
||||
if (Workspaces.current(context).origin.isEmpty()) return 409 to JSONObject().put("error", "Sign in on the TV first, then restore.")
|
||||
if (PhoneRestore(root(context), Workspaces.current(context).scheduleDir, arcade(context), AndroidPrefsBox(context)).pending()) return 409 to JSONObject().put("error", "A restore is waiting for Orbit to restart.")
|
||||
val (header, sealed) = try { BackupFormat.parse(text) } catch (refused: BackupFormat.Refused) { return 400 to JSONObject().put("error", refused.message) }
|
||||
if (header.build / 10 > version(context).second / 10) return 400 to JSONObject().put("error", "This backup was made by a newer Orbit (${header.app}). Update Orbit on this TV, then try again.")
|
||||
tries = 0; codeProblem = null
|
||||
screen = Arrived(phone, header, sealed)
|
||||
android.util.Log.i("OrbitBackup", "backup arrived bytes=${sealed.size}")
|
||||
return 200 to JSONObject().put("ok", true)
|
||||
}
|
||||
|
||||
/** Not now: the card goes, and an opened backup waiting for Restore is removed from the TV. */
|
||||
fun cancel(context: Context? = null) {
|
||||
if (screen is Made || screen == Restarting || busy) return
|
||||
screen = null
|
||||
context?.let { runCatching { File(root(it), "incoming").deleteRecursively() } }
|
||||
}
|
||||
|
||||
// --- On the TV. ---
|
||||
|
||||
/** The code, typed on the remote: opens, unpacks and checks the backup, then shows the preview. */
|
||||
suspend fun open(context: Context, typed: String) {
|
||||
val arrived = screen as? Arrived ?: return
|
||||
val code = BackupCode.normalise(typed) ?: run { codeProblem = "A backup code is 16 letters and numbers, like K7QM-2XTR-9HFD-W3PA."; return }
|
||||
busy = true; codeProblem = null
|
||||
val result = withContext(Dispatchers.IO) { runCatching {
|
||||
val zip = BackupFormat.open(arrived.header, arrived.sealed, code) ?: return@runCatching null
|
||||
val workspace = Workspaces.current(context)
|
||||
val r = restorer(context, workspace.scheduleDir)
|
||||
val manifest = BackupFormat.unpack(zip, r.incoming)
|
||||
val theirs = BackupContents.summarise(File(r.incoming, "schedule"), File(r.incoming, "arcade"), r.prefsIn(r.incoming))
|
||||
val here = r.summariseHere()
|
||||
val notes = buildList {
|
||||
if (manifest.optString("server") != Workspaces.keyOf(workspace.origin)) add("It was made with a different library server. Channels come across, but titles this server doesn't have won't play, and Orbit plans again where it needs to.")
|
||||
else if (theirs.user != null && here.user != null && theirs.user != here.user) add("It was made with a different account on this server, so the schedules will be planned again for this one.")
|
||||
if (manifest.optString("edition") != Edition.NAME) add("It was made on the ${manifest.optString("edition")} edition of Orbit. Everything comes across the same.")
|
||||
manifest.optJSONArray("leftOut")?.length()?.takeIf { it > 0 }?.let { add("$it file${if (it == 1) " was" else "s were"} left out when it was made, because ${if (it == 1) "it" else "they"} looked like ${if (it == 1) "it" else "they"} held a sign-in.") }
|
||||
val days = (System.currentTimeMillis() - arrived.header.madeMs) / 86_400_000L
|
||||
if (days >= 14) add("It's $days days old: anything learnt or watched since then is replaced.")
|
||||
}
|
||||
Preview(arrived.phone, arrived.header.madeMs, arrived.header.app, code, theirs, here, notes)
|
||||
} }
|
||||
busy = false
|
||||
result.fold({ preview ->
|
||||
if (preview == null) {
|
||||
if (++tries >= 5) { screen = Problem("That code didn't open the backup five times. Send it from the phone again to have another go."); return }
|
||||
codeProblem = "That code didn't open this backup. Check it and try again."
|
||||
} else screen = preview
|
||||
}, { failure -> screen = Problem((failure as? BackupFormat.Refused)?.message ?: "The backup couldn't be opened.") })
|
||||
}
|
||||
|
||||
/** Restore, confirmed: this TV's data kept aside, then Orbit starts again and the backup goes in place first thing. */
|
||||
suspend fun restore(activity: Activity) {
|
||||
val p = screen as? Preview ?: return
|
||||
busy = true
|
||||
val ok = withContext(Dispatchers.IO) { runCatching {
|
||||
val workspace = Workspaces.current(activity)
|
||||
restorer(activity, workspace.scheduleDir).prepare(System.currentTimeMillis(), p.made, p.phone ?: "a phone").also { BackupCode.adopt(activity.noBackupFilesDir, p.code) }
|
||||
} }
|
||||
busy = false
|
||||
ok.onFailure { screen = Problem("The restore couldn't start: ${it.message}. Nothing was changed."); return }
|
||||
screen = Restarting
|
||||
android.util.Log.i("OrbitBackup", "restore confirmed; restarting")
|
||||
delay(1_500)
|
||||
relaunch(activity)
|
||||
}
|
||||
|
||||
/** Undo (or redo) from Settings: the data kept aside goes back, the same way. */
|
||||
suspend fun undo(activity: Activity) {
|
||||
busy = true
|
||||
val ok = withContext(Dispatchers.IO) { runCatching {
|
||||
val workspace = Workspaces.current(activity)
|
||||
restorer(activity, workspace.scheduleDir).prepareUndo(System.currentTimeMillis())
|
||||
} }
|
||||
busy = false
|
||||
ok.onFailure { screen = Problem("It couldn't be undone: ${it.message}. Nothing was changed."); return }
|
||||
screen = Restarting
|
||||
delay(1_500)
|
||||
relaunch(activity)
|
||||
}
|
||||
|
||||
internal fun day(ms: Long): String = java.time.Instant.ofEpochMilli(ms).atZone(java.time.ZoneId.systemDefault()).let {
|
||||
"${it.dayOfMonth} ${it.month.getDisplayName(java.time.format.TextStyle.SHORT, java.util.Locale.UK)} ${it.year}, %02d:%02d".format(it.hour, it.minute) }
|
||||
}
|
||||
|
||||
/** Wherever the TV is, the backup's card: its code, the code to type, the preview, or how a restore went. */
|
||||
@Composable
|
||||
internal fun PhoneBackupOverlay() {
|
||||
val s = PhoneBackups.screen ?: return
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val first = remember(s) { FocusRequester() }
|
||||
var asking by remember(s) { mutableStateOf(false) }
|
||||
var problem by remember(s) { mutableStateOf<String?>(null) }
|
||||
fun back() { when { asking -> asking = false; s is PhoneBackups.Restarting || PhoneBackups.busy -> {}; else -> PhoneBackups.cancel(context).also { if (s is PhoneBackups.Made || s is PhoneBackups.Done || s is PhoneBackups.Problem) PhoneBackups.screen = null } } }
|
||||
// Its own window (10 November 2026), so it shows over a programme playing full screen, which is a window too. Kept out of
|
||||
// screenshots and screen recording, as the backup code is on it; a phone's camera still sees it.
|
||||
androidx.compose.ui.window.Dialog(onDismissRequest = ::back, properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false,
|
||||
dismissOnClickOutside = false, securePolicy = androidx.compose.ui.window.SecureFlagPolicy.SecureOn)) {
|
||||
BackHandler { back() }
|
||||
Box(Modifier.fillMaxSize().background(Navy.copy(alpha = .6f)), contentAlignment = Alignment.Center) {
|
||||
if (asking) { PinEntry("Enter the Adult PIN to restore", problem, onDone = { pin ->
|
||||
if (AfterDarkLock.check(context, pin)) { asking = false; scope.launch { (context as? Activity)?.let { PhoneBackups.restore(it) } } } else problem = AfterDarkLock.refusal(context, "That PIN didn't match.")
|
||||
}, onCancel = { asking = false }); return@Box }
|
||||
Column(Modifier.width(640.dp).heightIn(max = 560.dp).background(Panel, RoundedCornerShape(14.dp)).padding(24.dp).verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
when (s) {
|
||||
is PhoneBackups.Made -> {
|
||||
Text("Backup saved to ${s.phone ?: "your phone"}", color = Ink, fontFamily = Anton, fontSize = 26.sp)
|
||||
Text("It's locked with this TV's backup code. To restore it, you'll type the code here, on the TV. " +
|
||||
if (s.first) "Write it down, or take a photo of it, and keep it apart from the phone." else "It's the same code as this TV's earlier backups.", color = Muted, fontSize = 14.sp)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
s.code.chunked(4).forEach { part -> Box(Modifier.background(Navy, RoundedCornerShape(8.dp)).padding(horizontal = 14.dp, vertical = 8.dp)) {
|
||||
Text(part, color = Yellow, fontFamily = Anton, fontSize = 34.sp, letterSpacing = 3.sp) } }
|
||||
}
|
||||
Text("Without the code the file can't be opened, by anyone, and Orbit can't find a lost code for you. " +
|
||||
"It holds your 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." +
|
||||
if (s.leftOut > 0) " ${s.leftOut} file${if (s.leftOut == 1) " was" else "s were"} left out because ${if (s.leftOut == 1) "it" else "they"} looked like ${if (s.leftOut == 1) "it" else "they"} held a sign-in." else "",
|
||||
color = Muted, fontSize = 12.sp)
|
||||
OrbitButton("Done", Modifier.width(160.dp).focusRequester(first), centred = true) { PhoneBackups.screen = null }
|
||||
}
|
||||
is PhoneBackups.Arrived -> {
|
||||
Text("Restore a backup", color = Ink, fontFamily = Anton, fontSize = 26.sp)
|
||||
Text("${s.phone ?: "A phone"} sent a backup made on ${PhoneBackups.day(s.header.madeMs)} (Orbit ${s.header.app}). Type its backup code to see what's in it. Nothing changes yet.",
|
||||
color = Muted, fontSize = 14.sp)
|
||||
// Never disabled while it's opening: a disabled field loses the remote's focus, leaving nothing to press.
|
||||
BackupCodeField(first) { typed -> if (!PhoneBackups.busy) scope.launch { PhoneBackups.open(context, typed) } }
|
||||
if (PhoneBackups.busy) Text("Opening it…", color = Yellow, fontSize = 14.sp)
|
||||
PhoneBackups.codeProblem?.let { Text(it, color = Yellow, fontSize = 14.sp) }
|
||||
OrbitButton("Cancel", Modifier.width(160.dp), centred = true) { if (!PhoneBackups.busy) PhoneBackups.cancel(context) }
|
||||
}
|
||||
is PhoneBackups.Preview -> {
|
||||
Text("What's in this backup", color = Ink, fontFamily = Anton, fontSize = 26.sp)
|
||||
Text("Made on ${PhoneBackups.day(s.made)}${s.theirs.room?.let { " in $it" }.orEmpty()}, Orbit ${s.app}. Checked: every file is whole.", color = Muted, fontSize = 13.sp)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(18.dp)) {
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text("In the backup", color = Yellow, fontSize = 14.sp, fontWeight = FontWeight.SemiBold)
|
||||
s.theirs.lines().forEach { Text(it, color = Ink, fontSize = 13.sp) }
|
||||
}
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text("On this TV now", color = Muted, fontSize = 14.sp, fontWeight = FontWeight.SemiBold)
|
||||
s.here.lines().forEach { Text(it, color = Muted, fontSize = 13.sp) }
|
||||
}
|
||||
}
|
||||
s.notes.forEach { Text(it, color = Yellow, fontSize = 13.sp) }
|
||||
Text("Restoring replaces what's on this TV now with the backup's. Your sign-in, the Adult PIN, joined phones, room links and this TV's sound and player settings stay as they are. " +
|
||||
"This TV's data is kept aside first: Settings › Rooms and phones › Undo the restore puts it back. Orbit restarts to finish.", color = Muted, fontSize = 12.sp)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
OrbitButton(if (PhoneBackups.busy) "Keeping this TV's data aside…" else "Restore and restart", Modifier.focusRequester(first)) {
|
||||
if (PhoneBackups.busy) return@OrbitButton
|
||||
if (AfterDarkLock.pinSet) { problem = null; asking = true } else scope.launch { (context as? Activity)?.let { PhoneBackups.restore(it) } } }
|
||||
OrbitButton("Cancel", Modifier.width(140.dp), centred = true) { if (!PhoneBackups.busy) PhoneBackups.cancel(context) }
|
||||
}
|
||||
}
|
||||
PhoneBackups.Restarting -> {
|
||||
Text("Restoring", color = Ink, fontFamily = Anton, fontSize = 26.sp)
|
||||
Text("Orbit is restarting to put the backup in place. If it doesn't open again by itself, open it from the home screen: the restore finishes then.", color = Muted, fontSize = 14.sp)
|
||||
}
|
||||
is PhoneBackups.Done -> {
|
||||
val o = s.outcome; val undo = o.optString("kind") == "undo"
|
||||
Text(if (o.optBoolean("ok")) (if (undo) "Undone" else "Restored") else "That didn't finish", color = Ink, fontFamily = Anton, fontSize = 26.sp)
|
||||
Text(if (o.optBoolean("ok")) (if (undo) "This TV's data is back as it was. To go back to the backup's, use Settings › Rooms and phones again."
|
||||
else "The backup from ${PhoneBackups.day(o.optLong("made"))} is in place. What was here before is kept aside: Settings › Rooms and phones › Undo the restore.")
|
||||
else (o.optString("message") + if (o.optBoolean("putBack")) " This TV's data was put back as it was." else " Some of this TV's data may not have been put back."),
|
||||
color = if (o.optBoolean("ok")) Mint else Yellow, fontSize = 15.sp)
|
||||
OrbitButton("OK", Modifier.width(160.dp).focusRequester(first), centred = true) { PhoneBackups.screen = null }
|
||||
}
|
||||
is PhoneBackups.Problem -> {
|
||||
Text("Backup", color = Ink, fontFamily = Anton, fontSize = 26.sp)
|
||||
Text(s.message, color = Yellow, fontSize = 15.sp)
|
||||
OrbitButton("OK", Modifier.width(160.dp).focusRequester(first), centred = true) { PhoneBackups.screen = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(s, asking) { runCatching { first.requestFocus() } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The backup code, typed with the remote's keyboard: letters and numbers only, shown in fours as it's typed. */
|
||||
@Composable
|
||||
private fun BackupCodeField(focus: FocusRequester, onDone: (String) -> Unit) {
|
||||
// What's typed is kept as typed (letters and numbers), and only shown in capitals and fours (see [CodeLook]): rewriting
|
||||
// the text as each letter came in cut the on-screen keyboard off after its first letter, and put letters out of order.
|
||||
var value by remember { mutableStateOf(androidx.compose.ui.text.input.TextFieldValue("")) }
|
||||
val text = value.text
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
val keyboard = LocalSoftwareKeyboardController.current
|
||||
val focusManager = androidx.compose.ui.platform.LocalFocusManager.current
|
||||
BasicTextField(value = value, onValueChange = { v -> val t = v.text.filter { it.isLetterOrDigit() }.take(16)
|
||||
value = if (t == v.text) v else androidx.compose.ui.text.input.TextFieldValue(t, androidx.compose.ui.text.TextRange(t.length)) },
|
||||
visualTransformation = CodeLook,
|
||||
singleLine = true, textStyle = TextStyle(color = Ink, fontSize = 26.sp, letterSpacing = 3.sp), cursorBrush = SolidColor(Yellow),
|
||||
keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Characters, autoCorrectEnabled = false, keyboardType = KeyboardType.Ascii, imeAction = ImeAction.Done),
|
||||
keyboardActions = KeyboardActions(onDone = { keyboard?.hide(); onDone(text) }),
|
||||
modifier = Modifier.fillMaxWidth().focusRequester(focus).onFocusChanged { focused = it.isFocused }
|
||||
.background(Navy).border(2.dp, if (focused) Yellow else Blue)
|
||||
.onPreviewKeyEvent { event ->
|
||||
when (event.nativeKeyEvent.keyCode) {
|
||||
KeyEvent.KEYCODE_DPAD_CENTER -> { if (event.nativeKeyEvent.action == KeyEvent.ACTION_UP) keyboard?.show(); true }
|
||||
// Down leaves the field for Open it (a text field keeps the remote's down for itself otherwise).
|
||||
KeyEvent.KEYCODE_DPAD_DOWN -> { if (event.nativeKeyEvent.action == KeyEvent.ACTION_DOWN) focusManager.moveFocus(androidx.compose.ui.focus.FocusDirection.Down); true }
|
||||
else -> false
|
||||
}
|
||||
}.padding(12.dp))
|
||||
OrbitButton("Open it", Modifier.width(160.dp), centred = true, enabled = BackupCode.normalise(text) != null) { onDone(text) }
|
||||
}
|
||||
|
||||
/** The code as typed, shown in capitals and in fours (K7QM-2XTR-…), with the cursor kept in step. */
|
||||
internal object CodeLook : androidx.compose.ui.text.input.VisualTransformation {
|
||||
override fun filter(text: androidx.compose.ui.text.AnnotatedString): androidx.compose.ui.text.input.TransformedText {
|
||||
val raw = text.text
|
||||
val shown = raw.uppercase().chunked(4).joinToString("-")
|
||||
val map = object : androidx.compose.ui.text.input.OffsetMapping {
|
||||
override fun originalToTransformed(offset: Int) = (if (offset <= 0) 0 else offset + (offset - 1) / 4).coerceIn(0, shown.length)
|
||||
override fun transformedToOriginal(offset: Int) = (offset - offset / 5).coerceIn(0, raw.length)
|
||||
}
|
||||
return androidx.compose.ui.text.input.TransformedText(androidx.compose.ui.text.AnnotatedString(shown), map)
|
||||
}
|
||||
}
|
||||
@@ -159,7 +159,12 @@ internal object PhoneLink {
|
||||
if (parts.size < 2) return null
|
||||
val headers = lines.drop(1).filter { ':' in it }.associate { it.substringBefore(':').trim().lowercase() to it.substringAfter(':').trim() }
|
||||
// Rooms sync carries a family's changes, so it may be larger; everything else stays small.
|
||||
val cap = if (parts[1].substringBefore('?') == "/room/sync") 2_000_000 else 65_536
|
||||
// A backup coming back from a phone is larger again, and only a joined phone may send one (checked before it's read).
|
||||
val cap = when {
|
||||
parts[1].substringBefore('?') == "/room/sync" -> 2_000_000
|
||||
parts[1].substringBefore('?') == "/api/backup/upload" && headers["x-orbit"] == "1" && cookiePhone(headers["cookie"]) != null -> BackupFormat.MAX_TEXT
|
||||
else -> 65_536
|
||||
}
|
||||
val length = headers["content-length"]?.toIntOrNull()?.coerceIn(0, cap) ?: 0
|
||||
val body = ByteArray(length).also { var read = 0; while (read < length) { val n = input.read(it, read, length - read); if (n < 0) break; read += n } }.toString(Charsets.UTF_8)
|
||||
val path = parts[1].substringBefore('?')
|
||||
@@ -177,8 +182,9 @@ internal object PhoneLink {
|
||||
private fun json(out: OutputStream, status: Int, value: Any) = respond(out, status, "application/json; charset=utf-8", value.toString().toByteArray())
|
||||
private fun page(out: OutputStream, html: String, extra: List<String> = emptyList()) = respond(out, 200, "text/html; charset=utf-8", html.toByteArray(), extra)
|
||||
|
||||
private fun phoneOf(r: Request): String? {
|
||||
val token = r.headers["cookie"]?.split(';')?.map { it.trim() }?.firstOrNull { it.startsWith("$COOKIE=") }?.substringAfter('=') ?: return null
|
||||
private fun phoneOf(r: Request): String? = cookiePhone(r.headers["cookie"])
|
||||
private fun cookiePhone(cookie: String?): String? {
|
||||
val token = cookie?.split(';')?.map { it.trim() }?.firstOrNull { it.startsWith("$COOKIE=") }?.substringAfter('=') ?: return null
|
||||
if (token.length != 64) return null
|
||||
val id = hash(token)
|
||||
return prefs().get(id)?.let { id }
|
||||
@@ -312,6 +318,8 @@ internal object PhoneLink {
|
||||
// Kids on the phone (8 November 2026, audit S8): everything past the remote is Create's (browsing, searching and
|
||||
// making channels), so while Kids is watching none of it answers, not just the routes that change things.
|
||||
if (!OrbitCompanion.grownUp) return json(out, 403, JSONObject().put("error", "Kids is watching. Switch to Adult to use Create."))
|
||||
// Back up Orbit to my phone (10 November 2026): Adult only, and needs no library, so it's answered before Create's.
|
||||
if (r.path.startsWith("/api/backup")) return backup(r, out)
|
||||
val h = standIn ?: handler ?: return json(out, 403, JSONObject().put("error", "The TV isn't signed in to a library right now."))
|
||||
when ("${r.method} ${r.path}") {
|
||||
"GET /api/channels" -> json(out, 200, JSONObject().put("next", CustomChannels.nextNumber() ?: JSONObject.NULL).put("channels", JSONArray(CustomChannels.list.map { c ->
|
||||
@@ -488,6 +496,23 @@ internal object PhoneLink {
|
||||
}
|
||||
}
|
||||
|
||||
/** The Companion's Back up and restore (see [PhoneBackups]): the file travels sealed; the code stays on the TV. */
|
||||
private fun backup(r: Request, out: OutputStream) {
|
||||
val ctx = appContext ?: return json(out, 409, JSONObject().put("error", "Orbit is starting up on the TV."))
|
||||
val (status, reply) = when ("${r.method} ${r.path}") {
|
||||
"GET /api/backup" -> 200 to PhoneBackups.status(ctx)
|
||||
"POST /api/backup/make" -> runCatching { PhoneBackups.make(ctx, active) }.getOrElse { 500 to JSONObject().put("error", "The backup couldn't be made.") }
|
||||
"GET /api/backup/file" -> {
|
||||
val (name, text) = PhoneBackups.file(r.query["id"]) ?: return json(out, 410, JSONObject().put("error", "That backup has expired. Make it again."))
|
||||
return respond(out, 200, "application/octet-stream", text.toByteArray(Charsets.UTF_8), listOf("Content-Disposition: attachment; filename=\"$name\""))
|
||||
}
|
||||
"POST /api/backup/upload" -> runCatching { PhoneBackups.receive(ctx, active, r.body) }.getOrElse { 400 to JSONObject().put("error", "That file couldn't be read.") }
|
||||
"POST /api/backup/cancel" -> { PhoneBackups.cancel(ctx); 200 to PhoneBackups.status(ctx) }
|
||||
else -> 404 to JSONObject().put("error", "Not found")
|
||||
}
|
||||
json(out, status, reply)
|
||||
}
|
||||
|
||||
private val companionRoutes = setOf("GET /api/now", "GET /api/guide", "GET /api/catchup", "GET /api/rooms", "GET /api/looks", "POST /api/key", "POST /api/volume",
|
||||
"POST /api/channel", "POST /api/tune", "POST /api/remind", "POST /api/follow", "GET /api/times", "POST /api/section", "POST /api/catchup/watch",
|
||||
"GET /api/queue", "POST /api/queue", "POST /api/queue/remove", "GET /api/drivein", "POST /api/drivein/ticket", "POST /api/drivein/watch",
|
||||
|
||||
@@ -375,12 +375,26 @@ private fun FamilyDetail(totsOn: Boolean, windingDown: Boolean, onWindDown: (Boo
|
||||
|
||||
/** Rooms and phones: the phones that can make channels, and (with Multiroom) the other TVs in the home. */
|
||||
@Composable
|
||||
private fun RoomsDetail(firstSwitch: FocusRequester, modifier: Modifier) {
|
||||
private fun RoomsDetail(firstSwitch: FocusRequester, modifier: Modifier,
|
||||
/**
|
||||
* Parks the remote on this section's rail item before a button here is replaced by a panel (10 November 2026): with
|
||||
* the focused button gone, Android gave focus to the first rail item, which opened Channels instead of the panel.
|
||||
*/
|
||||
park: () -> Unit = {}) {
|
||||
val context = LocalContext.current
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
var naming by remember { mutableStateOf(false) }
|
||||
var connecting by remember { mutableStateOf(false) }
|
||||
var bringing by remember { mutableStateOf(false) }
|
||||
// Back up Orbit to my phone: the data kept aside by the last restore, which Undo puts back (with the Adult PIN if set).
|
||||
val undoable = remember(PhoneBackups.screen) { runCatching { PhoneBackups.restorer(context, Workspaces.current(context).scheduleDir).undoable() }.getOrNull() }
|
||||
var undoing by remember { mutableStateOf(false) }
|
||||
var undoPin by remember { mutableStateOf(false) }
|
||||
var undoProblem by remember { mutableStateOf<String?>(null) }
|
||||
val undoScope = rememberCoroutineScope()
|
||||
if (undoPin) { PinEntry("Enter the Adult PIN to undo the restore", undoProblem, onDone = { pin ->
|
||||
if (AfterDarkLock.check(context, pin)) { undoPin = false; undoScope.launch { (context as? android.app.Activity)?.let { PhoneBackups.undo(it) } } } else undoProblem = AfterDarkLock.refusal(context, "That PIN didn't match.")
|
||||
}, onCancel = { undoPin = false }); return }
|
||||
var brought by remember { mutableStateOf<String?>(null) }
|
||||
if (adding) { AddRoomPanel(onClose = { adding = false }, modifier = modifier); return }
|
||||
// Rooms sync (Paul, 7 November 2026): a TV already set up can bring in another room's family, Taste and Continue watching.
|
||||
@@ -421,10 +435,10 @@ private fun RoomsDetail(firstSwitch: FocusRequester, modifier: Modifier) {
|
||||
}
|
||||
Heading("Other rooms")
|
||||
SettingLine("Bring in from another room", brought ?: "Everyone's profiles, what Orbit has learnt for each, and their Continue watching, merged in from a TV that's already set up. Channels and schedules here stay as they are.") {
|
||||
OrbitButton("Bring in", onClick = { bringing = true })
|
||||
OrbitButton("Bring in", onClick = { park(); bringing = true })
|
||||
}
|
||||
SettingLine("Add a room", "Set up Orbit on another TV in your home by copying this one: channels, profiles, look and more. Your password never travels.") {
|
||||
OrbitButton("Add a room", onClick = { adding = true })
|
||||
OrbitButton("Add a room", onClick = { park(); adding = true })
|
||||
}
|
||||
// Rooms sync (7 November 2026): each paired room, when it last synced, and a switch to stop.
|
||||
RoomLinks.links.forEach { link ->
|
||||
@@ -439,10 +453,27 @@ private fun RoomsDetail(firstSwitch: FocusRequester, modifier: Modifier) {
|
||||
}
|
||||
Heading("Phones")
|
||||
SettingLine("Connect a phone", "Orbit Companion: your phone as a remote, with the guide, Catch Up and rooms. No app to install, just scan a code.") {
|
||||
OrbitButton("Connect", onClick = { connecting = true })
|
||||
OrbitButton("Connect", onClick = { park(); connecting = true })
|
||||
}
|
||||
PhoneLink.phones.forEachIndexed { i, (id, name) -> SettingLine(name, "A remote for this TV, and can make and edit your channels.") {
|
||||
OrbitButton("Remove", if (i == 0) Modifier.focusRequester(firstSwitch) else Modifier, onClick = { PhoneLink.forget(id) }) } }
|
||||
Heading("Backups")
|
||||
SettingLine("Back up to a phone", "In the Companion on a connected phone: More › Back up and restore. The file is locked with this TV's backup code, which is shown here, never on the phone.") {}
|
||||
undoable?.let { u ->
|
||||
val redo = u.optString("before") == "undo"
|
||||
SettingLine(if (redo) "Put the restore back" else "Undo the restore",
|
||||
(if (redo) "Goes back to the backup's data, as it was before you undid it." else "Puts back this TV's data from just before the restore of the backup from ${PhoneBackups.day(u.optLong("made"))}.") + " Orbit restarts to finish.") {
|
||||
if (!undoing) OrbitButton(if (redo) "Put back" else "Undo", onClick = { park(); undoing = true })
|
||||
else Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
val yes = remember { FocusRequester() }
|
||||
LaunchedEffect(Unit) { runCatching { yes.requestFocus() } }
|
||||
OrbitButton(if (PhoneBackups.busy) "Working…" else "Yes, restart Orbit", Modifier.focusRequester(yes), onClick = {
|
||||
if (PhoneBackups.busy) return@OrbitButton
|
||||
if (AfterDarkLock.pinSet) { undoProblem = null; undoPin = true } else undoScope.launch { (context as? android.app.Activity)?.let { PhoneBackups.undo(it) } } })
|
||||
OrbitButton("Not now", onClick = { park(); undoing = false })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -542,7 +573,7 @@ internal fun SettingsScreen(section: SettingsSection, onSection: (SettingsSectio
|
||||
LookPicker(firstSwitch, cardWidth = 150.dp)
|
||||
}
|
||||
SettingsSection.Family -> FamilyDetail(isOn(TOTS_NUMBER), windingDown, onWindDown, firstSwitch, detail)
|
||||
SettingsSection.Rooms -> RoomsDetail(firstSwitch, detail)
|
||||
SettingsSection.Rooms -> RoomsDetail(firstSwitch, detail, park = { runCatching { firstFocus.requestFocus() } })
|
||||
SettingsSection.Account -> AccountDetail(server, titles, onSignOut, onRemoveServer, firstSwitch, detail)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
|
||||
/**
|
||||
* Back up Orbit to my phone (Paul, 10 November 2026): the file, its seal and checks, what goes in and what never does, and
|
||||
* restoring, including a file cut short, a damaged one, a restore stopped part-way, and undo. Every code, name and setting
|
||||
* here is made up.
|
||||
*/
|
||||
class PhoneBackupTest {
|
||||
private lateinit var tv: File
|
||||
private lateinit var other: File
|
||||
private val code = "K7QM2XTR9HFDW3PA"
|
||||
|
||||
private class MapPrefs(val files: MutableMap<String, MutableMap<String, Any?>> = mutableMapOf()) : PrefsBox {
|
||||
override fun read(name: String): Map<String, Any?> = files[name].orEmpty().toMap()
|
||||
override fun write(name: String, values: Map<String, Any?>) { files[name] = values.toMutableMap() }
|
||||
}
|
||||
|
||||
private fun household(root: File, prefs: MapPrefs, who: String) {
|
||||
val s = File(root, "no_backup/schedule").apply { mkdirs() }
|
||||
File(s, "progress-101.json").writeText(JSONObject().put("schema", 1).put("user", "user-$who").put("channel", 101).put("enabled", true).toString())
|
||||
File(s, "progress-101.json.prev").writeText("an older copy")
|
||||
File(s, "schedule-101.json").writeText(JSONObject().put("schema", 1).put("user", "user-$who").put("channel", 101).put("plan", "$who's plan").toString())
|
||||
File(s, "yours.json").writeText(JSONArray().put(JSONObject().put("number", 701).put("name", "$who's Mysteries")).toString())
|
||||
File(s, "continue-grown.json").writeText(JSONArray().put(JSONObject().put("number", 101).put("startMs", 1).put("atMs", 2)).toString())
|
||||
File(s, "tickets-0.json").writeText(JSONObject().put("schema", 1).put("user", "user-$who").put("channel", 0).put("tickets", JSONObject().put("1794254400000", 2)).toString())
|
||||
File(s, "taste").mkdirs(); File(s, "taste/grown.events.jsonl").writeText("{\"e\":1}\n{\"e\":2}\n")
|
||||
File(s, "playback-notes.txt").writeText("diagnostics")
|
||||
File(root, "files/arcade").mkdirs(); File(root, "files/arcade/household-records.json").writeText("{\"who\":\"$who\"}")
|
||||
File(root, "files/arcade/hive-tone-v1-a.wav").writeText("generated")
|
||||
prefs.files["orbit_settings"] = mutableMapOf("look" to "Night-$who", "snake_best" to 380, "surround_to_amplifier" to (who == "A"), "provider_catalogue" to (who == "A"),
|
||||
"player_avi" to false, "subtitle_style_grown" to "1,box")
|
||||
prefs.files["orbit_profiles"] = mutableMapOf("profiles" to Profiles.encode(listOf(Profile("grown", "Adult $who", "sil-pink", ProfileKind.Grown, emptySet()))), "current" to "grown")
|
||||
prefs.files["orbit_rooms"] = mutableMapOf("name" to "Den $who", "joined" to "[]")
|
||||
prefs.files["orbit_lock"] = mutableMapOf("after_dark_pin" to "hash-$who", "after_dark_salt" to "salt")
|
||||
prefs.files["orbit_phones"] = mutableMapOf("phone-hash" to "Pixel|1")
|
||||
}
|
||||
|
||||
private val prefsA = MapPrefs(); private val prefsB = MapPrefs()
|
||||
private fun schedule(root: File) = File(root, "no_backup/schedule")
|
||||
private fun arcade(root: File) = File(root, "files/arcade")
|
||||
private fun restorer(root: File, prefs: MapPrefs) = PhoneRestore(File(root, "no_backup/phone-restore"), schedule(root), arcade(root), prefs)
|
||||
private fun backupOfA(): String = BackupFormat.seal(BackupContents.zip(schedule(tv), arcade(tv), prefsA, 1_000L, "0.127.0", 400, "household", "Den A", "server-a"),
|
||||
code, 1_000L, "0.127.0", 400, "household", iterations = 100_000)
|
||||
|
||||
@Before fun up() {
|
||||
tv = Files.createTempDirectory("orbit-backup-a").toFile(); other = Files.createTempDirectory("orbit-backup-b").toFile()
|
||||
household(tv, prefsA, "A"); household(other, prefsB, "B")
|
||||
}
|
||||
@After fun down() { tv.deleteRecursively(); other.deleteRecursively() }
|
||||
|
||||
/** Opens and unpacks [text] into [root]'s incoming folder, as the TV does once the code's typed. */
|
||||
private fun receive(text: String, root: File, typed: String = code): JSONObject {
|
||||
val (header, sealed) = BackupFormat.parse(text)
|
||||
val zip = BackupFormat.open(header, sealed, typed) ?: throw BackupFormat.Refused("wrong code")
|
||||
return BackupFormat.unpack(zip, File(root, "no_backup/phone-restore/incoming"))
|
||||
}
|
||||
|
||||
@Test fun aBackupOpensWithItsCodeAndHoldsTheHousehold() {
|
||||
val text = backupOfA()
|
||||
assertTrue(text.startsWith("ORBIT-BACKUP 1\n")); assertTrue(text.trimEnd().endsWith("END ORBIT-BACKUP"))
|
||||
val manifest = receive(text, other)
|
||||
val paths = manifest.getJSONArray("files").let { a -> (0 until a.length()).map { a.getJSONObject(it).getString("path") } }
|
||||
assertTrue(paths.containsAll(listOf("schedule/progress-101.json", "schedule/schedule-101.json", "schedule/yours.json", "schedule/continue-grown.json",
|
||||
"schedule/tickets-0.json", "schedule/taste/grown.events.jsonl", "arcade/household-records.json", "prefs/orbit_settings.json", "prefs/orbit_profiles.json", "prefs/orbit_rooms.json")))
|
||||
// Copies kept while saving, generated sounds and diagnostics stay behind.
|
||||
assertFalse(paths.any { it.endsWith(".prev") || it.endsWith(".wav") || it.endsWith("playback-notes.txt") })
|
||||
assertEquals("Den A", manifest.getString("room"))
|
||||
}
|
||||
|
||||
@Test fun noSecretEverGoesIn() {
|
||||
val text = backupOfA()
|
||||
val incoming = File(other, "no_backup/phone-restore/incoming"); receive(text, other)
|
||||
val everything = incoming.walkTopDown().filter { it.isFile }.joinToString("\n") { it.readText() }
|
||||
// No PIN, no phones, no sync keys, no sign-in, and none of this box's own switches.
|
||||
listOf("after_dark_pin", "hash-A", "phone-hash", "orbit_lock", "orbit_phones", "orbit_room_links", "surround_to_amplifier", "provider_catalogue", "player_avi", "joined")
|
||||
.forEach { assertFalse("$it travelled", everything.contains(it)) }
|
||||
// And the sealed file shows nothing readable at all.
|
||||
listOf("Den A", "Adult A", "Night-A", "Mysteries", "snake_best").forEach { assertFalse("$it readable in the file", text.contains(it)) }
|
||||
}
|
||||
|
||||
@Test fun aFileHoldingSomethingShapedLikeATokenIsLeftOut() {
|
||||
File(schedule(tv), "evidence-0.jsonl").writeText("{\"url\":\"http://x/Videos/1/stream?api_key=abc123\"}\n")
|
||||
val manifest = receive(backupOfA(), other)
|
||||
assertEquals(listOf("schedule/evidence-0.jsonl"), manifest.getJSONArray("leftOut").let { a -> (0 until a.length()).map { a.getString(it) } })
|
||||
assertFalse(File(other, "no_backup/phone-restore/incoming/schedule/evidence-0.jsonl").exists())
|
||||
}
|
||||
|
||||
@Test fun theWrongCodeOpensNothing() {
|
||||
val (header, sealed) = BackupFormat.parse(backupOfA())
|
||||
assertNull(BackupFormat.open(header, sealed, "K7QM2XTR9HFDW3PB"))
|
||||
assertNotNull(BackupFormat.open(header, sealed, code))
|
||||
}
|
||||
|
||||
@Test fun aFileCutShortIsCaughtBeforeTheCodeIsAsked() {
|
||||
val text = backupOfA()
|
||||
// Stopped part-way through the download: no end line, or the end line but bytes missing.
|
||||
val cut = text.substring(0, text.length / 2)
|
||||
assertTrue(runCatching { BackupFormat.parse(cut) }.exceptionOrNull()!!.message!!.contains("incomplete"))
|
||||
val lines = text.trimEnd('\n').split('\n')
|
||||
val missing = (lines.take(3) + lines.subList(3, lines.size - 1).dropLast(3) + lines.last()).joinToString("\n")
|
||||
assertTrue(runCatching { BackupFormat.parse(missing) }.exceptionOrNull()!!.message!!.contains("missing"))
|
||||
}
|
||||
|
||||
@Test fun aDamagedFileIsRefused() {
|
||||
val text = backupOfA(); val lines = text.trimEnd('\n').split('\n').toMutableList()
|
||||
// One character changed in the sealed part: caught by the checksum.
|
||||
val i = 5; lines[i] = lines[i].replaceRange(10, 11, if (lines[i][10] == 'A') "B" else "A")
|
||||
assertTrue(runCatching { BackupFormat.parse(lines.joinToString("\n")) }.exceptionOrNull()!!.message!!.contains("checksum"))
|
||||
// The header changed (an older format claimed, say) with the checksum left alone: the seal refuses it.
|
||||
val header = text.split('\n')[1]
|
||||
val forged = text.replace(header, header.replace("\"build\":400", "\"build\":300"))
|
||||
val (h, sealed) = BackupFormat.parse(forged)
|
||||
assertNull(BackupFormat.open(h, sealed, code))
|
||||
// Not a backup at all, and one from a newer Orbit.
|
||||
assertTrue(runCatching { BackupFormat.parse("hello") }.exceptionOrNull()!!.message!!.contains("isn't an Orbit backup"))
|
||||
assertTrue(runCatching { BackupFormat.parse(text.replaceFirst("ORBIT-BACKUP 1", "ORBIT-BACKUP 2")) }.exceptionOrNull()!!.message!!.contains("newer Orbit"))
|
||||
}
|
||||
|
||||
@Test fun aZipWithAnythingUnexpectedIsRefused() {
|
||||
fun zipOf(vararg entries: Pair<String, String>, manifest: JSONObject? = null): ByteArray = java.io.ByteArrayOutputStream().also { b ->
|
||||
java.util.zip.ZipOutputStream(b).use { z ->
|
||||
val listed = JSONArray(entries.map { (p, t) -> JSONObject().put("path", p).put("sha256", BackupFormat.sha256(t.toByteArray())) })
|
||||
z.putNextEntry(java.util.zip.ZipEntry("manifest.json")); z.write((manifest ?: JSONObject().put("format", 1).put("files", listed)).toString().toByteArray())
|
||||
entries.forEach { (p, t) -> z.putNextEntry(java.util.zip.ZipEntry(p)); z.write(t.toByteArray()) }
|
||||
} }.toByteArray()
|
||||
val into = File(other, "unpack")
|
||||
listOf("../escape.json", "schedule/../../escape.json", "prefs/orbit_lock.json", "no_backup/orbit-connection.v1", "/etc/x").forEach { bad ->
|
||||
assertTrue(bad, runCatching { BackupFormat.unpack(zipOf(bad to "{}"), into) }.exceptionOrNull() is BackupFormat.Refused)
|
||||
assertFalse(File(other, "escape.json").exists())
|
||||
}
|
||||
// A file changed after it was listed, and a file that isn't listed.
|
||||
val wrongSum = JSONObject().put("format", 1).put("files", JSONArray().put(JSONObject().put("path", "schedule/a.json").put("sha256", "0".repeat(64))))
|
||||
assertTrue(runCatching { BackupFormat.unpack(zipOf("schedule/a.json" to "{}", manifest = wrongSum), into) }.exceptionOrNull()!!.message!!.contains("checksum"))
|
||||
val unlisted = JSONObject().put("format", 1).put("files", JSONArray())
|
||||
assertTrue(runCatching { BackupFormat.unpack(zipOf("schedule/a.json" to "{}", manifest = unlisted), into) }.exceptionOrNull()!!.message!!.contains("don't match"))
|
||||
assertFalse(into.exists())
|
||||
}
|
||||
|
||||
@Test fun thePreviewSaysWhatIsInItAndWhatIsHere() {
|
||||
receive(backupOfA(), other)
|
||||
val r = restorer(other, prefsB)
|
||||
val theirs = BackupContents.summarise(File(r.incoming, "schedule"), File(r.incoming, "arcade"), r.prefsIn(r.incoming))
|
||||
assertEquals(listOf("Adult A"), theirs.profiles); assertEquals(1, theirs.channelsOn); assertEquals(listOf("A's Mysteries"), theirs.yourChannels)
|
||||
assertEquals(mapOf("Adult A" to 2), theirs.tasteEvents); assertEquals(1, theirs.continueEntries); assertEquals(1, theirs.tickets)
|
||||
assertEquals("Den A", theirs.room); assertEquals("user-A", theirs.user)
|
||||
val here = r.summariseHere()
|
||||
assertEquals(listOf("Adult B"), here.profiles); assertEquals("user-B", here.user)
|
||||
assertTrue(theirs.lines().any { it.startsWith("Profiles: Adult A") })
|
||||
}
|
||||
|
||||
@Test fun restoreReplacesTheHouseholdKeepsThisBoxAndCanBeUndone() {
|
||||
receive(backupOfA(), other)
|
||||
val r = restorer(other, prefsB)
|
||||
val before = schedule(other).walkTopDown().filter { it.isFile }.associate { it.relativeTo(schedule(other)).path to it.readText() }
|
||||
r.prepare(5_000L, 1_000L, "Pixel")
|
||||
// Nothing changes until Orbit starts again.
|
||||
assertEquals("{\"who\":\"B\"}", File(arcade(other), "household-records.json").readText())
|
||||
val done = r.finish(6_000L)!!
|
||||
assertTrue(done.optBoolean("ok"))
|
||||
assertTrue(File(schedule(other), "schedule-101.json").readText().contains("A's plan"))
|
||||
assertEquals("{\"who\":\"A\"}", File(arcade(other), "household-records.json").readText())
|
||||
assertEquals("Night-A", prefsB.files["orbit_settings"]!!["look"]); assertEquals("Den A", prefsB.files["orbit_rooms"]!!["name"])
|
||||
// This box's own: sound output and switches as they were here, and the PIN, phones and room history untouched.
|
||||
assertEquals(false, prefsB.files["orbit_settings"]!!["surround_to_amplifier"]); assertEquals(false, prefsB.files["orbit_settings"]!!["provider_catalogue"])
|
||||
assertEquals("hash-B", prefsB.files["orbit_lock"]!!["after_dark_pin"]); assertEquals("Pixel|1", prefsB.files["orbit_phones"]!!["phone-hash"])
|
||||
assertEquals("[]", prefsB.files["orbit_rooms"]!!["joined"])
|
||||
assertFalse(r.incoming.exists())
|
||||
// Undo puts back exactly what was here.
|
||||
assertEquals("restore", r.undoable()!!.getString("before"))
|
||||
r.prepareUndo(7_000L); assertTrue(r.finish(8_000L)!!.optBoolean("ok"))
|
||||
val after = schedule(other).walkTopDown().filter { it.isFile }.associate { it.relativeTo(schedule(other)).path to it.readText() }
|
||||
assertEquals(before, after)
|
||||
assertEquals("Night-B", prefsB.files["orbit_settings"]!!["look"]); assertEquals("{\"who\":\"B\"}", File(arcade(other), "household-records.json").readText())
|
||||
// And the undo can be undone, back to the backup's.
|
||||
assertEquals("undo", r.undoable()!!.getString("before"))
|
||||
}
|
||||
|
||||
@Test fun aRestoreStoppedPartWayFinishesOnTheNextStart() {
|
||||
// Stopped at every step in turn, as a power cut would, then started again: it always ends with the backup in place.
|
||||
val steps = listOf("copied schedule", "moved schedule", "schedule", "copied arcade", "moved arcade", "arcade", "prefs/orbit_settings", "prefs/orbit_profiles")
|
||||
steps.forEach { at ->
|
||||
down(); up()
|
||||
receive(backupOfA(), other)
|
||||
val r = restorer(other, prefsB); r.prepare(5_000L, 1_000L, "Pixel")
|
||||
r.step = { if (it == at) throw PowerCut() }
|
||||
assertTrue(runCatching { r.finish(6_000L) }.exceptionOrNull() is PowerCut)
|
||||
assertTrue(r.pending())
|
||||
val again = restorer(other, prefsB)
|
||||
assertTrue(at, again.finish(7_000L)!!.optBoolean("ok"))
|
||||
assertTrue(at, File(schedule(other), "schedule-101.json").readText().contains("A's plan"))
|
||||
assertEquals(at, "{\"who\":\"A\"}", File(arcade(other), "household-records.json").readText())
|
||||
assertEquals(at, "Night-A", prefsB.files["orbit_settings"]!!["look"])
|
||||
assertFalse(at, File(schedule(other).parentFile, "schedule.replaced").exists()); assertFalse(File(schedule(other).parentFile, "schedule.restoring").exists())
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun aRestoreThatKeepsFailingPutsTheOldDataBack() {
|
||||
receive(backupOfA(), other)
|
||||
val r = restorer(other, prefsB); r.prepare(5_000L, 1_000L, "Pixel")
|
||||
// Three starts that each stop part-way (a restore that crashes Orbit every time): the fourth puts things back.
|
||||
repeat(3) { val again = restorer(other, prefsB); again.step = { if (it == "arcade") throw PowerCut() }; runCatching { again.finish(6_000L + it) } }
|
||||
val outcome = restorer(other, prefsB).finish(9_000L)!!
|
||||
assertFalse(outcome.optBoolean("ok")); assertTrue(outcome.optBoolean("putBack"))
|
||||
assertTrue(File(schedule(other), "schedule-101.json").readText().contains("B's plan"))
|
||||
assertEquals("{\"who\":\"B\"}", File(arcade(other), "household-records.json").readText())
|
||||
assertEquals("Night-B", prefsB.files["orbit_settings"]!!["look"])
|
||||
assertFalse(r.pending())
|
||||
}
|
||||
|
||||
@Test fun aRestoreInterruptedBeforeItWasConfirmedChangesNothing() {
|
||||
receive(backupOfA(), other)
|
||||
// Keeping the data aside stopped part-way: a .part folder and no journal. The next start clears it and changes nothing.
|
||||
File(other, "no_backup/phone-restore/aside-5000.part/schedule").mkdirs()
|
||||
val r = restorer(other, prefsB)
|
||||
assertNull(r.finish(6_000L))
|
||||
assertFalse(File(other, "no_backup/phone-restore/aside-5000.part").exists())
|
||||
// The opened backup that was never confirmed doesn't stay on the TV either.
|
||||
assertFalse(r.incoming.exists())
|
||||
assertTrue(File(schedule(other), "schedule-101.json").readText().contains("B's plan"))
|
||||
assertNull(r.undoable())
|
||||
}
|
||||
|
||||
@Test fun onlyTheLastTwoCopiesAreKeptAside() {
|
||||
repeat(4) { i ->
|
||||
receive(backupOfA(), other)
|
||||
val r = restorer(other, prefsB); r.prepare(5_000L + i, 1_000L, "Pixel"); r.finish(6_000L + i)
|
||||
}
|
||||
assertEquals(listOf("aside-5002", "aside-5003"), File(other, "no_backup/phone-restore").list()!!.filter { it.startsWith("aside-") }.sorted())
|
||||
}
|
||||
|
||||
@Test fun theCodeShowsInFoursWithTheCursorInStep() {
|
||||
val t = CodeLook.filter(androidx.compose.ui.text.AnnotatedString("k7qm2xtr9h"))
|
||||
assertEquals("K7QM-2XTR-9H", t.text.text)
|
||||
for (o in 0..10) assertEquals(o, t.offsetMapping.transformedToOriginal(t.offsetMapping.originalToTransformed(o)))
|
||||
assertEquals(12, t.offsetMapping.originalToTransformed(10)); assertEquals(4, t.offsetMapping.originalToTransformed(4)); assertEquals(6, t.offsetMapping.originalToTransformed(5))
|
||||
assertEquals("K7QM2XTR9HFDW3PA", BackupCode.normalise(CodeLook.filter(androidx.compose.ui.text.AnnotatedString("k7qm2xtr9hfdw3pa")).text.text))
|
||||
}
|
||||
|
||||
@Test fun theBackupCodeReadsAndTypesWithoutMixUps() {
|
||||
val made = BackupCode.make(); assertEquals(16, made.length); assertEquals(made, BackupCode.normalise(BackupCode.shown(made).lowercase()))
|
||||
assertEquals("K7QM2XTR9HFDW3PA", BackupCode.normalise("k7qm-2xtr 9hfd-w3pa"))
|
||||
assertEquals("01100000000000000", BackupCode.normalise("OIL0-0000-0000-0000") + "0")
|
||||
assertNull(BackupCode.normalise("K7QM-2XTR-9HFD")); assertNull(BackupCode.normalise("K7QM-2XTR-9HFD-W3PU"))
|
||||
// One per TV, kept; a restored backup's code is adopted only by a TV without one.
|
||||
val nb = File(other, "nb").apply { mkdirs() }
|
||||
val (first, fresh) = BackupCode.ofThisTv(nb); assertTrue(fresh); assertEquals(first to false, BackupCode.ofThisTv(nb))
|
||||
BackupCode.adopt(nb, code); assertEquals(first, BackupCode.existing(nb))
|
||||
val nb2 = File(other, "nb2").apply { mkdirs() }; BackupCode.adopt(nb2, code); assertEquals(code, BackupCode.existing(nb2))
|
||||
}
|
||||
}
|
||||
@@ -91,6 +91,20 @@ class PhoneLinkTest {
|
||||
assertTrue(runCatching { call("/api/channels", cookie = cookie).body.contains("Enter the code") }.getOrDefault(true))
|
||||
}
|
||||
|
||||
@Test fun backupsAreOnlyForAJoinedPhoneAndOnlyItMaySendALargeFile() {
|
||||
// Not joined: the join page, whatever is asked, and a large upload is cut off at the usual size before it's read.
|
||||
assertTrue(call("/api/backup").body.contains("Enter the code"))
|
||||
assertTrue(call("/api/backup/upload", "POST", "x".repeat(200_000)).body.contains("Enter the code"))
|
||||
val p = PhoneLink.beginPairing()
|
||||
val cookie = call("/join", "POST", "code=${p.code}", form = true).cookie!!
|
||||
// Joined: a change still needs the header a cross-site page can't send; then the backup routes answer (here, with no
|
||||
// Android behind them, that Orbit is starting up).
|
||||
assertEquals(403, call("/api/backup/make", "POST", "{}", cookie = cookie, orbit = false).status)
|
||||
assertEquals(403, call("/api/backup/upload", "POST", "ORBIT-BACKUP 1", cookie = cookie, orbit = false).status)
|
||||
assertEquals(409, call("/api/backup", cookie = cookie).status)
|
||||
assertEquals(409, call("/api/backup/upload", "POST", "x".repeat(200_000), cookie = cookie).status)
|
||||
}
|
||||
|
||||
@Test fun guessingRunsOutAndThePinIsAskedWhenThereIsOne() {
|
||||
var now = System.currentTimeMillis(); PhoneLink.clock = { now }
|
||||
val p = PhoneLink.beginPairing()
|
||||
|
||||
Reference in New Issue
Block a user