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: add match.py, a per-package tally across examples/ lists
Mohamed Emada5c2cef6a2aa
diff --git a/README.md b/README.mdindex f044521bf..d1147513d 100644--- a/README.md+++ b/README.md@@ -199,6 +199,7 @@ tools/theme.sh themes/aurora # push a theme; --r| [`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/match.py`](tools/match.py) | Reads a saved `pm list packages` and prints, for each package, how many lists in `examples/` disable it, how many keep it commented out, and their most common note; Android's core packages show as `never`. Offline, changes nothing (`tools/venv/bin/python -I tools/match.py packages.txt`). || [`tools/adb-closed.py`](tools/adb-closed.py) | Checks that the TV's network ADB port is closed once debugging is off: exits 0 when the TV refuses the connection, 1 while it is still open, 2 when nothing answered or the check itself could not run. No `nc` needed. || [`tools/philips-api.py`](tools/philips-api.py) | Philips only: checks that the JointSpace control API Home Assistant uses still answers, before and after a debloat (`tools/venv/bin/python -I tools/philips-api.py <tv ip>`). Port 1926 over HTTPS first, then 1925; reads only what answers without pairing. || [`tools/privacy.py`](tools/privacy.py) | Audits the TV for voice, ACR and telemetry candidates and prints the evidence for each; `--write` turns the findings into a list `disable.sh` and `restore.sh` already understand. |diff --git a/tests/test_match.py b/tests/test_match.pynew file mode 100644index 000000000..620106b90--- /dev/null+++ b/tests/test_match.py@@ -0,0 +1,233 @@+"""tools/match.py reads a saved `pm list packages` and counts how the tested lists treat each package.++It reads files only: a package file and a folder of */debloat.txt lists. For each package it prints how+many lists disable it, how many name it commented out, and the note those lines give it most often; a+package disable.sh refuses as one of Android's core packages (#884) is printed as `never`. A packages+file or examples folder that cannot be used ends the run at 2 with one line, no traceback.++Run from the repository root: python3 -m unittest discover -s tests -v+"""+import io+from contextlib import redirect_stderr, redirect_stdout+from pathlib import Path+import subprocess+import sys+import tempfile+import unittest++ROOT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(ROOT / "tools"))+import match # noqa: E402++MATCH = ROOT / "tools" / "match.py"+++class MatchCase(unittest.TestCase):+ def setUp(self):+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ self.base = Path(tmp.name)+ self.examples = self.base / "examples"+ self.examples.mkdir()++ def write(self, name, text, encoding="utf-8"):+ path = self.base / name+ path.write_text(text, encoding=encoding)+ return path++ def add_list(self, folder, text):+ path = self.examples / folder / "debloat.txt"+ path.parent.mkdir(parents=True)+ path.write_text(text, encoding="utf-8")+ return path+++class ReadPackagesTest(MatchCase):+ def test_package_lines_are_read_sorted_without_repeats(self):+ path = self.write("p.txt", "package:com.b.two\npackage:com.a.one\npackage:com.b.two\n")+ self.assertEqual(["com.a.one", "com.b.two"], match.read_packages(path))++ def test_the_f_form_takes_the_name_after_the_last_equals(self):+ path = self.write("p.txt", "package:/system/app/Foo/base=1.apk=com.example.foo\n"+ "package:/data/app/x/base.apk=com.example.bar\n")+ self.assertEqual(["com.example.bar", "com.example.foo"], match.read_packages(path))++ def test_bare_names_and_crlf_and_bom_are_taken(self):+ path = self.base / "p.txt"+ path.write_bytes(b"\xef\xbb\xbfcom.example.first\r\n com.example.second \r\n")+ self.assertEqual(["com.example.first", "com.example.second"], match.read_packages(path))++ def test_lines_that_are_not_package_names_are_skipped(self):+ path = self.write("p.txt", "error: device offline\n\npackage:com.example.ok\nnot_a_package\n"+ "rm -rf /\npackage:bad;name.x\n")+ self.assertEqual(["com.example.ok"], match.read_packages(path))++ def test_a_file_with_no_names_stops(self):+ path = self.write("p.txt", "error: no devices/emulators found\n")+ with self.assertRaises(SystemExit) as caught:+ match.read_packages(path)+ self.assertIn("no package names", str(caught.exception.code))++ def test_a_missing_file_stops_naming_the_path(self):+ path = self.base / "gone.txt"+ with self.assertRaises(SystemExit) as caught:+ match.read_packages(path)+ self.assertIn(str(path), str(caught.exception.code))+ self.assertIn("could not read", str(caught.exception.code))+++class ReadListTest(unittest.TestCase):+ def test_disabled_lines_carry_their_note(self):+ disabled, commented = match.read_list("com.example.ads # ads\ncom.example.music\n")+ self.assertEqual({"com.example.ads": "ads", "com.example.music": ""}, disabled)+ self.assertEqual({}, commented)++ def test_a_commented_out_package_counts_as_kept(self):+ disabled, commented = match.read_list("# com.example.store # needed for updates\n#com.example.x\n")+ self.assertEqual({}, disabled)+ self.assertEqual({"com.example.store": "needed for updates", "com.example.x": ""}, commented)++ def test_a_header_sentence_starting_with_a_package_name_is_not_counted(self):+ disabled, commented = match.read_list("# com.example.store is kept because it updates apps\n")+ self.assertEqual(({}, {}), (disabled, commented))++ def test_plain_comments_and_blank_lines_are_ignored(self):+ self.assertEqual(({}, {}), match.read_list("# My TV\n\n#\n# tested on firmware 1.2\n"))++ def test_a_package_both_disabled_and_commented_counts_as_disabled(self):+ disabled, commented = match.read_list("# com.example.ads # maybe\ncom.example.ads # off\n")+ self.assertEqual({"com.example.ads": "off"}, disabled)+ self.assertEqual({}, commented)++ def test_the_first_note_for_a_repeated_name_is_kept(self):+ disabled, _ = match.read_list("com.example.ads # first\ncom.example.ads # second\n")+ self.assertEqual({"com.example.ads": "first"}, disabled)+++class TallyTest(MatchCase):+ def test_counts_over_every_list(self):+ self.add_list("a", "com.example.ads # ads\n# com.example.store\n")+ self.add_list("b", "com.example.ads # ads\ncom.example.store # store\n")+ self.add_list("c", "com.example.ads # telemetry\n# com.example.store # updates\n")+ counts, read = match.tally(["com.example.ads", "com.example.store", "com.example.other"],+ self.examples)+ self.assertEqual(3, read)+ self.assertEqual((3, 0, "ads"), counts["com.example.ads"])+ self.assertEqual(1, counts["com.example.store"][0])+ self.assertEqual(2, counts["com.example.store"][1])+ self.assertEqual((0, 0, ""), counts["com.example.other"])++ def test_packages_the_tv_lacks_are_not_reported(self):+ self.add_list("a", "com.example.ads\ncom.example.elsewhere\n")+ counts, _ = match.tally(["com.example.ads"], self.examples)+ self.assertEqual(["com.example.ads"], list(counts))++ def test_only_debloat_txt_one_folder_down_is_read(self):+ self.add_list("a", "com.example.ads\n")+ (self.examples / "a" / "debloat-extra.txt").write_text("com.example.ads\n")+ (self.examples / "debloat.txt").write_text("com.example.ads\n")+ counts, read = match.tally(["com.example.ads"], self.examples)+ self.assertEqual(1, read)+ self.assertEqual((1, 0, ""), counts["com.example.ads"])++ def test_a_folder_without_lists_stops(self):+ with self.assertRaises(SystemExit) as caught:+ match.tally(["com.example.ads"], self.examples)+ self.assertIn("no */debloat.txt", str(caught.exception.code))+++class MainTest(MatchCase):+ def run_main(self, *args):+ out, err = io.StringIO(), io.StringIO()+ with redirect_stdout(out), redirect_stderr(err):+ code = match.main(list(args))+ return code, out.getvalue(), err.getvalue()++ def test_the_table_lists_every_package_with_its_counts(self):+ self.add_list("a", "com.example.ads # ads\n# com.example.store # updates\n")+ self.add_list("b", "com.example.ads # ads\n")+ packages = self.write("p.txt", "package:com.example.store\npackage:com.example.ads\n"+ "package:com.example.none\n")+ code, out, err = self.run_main(str(packages), "--examples", str(self.examples))+ self.assertEqual(0, code, err)+ lines = out.splitlines()+ self.assertEqual(["package", "disabled", "commented", "note"], lines[0].split())+ rows = {line.split()[0]: line.split() for line in lines[1:]}+ self.assertEqual(["com.example.ads", "2", "0", "ads"], rows["com.example.ads"])+ self.assertEqual(["com.example.none", "0", "0"], rows["com.example.none"])+ self.assertEqual(["com.example.store", "0", "1", "updates"], rows["com.example.store"])+ self.assertEqual(["com.example.ads", "com.example.none", "com.example.store"],+ [line.split()[0] for line in lines[1:]])+ self.assertTrue(all(line == line.rstrip() for line in lines))+ self.assertIn("3 packages, counted over 2 lists", err)++ def test_core_packages_show_as_never_whatever_a_list_says(self):+ self.add_list("a", "com.android.packageinstaller # bad idea\ncom.example.ads\n")+ packages = self.write("p.txt", "package:com.android.packageinstaller\npackage:com.example.ads\n"+ "package:com.android.providers.calendar\n")+ code, out, err = self.run_main(str(packages), "--examples", str(self.examples))+ self.assertEqual(0, code, err)+ rows = {line.split()[0]: line.split()[1:] for line in out.splitlines()[1:]}+ self.assertEqual(["never"], rows["com.android.packageinstaller"])+ self.assertEqual(["1", "0"], rows["com.example.ads"])+ self.assertEqual(["0", "0"], rows["com.android.providers.calendar"])++ def test_columns_line_up_with_the_longest_name(self):+ self.add_list("a", "com.example.a\n")+ packages = self.write("p.txt", "package:com.example.a\npackage:com.example.much.longer.name\n")+ code, out, _ = self.run_main(str(packages), "--examples", str(self.examples))+ self.assertEqual(0, code)+ width = len("com.example.much.longer.name")+ for line in out.splitlines():+ self.assertEqual(" ", line[width:width + 2], line)+ self.assertTrue(out.splitlines()[-1].startswith("com.example.much.longer.name "))++ def test_a_missing_packages_file_is_2(self):+ self.add_list("a", "com.example.ads\n")+ code, out, err = self.run_main(str(self.base / "gone.txt"), "--examples", str(self.examples))+ self.assertEqual(2, code)+ self.assertEqual("", out)+ self.assertIn("could not read", err)++ def test_an_examples_folder_without_lists_is_2(self):+ packages = self.write("p.txt", "package:com.example.ads\n")+ code, out, err = self.run_main(str(packages), "--examples", str(self.examples))+ self.assertEqual(2, code)+ self.assertEqual("", out)+ self.assertIn("no */debloat.txt", err)++ def test_the_default_examples_folder_is_this_checkout(self):+ self.assertEqual(ROOT / "examples", match.EXAMPLES)+++class CommandLineTest(MatchCase):+ def run_script(self, *args):+ return subprocess.run([sys.executable, "-I", str(MATCH), *args], capture_output=True,+ text=True, stdin=subprocess.DEVNULL, timeout=60)++ def test_runs_isolated_and_exits_0(self):+ self.add_list("a", "com.example.ads # ads\n")+ packages = self.write("p.txt", "package:com.example.ads\n")+ result = self.run_script(str(packages), "--examples", str(self.examples))+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertIn("com.example.ads", result.stdout)+ self.assertNotIn("Traceback", result.stderr)++ def test_an_unreadable_file_exits_2_without_a_traceback(self):+ result = self.run_script(str(self.base / "gone.txt"), "--examples", str(self.examples))+ self.assertEqual(2, result.returncode, result.stdout + result.stderr)+ self.assertNotIn("Traceback", result.stderr)+ self.assertEqual("", result.stdout)++ def test_the_checkouts_own_examples_are_read_by_default(self):+ packages = self.write("p.txt", "package:com.example.unlikely.to.exist\n")+ result = self.run_script(str(packages))+ self.assertEqual(0, result.returncode, result.stderr)+ self.assertIn(str(ROOT / "examples"), result.stderr)++ def test_the_readme_lists_the_tool(self):+ self.assertIn("[`tools/match.py`](tools/match.py)", (ROOT / "README.md").read_text(encoding="utf-8"))+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/match.py b/tools/match.pynew file mode 100644index 000000000..f0ce203f7--- /dev/null+++ b/tools/match.py@@ -0,0 +1,129 @@+#!/usr/bin/env python3+"""How the tested lists in examples/ treat each package a TV has, read offline.++ match.py <saved pm list packages> [--examples <folder>]++Save the TV's packages once (`tools/venv/bin/python -I tools/tv.py 'pm list packages' > packages.txt`),+then run this: for every package in that file it prints how many examples/*/debloat.txt disable it, how+many name it commented out (kept on), and the trailing comment those lines give it most often. A package+that disable.sh refuses as one of Android's core packages (#884) is marked `never`, whatever any list+says.++It reads files only: no TV, no ADB client, nothing written. It ranks nothing and suggests no list; the+counts are what the lists say, not a verdict for this TV.++Exit codes: 0 the table was printed, 2 the packages file or the examples folder could not be read.+"""+import argparse+from collections import Counter+import os+from pathlib import Path+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)++EXAMPLES = Path(__file__).resolve().parents[1] / "examples"+++def read_packages(path):+ """The package names in a saved `pm list packages` answer, sorted and without repeats.++ `package:<name>` lines are what pm prints; with -f the line is `package:<apk path>=<name>`. A bare+ name on its own line is taken too, so a hand-trimmed file works.+ """+ try:+ text = Path(path).read_text(encoding="utf-8-sig", errors="replace")+ except OSError as e:+ raise SystemExit(f"could not read {path} ({e.strerror or e}): pass a saved `pm list packages`")+ names = set()+ for line in text.splitlines():+ line = line.strip()+ if line.startswith("package:"):+ line = line[len("package:"):].rsplit("=", 1)[-1].strip()+ if recovery.PACKAGE_RE.fullmatch(line):+ names.add(line)+ if not names:+ raise SystemExit(f"{path}: no package names in it: pass a saved `pm list packages`")+ return sorted(names)+++def read_list(text):+ """({package: note} disabled, {package: note} commented out) for one debloat list.++ A disabled line is a package name, with an optional `# note`. A commented-out line is `#`, one+ package name and nothing else but an optional `# note`, so a header sentence that happens to start+ with a package name is not counted.+ """+ disabled, commented = {}, {}+ for line in text.splitlines():+ line = line.strip()+ target = disabled+ if line.startswith("#"):+ line = line[1:].strip()+ target = commented+ body, _, note = line.partition("#")+ words = body.split()+ if not words or not recovery.PACKAGE_RE.fullmatch(words[0]):+ continue+ if target is commented and len(words) != 1:+ continue+ target.setdefault(words[0], note.strip())+ for name in disabled:+ commented.pop(name, None)+ return disabled, commented+++def tally(packages, examples):+ """{package: (disabled, commented, most common note)} over every examples/*/debloat.txt."""+ lists = sorted(Path(examples).glob("*/debloat.txt"))+ if not lists:+ raise SystemExit(f"{examples}: no */debloat.txt lists in it")+ wanted = set(packages)+ disabled, commented = Counter(), Counter()+ notes = {name: Counter() for name in packages}+ for path in lists:+ off, kept = read_list(path.read_text(encoding="utf-8-sig", errors="replace"))+ for counter, entries in ((disabled, off), (commented, kept)):+ for name, note in entries.items():+ if name not in wanted:+ continue+ counter[name] += 1+ if note:+ notes[name][note] += 1+ result = {}+ for name in packages:+ common = notes[name].most_common(1)+ result[name] = (disabled[name], commented[name], common[0][0] if common else "")+ return result, len(lists)+++def main(argv=None):+ parser = argparse.ArgumentParser(+ description="For each package in a saved `pm list packages`, how many tested lists in examples/ "+ "disable it or keep it commented out. Reads files only.")+ parser.add_argument("packages", help="a saved `pm list packages` answer")+ parser.add_argument("--examples", default=str(EXAMPLES),+ help="the folder of tested lists (default: this checkout's examples/)")+ args = parser.parse_args(argv)+ try:+ packages = read_packages(args.packages)+ counts, read = tally(packages, args.examples)+ except SystemExit as e:+ sys.stderr.write(f"{e.code}\n")+ return 2+ never = set(recovery.core_packages(packages))+ width = max(len("package"), *(len(name) for name in packages))+ print(f"{'package':<{width}} disabled commented note")+ for name in packages:+ if name in never:+ print(f"{name:<{width}} never")+ continue+ off, kept, note = counts[name]+ print(f"{name:<{width}} {off:>8} {kept:>9} {note}".rstrip())+ sys.stderr.write(f"{len(packages)} packages, counted over {read} lists in {args.examples}\n")+ return 0+++if __name__ == "__main__":+ sys.exit(main())