Debloat your Android TV, install apps, browse and transfer files on it, all from your phone. Just 3 MB, no tracking, no root, no PC.
Fail gracefully on bad ports, pairing drops and deep JSON; confirm undo-disable
jesse-agent-3623000bce61184
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a58a05d..5094f34 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,3 +24,7 @@ until this file has a section for its version.- **Fixed:** Undo and results always go to the TV the action ran on. [#20](../../pull/20)- **New:** Debloat in two steps: pick your TV, then review every app it turns off. [#23](../../pull/23)- **Improved:** The TV page leads with the TV, its vitals and big action buttons. [#23](../../pull/23)+- **Fixed:** Adding a TV with a port above 65535 shows a message, not a crash. [#25](../../pull/25)+- **Fixed:** Losing Wi-Fi while pairing shows a message, not a crash. [#25](../../pull/25)+- **Fixed:** A broken suggestions list can no longer crash the app. [#25](../../pull/25)+- **Improved:** Undoing a Turn on in History asks before disabling the app. [#25](../../pull/25)diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt b/adb/src/main/kotlin/app/tellyscope/adb/Connector.ktindex 4081a25..d57c0b8 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt@@ -29,6 +29,13 @@ sealed interface ConnectResult {data class Unreachable(val reason: String) : ConnectResult}+sealed interface PairResult {+ data object Paired : PairResult+ data class WrongCode(val reason: String) : PairResult+ /** The pairing port refused, timed out or dropped mid-handshake. */+ data class Unreachable(val reason: String) : PairResult+}+/*** Opens ADB connections with one persisted host key, so the TV's "always allow" survives restarts.* Call [init] once per process before anything else.@@ -52,6 +59,8 @@ object Connector {* [allowWaitMs]; the UI shows WAITING for that whole time. Cancelling it closes the attempt.*/suspend fun connect(host: String, port: Int, allowWaitMs: Int = ALLOW_WAIT_MS): ConnectResult {+ // InetSocketAddress throws IllegalArgumentException outside this range.+ if (port !in 1..65535) return ConnectResult.Unreachable("port $port is not between 1 and 65535")// Probe TCP first: a refused or silent port is "unreachable", not "not allowed".try {runInterruptible(Dispatchers.IO) { Socket().use { it.connect(InetSocketAddress(host, port), TCP_TIMEOUT_MS) } }@@ -77,10 +86,24 @@ object Connector {}}- /** Android 11+ wireless debugging: pair once with the 6-digit code, then [connect] to the connect port. */- suspend fun pair(host: String, pairingPort: Int, code: String) {- require(code.length == 6 && code.all(Char::isDigit)) { "pairing code must be 6 digits" }- Kadb.pair(host, pairingPort, code)+ /**+ * Android 11+ wireless debugging: pair once with the 6-digit code, then [connect] to the connect+ * port. Never throws, except to cancel.+ */+ suspend fun pair(host: String, pairingPort: Int, code: String): PairResult {+ if (code.length != 6 || !code.all(Char::isDigit)) return PairResult.WrongCode("pairing code must be 6 digits")+ if (pairingPort !in 1..65535) return PairResult.Unreachable("port $pairingPort is not between 1 and 65535")+ return try {+ Kadb.pair(host, pairingPort, code)+ PairResult.Paired+ } catch (e: CancellationException) {+ throw e+ } catch (e: AdbPairAuthException) {+ PairResult.WrongCode(e.message ?: "pairing failed")+ } catch (e: Exception) {+ // A Wi-Fi drop mid-handshake surfaces as an IOException, or as Kadb's IllegalStateException.+ PairResult.Unreachable(e.message ?: e.javaClass.simpleName)+ }}private fun Throwable.isAuthFailure(): Boolean =diff --git a/adb/src/test/kotlin/app/tellyscope/adb/ConnectorTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/ConnectorTest.ktnew file mode 100644index 0000000..0528230--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/ConnectorTest.kt@@ -0,0 +1,42 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import java.io.File+import java.net.InetAddress+import java.net.ServerSocket+import java.nio.file.Files+import kotlin.concurrent.thread+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs++class ConnectorTest {+ @BeforeTest fun key() = Connector.init(File(Files.createTempDirectory("adbkey").toFile(), "adbkey"))++ @Test fun portOutOfRangeIsUnreachable() = runBlocking<Unit> {+ // InetSocketAddress threw IllegalArgumentException here, which nothing caught.+ assertIs<ConnectResult.Unreachable>(Connector.connect("127.0.0.1", 70000))+ assertIs<ConnectResult.Unreachable>(Connector.connect("127.0.0.1", 0))+ }++ @Test fun pairingThatDropsMidHandshakeIsUnreachable() = runBlocking<Unit> {+ // A pairing port that hangs up straight away, as one does when the Wi-Fi drops.+ ServerSocket(0, 50, InetAddress.getByName("127.0.0.1")).use { server ->+ thread(isDaemon = true) { runCatching { while (true) server.accept().close() } }+ val r = withTimeout(30_000) { Connector.pair("127.0.0.1", server.localPort, "123456") }+ assertIs<PairResult.Unreachable>(r)+ }+ }++ @Test fun pairingWithNothingListeningIsUnreachable() = runBlocking<Unit> {+ val port = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1")).use { it.localPort }+ assertIs<PairResult.Unreachable>(withTimeout(30_000) { Connector.pair("127.0.0.1", port, "123456") })+ }++ @Test fun badCodeIsWrongCode() = runBlocking<Unit> {+ assertEquals(PairResult.WrongCode("pairing code must be 6 digits"), Connector.pair("127.0.0.1", 1, "12a456"))+ }+}diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex a123e41..8b30755 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -24,7 +24,7 @@ import app.tellyscope.adb.Protectedimport app.tellyscope.adb.ProtectedReasonimport app.tellyscope.adb.Remoteimport app.tellyscope.adb.RemoteKey-import com.flyfishxu.kadb.exception.AdbPairAuthException+import app.tellyscope.adb.PairResultimport com.flyfishxu.kadb.mdns.KadbMdnsAndroidimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.CoroutineScope@@ -203,12 +203,10 @@ class AdbDeviceSource(context: Context) : DeviceSource {}override suspend fun pair(hit: ScanHit, code: String): ConnectResult {- try {- Connector.pair(hit.ip, pairingPorts[hit.ip] ?: hit.port, code)- } catch (e: AdbPairAuthException) {- return ConnectResult.WrongCode(e.message ?: "pairing failed")- } catch (e: IllegalArgumentException) {- return ConnectResult.WrongCode(e.message ?: "pairing code must be 6 digits")+ when (val r = Connector.pair(hit.ip, pairingPorts[hit.ip] ?: hit.port, code)) {+ PairResult.Paired -> Unit+ is PairResult.WrongCode -> return ConnectResult.WrongCode(r.reason)+ is PairResult.Unreachable -> return ConnectResult.Unreachable(r.reason)}// After pairing, the connect port is the one mDNS advertised, not the pairing port.val connectHit = hits[hit.ip]?.takeIf { it.port != pairingPorts[hit.ip] } ?: hitdiff --git a/app/src/main/java/app/tellyscope/data/DeviceLists.kt b/app/src/main/java/app/tellyscope/data/DeviceLists.ktindex 54393db..27f029d 100644--- a/app/src/main/java/app/tellyscope/data/DeviceLists.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceLists.kt@@ -86,7 +86,7 @@ fun matches(rule: Map<String, List<String>>?, props: Map<String, String?>): Bool/** Null unless it is a schema 1 index. Entries with a bad file name or checksum are dropped. */fun parseIndex(text: String): ListIndex? = try {- val o = JSONObject(text)+ val o = jsonObject(text)if (o.optInt("schema") != SCHEMA) null else ListIndex(commit = o.optJSONObject("source")?.optStringOrNull("commit"),devices = o.getJSONArray("devices").objects().mapNotNull { d ->@@ -108,7 +108,7 @@ fun parseIndex(text: String): ListIndex? = try {/** Null unless it is a schema 1 device file for [id]. Names that aren't package names are dropped. */fun parseList(text: String, id: String): DeviceList? = try {- val o = JSONObject(text)+ val o = jsonObject(text)val tested = o.optJSONObject("tested")fun packages(a: JSONArray?) = a?.objects().orEmpty().map { ListPackage(it.getString("pkg"), it.optStringOrNull("note"), it.optBoolean("optional")) }@@ -250,6 +250,35 @@ private suspend fun download(url: String): ByteArray = withContext(Dispatchers.Iprivate fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }+/** Real lists nest about four deep; org.json parses recursively, so a deeply nested file would overflow the stack. */+private const val MAX_DEPTH = 32++private fun jsonObject(text: String): JSONObject {+ if (depth(text) > MAX_DEPTH) throw org.json.JSONException("nested deeper than $MAX_DEPTH")+ return JSONObject(text)+}++/** Deepest `{`/`[` nesting outside strings. */+internal fun depth(text: String): Int {+ var depth = 0+ var max = 0+ var inString = false+ var escaped = false+ for (c in text) {+ when {+ escaped -> escaped = false+ inString -> when (c) {+ '\\' -> escaped = true+ '"' -> inString = false+ }+ c == '"' -> inString = true+ c == '{' || c == '[' -> { depth++; if (depth > max) max = depth }+ c == '}' || c == ']' -> depth--+ }+ }+ return max+}+private fun JSONArray.objects() = (0 until length()).map { getJSONObject(it) }private fun JSONArray.strings() = (0 until length()).map { getString(it) }private fun JSONObject.optStringOrNull(k: String) = if (isNull(k)) null else optString(k)diff --git a/app/src/main/java/app/tellyscope/ui/Copy.kt b/app/src/main/java/app/tellyscope/ui/Copy.ktindex c8f9fcc..c7fb615 100644--- a/app/src/main/java/app/tellyscope/ui/Copy.kt+++ b/app/src/main/java/app/tellyscope/ui/Copy.kt@@ -51,8 +51,15 @@ object Copy {Action.Open -> "Opened $app"}- /** Force-stop has no true undo; the button says what it actually does. */- fun undo(undo: Action) = if (undo == Action.Open) "Open again" else "Undo"+ /**+ * Force-stop has no true undo, and undoing a Turn on disables the app; the button says what it+ * actually does.+ */+ fun undo(undo: Action) = when (undo) {+ Action.Open -> "Open again"+ Action.Disable -> button(Action.Disable)+ else -> "Undo"+ }fun ago(at: Long, now: Long): String {val s = ((now - at) / 1000).coerceAtLeast(0)diff --git a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt b/app/src/main/java/app/tellyscope/ui/DeviceScreen.ktindex 8ed8937..71c7085 100644--- a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt+++ b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt@@ -429,6 +429,18 @@ private fun DevicePicker(state: UiState, actions: DeviceActions) {}}+/** Undoing a Turn on disables the app; it names the app and asks like any other Disable. */+@Composable+fun UndoDisableDialog(entry: HistoryEntry, onDisable: () -> Unit, onDismiss: () -> Unit) {+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text("Disable ${entry.label}?") },+ text = { Text(Copy.explain(Action.Disable, entry.label, entry.packageName)) },+ confirmButton = { Button(onClick = onDisable) { Text(Copy.confirm(Action.Disable)) } },+ dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },+ )+}+/** Restore only touches what Tellyscope turned off; the dialog says so before anything runs. */@Composablefun RestoreDialog(count: Int, onRestore: () -> Unit, onDismiss: () -> Unit) {@@ -722,6 +734,10 @@ private fun HistoryList(var confirming by rememberSaveable { mutableStateOf(false) }val off = HistoryBook.leftDisabled(history).sizeif (confirming) RestoreDialog(off, onRestore = { confirming = false; onRestoreAll() }, onDismiss = { confirming = false })+ var disabling by remember { mutableStateOf<HistoryEntry?>(null) }+ disabling?.let { h ->+ UndoDisableDialog(h, onDisable = { disabling = null; onUndo(h) }, onDismiss = { disabling = null })+ }if (off > 0) {OutlinedButton(onClick = { confirming = true }, enabled = !restoring) {Text(if (restoring) "Turning apps back on…" else "Restore everything ($off)")@@ -743,7 +759,7 @@ private fun HistoryList(}when {h.undoneAt != null -> Text("Undone", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)- h.undo != null -> TextButton(onClick = { onUndo(h) }) { Text(Copy.undo(h.undo)) }+ h.undo != null -> TextButton(onClick = { if (h.undo == Action.Disable) disabling = h else onUndo(h) }) { Text(Copy.undo(h.undo)) }}}}diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex b52e3c0..2eddd23 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -243,6 +243,7 @@ class TellyscopeViewModel(val m = Regex("""^(\d{1,3}(?:\.\d{1,3}){3})(?::(\d{1,5}))?$""").find(text.trim())?: return "That doesn't look like an IP address. It should look like four numbers with dots, like the one in your TV's network settings."val port = m.groupValues[2].toIntOrNull() ?: 5555+ if (port !in 1..65535) return "The port after the colon should be a number from 1 to 65535, like 5555."val kind = if (port == 5555) app.tellyscope.data.ScanKind.Classic else app.tellyscope.data.ScanKind.Wirelessval hit = ScanHit(m.groupValues[1], port, kind, null, null)_state.update { s ->diff --git a/app/src/test/java/app/tellyscope/DeviceListsTest.kt b/app/src/test/java/app/tellyscope/DeviceListsTest.ktindex d58afcb..83934e4 100644--- a/app/src/test/java/app/tellyscope/DeviceListsTest.kt+++ b/app/src/test/java/app/tellyscope/DeviceListsTest.kt@@ -12,7 +12,9 @@ import app.tellyscope.data.ListGroupimport app.tellyscope.data.ListPackageimport app.tellyscope.data.keepRefusesimport app.tellyscope.data.matches+import app.tellyscope.data.depthimport app.tellyscope.data.parseIndex+import app.tellyscope.data.parseListimport app.tellyscope.data.suggestimport app.tellyscope.data.withKeepimport kotlinx.coroutines.test.runTest@@ -157,4 +159,12 @@ class DeviceListsTest {}private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }+ @Test fun deeplyNestedJsonIsRejectedNotACrash() {+ // org.json parses recursively: this used to throw StackOverflowError on every TV page open.+ val bomb = "[".repeat(200_000) + "]".repeat(200_000)+ assertNull(parseList("""{"schema":1,"id":"x","name":"x","groups":$bomb}""", "x"))+ assertNull(parseIndex("""{"schema":1,"devices":$bomb}"""))+ // Brackets inside strings don't count.+ assertEquals(2, depth("""{"a":["[[[{{{\"]"]}"""))+ }}diff --git a/app/src/test/java/app/tellyscope/ScreenshotTest.kt b/app/src/test/java/app/tellyscope/ScreenshotTest.ktindex e96da39..a231b6a 100644--- a/app/src/test/java/app/tellyscope/ScreenshotTest.kt+++ b/app/src/test/java/app/tellyscope/ScreenshotTest.kt@@ -69,6 +69,7 @@ import java.io.RandomAccessFileimport java.nio.file.Filesimport kotlin.random.Randomimport kotlinx.coroutines.runBlocking+import org.junit.Assert.assertEqualsimport org.junit.Ruleimport org.junit.Testimport org.junit.runner.RunWith@@ -233,6 +234,28 @@ class ScreenshotTest {shot("07_device_history", before = openHistory) { DeviceScreen(deviceState { copy(history = history) }, DeviceActions()) }}+ @Config(qualifiers = "w411dp-h2600dp-xxhdpi")+ @Test fun history_undoOfTurnOnAsksFirst() {+ val turnedOn = HistoryEntry(3, xgimi.ip, now - 20_000, Action.Enable, "com.xgimi.assistant", "XGIMI Assistant", Action.Disable, null)+ val undone = mutableListOf<HistoryEntry>()+ val openAndTap = {+ compose.onNodeWithText("Apps").performClick()+ compose.onNodeWithText("History").performClick()+ compose.mainClock.advanceTimeBy(1_000)+ // The button says what it does, and a tap only asks.+ compose.onNodeWithText("Disable").performClick()+ Unit+ }+ shot("16_history_undo_disable", screen = true, before = openAndTap) {+ DeviceScreen(deviceState { copy(history = listOf(turnedOn)) }, DeviceActions(undo = { undone += it }))+ }+ compose.onNodeWithText("Disable XGIMI Assistant?").assertExists()+ assertEquals(emptyList<HistoryEntry>(), undone)+ compose.onNodeWithText("Yes, disable it").performClick()+ compose.mainClock.advanceTimeBy(1_000)+ assertEquals(listOf(turnedOn), undone)+ }+/** A real TV's app list: no per-process stats yet, so the apps sit right under the stat grid. */private fun appsState(apps: List<AppInfo>): UiState {val base = deviceState()