diff --git a/tools/compare_snapshots.py b/tools/compare_snapshots.py new file mode 100755 index 00000000..cb9d3a57 --- /dev/null +++ b/tools/compare_snapshots.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Compares Orbit's install snapshots (before and after an install). Exit 0 = nothing the household owns changed. + +Checked: every file present before is still there; decisions, history, tickets, choices, learning, yours, profiles, +Taste events and Continue watching are byte-identical; every booking from before is still booked (new ones may be +added as Orbit plans ahead); every planned programme still in the window is unchanged. Counts only, no titles. +Usage: compare_snapshots.py +""" +import glob, hashlib, json, os, sys + +UNCHANGED = ("decisions", "history", "tickets", "choices", "learning", "yours", "orbit_profiles", "taste/", "continue") + + +def files(root): + return {os.path.relpath(p, root): p for p in glob.glob(root + "/**/*", recursive=True) if os.path.isfile(p)} + + +def digest(path): + return hashlib.sha256(open(path, "rb").read()).hexdigest() + + +def booked_ids(path): + o = json.load(open(path)) + if isinstance(o, dict): + out = [] + for v in o.values(): + if isinstance(v, list): + out += [json.dumps(x, sort_keys=True) for x in v] + return out + return [json.dumps(x, sort_keys=True) for x in o] if isinstance(o, list) else [] + + +def compare(before, after): + b, a = files(before), files(after) + problems, lines = [], [] + missing = [k for k in b if k not in a and not k.endswith((".bak", ".writing", ".tmp")) and "continue-" not in k] + if missing: + problems.append(f"missing after install: {len(missing)}") + for pat in UNCHANGED: + ks = [k for k in b if pat in k and not k.endswith((".bak", ".writing", ".tmp", ".before-catchup-only")) and k in a] + changed = [k for k in ks if digest(b[k]) != digest(a[k])] + lines.append(f"{pat.rstrip('/')}: {len(ks)} files, changed {len(changed)}") + if changed: + problems.append(f"{pat.rstrip('/')} changed: {len(changed)} files") + for k in [k for k in b if os.path.basename(k).startswith("booked-") and k.endswith(".json") and k in a]: + before_ids, after_ids = booked_ids(b[k]), set(booked_ids(a[k])) + lost = [x for x in before_ids if x not in after_ids] + lines.append(f"{os.path.basename(k)}: {len(before_ids)} bookings before, {len(after_ids)} after, {len(lost)} lost") + if lost: + problems.append(f"bookings lost: {len(lost)}") + total = changed = 0 + for bp in glob.glob(before + "/no_backup/schedule/schedule-*.json"): + ap = bp.replace(before, after, 1) + try: + eb, ea = json.load(open(bp)).get("entries", []), json.load(open(ap)).get("entries", []) + except Exception: + continue + if not eb or not ea: + continue + key = lambda e: e.get("a", e.get("startMs")) + lo, after_by = min(key(e) for e in ea), {key(e): e for e in ea} + for e in eb: + if key(e) >= lo: + total += 1 + changed += after_by.get(key(e)) != e + lines.append(f"planned programmes compared {total}, changed {changed}") + if changed: + problems.append(f"planned programmes changed: {changed}") + return lines, problems + + +if __name__ == "__main__": + lines, problems = compare(sys.argv[1], sys.argv[2]) + print("\n".join(lines)) + print("UNCHANGED" if not problems else "PROBLEMS: " + "; ".join(problems)) + sys.exit(0 if not problems else 1) diff --git a/tools/install-tv.sh b/tools/install-tv.sh new file mode 100755 index 00000000..18832d60 --- /dev/null +++ b/tools/install-tv.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# Orbit's install routine for one TV (9 November 2026), as run by hand since 6 November, in one command: +# tools/install-tv.sh [room] e.g. 192.168.0.252:5555 0.122.2-provider downstairs +# 1. Refuses if Orbit is playing something (pass FORCE=1 to override) or the APK's checksum is wrong. +# 2. Keeps a rollback copy of the installed APK, and checks it against apks/ when that version is there. +# 3. Takes the before snapshot, sets the schedules aside on the TV, installs, compiles for speed and reopens Orbit. +# 4. Checks one copy of Orbit is running, takes the after snapshot and compares (tools/compare_snapshots.py). +# 5. Keeps the last three backups for this room. Exit 0 only when everything checked out. +# Restore, if ever needed: tools/restore-tv.sh /before +set -uo pipefail +A=${ADB:-/opt/android-sdk/platform-tools/adb}; D=$1; NEW=$2; ROOM=${3:-downstairs} +OT=${ORBIT_HOME:-/home/pauljd/Documents/OrbitTV}; APKS=$OT/apks; TOOLS="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +PFX=$([ "$ROOM" = downstairs ] && echo "" || echo "$ROOM-") +R="$A -s $D shell am broadcast -f 0x20 -n tv.orbit.classic/.InstallSnapshotReceiver -a tv.orbit.classic.INSTALL_SNAPSHOT" +( cd "$APKS" && sha256sum -c "orbit-tv-$NEW.apk.sha256" >/dev/null ) || { echo "Checksum of orbit-tv-$NEW.apk failed or missing; nothing installed."; exit 1; } +PLAYING=$($A -s $D shell "dumpsys audio | grep -E 'AudioPlaybackConfiguration.*state:started' | grep -c \$(dumpsys package tv.orbit.classic | grep -m1 -o 'userId=[0-9]*' | cut -d= -f2)" | tr -d '\r') +[ "${PLAYING:-0}" != "0" ] && [ "${FORCE:-0}" != "1" ] && { echo "Orbit is playing on $ROOM; not interrupting. FORCE=1 to install anyway."; exit 2; } +PREV=$($A -s $D shell dumpsys package tv.orbit.classic | grep -m1 versionName | sed 's/.*versionName=//' | tr -d '\r ') +B=$OT/backups/${PFX}install-$NEW-$(date +%Y%m%d-%H%M); mkdir -p "$B"; echo "room $ROOM, installed $PREV, backup $B" +P=$($A -s $D shell pm path tv.orbit.classic | sed -n 's/package://p' | head -1 | tr -d '\r'); $A -s $D pull "$P" "$B/rollback-$PREV.apk" >/dev/null || { echo "Couldn't keep a rollback copy; nothing installed."; exit 1; } +if [ -f "$APKS/orbit-tv-$PREV.apk.sha256" ]; then + [ "$(sha256sum "$B/rollback-$PREV.apk" | cut -d' ' -f1)" = "$(cut -d' ' -f1 "$APKS/orbit-tv-$PREV.apk.sha256")" ] && echo "rollback copy verified" || { echo "Rollback copy doesn't match apks/; nothing installed."; exit 1; } +fi +snap() { for i in 1 2 3; do r=$($R --es do snapshot | grep -o 'data="[^"]*"'); echo "$1 snapshot $r"; echo "$r" | grep -q failed || break; sleep 3; done + $A -s $D pull /sdcard/Android/data/tv.orbit.classic/files/install-snapshot "$B/$1" >/dev/null && $R --es do clear >/dev/null; } +snap before +$R --es do rollback --es version "$(echo "$PREV" | grep -oE '^[0-9]+\.[0-9]+\.[0-9]+')" | grep -o 'data="[^"]*"' +$A -s $D install -r "$APKS/orbit-tv-$NEW.apk" | tail -1 || exit 1 +$A -s $D shell cmd package compile -m speed -f tv.orbit.classic >/dev/null +$A -s $D shell am start -n tv.orbit.classic/.MainActivity >/dev/null +sleep 25 +NOW=$($A -s $D shell dumpsys package tv.orbit.classic | grep -m1 versionName | sed 's/.*versionName=//' | tr -d '\r ') +COPIES=$($A -s $D shell "dumpsys activity activities | grep -c 'Hist.*tv.orbit.classic/.MainActivity'" | tr -d '\r') +echo "now $NOW, copies of Orbit running: $COPIES" +snap after +python3 "$TOOLS/compare_snapshots.py" "$B/before" "$B/after"; RESULT=$? +ls -d "$OT/backups/${PFX}install-"* 2>/dev/null | sort | head -n -3 | xargs -r rm -rf +[ "$NOW" = "$NEW" ] && [ "$COPIES" = "1" ] && [ $RESULT -eq 0 ] && { echo "Install checked out."; exit 0; } +echo "Install needs a look (version $NOW, copies $COPIES, comparison exit $RESULT)."; exit 3 diff --git a/tools/test_compare_snapshots.py b/tools/test_compare_snapshots.py new file mode 100644 index 00000000..64cecf1a --- /dev/null +++ b/tools/test_compare_snapshots.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Offline tests for compare_snapshots.py (9 November 2026), with made-up snapshots. Run: python3 tools/test_compare_snapshots.py""" +import json, os, shutil, sys, tempfile, unittest +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from compare_snapshots import compare + + +def write(root, rel, obj): + p = os.path.join(root, rel); os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "w") as f: + f.write(obj if isinstance(obj, str) else json.dumps(obj)) + + +def snapshot(root, bookings=("a", "b"), schedule=((100, "x"), (200, "y"), (300, "z")), history="h1"): + write(root, "shared_prefs/orbit_profiles.xml", "") + write(root, "files/history-1.json", history) + write(root, "files/taste/events.json", "[]") + write(root, "files/booked-1.json", {"bookings": [{"id": b} for b in bookings]}) + write(root, "no_backup/schedule/schedule-101.json", {"entries": [{"a": a, "t": t} for a, t in schedule]}) + + +class CompareSnapshotsTest(unittest.TestCase): + def setUp(self): + self.dir = tempfile.mkdtemp(); self.b = os.path.join(self.dir, "before"); self.a = os.path.join(self.dir, "after") + snapshot(self.b) + + def tearDown(self): + shutil.rmtree(self.dir) + + def test_identical_is_unchanged(self): + snapshot(self.a); self.assertEqual([], compare(self.b, self.a)[1]) + + def test_new_bookings_and_planning_ahead_are_fine(self): + snapshot(self.a, bookings=("a", "b", "c"), schedule=((200, "y"), (300, "z"), (400, "w"))) + self.assertEqual([], compare(self.b, self.a)[1]) + + def test_lost_booking_is_a_problem(self): + snapshot(self.a, bookings=("a",)); self.assertIn("bookings lost: 1", compare(self.b, self.a)[1]) + + def test_changed_programme_is_a_problem(self): + snapshot(self.a, schedule=((100, "x"), (200, "CHANGED"), (300, "z"))) + self.assertIn("planned programmes changed: 1", compare(self.b, self.a)[1]) + + def test_changed_history_is_a_problem(self): + snapshot(self.a, history="h2"); self.assertIn("history changed: 1 files", compare(self.b, self.a)[1]) + + def test_missing_file_is_a_problem(self): + snapshot(self.a); os.remove(os.path.join(self.a, "files/taste/events.json")) + self.assertIn("missing after install: 1", compare(self.b, self.a)[1]) + + def test_temporary_files_are_ignored(self): + write(self.b, "files/history-1.json.writing", "partial"); snapshot(self.a) + self.assertEqual([], compare(self.b, self.a)[1]) + + +if __name__ == "__main__": + unittest.main(verbosity=1) diff --git a/tools/verify.sh b/tools/verify.sh index 3ecc7a50..23b74a4e 100755 --- a/tools/verify.sh +++ b/tools/verify.sh @@ -9,6 +9,7 @@ TOOLING="${ORBIT_TOOLING:-$ROOT/../orbit-tv/.tooling}" OFFLINE=() if [ -d "$TOOLING/gradle-cache" ]; then export GRADLE_USER_HOME="$TOOLING/gradle-cache" ANDROID_USER_HOME="$TOOLING/android"; OFFLINE=(--offline); fi export ANDROID_HOME="${ANDROID_HOME:-/opt/android-sdk}" +python3 "$ROOT/tools/test_compare_snapshots.py" 2>&1 | tail -1 # the install checker is tested too cd "$ROOT/android" ./gradlew --no-daemon "${OFFLINE[@]}" -q :app:assembleRelease :app:testDebugUnitTest --rerun :app:lintRelease python3 - <<'PY'