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: fix name resolution crash when target includes a port
yadavnikhil035bc64252b748
diff --git a/tests/test_adb_closed.py b/tests/test_adb_closed.pyindex 4b22a7d38..3fccdd16c 100644--- a/tests/test_adb_closed.py+++ b/tests/test_adb_closed.py@@ -2,6 +2,7 @@Run from the repository root: python3 -m unittest discover -s tests -v"""+import osfrom pathlib import Pathimport socketimport subprocess@@ -13,9 +14,9 @@ ROOT = Path(__file__).resolve().parents[1]SCRIPT = ROOT / "tools" / "adb-closed.py"-def check(*args):+def check(*args, env=None):return subprocess.run([sys.executable, "-I", str(SCRIPT), *args],- capture_output=True, text=True, timeout=30)+ capture_output=True, text=True, timeout=30, env=env)class AdbClosedTest(unittest.TestCase):@@ -36,8 +37,47 @@ class AdbClosedTest(unittest.TestCase):self.assertEqual(result.returncode, 0, result.stderr)self.assertIn("is closed: the TV refused", result.stdout)+ def test_endpoint_with_port(self):+ with socket.socket() as server:+ server.bind(("127.0.0.1", 0))+ server.listen(1)+ port = server.getsockname()[1]+ result = check(f"127.0.0.1:{port}")+ self.assertEqual(result.returncode, 1, result.stderr)+ self.assertIn(f"127.0.0.1:{port} is still open", result.stderr)++ def test_closed_endpoint_with_port(self):+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ port = probe.getsockname()[1]+ result = check(f"127.0.0.1:{port}")+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn(f"127.0.0.1:{port} is closed: the TV refused", result.stdout)++ def test_endpoint_from_tv_host_env(self):+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ port = probe.getsockname()[1]+ env = dict(os.environ, TV_HOST=f"127.0.0.1:{port}")+ result = check(env=env)+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn(f"127.0.0.1:{port} is closed", result.stdout)++ def test_cli_port_overrides_endpoint_port(self):+ with socket.socket() as server:+ server.bind(("127.0.0.1", 0))+ server.listen(1)+ port = server.getsockname()[1]+ result = check("127.0.0.1:1", str(port))+ self.assertEqual(result.returncode, 1, result.stderr)+ self.assertIn(f"127.0.0.1:{port} is still open", result.stderr)+def test_bad_arguments(self):self.assertEqual(check("127.0.0.1", "not-a-port").returncode, 2)+ self.assertEqual(check("127.0.0.1:not-a-port").returncode, 2)+ self.assertIn("not a port number: 'not-a-port'", check("127.0.0.1:not-a-port").stderr)+ self.assertEqual(check("[::1]:not-a-port").returncode, 2)+ self.assertEqual(check("127.0.0.1:99999").returncode, 2)self.assertEqual(check("a", "b", "c").returncode, 2)diff --git a/tests/test_tv_target.py b/tests/test_tv_target.pynew file mode 100644index 000000000..f1389428b--- /dev/null+++ b/tests/test_tv_target.py@@ -0,0 +1,112 @@+"""tools/tv.py accepts host:port endpoints in TV_HOST and respects TV_PORT.++Run from the repository root: python3 -m unittest discover -s tests -v+"""+import importlib.util+import os+from pathlib import Path+import sys+import types+import unittest+from unittest import mock+++ROOT = Path(__file__).resolve().parents[1]+SCRIPT = ROOT / "tools" / "tv.py"+++def load_tv(env):+ stubs = {}+ for name in ("adb_shell", "adb_shell.auth"):+ stubs[name] = types.ModuleType(name)+ device = types.ModuleType("adb_shell.adb_device")+ device.AdbDeviceTcp = object+ keygen = types.ModuleType("adb_shell.auth.keygen")+ keygen.keygen = lambda path: None+ signer = types.ModuleType("adb_shell.auth.sign_pythonrsa")+ signer.PythonRSASigner = lambda pub, priv: None+ stubs.update({"adb_shell.adb_device": device, "adb_shell.auth.keygen": keygen,+ "adb_shell.auth.sign_pythonrsa": signer})+ spec = importlib.util.spec_from_file_location("cyt_tv_target_test", SCRIPT)+ module = importlib.util.module_from_spec(spec)+ clean_env = {k: v for k, v in os.environ.items() if k not in ("TV_HOST", "TV_PORT")}+ clean_env.update(env)+ with mock.patch.dict(os.environ, clean_env, clear=True), mock.patch.dict(sys.modules, stubs):+ spec.loader.exec_module(module)+ return module+++class TvTargetTest(unittest.TestCase):+ def test_split_host_port_function(self):+ tv = load_tv({"TV_HOST": "192.0.2.1"})+ self.assertEqual(tv.split_host_port("192.0.2.1"), ("192.0.2.1", None))+ self.assertEqual(tv.split_host_port("192.0.2.1:5555"), ("192.0.2.1", "5555"))+ self.assertEqual(tv.split_host_port("[::1]:5555"), ("::1", "5555"))+ self.assertEqual(tv.split_host_port("[::1]"), ("::1", None))+ self.assertEqual(tv.split_host_port("::1"), ("::1", None))++ def test_default_port(self):+ tv = load_tv({"TV_HOST": "192.0.2.1"})+ self.assertEqual(tv.HOST, "192.0.2.1")+ self.assertEqual(tv.PORT, 5555)++ def test_endpoint_with_port(self):+ tv = load_tv({"TV_HOST": "192.0.2.1:5555"})+ self.assertEqual(tv.HOST, "192.0.2.1")+ self.assertEqual(tv.PORT, 5555)++ def test_endpoint_with_custom_port(self):+ tv = load_tv({"TV_HOST": "192.0.2.1:39482"})+ self.assertEqual(tv.HOST, "192.0.2.1")+ self.assertEqual(tv.PORT, 39482)++ def test_tv_port_env_overrides_endpoint_port(self):+ tv = load_tv({"TV_HOST": "192.0.2.1:39482", "TV_PORT": "15555"})+ self.assertEqual(tv.HOST, "192.0.2.1")+ self.assertEqual(tv.PORT, 15555)++ def test_ipv6_bracketed_endpoint(self):+ tv = load_tv({"TV_HOST": "[::1]:5555"})+ self.assertEqual(tv.HOST, "::1")+ self.assertEqual(tv.PORT, 5555)++ def test_ipv6_bracketed_without_port(self):+ tv = load_tv({"TV_HOST": "[::1]"})+ self.assertEqual(tv.HOST, "::1")+ self.assertEqual(tv.PORT, 5555)++ def test_missing_host_raises_system_exit(self):+ with self.assertRaises(SystemExit) as cm:+ load_tv({})+ self.assertIn("Set TV_HOST to your TV's IP address", str(cm.exception))++ def test_bad_port_raises_system_exit(self):+ with self.assertRaises(SystemExit) as cm:+ load_tv({"TV_HOST": "192.0.2.1:not-a-port"})+ self.assertIn("not a port number: 'not-a-port'", str(cm.exception))++ def test_out_of_range_port_raises_system_exit(self):+ with self.assertRaises(SystemExit) as cm:+ load_tv({"TV_HOST": "192.0.2.1:70000"})+ self.assertIn("not a port number: '70000'", str(cm.exception))+++ def test_connect_passes_host_and_port(self):+ created_devices = []++ class StubAdbDeviceTcp:+ def __init__(self, host, port, **kwargs):+ created_devices.append((host, port))++ def connect(self, **kwargs):+ pass++ tv = load_tv({"TV_HOST": "192.0.2.1:39482"})+ with mock.patch.object(tv, "AdbDeviceTcp", StubAdbDeviceTcp), \+ mock.patch.object(tv, "get_signer", return_value=None):+ tv.connect()+ self.assertEqual(created_devices, [("192.0.2.1", 39482)])+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/adb-closed.py b/tools/adb-closed.pyindex 5b26114ba..c0f248cb6 100644--- a/tools/adb-closed.py+++ b/tools/adb-closed.py@@ -1,7 +1,7 @@#!/usr/bin/env python3"""Check that the TV's network ADB port is closed, after turning debugging off (no nc needed).- adb-closed.py <tv ip> [port] port defaults to TV_PORT or 5555; the IP to TV_HOST+ adb-closed.py <tv ip[:port]> [port] port defaults to TV_PORT or 5555; the IP to TV_HOSTExits 0 when the port refuses the connection or does not answer, 1 when it is still open, and 2when the check itself could not run (a name that does not resolve, no route to the TV).@@ -13,19 +13,45 @@ import sysTIMEOUT_S = 3.0+def split_host_port(endpoint):+ """Split host:port or [ipv6]:port into (host, port_or_none)."""+ if endpoint.startswith("["):+ end = endpoint.find("]")+ if end != -1:+ host = endpoint[1:end]+ rest = endpoint[end + 1:]+ if rest.startswith(":"):+ return host, rest[1:]+ return host, None+ elif endpoint.count(":") == 1:+ host, port = endpoint.split(":", 1)+ return host, port+ return endpoint, None++def main():args = sys.argv[1:]if len(args) > 2 or args[:1] in (["-h"], ["--help"]):sys.stderr.write(__doc__)return 2- host = args[0] if args else os.environ.get("TV_HOST", "")- if not host:+ raw_host = args[0] if args else os.environ.get("TV_HOST", "")+ if not raw_host:sys.stderr.write("usage: adb-closed.py <tv ip> [port]\n")return 2+ host, endpoint_port = split_host_port(raw_host)+ if len(args) == 2:+ port_str = args[1]+ elif len(args) == 1 and endpoint_port is not None:+ port_str = endpoint_port+ else:+ port_str = os.environ.get("TV_PORT") or endpoint_port or "5555"+try:- port = int(args[1] if len(args) == 2 else os.environ.get("TV_PORT", "5555"))+ port = int(port_str)+ if not (1 <= port <= 65535):+ raise ValueErrorexcept ValueError:- sys.stderr.write(f"not a port number: {args[1]!r}\n")+ sys.stderr.write(f"not a port number: {port_str!r}\n")return 2try:diff --git a/tools/tv.py b/tools/tv.pyindex 601b0d400..10af800ff 100644--- a/tools/tv.py+++ b/tools/tv.py@@ -1,7 +1,7 @@#!/usr/bin/env python3"""Minimal ADB-over-TCP client for an Android TV using adb_shell (no adb binary needed).-Set TV_HOST to the TV's IP. Usage:+Set TV_HOST to the TV's IP (or IP:port). Usage:tv.py --probe connect and print model / Android versiontv.py <shell command...> run one shell commandtv.py --screenshot <local.png> [KEY ...] [--wait SECONDS]@@ -28,11 +28,34 @@ for _stream in (sys.stdout, sys.stderr):except (AttributeError, ValueError):pass-HOST = os.environ.get("TV_HOST")-PORT = int(os.environ.get("TV_PORT", "5555"))-if not HOST:+def split_host_port(endpoint):+ """Split host:port or [ipv6]:port into (host, port_or_none)."""+ if endpoint.startswith("["):+ end = endpoint.find("]")+ if end != -1:+ host = endpoint[1:end]+ rest = endpoint[end + 1:]+ if rest.startswith(":"):+ return host, rest[1:]+ return host, None+ elif endpoint.count(":") == 1:+ host, port = endpoint.split(":", 1)+ return host, port+ return endpoint, None+++_raw_host = os.environ.get("TV_HOST")+if not _raw_host:sys.exit("Set TV_HOST to your TV's IP address, e.g. TV_HOST=192.168.1.50 tools/tv.py --probe\n""(find it under Settings → Network, or look for the TV in `arp -a`)")+HOST, _endpoint_port = split_host_port(_raw_host)+_port_str = os.environ.get("TV_PORT") or _endpoint_port or "5555"+try:+ PORT = int(_port_str)+ if not (1 <= PORT <= 65535):+ raise ValueError+except ValueError:+ sys.exit(f"not a port number: {_port_str!r}")KEYDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "adbkey")KEY = os.path.join(KEYDIR, "adbkey")# Reuse the stock adb key when the TV already trusts it (platform-tools / Android Studio users), so the