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: record the state a debloat list changes, so restore replays it (#239)
xbsheng0e87499cfa88
diff --git a/README.md b/README.mdindex f3701deb0..63ebb25c1 100644--- a/README.md+++ b/README.md@@ -213,7 +213,8 @@ tools/theme.sh themes/aurora # push a theme; --r|---|---|| [`tools/tv.py`](tools/tv.py) | Pure-Python ADB client: shell, batch, push, pull. Works where the stock `adb` binary is blocked. || [`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. |+| [`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/theme.sh`](tools/theme.sh) | Push a folder from [`themes/`](themes/) to the launcher and restart Home. || [`launcher/build-and-install.sh`](launcher/build-and-install.sh) | Builds a shrunk release (about 300 KB), installs it, switches Home, and rolls back if Home does not land on it. |@@ -257,14 +258,24 @@ the install script finds `~/Android/Sdk` and the `java` on your PATH.## Restoring your TV-Keep the list you applied. The restore script re-enables exactly those packages, puts the stock-launcher back as Home and resets the animation scales:+Before `tools/disable.sh` changes anything it writes down what the TV looked like: for every package+in the list whether it was enabled, already disabled or not installed, which component owned Home,+and the three animation scales. That record lives in `~/.cleanyourtv/`, one file per TV and list, and+a second run of the same list keeps the first record instead of saving the cleaned-up state over it.++Keep the list you applied. The restore script replays the record, so a package you had disabled+yourself stays disabled and Home goes back to the component that owned it:```bashTV_HOST=192.168.1.50 tools/restore.sh examples/<your tv>/debloat.txt # Android TVTV_HOST=192.168.1.50 tools/restore.sh examples/<your tv>/debloat.txt com.google.android.apps.tv.launcherx # Google TV```+The `stock launcher` argument is only a fallback: with a record, the launcher that actually owned Home+is the one that gets it back, and the argument is used only when nothing answered HOME at the time.+Without a record (an older run, or a record you deleted) the script says so and falls back to+enabling the whole list and resetting the scales to `1.0`, which is what it used to do.+It leaves the new launcher installed (remove it from the TV's Settings → Apps if you want it gone)and does not know about packages you disabled outside the list. To switch back later, run theinstall script again; it works out which launcher to disable even when Home has fallen back todiff --git a/tests/test_debloat_paths.py b/tests/test_debloat_paths.pyindex c466adcb5..c07859272 100644--- a/tests/test_debloat_paths.py+++ b/tests/test_debloat_paths.py@@ -6,6 +6,7 @@ import osfrom pathlib import Pathimport shutilimport subprocess+import sysimport tempfileimport unittest@@ -32,29 +33,56 @@ class DebloatPathsTest(unittest.TestCase):with self.subTest(script=script):self.check_windows_list(script)+ def prepare(self, repo, script):+ """Copy the script under test and stand in for tools/venv/bin/python.++ Both scripts ask tools/recovery.py first: disable.sh for the record of what it is about to+ change, restore.sh for the batch that replays it. Taking a record needs a TV, so the fake+ accepts --save as a no-op; building the batch from a record does not, so --commands goes to+ the real recovery.py and the test sees exactly what would be sent (#239).+ """+ tools = repo / "tools"+ tools.mkdir(parents=True)+ shutil.copy2(ROOT / "tools" / script, tools / script)+ client = tools / "venv" / "bin" / "python"+ client.parent.mkdir(parents=True)+ client.write_text(+ '#!/bin/sh\n'+ 'if [ "$1" = "-I" ] && [ "$2" = "tools/recovery.py" ]; then\n'+ ' [ "$3" = "--save" ] && exit 0\n'+ ' shift 2\n'+ f' exec "{sys.executable}" "{ROOT / "tools" / "recovery.py"}" "$@"\n'+ 'fi\n'+ 'cat > "$CAPTURE"\n'+ )+ client.chmod(0o755)+ home = repo.parent / "home"+ home.mkdir(exist_ok=True)+ return tools, home++ def run_script(self, script_path, argument, cwd, base, home):+ capture = base / "commands.txt"+ # No TV_HOST, so recovery.py looks for a record that cannot exist: that is the fallback these+ # tests exercise. HOME is isolated so a record from a real run cannot answer instead.+ env = {k: v for k, v in os.environ.items() if k != "TV_HOST"}+ env.update(CAPTURE=str(capture), HOME=str(home))+ result = subprocess.run(+ ["bash", str(script_path), argument], cwd=cwd, env=env,+ capture_output=True, text=True,+ )+ return result, capture+def check_windows_list(self, script):with tempfile.TemporaryDirectory() as tmp:base = Path(tmp)- tools = base / "repo" / "tools"- tools.mkdir(parents=True)- shutil.copy2(ROOT / "tools" / script, tools / script)- client = tools / "venv" / "bin" / "python"- client.parent.mkdir(parents=True)- client.write_text('#!/bin/sh\ncat > "$CAPTURE"\n')- client.chmod(0o755)-+ tools, home = self.prepare(base / "repo", script)package_list = base / "debloat.txt"package_list.write_bytes(b"\xef\xbb\xbf# My TV, saved in Notepad\r\n"b"com.example.one\r\n"b"com.example.two # a note\r\n")- capture = base / "commands.txt"- result = subprocess.run(- ["bash", str(tools / script), str(package_list)], cwd=base,- env=dict(os.environ, CAPTURE=str(capture)),- capture_output=True, text=True,- )+ result, capture = self.run_script(tools / script, str(package_list), base, base, home)self.assertEqual(result.returncode, 0, result.stderr)sent = capture.read_bytes()self.assertNotIn(b"\xef\xbb\xbf", sent, "BOM reached the TV")@@ -68,24 +96,12 @@ class DebloatPathsTest(unittest.TestCase):def check_injected_line(self, script):with tempfile.TemporaryDirectory() as tmp:base = Path(tmp)- tools = base / "repo" / "tools"- tools.mkdir(parents=True)- shutil.copy2(ROOT / "tools" / script, tools / script)- client = tools / "venv" / "bin" / "python"- client.parent.mkdir(parents=True)- client.write_text('#!/bin/sh\ncat > "$CAPTURE"\n')- client.chmod(0o755)-+ tools, home = self.prepare(base / "repo", script)package_list = base / "debloat.txt"package_list.write_text("# My TV\ncom.example.good\ncom.example.evil;settings put global adb_enabled 0\n")- capture = base / "commands.txt"- result = subprocess.run(- ["bash", str(tools / script), str(package_list)], cwd=base,- env=dict(os.environ, CAPTURE=str(capture)),- capture_output=True, text=True,- )+ result, capture = self.run_script(tools / script, str(package_list), base, base, home)self.assertNotEqual(result.returncode, 0, "the list should have been refused")self.assertIn("not a package name", result.stderr)sent = capture.read_text() if capture.exists() else ""@@ -96,13 +112,7 @@ class DebloatPathsTest(unittest.TestCase):with tempfile.TemporaryDirectory() as tmp:base = Path(tmp)repo = base / "repo checkout"- tools = repo / "tools"- tools.mkdir(parents=True)- shutil.copy2(ROOT / "tools" / script, tools / script)- client = tools / "venv" / "bin" / "python"- client.parent.mkdir(parents=True)- client.write_text('#!/bin/sh\ncat > "$CAPTURE"\n')- client.chmod(0o755)+ tools, home = self.prepare(repo, script)caller = base / "caller folder"caller.mkdir()@@ -117,12 +127,7 @@ class DebloatPathsTest(unittest.TestCase):decoy.parent.mkdir()decoy.write_text("com.example.wrong_tv\n")argument = str(package_list) if path_kind == "absolute" else str(relative)- capture = base / "commands.txt"- env = dict(os.environ, CAPTURE=str(capture))- result = subprocess.run(- ["bash", str(tools / script), argument], cwd=cwd, env=env,- capture_output=True, text=True,- )+ result, capture = self.run_script(tools / script, argument, cwd, base, home)self.assertEqual(result.returncode, 0, result.stderr)commands = capture.read_text().splitlines()operation = "pm disable-user --user 0" if script == "disable.sh" else "pm enable"diff --git a/tests/test_recovery_record.py b/tests/test_recovery_record.pynew file mode 100644index 000000000..fa268ae7e--- /dev/null+++ b/tests/test_recovery_record.py@@ -0,0 +1,274 @@+"""Run tools/recovery.py and the shell that calls it against a simulated TV (#239).++The property worth testing is the one no TV reproduces on demand: what undo does to a package the+owner had already disabled before cleanup, and whether the record survives a retry. tools/tv.py is+replaced by a fake that answers the queries from a JSON file, so the real recovery.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_HOME = "com.google.android.tvlauncher/.MainActivity"++# Stands in for tools/tv.py: answers the queries recovery.py makes, and records what a batch 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 command.startswith("settings get global "):+ key = command.split()[-1]+ return str(state["settings"].get(key, "null")) + "\n"+ return ""+++class Device:+ def shell(self, command, read_timeout_s=None):+ 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("#"):+ state["commands"].append(line)+ save()+ return 0+++if __name__ == "__main__":+ sys.exit(main())+'''+++class RecoveryRecordTest(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 ("disable.sh", "restore.sh", "recovery.py"):+ shutil.copy2(ROOT / "tools" / name, tools / name)+ (tools / "tv.py").write_text(FAKE_TV)+ # The scripts call tools/venv/bin/python; run the real interpreter, which imports the fake+ # tv.py for the transport and the real recovery.py for the logic.+ client = tools / "venv" / "bin" / "python"+ client.parent.mkdir(parents=True)+ client.write_text(f'#!/bin/sh\nexec "{sys.executable}" "$@"\n')+ client.chmod(0o755)++ 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.enabled", "com.example.already_off", "com.example.absent"])++ 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.enabled", "com.example.already_off",+ "com.google.android.tvlauncher"],+ "disabled": ["com.example.already_off"],+ "home": STOCK_HOME,+ "settings": {"window_animation_scale": "0.5",+ "transition_animation_scale": "null",+ "animator_duration_scale": "1.0"},+ "commands": [],+ "unreachable": False,+ }+ state.update(overrides)+ self.state_path.write_text(json.dumps(state))++ def run_script(self, script, *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(+ ["bash", str(self.repo / "tools" / script), *args],+ cwd=self.repo, env=env, capture_output=True, text=True, timeout=120,+ )++ def record(self):+ files = list((self.home / ".cleanyourtv").glob("recovery-*.json"))+ self.assertLessEqual(len(files), 1, "one record per TV and list")+ return json.loads(files[0].read_text()) if files else None++ def sent(self):+ with open(self.state_path) as f:+ return json.load(f)["commands"]++ def test_save_records_the_state_undo_needs(self):+ self.tv()+ result = self.run_script("disable.sh", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ record = self.record()+ self.assertIsNotNone(record)+ self.assertEqual(record["packages"], {+ "com.example.enabled": "enabled",+ "com.example.already_off": "disabled",+ "com.example.absent": "absent",+ # Home's package is recorded even though the list does not mention it: undo has to put it+ # back if the list disabled it.+ "com.google.android.tvlauncher": "enabled",+ })+ self.assertEqual(record["home"], STOCK_HOME)+ self.assertEqual(record["settings"]["window_animation_scale"], "0.5")+ # The list itself still reaches the TV, after the record is on disk.+ self.assertEqual(self.sent()[:3], [+ "pm disable-user --user 0 com.example.enabled",+ "pm disable-user --user 0 com.example.already_off",+ "pm disable-user --user 0 com.example.absent",+ ])++ def test_retry_keeps_the_original_record(self):+ self.tv()+ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)+ first = self.record()+ # A second run happens on a TV where the list has already been applied: enabled is now off.+ self.tv(installed=["com.example.already_off", "com.google.android.tvlauncher"],+ disabled=["com.example.enabled", "com.example.already_off"])+ result = self.run_script("disable.sh", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("keeping the recovery record", result.stdout)+ self.assertEqual(self.record()["packages"], first["packages"])++ def test_failed_save_disables_nothing(self):+ self.tv(unreachable=True)+ result = self.run_script("disable.sh", str(self.list_path))+ self.assertNotEqual(result.returncode, 0)+ self.assertEqual(self.sent(), [], "a failed record must not be followed by a mutation")+ self.assertIsNone(self.record())++ def test_corrupt_record_is_not_overwritten(self):+ self.tv()+ folder = self.home / ".cleanyourtv"+ # Take a record, then damage it the way an interrupted copy would.+ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)+ path = next(folder.glob("recovery-*.json"))+ path.write_text("{not json")+ with open(self.state_path) as f:+ state = json.load(f)+ state["commands"] = []+ self.state_path.write_text(json.dumps(state))++ result = self.run_script("disable.sh", str(self.list_path))+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("not a usable recovery record", result.stderr)+ self.assertEqual(path.read_text(), "{not json", "the original file is left for inspection")+ self.assertEqual(self.sent(), [], "nothing was disabled")++ def test_restore_replays_recorded_states(self):+ self.tv(settings={"window_animation_scale": "0.5",+ "transition_animation_scale": "null",+ "animator_duration_scale": "3.0"})+ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)+ with open(self.state_path) as f:+ state = json.load(f)+ state["commands"] = []+ self.state_path.write_text(json.dumps(state))++ result = self.run_script("restore.sh", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ sent = self.sent()+ self.assertIn("pm enable com.example.enabled", sent)+ self.assertNotIn("pm enable com.example.already_off",+ sent, "a package that was already disabled stays disabled")+ self.assertNotIn("pm enable com.example.absent", sent)+ # Home is the component that owned it, not a package name resolved on the fly.+ self.assertIn(f"cmd package set-home-activity --user 0 {STOCK_HOME}", sent)+ # Settings go back to the recorded values, including the one that was unset before.+ self.assertIn("settings put global window_animation_scale 0.5", sent)+ self.assertIn("settings delete global transition_animation_scale", sent)+ self.assertIn("settings put global animator_duration_scale 3.0", sent)+ self.assertEqual(sent[-1], "pm list packages -d")+ self.assertIn("leaving com.example.already_off alone", result.stderr)++ def test_restore_without_a_record_says_so_and_falls_back(self):+ self.tv()+ result = self.run_script("restore.sh", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ sent = self.sent()+ self.assertIn("no recovery record", result.stderr)+ self.assertEqual(sent[:3], [+ "pm enable com.example.enabled",+ "pm enable com.example.already_off",+ "pm enable com.example.absent",+ ])+ self.assertIn("pm enable com.google.android.tvlauncher", sent)+ self.assertIn("settings put global window_animation_scale 1.0", sent)++ def test_edited_list_leaves_new_names_alone(self):+ self.tv()+ self.assertEqual(self.run_script("disable.sh", str(self.list_path)).returncode, 0)+ self.write_list(["com.example.enabled", "com.example.added_later"])+ with open(self.state_path) as f:+ state = json.load(f)+ state["commands"] = []+ self.state_path.write_text(json.dumps(state))++ result = self.run_script("restore.sh", str(self.list_path))+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertNotIn("pm enable com.example.added_later", self.sent())+ self.assertIn("not in the record, leaving alone: com.example.added_later", result.stderr)++ def test_list_that_is_not_package_names_is_refused(self):+ self.tv()+ self.list_path.write_text("com.example.good\ncom.example.evil;settings put global adb_enabled 0\n")+ for script in ("disable.sh", "restore.sh"):+ with self.subTest(script=script):+ result = self.run_script(script, str(self.list_path))+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("not a package name", result.stderr)+ self.assertIn("com.example.evil;settings", result.stderr)+ self.assertEqual(self.sent(), [])+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/disable.ps1 b/tools/disable.ps1index 272e69d1e..f0fe345f6 100644--- a/tools/disable.ps1+++ b/tools/disable.ps1@@ -33,5 +33,10 @@ if ($pkgs -contains $setup -and -not $env:FORCE_SETUPWRAITH) {$pkgs = @($pkgs | Where-Object { $_ -ne $setup })}}+# Same as disable.sh: the state undo needs is recorded before the first command reaches the TV, and+# a failed save leaves the TV untouched (#239).+& $py -I (Join-Path $repo 'tools\recovery.py') --save $List+if ($LASTEXITCODE -ne 0) { throw 'no recovery record was written, so nothing was disabled' }+$cmds = @($pkgs | ForEach-Object { "pm disable-user --user 0 $_" }) + 'pm list packages -d'$cmds | & $py -I (Join-Path $repo 'tools\tv.py') --batchdiff --git a/tools/disable.sh b/tools/disable.shindex 673156d7c..d4c7ebcfc 100755--- a/tools/disable.sh+++ b/tools/disable.sh@@ -40,6 +40,11 @@ if printf '%s\n' "$PKGS" | grep -x "$SETUP" >/dev/null && [ -z "${FORCE_SETUPWRAfifi+# The state undo needs goes to disk before the first command reaches the TV, and a failed save stops+# here with the TV untouched: a record written afterwards would describe a TV that is already broken,+# and a retry must not overwrite the one taken before the first change (#239).+"$PY" -I tools/recovery.py --save "$LIST"+{[ -n "$PKGS" ] && printf '%s\n' "$PKGS" | sed 's/^/pm disable-user --user 0 /'echo "pm list packages -d"diff --git a/tools/recovery.py b/tools/recovery.pynew file mode 100644index 000000000..422c9ac61--- /dev/null+++ b/tools/recovery.py@@ -0,0 +1,252 @@+#!/usr/bin/env python3+"""The state a debloat list is about to change, so that undo means undo (#239).++ recovery.py --save <debloat list> read the TV and write the record+ recovery.py --commands <list> [stock launcher] print a batch for tools/tv.py --batch that puts+ the recorded states back++`tools/restore.sh` used to enable every package in the list, including ones the owner had already+disabled, and reset Home and the animation scales to fixed values instead of to what was there+before. Both scripts now go through this record: `disable.sh` writes it before the first command+reaches the TV, and `restore.sh` replays it.++Records live in ~/.cleanyourtv/, one per TV and list. The first one wins: a retry after a+half-applied list must not record the broken state as the original.+"""+import hashlib+import json+import os+from pathlib import Path+import re+import sys+import time++# Every name from the TV or from the list ends up inside a command run by the TV's shell, so nothing+# that could carry shell syntax is allowed through.+PACKAGE_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+")+HOME_RE = re.compile(r"[A-Za-z_][\w.]*/[\w.$]+")+SCALE_RE = re.compile(r"-?\d+(\.\d+)?")+SETTINGS = ("window_animation_scale", "transition_animation_scale", "animator_duration_scale")+VERSION = 1+++def read_list(path):+ """Package names from a debloat list, in file order.++ A BOM and CRLF from a Windows editor are dropped, as is a trailing `# note`; anything that is not+ a bare package name stops the run before the TV is touched.+ """+ text = Path(path).read_text(encoding="utf-8-sig", errors="replace")+ names = []+ for number, line in enumerate(text.splitlines(), 1):+ line = line.split("#", 1)[0].strip()+ if not line:+ continue+ name = line.split()[0]+ if not PACKAGE_RE.fullmatch(name):+ raise SystemExit(f"{path}:{number}: not a package name: {name!r}")+ names.append(name)+ if not names:+ raise SystemExit(f"{path}: no package names in this list")+ return names+++def record_path(list_path, host):+ """One record per TV and list. The list is identified by its absolute path, so a copy of the+ same file somewhere else gets its own record."""+ tag = re.sub(r"[^A-Za-z0-9.-]", "_", host or "no-host")+ digest = hashlib.sha1(str(Path(list_path).resolve()).encode()).hexdigest()[:8]+ return Path.home() / ".cleanyourtv" / f"recovery-{tag}-{digest}.json"+++def load_record(path):+ try:+ with open(path) as f:+ record = json.load(f)+ except (OSError, ValueError) as e:+ raise SystemExit(f"{path}: not a usable recovery record ({e}).\n"+ "It is left where it is: move it aside deliberately, a retry must not "+ "replace the state recorded before the first change.")+ if record.get("version") != VERSION or not isinstance(record.get("packages"), dict):+ raise SystemExit(f"{path}: unknown recovery record format; move it aside deliberately.")+ return record+++def write_record(path, record):+ # Written next to its final name first: a crash halfway through must not leave a truncated record+ # that then blocks every retry as "already recorded".+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_name(path.name + ".tmp")+ with open(tmp, "w") as f:+ json.dump(record, f, indent=2, sort_keys=True)+ f.write("\n")+ f.flush()+ os.fsync(f.fileno())+ os.replace(tmp, path)+++def shell(dev, command):+ return (dev.shell(command, read_timeout_s=120.0) or "").strip()+++def query_packages(dev):+ installed = {line.split(":", 1)[1].strip()+ for line in shell(dev, "pm list packages").splitlines()+ if line.startswith("package:")}+ if not installed:+ raise SystemExit("the TV returned no packages, so nothing was recorded and nothing will be "+ "disabled. Check the connection (tools/tv.py --probe) and try again.")+ disabled = {line.split(":", 1)[1].strip()+ for line in shell(dev, "pm list packages -d").splitlines()+ if line.startswith("package:")}+ return installed, disabled+++def query_home(dev):+ answer = shell(dev, "cmd package resolve-activity --brief -a android.intent.action.MAIN -c "+ "android.intent.category.HOME")+ candidate = answer.splitlines()[-1].strip() if answer else ""+ # Android answers "android" (the chooser) when nothing handles HOME; that is not a component and+ # must never be written into a set-home-activity command.+ return candidate if HOME_RE.fullmatch(candidate) else None+++def connect():+ # Imported here so --commands works on a machine where adb_shell is not installed: printing the+ # restore batch needs no TV. tv.py itself exits with a readable message when TV_HOST is unset.+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+ try:+ import tv+ except ImportError as e:+ raise SystemExit(f"cannot load tools/tv.py ({e}).\nrun: python3 -m venv tools/venv && "+ "tools/venv/bin/pip install -r tools/requirements.txt")+ return tv.connect()+++def save(list_path, host):+ path = record_path(list_path, host)+ if path.exists():+ record = load_record(path)+ print(f"keeping the recovery record from {record.get('created')}: {path}")+ print("nothing was recorded again: it holds the state from before the first run.")+ return 0++ packages = read_list(list_path)+ dev = connect()+ try:+ installed, disabled = query_packages(dev)+ home = query_home(dev)+ scales = {key: shell(dev, f"settings get global {key}") for key in SETTINGS}+ finally:+ dev.close()++ # The launcher that owns Home may not be in the list, but it is what undo has to put back.+ home_package = home.split("/", 1)[0] if home else None+ targets = packages + ([home_package] if home_package and home_package not in packages else [])+ record = {+ "version": VERSION,+ "created": time.strftime("%Y-%m-%dT%H:%M:%S%z"),+ "host": host,+ "list": str(Path(list_path).resolve()),+ "home": home,+ "settings": scales,+ "packages": {+ name: ("absent" if name not in installed+ else "disabled" if name in disabled+ else "enabled")+ for name in targets+ },+ }+ write_record(path, record)++ already = sum(1 for state in record["packages"].values() if state == "disabled")+ print(f"recorded {len(record['packages'])} packages on {host} "+ f"({already} already disabled, left alone by undo) -> {path}")+ print(f"HOME before: {home or 'no component answered'}")+ print("undo with tools/restore.sh <same list>; keep this file, it is the only copy.")+ return 0+++def restore_commands(list_path, stock, host):+ """The batch that puts the recorded states back, one command per line."""+ packages = read_list(list_path)+ if stock and not PACKAGE_RE.fullmatch(stock):+ raise SystemExit(f"not a package name: {stock!r}")+ path = record_path(list_path, host)+ commands = []++ if not path.exists():+ sys.stderr.write(+ f"no recovery record for this TV and list ({path}).\n"+ "Enabling every listed package and resetting Home and the animation scales to their\n"+ "defaults. Packages that were already disabled before cleanup will be enabled too:\n"+ "check the list before running this.\n")+ for name in packages:+ commands.append(f"pm enable {name}")+ if stock:+ commands.append(f"pm enable {stock}")+ commands.append(f"cmd package set-home-activity --user 0 $(cmd package resolve-activity "+ f"--brief -a android.intent.action.MAIN -c android.intent.category.HOME "+ f"{stock or 'com.google.android.tvlauncher'} | tail -n 1)")+ commands.extend(f"settings put global {key} 1.0" for key in SETTINGS)+ commands.append("pm list packages -d")+ return commands++ record = load_record(path)+ states = record["packages"]+ re_enable = [name for name, state in states.items() if state == "enabled"]+ for name in re_enable:+ commands.append(f"pm enable {name}")+ untouched = [(name, state) for name, state in states.items() if state != "enabled"]+ for name, state in untouched:+ sys.stderr.write(f" leaving {name} alone ({state} when the record was taken)\n")++ home = record.get("home")+ if home:+ commands.append(f"cmd package set-home-activity --user 0 {home}")+ else:+ # Nothing handled HOME before cleanup (fresh TV, chooser only), so there is no component to+ # replay; ask the TV to resolve the stock launcher the way restore.sh always did.+ fallback = stock or "com.google.android.tvlauncher"+ commands.append(f"cmd package set-home-activity --user 0 $(cmd package resolve-activity "+ f"--brief -a android.intent.action.MAIN -c android.intent.category.HOME "+ f"{fallback} | tail -n 1)")+ for key in SETTINGS:+ value = str(record.get("settings", {}).get(key, "")).strip()+ if value == "null":+ commands.append(f"settings delete global {key}")+ elif SCALE_RE.fullmatch(value):+ commands.append(f"settings put global {key} {value}")+ else:+ sys.stderr.write(f" skipping {key}: the record holds {value!r}, not a number\n")+ # The list is not in the record (it may have been edited since); packages added afterwards are+ # left as they are, which is what "leave the TV alone" means for them.+ edited = [name for name in packages if name not in states]+ if edited:+ sys.stderr.write(f"not in the record, leaving alone: {', '.join(edited)}\n")+ commands.append("pm list packages -d")++ sys.stderr.write(f"restoring the state recorded on {record.get('created')}: "+ f"re-enabling {len(re_enable)}, leaving {len(untouched)} as they were.\n")+ return commands+++def main():+ args = sys.argv[1:]+ host = os.environ.get("TV_HOST", "")+ if len(args) == 2 and args[0] == "--save":+ return save(args[1], host)+ if len(args) in (2, 3) and args[0] == "--commands":+ if not host:+ sys.stderr.write("Set TV_HOST to your TV's IP address, e.g. TV_HOST=192.168.1.50\n")+ stock = args[2] if len(args) == 3 else "com.google.android.tvlauncher"+ for command in restore_commands(args[1], stock, host):+ print(command)+ return 0+ sys.stderr.write("usage: recovery.py --save <debloat list>\n"+ " recovery.py --commands <debloat list> [stock launcher package]\n")+ return 2+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/restore.ps1 b/tools/restore.ps1index 9b363526f..4ec964f3d 100644--- a/tools/restore.ps1+++ b/tools/restore.ps1@@ -1,5 +1,7 @@-# Windows version of restore.sh: re-enable every package listed in a debloat file, restore the-# stock launcher as home and reset animation scales. Pass the same list you used with disable.ps1.+# Windows version of restore.sh: put the TV back the way it was before disable.ps1, from the state+# recorded at that time - packages that were already disabled stay disabled, Home goes back to the+# component that owned it and the animation scales go back to their recorded values. Pass the same+# list you used with disable.ps1.## Usage: tools\restore.ps1 -TvHost 192.168.1.50 examples\xiaomi-mi-tv-4a\debloat.txt [-Stock stock.launcher.package]param(@@ -16,19 +18,9 @@ $py = Join-Path $repo 'tools\venv\Scripts\python.exe'if (-not $TvHost) { throw 'pass -TvHost <tv ip> or set $env:TV_HOST' }$env:TV_HOST = $TvHost-$pkgs = Get-Content $List | ForEach-Object { ($_ -replace '#.*$', '').Trim() } | Where-Object { $_ } | ForEach-Object { ($_ -split '\s+')[0] }-# Same check as disable.ps1: the list is contributor-supplied (#165).-$bad = @($pkgs | Where-Object { $_ -notmatch '^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$' })-if ($bad.Count -gt 0) {- throw "refusing $List, not a package name: $($bad -join ', ')"-}-$cmds = @($pkgs | ForEach-Object { "pm enable $_" }) + @(- "pm enable $Stock",- # resolve the stock HOME component on the TV (Android 9 needs pkg/activity, not just pkg)- ('cmd package set-home-activity --user 0 $(cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME ' + $Stock + ' | tail -n 1)'),- 'settings put global window_animation_scale 1.0',- 'settings put global transition_animation_scale 1.0',- 'settings put global animator_duration_scale 1.0',- 'pm list packages -d'-)+# Same as restore.sh: replay the recorded states instead of enabling the whole list, so packages that+# were already disabled stay disabled (#239). recovery.py reads and validates the list itself, warns+# when no record exists and then falls back to the old behaviour.+$cmds = & $py -I (Join-Path $repo 'tools\recovery.py') --commands $List $Stock+if ($LASTEXITCODE -ne 0) { throw 'no restore plan was built, the TV was not changed' }$cmds | & $py -I (Join-Path $repo 'tools\tv.py') --batchdiff --git a/tools/restore.sh b/tools/restore.shindex b073d80d6..2c74d96d7 100755--- a/tools/restore.sh+++ b/tools/restore.sh@@ -1,6 +1,7 @@#!/usr/bin/env bash-# Re-enable every package listed in a debloat file, restore the stock launcher as home and reset-# animation scales. Pass the same list you used with tools/disable.sh.+# Put the TV back the way it was before tools/disable.sh, using the state recorded at that time:+# packages that were already disabled stay disabled, Home goes back to the component that owned it,+# and the animation scales go back to their recorded values. Pass the same list you ran disable with.## Usage: TV_HOST=192.168.1.50 tools/restore.sh examples/xiaomi-mi-tv-4a/debloat.txt [stock.launcher.package]set -euo pipefail@@ -13,22 +14,7 @@ STOCK="${2:-com.google.android.tvlauncher}"PY=tools/venv/bin/python[ -x "$PY" ] || PY=tools/venv/Scripts/python.exeexport MSYS_NO_PATHCONV=1-# Same check as disable.sh: the list is contributor-supplied and each entry becomes a shell-# command on the TV. A BOM and CRLF from a Windows editor are dropped first (#165, #208).-PKGS=$(LC_ALL=C awk 'NR==1{sub(/^\357\273\277/,"")} {sub(/\r$/,""); print}' "$LIST" \- | grep -vE '^\s*(#|$)' | sed -E 's/\s+#.*$//' | awk '{print $1}')-BAD=$(printf '%s\n' "$PKGS" | grep -vE '^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$' || true)-if [ -n "$BAD" ]; then- { echo "refusing $LIST: not a package name:"; printf '%s\n' "$BAD" | sed 's/^/ /'; } >&2- exit 1-fi-{- [ -n "$PKGS" ] && printf '%s\n' "$PKGS" | sed 's/^/pm enable /'- echo "pm enable $STOCK"- # resolve the stock HOME component on the TV (Android 9 needs pkg/activity, not just pkg)- echo "cmd package set-home-activity --user 0 \$(cmd package resolve-activity --brief -a android.intent.action.MAIN -c android.intent.category.HOME $STOCK | tail -n 1)"- echo "settings put global window_animation_scale 1.0"- echo "settings put global transition_animation_scale 1.0"- echo "settings put global animator_duration_scale 1.0"- echo "pm list packages -d"-} | "$PY" -I tools/tv.py --batch+# recovery.py reads and validates the list itself, prints the batch for tv.py and says on stderr what+# it will leave alone. Without a record it warns and falls back to enabling the whole list. pipefail+# keeps a refused plan from reaching the TV.+"$PY" -I tools/recovery.py --commands "$LIST" "$STOCK" | "$PY" -I tools/tv.py --batch