Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.
Python adbadblockandroid-tvandroid-tv-launcherapple-tvbloatware-removalclaude-codedebloatfire-tvgoogle-tvlauncherprivacysmart-tvsony-braviatclvibe-codingxiaomi
tools: check.py, what a firmware update undid compared with the list
xbshenga3ec3ccfdbb7
diff --git a/README.md b/README.mdindex 6226ebc37..a8b6b7f81 100644--- a/README.md+++ b/README.md@@ -265,6 +265,7 @@ tools/venv/bin/python -I tools/tv.py --probe # model, Android vetools/venv/bin/python -I tools/tv.py 'pm list packages' # one shell command on the TVtools/disable.sh examples/xiaomi-mi-tv-4a/debloat.txt # apply a debloat listtools/restore.sh examples/xiaomi-mi-tv-4a/debloat.txt # undo it, stock launcher back+tools/venv/bin/python -I tools/check.py examples/xiaomi-mi-tv-4a/debloat.txt # what a firmware update undidTV_HOST=192.168.1.50 launcher/build-and-install.sh # build the launcher and make it Hometools/theme.sh themes/aurora # push a theme; --reset removes it```@@ -275,6 +276,7 @@ tools/theme.sh themes/aurora # push a theme; --r| [`tools/b64push.py`](tools/b64push.py) | Uploads large files such as APKs in base64 chunks and verifies the checksum. || [`tools/disable.sh`](tools/disable.sh), [`restore.sh`](tools/restore.sh) | Apply or undo a debloat list, the undo from the state recorded before the change. || [`tools/recovery.py`](tools/recovery.py) | Writes the record `disable.sh` needs to undo itself, and prints the restore batch. |+| [`tools/check.py`](tools/check.py) | Compares the TV with the list that was applied, for what a firmware update undid; `--fix` puts it back. || [`tools/theme.sh`](tools/theme.sh) | Push a folder from [`themes/`](themes/) to the launcher and restart Home. || [`tools/race_calendar.py`](tools/race_calendar.py) | Writes this season's F1 calendar into a theme for race-weekend mode, from the free Jolpica API. || [`launcher/build-and-install.sh`](launcher/build-and-install.sh) | Builds a shrunk release (about 405 KB), installs it, switches Home, and rolls back if Home does not land on it. |@@ -353,6 +355,35 @@ install script again; it works out which launcher to disable even when Home hasAndroid's chooser. If the TV is unreachable, its ownSettings → Apps page can re-enable packages too.+## After a firmware update++An update installs over the cleaned-up system: the listed packages come back, Home goes to the+stock launcher, and new preloads appear that no list mentions. Nothing else here notices, so+compare the TV with the list you applied:++```bash+TV_HOST=192.168.1.50 tools/venv/bin/python -I tools/check.py examples/<your tv>/debloat.txt+```++It prints what drifted and exits 1 when anything did, so a weekly job on a home server or a Pi is+enough to hear about it:++```bash+0 9 * * 1 cd ~/cleanyourtv && TV_HOST=192.168.1.50 tools/venv/bin/python -I tools/check.py examples/<your tv>/debloat.txt+```++`--fix` reapplies the list to what drifted: it switches Home to the launcher the list does not+disable (pass a package as the second argument if you run a fork), then disables the listed packages+that came back, and reads the TV back to confirm both. It writes no recovery record, because the+record already holds the state from before the first run: `tools/restore.sh` still returns the TV to+stock afterwards. Home is fixed first; if no launcher is left to take it, `--fix` changes nothing+and says so.++Lists that also disable the updater get no updates at all. To install one, re-enable the updater on+the TV, let it update, run `check.py --fix`, and disable the updater again.++On Windows the same command is `tools\venv\Scripts\python.exe -I tools\check.py <list>`.+## When something goes wrongThe full list of things that bit us is in [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md). Thediff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex b23592a85..d0b09710b 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -204,6 +204,13 @@ Things that bit us or contributors, so they don't bite you. Commands use `tools/package that also claims HOME (PatchWall on Xiaomi) makes Android drop the default. The installscript now picks the known stock launcher among the candidates by itself; otherwise choose one onthe TV or pass `STOCK_LAUNCHER=<package>`.+- **A firmware update quietly undoes the cleanup.** The update installs over the cleaned-up system, so+ every listed package is enabled again, Home goes back to the stock launcher and new preloads+ appear that no list mentions. `tools/venv/bin/python -I tools/check.py <list>` reports the first+ two and exits 1; `--fix` disables them again and puts the launcher back on Home. New preloads it+ cannot know about, so after a big update compare `tools/tv.py 'pm list packages'` with the list+ once by hand. On a TV whose list disables the updater, this only happens when you install an+ update on purpose: enable the updater, update, `check.py --fix`, disable it again.## Accessibility helper enabled but the remote button does nothingdiff --git a/tests/test_drift_check.py b/tests/test_drift_check.pynew file mode 100644index 000000000..3c760e5f5--- /dev/null+++ b/tests/test_drift_check.py@@ -0,0 +1,253 @@+"""tools/check.py against a simulated TV (#359).++The property worth testing is the one no TV shows on demand: what the drift report says after a+firmware update, and that --fix puts back only what drifted, without touching the recovery record+undo depends on. tools/tv.py is replaced by a fake that answers the queries from a JSON file, so the+real check.py logic runs and only the ADB transport is simulated.++Run from the repository root: python3 -m unittest discover -s tests -v+"""+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+import tempfile+import unittest+++ROOT = Path(__file__).resolve().parents[1]+STOCK = "com.google.android.tvlauncher"+CUSTOM = "com.gathin.tvhome"++# Stands in for tools/tv.py: answers the queries check.py makes, and applies what --fix sends.+FAKE_TV = r'''+import json+import os+import sys++STATE_PATH = os.environ["FAKE_TV_STATE"]+++def load():+ with open(STATE_PATH) as f:+ return json.load(f)+++state = load()+++def save():+ with open(STATE_PATH, "w") as f:+ json.dump(state, f)+++def answer(command):+ if command == "pm list packages":+ return "".join(f"package:{name}\n" for name in state["installed"])+ if command == "pm list packages -d":+ return "".join(f"package:{name}\n" for name in state["disabled"])+ if "resolve-activity" in command:+ return (state["home"] or "") + "\n"+ if "query-activities" in command:+ return "".join(f" {component}\n" for component in state["home_activities"])+ return ""+++def apply(command):+ state["commands"].append(command)+ if command.startswith("pm disable-user --user 0 "):+ name = command.split()[-1]+ # A firmware that pins a package ignores the command, like some OEM builds do.+ if name not in state["disabled"] and name not in state.get("pinned", []):+ state["disabled"].append(name)+ elif command.startswith("cmd package set-home-activity --user 0 "):+ state["home"] = command.split()[-1]+ save()+++class Device:+ def shell(self, command, read_timeout_s=None):+ # The TV runs what it is sent and answers the queries; the fake does the same.+ if command.startswith(("pm disable-user", "pm enable", "cmd package set-home-activity")):+ apply(command)+ return ""+ return answer(command)++ def close(self):+ pass+++def connect():+ if state.get("unreachable"):+ raise ConnectionError("could not connect to 192.168.1.50:5555")+ return Device()+++def main():+ args = sys.argv[1:]+ if "--batch" in args:+ for line in sys.stdin:+ line = line.strip()+ if line and not line.startswith("#"):+ apply(line)+ return 0+++if __name__ == "__main__":+ sys.exit(main())+'''+++class DriftCheckTest(unittest.TestCase):+ def setUp(self):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ self.base = Path(tmp.name)+ self.repo = self.base / "repo"+ tools = self.repo / "tools"+ tools.mkdir(parents=True)+ for name in ("check.py", "recovery.py"):+ shutil.copy2(ROOT / "tools" / name, tools / name)+ (tools / "tv.py").write_text(FAKE_TV)++ self.home = self.base / "home"+ self.home.mkdir()+ self.state_path = self.base / "tv-state.json"+ self.list_path = self.base / "debloat.txt"+ self.write_list(["com.example.music", "com.example.store", STOCK])++ def write_list(self, names):+ self.list_path.write_text("# My TV\n" + "".join(f"{name}\n" for name in names))++ def tv(self, **overrides):+ state = {+ "installed": ["com.example.music", "com.example.store", STOCK, CUSTOM],+ "disabled": ["com.example.music", "com.example.store", STOCK],+ "home": f"{CUSTOM}/.MainActivity",+ "home_activities": [f"{CUSTOM}/.MainActivity", f"{STOCK}/.MainActivity"],+ "pinned": [],+ "commands": [],+ "unreachable": False,+ }+ state.update(overrides)+ self.state_path.write_text(json.dumps(state))++ def run_check(self, *args):+ env = dict(os.environ, TV_HOST="192.168.1.50", HOME=str(self.home),+ FAKE_TV_STATE=str(self.state_path))+ return subprocess.run(+ [sys.executable, str(self.repo / "tools" / "check.py"), *args],+ cwd=self.repo, env=env, capture_output=True, text=True, timeout=120,+ )++ def sent(self):+ with open(self.state_path) as f:+ return json.load(f)["commands"]++ def test_clean_tv_reports_nothing(self):+ self.tv()+ result = self.run_check(str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("nothing drifted", result.stdout)+ self.assertNotIn("back on", result.stdout)+ self.assertEqual(self.sent(), [])++ def test_package_turned_back_on_is_drift(self):+ self.tv(disabled=[STOCK])+ result = self.run_check(str(self.list_path))+ self.assertEqual(result.returncode, 1)+ self.assertIn("back on (2): com.example.music, com.example.store", result.stdout)+ self.assertIn("drift", result.stdout)+ # A report-only run changes nothing on the TV.+ self.assertEqual(self.sent(), [])++ def test_missing_package_is_not_drift(self):+ # A firmware update can drop an app for good; there is nothing to disable afterwards.+ self.tv(installed=["com.example.store", STOCK, CUSTOM], disabled=["com.example.store", STOCK])+ result = self.run_check(str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("not installed any more (1): com.example.music", result.stdout)++ def test_home_back_on_the_stock_launcher_is_drift(self):+ self.tv(home=f"{STOCK}/.MainActivity")+ result = self.run_check(str(self.list_path))+ self.assertEqual(result.returncode, 1)+ self.assertIn(f"Home is {STOCK}/.MainActivity, which this list disables", result.stdout)++ def test_fix_disables_what_came_back(self):+ self.tv(disabled=[STOCK])+ result = self.run_check("--fix", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("disabled 2 package(s)", result.stdout)+ self.assertEqual(self.sent(), ["pm disable-user --user 0 com.example.music",+ "pm disable-user --user 0 com.example.store"])+ # The next run is clean: --fix left the TV in the state the list describes.+ again = self.run_check(str(self.list_path))+ self.assertEqual(again.returncode, 0, again.stdout + again.stderr)++ def test_fix_reports_a_package_the_firmware_pins(self):+ self.tv(disabled=[STOCK], pinned=["com.example.store"])+ result = self.run_check("--fix", str(self.list_path))+ self.assertEqual(result.returncode, 1)+ self.assertIn("still enabled after --fix: com.example.store", result.stdout)++ def test_fix_puts_the_new_launcher_back_on_home(self):+ self.tv(home=f"{STOCK}/.MainActivity")+ result = self.run_check("--fix", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn(f"Home: set to {CUSTOM}/.MainActivity", result.stdout)+ self.assertEqual(self.sent(), [f"cmd package set-home-activity --user 0 {CUSTOM}/.MainActivity"])++ def test_fix_without_a_launcher_to_switch_to_says_so(self):+ # Nothing but launchers the list disables answers HOME: switching Home would leave the TV+ # without one, so --fix refuses instead of disabling the stock launcher first.+ self.tv(installed=["com.example.music", "com.example.store", STOCK],+ disabled=["com.example.music", "com.example.store"],+ home=f"{STOCK}/.MainActivity",+ home_activities=[f"{STOCK}/.MainActivity"])+ result = self.run_check("--fix", str(self.list_path))+ self.assertEqual(result.returncode, 1)+ self.assertIn("launcher/build-and-install.sh", result.stdout)+ self.assertNotIn("cmd package set-home-activity", " ".join(self.sent()))++ def test_fix_takes_the_launcher_it_is_given(self):+ self.tv(home=f"{STOCK}/.MainActivity", installed=COMMON_LAUNCHERS,+ disabled=["com.example.music", "com.example.store"],+ home_activities=[f"{STOCK}/.MainActivity", f"{CUSTOM}/.MainActivity",+ f"{FORK}/.MainActivity"])+ result = self.run_check("--fix", str(self.list_path), FORK)+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertIn(f"Home: set to {FORK}/.MainActivity", result.stdout)++ def test_fix_leaves_the_recovery_record_alone(self):+ # Undo still means undo: --fix re-disables packages the record already describes, so it must+ # not write a record of its own that would make restore.sh enable everything afterwards.+ self.tv(disabled=[STOCK])+ self.assertEqual(self.run_check("--fix", str(self.list_path)).returncode, 0)+ records = list((self.home / ".cleanyourtv").glob("*.json")) \+ if (self.home / ".cleanyourtv").exists() else []+ self.assertEqual(records, [])++ def test_unreachable_tv_is_not_drift(self):+ self.tv(unreachable=True)+ result = self.run_check(str(self.list_path))+ self.assertEqual(result.returncode, 2)+ self.assertIn("could not reach the TV", result.stderr)++ def test_a_hand_edited_list_stops_before_the_tv(self):+ self.write_list(["com.example.music", "com.example.store; reboot"])+ self.tv(disabled=[STOCK])+ result = self.run_check("--fix", str(self.list_path))+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("not a package name", result.stderr)+ self.assertEqual(self.sent(), [])+++FORK = "com.example.forklauncher"+COMMON_LAUNCHERS = ["com.example.music", "com.example.store", STOCK, CUSTOM, FORK]+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/check.py b/tools/check.pynew file mode 100644index 000000000..a05fa2fd7--- /dev/null+++ b/tools/check.py@@ -0,0 +1,167 @@+#!/usr/bin/env python3+"""What a firmware update undid, compared with the list that was applied (#359).++ check.py <debloat list> report the drift; exit 1 when there is any+ check.py --fix <debloat list> [launcher] re-disable the listed packages that came back and put+ the launcher back on Home++A firmware update re-enables listed packages, hands Home back to the stock launcher and adds new+preloads, and nothing in this repo notices: nobody runs disable.sh again, and restore.sh would undo+the cleanup instead of redoing it. This command compares the TV with the list and exits 1 when the+TV drifted, so it fits a cron job; --fix applies the list again without touching the recovery+record (the packages were already recorded before the first run, so undo still means undo).++It reads the list, not the record: the record holds what the TV looked like *before* cleanup, which+is what restore needs, while the target here is the list itself.++Exit codes: 0 in sync (or fixed), 1 drift (or a fix that did not take), 2 the TV could not be read.+"""+import os+import sys++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import recovery # noqa: E402 (needs the tools/ directory on the path first)++# Same three special cases as disable.sh: these answer HOME but they are not launchers, so Home+# landing on one of them is the crash loop the Home guard exists to prevent, not a working Home.+NOT_LAUNCHERS = {"com.google.android.tungsten.setupwraith", "com.android.tv.settings",+ "com.android.settings", "com.android.provision"}+HOME_QUERY = ("cmd package resolve-activity --brief -a android.intent.action.MAIN "+ "-c android.intent.category.HOME")+CLAIMS_QUERY = ("cmd package query-activities --brief -a android.intent.action.MAIN "+ "-c android.intent.category.HOME")+++def home_of(component):+ return component.split("/", 1)[0] if component else None+++def home_activities(dev):+ """Every HOME activity the TV can start, as package/activity, in the TV's order."""+ found = []+ for line in recovery.shell(dev, CLAIMS_QUERY).splitlines():+ candidate = line.strip()+ if recovery.HOME_RE.fullmatch(candidate):+ found.append(candidate)+ return found+++def launcher_to_use(dev, listed, preferred=None):+ """The HOME activity --fix should switch to: asked for, or the only launcher the list keeps.++ After a firmware update both the stock launcher and the new one answer HOME. Every candidate+ that the list disables is a launcher this run is about to take Home away from, so what is left+ is the one the owner installed.+ """+ if preferred:+ if not recovery.PACKAGE_RE.fullmatch(preferred):+ raise SystemExit(f"not a package name: {preferred!r}")+ match = [c for c in home_activities(dev) if home_of(c) == preferred]+ if not match:+ raise SystemExit(f"{preferred} has no HOME activity on this TV: is the launcher "+ f"installed? (launcher/build-and-install.sh)")+ return match[0]+ candidates = [c for c in home_activities(dev)+ if home_of(c) not in listed and home_of(c) not in NOT_LAUNCHERS]+ if not candidates:+ return None+ own = [c for c in candidates if home_of(c) == recovery.CUSTOM_LAUNCHER]+ return own[0] if own else candidates[0]+++def inspect(dev, listed):+ installed, disabled = recovery.query_packages(dev)+ home = recovery.query_home(dev)+ back_on = [name for name in listed if name in installed and name not in disabled]+ gone = [name for name in listed if name not in installed]+ home_drifted = home is None or home_of(home) in set(listed)+ return installed, disabled, home, back_on, gone, home_drifted+++def report(list_path, listed, home, back_on, gone, home_drifted):+ print(f"checking {list_path} ({len(listed)} packages) on {os.environ.get('TV_HOST', '?')}")+ if back_on:+ print(f" back on ({len(back_on)}): {', '.join(back_on)}")+ if home_drifted:+ print(f" Home is {home or 'nothing (no component answers HOME)'}"+ + (", which this list disables" if home else ""))+ if gone:+ # Not drift: the update may have removed an app for good, and there is nothing to disable.+ print(f" not installed any more ({len(gone)}): {', '.join(gone)}")+ drift = len(back_on) + (1 if home_drifted else 0)+ if not drift:+ print(f"nothing drifted: {len(listed) - len(gone)} listed packages are still disabled and "+ f"Home is {home}")+ return 0+ print(f"drift: {drift} of {len(listed)}; re-apply the list with --fix, or run "+ f"tools/disable.sh and the install script by hand")+ return 1+++def fix(dev, listed, back_on, home_drifted, preferred):+ failed = False+ # Home first: on Google TV a disabled stock launcher with nothing to replace it is the crash+ # loop the Home guard exists to prevent, so a Home that cannot be fixed stops the run before+ # anything is disabled.+ if home_drifted:+ target = launcher_to_use(dev, listed, preferred)+ if not target:+ print("Home: nothing to switch to: the launcher is not installed, or nothing but the "+ "packages this list disables answers HOME. Run launcher/build-and-install.sh, "+ "then check again; nothing was changed on the TV.")+ return 1+ recovery.shell(dev, f"cmd package set-home-activity --user 0 {target}")+ home = recovery.query_home(dev)+ if home != target:+ print(f"Home: asked for {target} but the TV still resolves {home or 'nothing'}; "+ f"reboot it and check again")+ failed = True+ else:+ print(f"Home: set to {target}")+ if back_on:+ for name in back_on:+ recovery.shell(dev, f"pm disable-user --user 0 {name}")+ # Read the TV back instead of trusting the command's silence: a package the firmware pins+ # stays enabled and the run has to say so.+ _, disabled = recovery.query_packages(dev)+ still_on = [name for name in back_on if name not in disabled]+ if still_on:+ failed = True+ print(f"still enabled after --fix: {', '.join(still_on)} (the firmware may pin them; "+ f"re-run the list by hand after the next reboot)")+ else:+ print(f"disabled {len(back_on)} package(s) the update had turned back on")+ return 1 if failed else 0+++def main():+ args = sys.argv[1:]+ wanted = "--fix" in args+ args = [a for a in args if a != "--fix"]+ if not 1 <= len(args) <= 2:+ sys.stderr.write("usage: check.py [--fix] <debloat list> [launcher package]\n")+ return 2+ list_path = args[0]+ preferred = args[1] if len(args) == 2 else None+ # read_list validates every name before anything is sent to the TV: its entries end up in the+ # TV's shell, and a list edited by hand since then is not to be trusted.+ listed = recovery.read_list(list_path)++ try:+ dev = recovery.connect()+ except (OSError, ConnectionError) as e:+ sys.stderr.write(f"could not reach the TV ({e}). Check it is on and TV_HOST is right "+ f"(tools/venv/bin/python -I tools/tv.py --probe).\n")+ return 2+ try:+ installed, disabled, home, back_on, gone, home_drifted = inspect(dev, listed)+ code = report(list_path, listed, home, back_on, gone, home_drifted)+ if code and wanted:+ code = fix(dev, listed, back_on, home_drifted, preferred)+ finally:+ dev.close()+ return code+++if __name__ == "__main__":+ sys.exit(main())