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: philips-api.py, to check the JointSpace API that Home Assistant uses survives a debloat
Damian Wolgast548c759ce1c3
diff --git a/README.md b/README.mdindex bc331256f..a57673e9f 100644--- a/README.md+++ b/README.md@@ -197,6 +197,7 @@ tools/theme.sh themes/aurora # push a theme; --r| [`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/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. || [`tools/theme.sh`](tools/theme.sh), [`theme_restart.py`](tools/theme_restart.py) | Push a folder from [`themes/`](themes/) to the launcher and restart Home. || [`tools/manage.py`](tools/manage.py) | List every add-on, theme and switch with its screenshot, see what is on the TV, and install, update or remove one by running its creator's own script. |diff --git a/tests/test_philips_api.py b/tests/test_philips_api.pynew file mode 100644index 000000000..09d63f94c--- /dev/null+++ b/tests/test_philips_api.py@@ -0,0 +1,73 @@+"""tools/philips-api.py finds the JointSpace API on 1926 before 1925, and says which package to check.++On a 77OLED806/12 (Android TV 11) port 1925 is open and answers nothing, while+https://<tv>:1926/6/system answers without pairing. The tool must report the API from 1926, count a 401+on the other endpoints as present (they wait for pairing), and exit 1 naming org.droidtv.xtv when+neither port answers. No TV and no network: the HTTP calls are replaced with a fake.++Run from the repository root: python3 -m unittest discover -s tests -v+"""+import contextlib+import importlib.util+import io+import json+import unittest+from pathlib import Path+from unittest import mock++ROOT = Path(__file__).resolve().parents[1]+spec = importlib.util.spec_from_file_location("philips_api", ROOT / "tools" / "philips-api.py")+philips_api = importlib.util.module_from_spec(spec)+spec.loader.exec_module(philips_api)++SYSTEM = json.dumps({+ "name": "77OLED806/12",+ "api_version": {"Major": 6, "Minor": 1, "Patch": 0},+ "featuring": {"systemfeatures": {"pairing_type": "digest_auth_pairing"},+ "jsonfeatures": {"ambilight": ["LoungeLight", "Hue", "Ambilight", "HueStreaming"]}},+})+++def run(answers, argv=("philips-api.py", "192.168.1.50")):+ """Exit code and output, with get() answering from {url: (status, body)}; anything else is unreachable."""+ asked = []++ def fake_get(url, timeout=8):+ asked.append(url)+ return answers.get(url, (None, "timed out"))++ out = io.StringIO()+ with mock.patch.object(philips_api, "get", fake_get), contextlib.redirect_stdout(out), \+ contextlib.redirect_stderr(io.StringIO()):+ code = philips_api.main(list(argv))+ return code, out.getvalue(), asked+++class PhilipsApi(unittest.TestCase):+ def test_the_api_on_1926_is_found_and_401_counts_as_there(self):+ base = "https://192.168.1.50:1926/6/"+ answers = {base + "system": (200, SYSTEM)}+ answers.update({base + p: (401, "") for p in philips_api.PROBE})+ code, out, asked = run(answers)+ self.assertEqual(code, 0)+ self.assertIn("API on https://192.168.1.50:1926", out)+ self.assertIn("6.1.0", out)+ self.assertIn("LoungeLight", out)+ self.assertNotIn("MISSING", out)+ self.assertFalse([u for u in asked if ":1925/" in u], "1925 was tried although 1926 answered")++ def test_an_empty_1925_is_not_taken_for_the_api(self):+ answers = {"http://192.168.1.50:1925/6/system": (200, "")}+ code, out, _ = run(answers)+ self.assertEqual(code, 1)+ self.assertIn("org.droidtv.xtv", out)++ def test_no_address_is_a_usage_error(self):+ with mock.patch.dict("os.environ", {"TV_HOST": ""}):+ code, _, asked = run({}, argv=("philips-api.py",))+ self.assertEqual(code, 2)+ self.assertEqual(asked, [])+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/philips-api.py b/tools/philips-api.pynew file mode 100644index 000000000..3203c37e2--- /dev/null+++ b/tools/philips-api.py@@ -0,0 +1,101 @@+#!/usr/bin/env python3+"""Check that a Philips TV's JointSpace control API still answers, before and after a debloat.++ philips-api.py [tv ip] the IP defaults to TV_HOST++Exits 0 when the API answers, 1 when neither port does, and 2 on a usage error.++Philips Android TVs are driven from Home Assistant (the built-in philips_js integration), openHAB and+the like over the JointSpace API. It is served by org.droidtv.xtv, which is in the DO NOT DISABLE block+of examples/philips-50pus8517; a TV that loses it drops out of Home Assistant, and nothing on the TV's+screen says why. Run this once before the first batch and again after the last.++Two things trip people up, and this handles both:++ * On Android TV sets the API is on port 1926 over HTTPS, not the 1925 that older guides name. 1925 may+ be open and answer nothing (a 77OLED806/12 on Android TV 11 does).+ * The certificate is self-signed, so it is not verified here, as Home Assistant does not verify it+ either. This only reads from a TV on your own network.++/6/system answers without pairing, so this needs no credentials and changes nothing on the TV. The other+endpoints answer 401 until a client has done the digest-auth pairing, and for this check a 401 is the good+answer: the endpoint is there.+"""+import json+import os+import ssl+import sys+import urllib.error+import urllib.request++PORTS = ((1926, "https"), (1925, "http"))+PROBE = ("ambilight/topology", "ambilight/power", "ambilight/mode", "ambilight/currentconfiguration",+ "powerstate")+++def get(url, timeout=8):+ """(status, body); status is None when nothing answered, and body then says why."""+ ctx = ssl.create_default_context()+ ctx.check_hostname = False+ ctx.verify_mode = ssl.CERT_NONE+ try:+ with urllib.request.urlopen(url, timeout=timeout, context=ctx) as r:+ return r.status, r.read().decode("utf-8", "replace")+ except urllib.error.HTTPError as e:+ return e.code, ""+ except Exception as failure:+ return None, str(failure)+++def find_api(host):+ """The base URL whose /6/system answers with a body, or None. Prints each port it tried."""+ for port, scheme in PORTS:+ base = f"{scheme}://{host}:{port}"+ status, body = get(f"{base}/6/system")+ if status == 200 and body.strip():+ return base, body+ print(f" {base}/6/system -> {status if status is not None else body}")+ return None, ""+++def main(argv):+ args = argv[1:]+ host = args[0] if args else os.environ.get("TV_HOST", "")+ if len(args) > 1 or not host or host.startswith("-"):+ print(__doc__.split("\n\n")[1], file=sys.stderr)+ return 2++ base, body = find_api(host)+ if not base:+ print("\nNo JointSpace API. If this TV used to work with Home Assistant, check that\n"+ "org.droidtv.xtv is still enabled:\n"+ f" TV_HOST={host} tools/tv.py 'pm list packages -d' | grep droidtv")+ return 1++ print(f"API on {base}")+ try:+ info = json.loads(body)+ except ValueError:+ print(" /6/system answered, but not with JSON")+ return 0+ api = info.get("api_version", {})+ feat = info.get("featuring", {})+ ambilight = feat.get("jsonfeatures", {}).get("ambilight")+ print(f" name {info.get('name')}")+ print(f" api_version {api.get('Major')}.{api.get('Minor')}.{api.get('Patch')}")+ print(f" pairing {feat.get('systemfeatures', {}).get('pairing_type')}")+ print(f" ambilight {ambilight}")+ if ambilight and "LoungeLight" in ambilight:+ print(" (LoungeLight is Ambilight with the panel off. For it to answer while\n"+ " the TV is off, turn on Eco settings > Quick start.)")++ print("\nendpoints (401 = there, waiting for pairing):")+ for path in PROBE:+ status, _ = get(f"{base}/6/{path}")+ verdict = {200: "open", 401: "there", 404: "MISSING"}.get(status, str(status))+ print(f" {path:32s} {verdict}")+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv))