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
check.py: --fix runs disable.sh's safety checks, and Home counts as drift anywhere but our launcher
xbshengdb074b20a7ac
diff --git a/README.md b/README.mdindex a8b6b7f81..a5aa1ed5c 100644--- a/README.md+++ b/README.md@@ -379,6 +379,13 @@ record already holds the state from before the first run: `tools/restore.sh` stistock afterwards. Home is fixed first; if no launcher is left to take it, `--fix` changes nothingand says so.+It runs the same safety checks as `tools/disable.sh` before it disables anything, since an update is+the moment they matter again: it leaves setupwraith on while the saved Wi-Fi network belongs to it+(`FORCE_SETUPWRAITH=1` on Ethernet), leaves the packages under the HDMI/AV inputs on+(`TVINPUT_ALLOW=1` if you really want them off), and never takes Home to a vendor `FallbackHome`.+Each package it leaves on comes with the reason and exits 1, because the TV is not back to the list+until you deal with that one by hand.+Lists that also disable the updater get no updates at all. To install one, re-enable the updater onthe TV, let it update, run `check.py --fix`, and disable the updater again.diff --git a/tests/test_drift_check.py b/tests/test_drift_check.pyindex 3c760e5f5..9c9aa10c1 100644--- a/tests/test_drift_check.py+++ b/tests/test_drift_check.py@@ -48,6 +48,10 @@ def answer(command):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 command.startswith("dumpsys wifi"):+ return state.get("wifi", "")+ if command.startswith("dumpsys package "):+ return dumpsys_package(command.split()[-1])if "resolve-activity" in command:return (state["home"] or "") + "\n"if "query-activities" in command:@@ -55,6 +59,18 @@ def answer(command):return ""+def dumpsys_package(name):+ """What `dumpsys package <name>` prints, scoped to the permissions the package asks for."""+ requested = ["android.permission.INTERNET"]+ if name in state.get("input_drivers", []):+ requested.append("android.permission.TV_INPUT_HARDWARE")+ lines = [f"Packages:", f" Package [{name}]", " requested permissions:"]+ lines += [f" {permission}" for permission in requested]+ lines.append(" install permissions:")+ lines.append(" android.permission.INTERNET: granted=true")+ return "\n".join(lines) + "\n"++def apply(command):state["commands"].append(command)if command.startswith("pm disable-user --user 0 "):@@ -130,13 +146,17 @@ class DriftCheckTest(unittest.TestCase):"pinned": [],"commands": [],"unreachable": False,+ # Empty means the TV shows no saved network at all, which is what the safety checks treat+ # as "could not tell" - the same answer a set with Wi-Fi off gives.+ "wifi": "",+ "input_drivers": [],}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))+ def run_check(self, *args, env=None):+ env = dict(dict(os.environ, TV_HOST="192.168.1.50", HOME=str(self.home),+ FAKE_TV_STATE=str(self.state_path)), **(env or {}))return subprocess.run([sys.executable, str(self.repo / "tools" / "check.py"), *args],cwd=self.repo, env=env, capture_output=True, text=True, timeout=120,@@ -230,6 +250,125 @@ class DriftCheckTest(unittest.TestCase):if (self.home / ".cleanyourtv").exists() else []self.assertEqual(records, [])+ def test_home_on_a_stock_launcher_the_list_leaves_out_is_drift(self):+ # The case that prompted #359: build-and-install.sh disables the stock launcher, so no list+ # names it, and an update that turns it back on and takes Home matches no line of the list.+ self.write_list(["com.example.music", "com.example.store"])+ self.tv(disabled=["com.example.music", "com.example.store"], home=f"{STOCK}/.MainActivity")+ result = self.run_check(str(self.list_path))+ self.assertEqual(result.returncode, 1)+ self.assertIn(f"Home is {STOCK}/.MainActivity, not {CUSTOM}", result.stdout)++ def test_fix_takes_home_back_from_a_stock_launcher_the_list_leaves_out(self):+ self.write_list(["com.example.music", "com.example.store"])+ self.tv(disabled=["com.example.music", "com.example.store"], home=f"{STOCK}/.MainActivity")+ result = self.run_check("--fix", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertIn(f"Home: set to {CUSTOM}/.MainActivity", result.stdout)+ again = self.run_check(str(self.list_path))+ self.assertEqual(again.returncode, 0, again.stdout + again.stderr)++ def test_stock_home_without_our_launcher_is_not_drift(self):+ # Debloat only, no launcher installed: the stock launcher on Home is the intended state, and+ # --fix has nothing to switch Home to.+ self.write_list(["com.example.music", "com.example.store"])+ 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(str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)++ def test_home_on_another_launcher_than_the_one_given_is_drift(self):+ self.tv(installed=COMMON_LAUNCHERS, disabled=["com.example.music", "com.example.store", STOCK],+ home=f"{CUSTOM}/.MainActivity",+ home_activities=[f"{CUSTOM}/.MainActivity", f"{FORK}/.MainActivity"])+ result = self.run_check(str(self.list_path), FORK)+ self.assertEqual(result.returncode, 1)+ self.assertIn(f"not {FORK}", result.stdout)++ def test_fix_leaves_setupwraith_on_while_it_owns_the_wifi(self):+ # The update turned setupwraith back on, and disabling it again deletes the saved network and+ # takes the TV off Wi-Fi - the one mistake here a cron --fix could make on its own.+ self.write_list([SETUP, "com.example.music"])+ self.tv(installed=BASE + [SETUP], disabled=["com.example.music", "com.example.store", STOCK],+ wifi=f" cuid=10031 cname={SETUP}:10031 allowAutojoin=true")+ result = self.run_check("--fix", str(self.list_path))+ self.assertEqual(result.returncode, 1)+ self.assertIn(f"leaving {SETUP} on", result.stdout)+ self.assertIn("not fully back to the list", result.stdout)+ self.assertNotIn(f"pm disable-user --user 0 {SETUP}", self.sent())++ def test_fix_disables_setupwraith_when_the_system_owns_the_wifi(self):+ self.write_list([SETUP, "com.example.music"])+ self.tv(installed=BASE + [SETUP], disabled=["com.example.music", "com.example.store", STOCK],+ wifi=" cuid=1000 cname=android.uid.system:1000 allowAutojoin=true")+ result = self.run_check("--fix", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertIn(f"pm disable-user --user 0 {SETUP}", self.sent())++ def test_fix_leaves_setupwraith_on_when_the_wifi_cannot_be_read(self):+ self.write_list([SETUP])+ self.tv(installed=BASE + [SETUP], disabled=["com.example.store", STOCK], wifi="")+ result = self.run_check("--fix", str(self.list_path))+ self.assertEqual(result.returncode, 1)+ self.assertIn(f"leaving {SETUP} on", result.stdout)+ self.assertIn("FORCE_SETUPWRAITH=1", result.stdout)++ def test_fix_takes_the_forced_setupwraith(self):+ self.write_list([SETUP])+ self.tv(installed=BASE + [SETUP], disabled=["com.example.store", STOCK],+ wifi=f" cuid=10031 cname={SETUP}:10031 allowAutojoin=true")+ result = self.run_check("--fix", str(self.list_path), env={"FORCE_SETUPWRAITH": "1"})+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertIn(f"pm disable-user --user 0 {SETUP}", self.sent())++ def test_fix_leaves_an_hdmi_input_driver_on(self):+ # #321: disabling the package under the HDMI/AV inputs leaves every port black until a full+ # restore and a cold boot, so --fix has to keep the same guard disable.sh has.+ self.write_list([MEDIATEK_INPUT, "com.example.music"])+ self.tv(installed=BASE + [MEDIATEK_INPUT],+ disabled=["com.example.store", STOCK],+ input_drivers=[MEDIATEK_INPUT])+ result = self.run_check("--fix", str(self.list_path))+ self.assertEqual(result.returncode, 1)+ self.assertIn(f"leaving {MEDIATEK_INPUT} on", result.stdout)+ self.assertIn("TV_INPUT_HARDWARE", result.stdout)+ self.assertNotIn(f"pm disable-user --user 0 {MEDIATEK_INPUT}", self.sent())+ # The rest of the drift is still fixed.+ self.assertIn("pm disable-user --user 0 com.example.music", self.sent())++ def test_fix_takes_an_input_driver_with_TVINPUT_ALLOW(self):+ self.write_list([MEDIATEK_INPUT])+ self.tv(installed=BASE + [MEDIATEK_INPUT],+ disabled=["com.example.music", "com.example.store", STOCK],+ input_drivers=[MEDIATEK_INPUT])+ result = self.run_check("--fix", str(self.list_path), env={"TVINPUT_ALLOW": "1"})+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertIn(f"pm disable-user --user 0 {MEDIATEK_INPUT}", self.sent())++ def test_fix_prefers_the_launcher_over_a_vendor_fallback(self):+ # A FallbackHome is the placeholder a TCL set shows when no launcher is enabled; taking it+ # as Home would leave the TV in the placeholder (#435).+ self.write_list(["com.example.music", STOCK])+ self.tv(disabled=["com.example.music", "com.example.store"],+ home=f"{STOCK}/.MainActivity",+ home_activities=[f"{STOCK}/.MainActivity", FALLBACK, f"{CUSTOM}/.MainActivity"])+ result = self.run_check("--fix", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertIn(f"Home: set to {CUSTOM}/.MainActivity", result.stdout)+ self.assertNotIn(FALLBACK, " ".join(self.sent()))++ def test_fix_refuses_a_home_only_a_fallback_can_take(self):+ self.write_list(["com.example.music", STOCK])+ self.tv(installed=["com.example.music", "com.example.store", STOCK, "com.tcl.tv"],+ disabled=["com.example.music", "com.example.store"],+ home=f"{STOCK}/.MainActivity",+ home_activities=[f"{STOCK}/.MainActivity", FALLBACK])+ 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("set-home-activity", " ".join(self.sent()))+def test_unreachable_tv_is_not_drift(self):self.tv(unreachable=True)result = self.run_check(str(self.list_path))@@ -247,6 +386,14 @@ class DriftCheckTest(unittest.TestCase):FORK = "com.example.forklauncher"COMMON_LAUNCHERS = ["com.example.music", "com.example.store", STOCK, CUSTOM, FORK]+# The first-run wizard's app, which owns the Wi-Fi network a TV saved during setup.+SETUP = "com.google.android.tungsten.setupwraith"+# On MediaTek sets this is the package behind every HDMI, AV and tuner input.+MEDIATEK_INPUT = "com.mediatek.tvinput"+# The packages every fake TV here starts with, before a test adds the one it is about.+BASE = ["com.example.music", "com.example.store", STOCK, CUSTOM]+# What a TCL set shows when no launcher is enabled; not a home the viewer can use.+FALLBACK = "com.tcl.keycustomfunctionservice/.FallbackHome"if __name__ == "__main__":diff --git a/tools/check.py b/tools/check.pyindex a05fa2fd7..c2f54cb91 100644--- a/tools/check.py+++ b/tools/check.py@@ -1,9 +1,9 @@#!/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+ check.py <debloat list> [launcher package] report the drift; exit 1 when there is any+ check.py --fix <debloat list> [launcher package] re-disable what came back and put the launcher+ back on HomeA firmware update re-enables listed packages, hands Home back to the stock launcher and adds newpreloads, and nothing in this repo notices: nobody runs disable.sh again, and restore.sh would undo@@ -14,9 +14,16 @@ record (the packages were already recorded before the first run, so undo still mIt reads the list, not the record: the record holds what the TV looked like *before* cleanup, whichis 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.+--fix runs the same safety checks as disable.sh before it disables anything (the Wi-Fi network+setupwraith owns, the packages under the HDMI/AV inputs), because a firmware update is exactly the+moment those come back into play: the update can turn setupwraith back on for a TV whose network it+owns, and a fix that skipped the checks would take that TV off Wi-Fi with no way back in.++Exit codes: 0 in sync (or fixed), 1 drift, an incomplete fix, or packages a safety check left on,+2 the TV could not be read."""import os+import reimport syssys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))@@ -26,6 +33,18 @@ import recovery # noqa: E402 (needs the tools/ directory on the path first)# 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"}+# A vendor's own fallback is a placeholder the firmware shows when no launcher is enabled, not a home+# the viewer can use: TCL sets register com.tcl.keycustomfunctionservice/.FallbackHome (and+# com.android.tv.settings/.system.FallbackHome). disable.sh already refuses to count one as a+# launcher (#435); --fix must not move Home onto one either, or the next boot lands in the placeholder.+FALLBACK_HOME_RE = re.compile(r"/\S*FallbackHome$")+# The first-run wizard's app. Android deletes a Wi-Fi network saved by it the moment it is disabled.+SETUPWRAITH = "com.google.android.tungsten.setupwraith"+INPUT_PERMISSION = "android.permission.TV_INPUT_HARDWARE"+# Only the package's own "requested permissions" block counts: a vendor app in a shared UID would+# otherwise match through its shared user's permissions, the same reason disable.sh scopes its grep.+REQUESTED_RE = re.compile(r"requested permissions:(.*?)"+ r"(?:\n\s*(?:install|runtime) permissions:|\n\s*User \d+:|$)", re.S)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 "@@ -51,7 +70,7 @@ def launcher_to_use(dev, listed, preferred=None):After a firmware update both the stock launcher and the new one answer HOME. Every candidatethat 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.+ is the one the owner installed. A vendor FallbackHome answers HOME too and is not one of them."""if preferred:if not recovery.PACKAGE_RE.fullmatch(preferred):@@ -62,29 +81,50 @@ def launcher_to_use(dev, listed, preferred=None):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 home_of(c) not in listed and home_of(c) not in NOT_LAUNCHERS+ and not FALLBACK_HOME_RE.search(c)]if not candidates:return Noneown = [c for c in candidates if home_of(c) == recovery.CUSTOM_LAUNCHER]return own[0] if own else candidates[0]-def inspect(dev, listed):+def expected_launcher(installed, preferred=None):+ """The package Home should be on: the one asked for, else this repo's when it is installed.++ None when neither is installed: debloat without a launcher, where the stock launcher on Home is+ the intended state and only a Home on a listed package (or no Home at all) is drift.+ """+ wanted = preferred or recovery.CUSTOM_LAUNCHER+ return wanted if wanted in installed else None+++def inspect(dev, listed, preferred=None):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+ # Home on a package the list disables is drift, and so is Home anywhere but the launcher we+ # expect: build-and-install.sh disables the stock launcher instead of naming it in the list, so+ # an update that turns it back on and hands it Home matches no line of the list at all (#434).+ expected = expected_launcher(installed, preferred)+ home_drifted = (home is None or home_of(home) in set(listed)+ or (expected is not None and home_of(home) != expected))+ return installed, disabled, home, back_on, gone, home_drifted, expected-def report(list_path, listed, home, back_on, gone, home_drifted):+def report(list_path, listed, home, back_on, gone, home_drifted, expected=None):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 not home:+ why = ""+ elif home_of(home) in set(listed):+ why = ", which this list disables"+ else:+ why = f", not {expected}"+ print(f" Home is {home or 'nothing (no component answers HOME)'}{why}")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)}")@@ -98,6 +138,53 @@ def report(list_path, listed, home, back_on, gone, home_drifted):return 1+def setupwraith_owns_wifi(dev):+ """Whether the saved Wi-Fi networks belong to setupwraith; None when the TV could not say."""+ owners = re.findall(r"cname=(\S*)", recovery.shell(dev, "dumpsys wifi"))+ if not owners:+ return None+ return any("setupwraith" in owner for owner in owners)+++def asks_for_input_hardware(dev, name):+ """Whether the package itself asks for TV_INPUT_HARDWARE, i.e. it drives the HDMI/AV inputs."""+ block = REQUESTED_RE.search(recovery.shell(dev, f"dumpsys package {name}"))+ return bool(block and INPUT_PERMISSION in block.group(1))+++def safety_checks(dev, names):+ """The names disable.sh would leave enabled, each with the reason, as a list of (name, why).++ These are the checks disable.sh runs, in the same order, repeated here for the same reason they+ exist there: each one is a package an owner cannot put back from the couch. FORCE_SETUPWRAITH=1+ and TVINPUT_ALLOW=1 mean what they mean in disable.sh, so a TV on Ethernet or an owner who wants+ the inputs off does not have to remember two switches.+ """+ skipped = []+ if SETUPWRAITH in names and not os.environ.get("FORCE_SETUPWRAITH"):+ owns = setupwraith_owns_wifi(dev)+ if owns is not False:+ # Be safe when the TV could not say: a wrong guess here is the TV off the network.+ why = ("the saved Wi-Fi network belongs to it, so disabling it deletes that network and "+ "takes the TV off Wi-Fi: on the TV, forget the network and join it again in "+ "Settings > Network & Internet, then run --fix again (or set "+ "FORCE_SETUPWRAITH=1 if it uses Ethernet)" if owns else+ "could not read which app owns the saved Wi-Fi networks (dumpsys wifi failed or "+ "showed none); set FORCE_SETUPWRAITH=1 if the TV uses Ethernet")+ skipped.append((SETUPWRAITH, why))+ if not os.environ.get("TVINPUT_ALLOW"):+ for name in names:+ if any(name == skipped_name for skipped_name, _ in skipped):+ continue+ if asks_for_input_hardware(dev, name):+ skipped.append((name, "it asks for android.permission.TV_INPUT_HARDWARE, so it is "+ "the software layer under the HDMI/AV/tuner inputs: with it "+ "disabled those ports stay black and only a full restore and "+ "a cold boot bring them back (set TVINPUT_ALLOW=1 to disable "+ "it)"))+ return skipped++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@@ -118,20 +205,31 @@ def fix(dev, listed, back_on, home_drifted, preferred):failed = Trueelse:print(f"Home: set to {target}")+ left_on = []if back_on:- for name in back_on:+ left_on = safety_checks(dev, back_on)+ for name, why in left_on:+ print(f"leaving {name} on: {why}")+ todo = [name for name in back_on if name not in {n for n, _ in left_on}]+ for name in todo: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]+ still_on = [name for name in todo if name not in disabled]if still_on:failed = Trueprint(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+ elif todo:+ print(f"disabled {len(todo)} package(s) the update had turned back on")+ if left_on:+ # Not a failure of the fix, but not a clean run either: the list asks for something this+ # TV cannot give up safely, and the next check reports the same drift until the owner+ # clears the obstacle (the Wi-Fi network) or accepts it (TVINPUT_ALLOW=1).+ print(f"left {len(left_on)} package(s) on that this list disables; the TV is not fully "+ f"back to the list until they are dealt with")+ return 1 if failed or left_on else 0def main():@@ -154,8 +252,8 @@ def main():f"(tools/venv/bin/python -I tools/tv.py --probe).\n")return 2try:- installed, disabled, home, back_on, gone, home_drifted = inspect(dev, listed)- code = report(list_path, listed, home, back_on, gone, home_drifted)+ _, _, home, back_on, gone, home_drifted, expected = inspect(dev, listed, preferred)+ code = report(list_path, listed, home, back_on, gone, home_drifted, expected)if code and wanted:code = fix(dev, listed, back_on, home_drifted, preferred)finally: