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.
Log out when a TV takes back a key it had allowed
jesse-agent-82111c31800295b
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt b/adb/src/main/kotlin/app/tellyscope/adb/Connector.ktindex 9bcf138..018d20a 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt@@ -162,39 +162,46 @@ object Connector {}internal class KadbSession(private val kadb: Kadb) : AdbSession {+ /**+ * The connection this session opened, or an IOException once it has dropped. Kadb would open a+ * fresh one behind our back, which puts a new "Allow debugging?" prompt on a TV that took the key+ * back; the link reconnects instead, where a refusal stops it.+ */+ private fun live(): Kadb = kadb.takeIf { it.connectionCheck() } ?: throw IOException("connection closed")+/*** Kadb blocks the calling thread while it waits for the reply; that wait is interruptible, so* cancelling one call (a closed screen, a timeout) ends only that stream, not the connection.*/override suspend fun shell(command: String): ShellResult {- val r = runInterruptible(Dispatchers.IO) { kadb.shell(command) }+ val r = runInterruptible(Dispatchers.IO) { live().shell(command) }return ShellResult(r.output, r.exitCode)}override suspend fun push(bytes: ByteArray, remotePath: String) = runInterruptible(Dispatchers.IO) {- kadb.push(Buffer().write(bytes), remotePath, "644".toInt(8), System.currentTimeMillis())+ live().push(Buffer().write(bytes), remotePath, "644".toInt(8), System.currentTimeMillis())}- override fun install(source: Source, size: Long, vararg options: String) = kadb.install(source, size, *options)+ override fun install(source: Source, size: Long, vararg options: String) = live().install(source, size, *options)- override fun installMultiple(apks: List<File>, vararg options: String) = kadb.installMultiple(apks, *options)+ override fun installMultiple(apks: List<File>, vararg options: String) = live().installMultiple(apks, *options)override fun push(source: Source, remotePath: String, mode: Int, lastModifiedMs: Long) =- kadb.push(source, remotePath, mode, lastModifiedMs)+ live().push(source, remotePath, mode, lastModifiedMs)- override fun pull(sink: Sink, remotePath: String) = kadb.pull(sink, remotePath)+ override fun pull(sink: Sink, remotePath: String) = live().pull(sink, remotePath)- override fun list(remoteDir: String): List<RemoteEntry> = kadb.openSync().use { sync ->+ override fun list(remoteDir: String): List<RemoteEntry> = live().openSync().use { sync ->sync.list(remoteDir).map { RemoteEntry(it.name, it.mode, it.size, it.mtimeSec) }}override suspend fun reboot() {- runInterruptible(Dispatchers.IO) { kadb.open("reboot:").close() }+ runInterruptible(Dispatchers.IO) { live().open("reboot:").close() }}/** `exec:` is adbd's raw service: no pty, so bytes go both ways untouched. */override suspend fun exec(command: String): AdbPipe {- val stream = runInterruptible(Dispatchers.IO) { kadb.open("exec:$command") }+ val stream = runInterruptible(Dispatchers.IO) { live().open("exec:$command") }return object : AdbPipe {// Already buffered: `.buffer()` here would be their internal Buffer, cut off from the TV.override val stdin = stream.sinkdiff --git a/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt b/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.ktindex 54ba410..d30cece 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt@@ -15,11 +15,13 @@ import kotlin.time.Duration.Companion.seconds/*** One device's connection lifecycle: connect, stream stats while online, reconnect on its own* after the TV sleeps or drops off Wi-Fi. NOT_ALLOWED and NEEDS_PAIRING stop the loop until- * [connect] is called again. A device that was online before gets [notAllowedLimit] tries first,- * since a TV waking up can stall the handshake exactly like an unanswered prompt; past that it- * stops, because each try puts a fresh "Allow debugging?" prompt on the TV (revoked access, a- * reset, or Deny). [knownGood] marks a device remembered from an earlier launch, which counts as- * online before.+ * [connect] is called again: every try puts a fresh "Allow debugging?" prompt on the TV.+ *+ * A device that let this phone in before and then refuses it has taken the key back (revoked, Remove+ * all other access from another build, a reset): that's a logout, stamped in [loggedOutAt]. [knownGood]+ * marks a device remembered from an earlier launch, which counts as let in before. After+ * `connect(asked = true)` the user is watching the prompt, so a refusal is a plain NOT_ALLOWED until+ * the TV lets the phone in again.*/class DeviceLink(val host: String,@@ -28,8 +30,7 @@ class DeviceLink(private val retryEvery: Duration = 5.seconds,private val monitorFor: (AdbShell, StatsGate) -> MonitorSource = { s, gate -> DeviceMonitor(s, gate = gate) },private val open: suspend (String, Int) -> ConnectResult = { h, p -> Connector.connect(h, p) },- private val knownGood: Boolean = false,- private val notAllowedLimit: Int = 3,+ knownGood: Boolean = false,) {private val _state = MutableStateFlow(DeviceState.FOUND)val state: StateFlow<DeviceState> = _state.asStateFlow()@@ -46,15 +47,43 @@ class DeviceLink(@Volatile var lastSeenMillis: Long? = nullprivate set+ /**+ * Epoch millis of the last logout; null once the TV lets this phone in, or refuses it after+ * `connect(asked = true)`. Kept through a reconnect attempt, so it only means "logged out" while+ * [state] is NOT_ALLOWED. Always written before [state], so a reader that reads [state] first+ * never sees a fresh NOT_ALLOWED with a stale value.+ */+ private val _loggedOutAt = MutableStateFlow<Long?>(null)+ val loggedOutAt: StateFlow<Long?> = _loggedOutAt.asStateFlow()++ /** The TV let this phone in before, so a refusal now means it took the key back. */+ @Volatile private var allowedBefore = knownGood+private var job: Job? = null- /** Starts over. The old session is let go at once, so nothing reads through it while the new one opens. */- fun connect() {+ /**+ * Starts over. The old session is let go at once, so nothing reads through it while the new one+ * opens. [asked]: the user pressed connect, see the class doc.+ */+ fun connect(asked: Boolean = false) {job?.cancel()session = null+ if (asked) allowedBefore = false+ // Set here, not in the loop: nobody may see the old state once connect has returned.+ _state.value = _state.value.on(DeviceEvent.Connect)job = scope.launch { loop() }}+ /** Logged out [at]: stays at NOT_ALLOWED without trying, so the TV gets no prompt until [connect]. */+ fun holdLoggedOut(at: Long) {+ job?.cancel()+ job = null+ session = null+ allowedBefore = false+ _loggedOutAt.value = at+ _state.value = DeviceState.NOT_ALLOWED+ }+fun disconnect() {job?.cancel()job = null@@ -62,14 +91,11 @@ class DeviceLink(}private suspend fun loop() {- _state.value = _state.value.on(DeviceEvent.Connect)- var wasOnline = knownGood- var notAllowed = 0while (true) {- val r = open(host, port)- notAllowed = if (r is ConnectResult.NotAllowed) notAllowed + 1 else 0- when (r) {- is ConnectResult.NotAllowed -> if (!wasOnline || notAllowed >= notAllowedLimit) {+ when (val r = open(host, port)) {+ is ConnectResult.NotAllowed -> {+ _loggedOutAt.value = if (allowedBefore) System.currentTimeMillis() else null+ allowedBefore = false_state.value = _state.value.on(DeviceEvent.AuthTimedOut)return}@@ -79,7 +105,8 @@ class DeviceLink(}is ConnectResult.Unreachable -> _state.value = _state.value.on(DeviceEvent.Unreachable)is ConnectResult.Online -> {- wasOnline = true+ allowedBefore = true+ _loggedOutAt.value = nullonline(r.session)_state.value = _state.value.on(DeviceEvent.Lost)}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.ktindex 15274ee..7b33d25 100644--- a/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt+++ b/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt@@ -25,29 +25,39 @@ class DeviceLinkTest {assertEquals(1, calls)}- @Test fun rememberedDeviceStopsAfterThreeNotAllowed() = runTest {- // Each try shows "Allow debugging?" on the TV again, so a revoked key mustn't loop forever.+ @Test fun rememberedDeviceRefusedOnceIsLoggedOut() = runTest {+ // Each try shows "Allow debugging?" on the TV again, so a revoked key gets exactly one.var calls = 0val link = DeviceLink("tv", 5555, backgroundScope, open = { _, _ -> calls++; ConnectResult.NotAllowed }, knownGood = true)link.connect(); runCurrent()advanceTimeBy(60_000)assertEquals(DeviceState.NOT_ALLOWED, link.state.value)- assertEquals(3, calls)+ assertTrue(link.loggedOutAt.value != null)+ assertEquals(1, calls)}- @Test fun unreachableResetsTheNotAllowedCount() = runTest {- // A TV waking up: stalls and timeouts interleave, and it keeps retrying until it answers.- val answers = ArrayDeque(listOf<ConnectResult>(- ConnectResult.NotAllowed, ConnectResult.NotAllowed, ConnectResult.Unreachable("asleep"),- ConnectResult.NotAllowed, ConnectResult.NotAllowed,- ))- var calls = 0- val link = DeviceLink("tv", 5555, backgroundScope, knownGood = true,- open = { _, _ -> calls++; answers.removeFirstOrNull() ?: ConnectResult.Unreachable("off") })+ @Test fun refusalAfterAskingIsNotALogout() = runTest {+ // Connect again, then Deny: the user saw it happen, so it's a plain "not allowed".+ val link = DeviceLink("tv", 5555, backgroundScope, open = { _, _ -> ConnectResult.NotAllowed }, knownGood = true)+ link.connect(asked = true); runCurrent()+ assertEquals(DeviceState.NOT_ALLOWED, link.state.value)+ assertEquals(null, link.loggedOutAt.value)+ }++ @Test fun firstRefusalIsNotALogout() = runTest {+ val link = DeviceLink("tv", 5555, backgroundScope, open = { _, _ -> ConnectResult.NotAllowed })link.connect(); runCurrent()- advanceTimeBy(30_001)- assertEquals(DeviceState.OFFLINE, link.state.value)- assertTrue(calls > 5)+ assertEquals(null, link.loggedOutAt.value)+ }++ @Test fun holdingALogoutNeverConnects() = runTest {+ var calls = 0+ val link = DeviceLink("tv", 5555, backgroundScope, open = { _, _ -> calls++; ConnectResult.NotAllowed }, knownGood = true)+ link.holdLoggedOut(1_000)+ advanceTimeBy(60_000)+ assertEquals(DeviceState.NOT_ALLOWED, link.state.value)+ assertTrue(link.loggedOutAt.value != null)+ assertEquals(0, calls)}@Test fun dropsToOfflineThenReconnects() = runTest {@@ -86,8 +96,8 @@ class DeviceLinkTest {assertEquals(1, calls)}- @Test fun notAllowedAfterADropStopsAfterThreeTries() = runTest {- // Online once, then the key is revoked: three tries, then NOT_ALLOWED instead of a prompt every 5 s.+ @Test fun refusedAfterADropLogsOutAfterOneTry() = runTest {+ // Online once, then the key is revoked: one try, then a logout instead of a prompt every 5 s.var calls = 0val link = DeviceLink("tv", 5555, backgroundScope,@@ -97,7 +107,8 @@ class DeviceLinkTest {link.connect(); runCurrent()advanceTimeBy(60_000)assertEquals(DeviceState.NOT_ALLOWED, link.state.value)- assertEquals(1 + 3, calls)+ assertTrue(link.loggedOutAt.value != null)+ assertEquals(1 + 1, calls)}@Test fun disconnectClosesSessionAndResets() = runTest {diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex d9369bc..d8eabd5 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -117,13 +117,17 @@ class AdbDeviceSource(context: Context) : DeviceSource {saved[d.host] = dd.historyKey?.let { keys[d.host] = it }hits[d.host] = ScanHit(d.host, d.port, d.kind, d.name, null)- restoring += d.host- link(d.host, d.port, first = null, knownGood = true)+ // A TV that logged this phone out stays quiet: reconnecting would prompt on it again.+ if (d.loggedOutAt == null) restoring += d.host+ link(d.host, d.port, first = null, knownGood = true, loggedOutAt = d.loggedOutAt)}}- /** Starts the reconnecting link for a TV and keeps its saved entry current as it comes and goes. */- private fun link(host: String, port: Int, first: AdbConnectResult?, knownGood: Boolean) {+ /**+ * Starts the reconnecting link for a TV and keeps its saved entry current as it comes and goes.+ * A TV [loggedOutAt] a time gets its link without a connect.+ */+ private fun link(host: String, port: Int, first: AdbConnectResult?, knownGood: Boolean, loggedOutAt: Long? = null) {var pending = firstval link = DeviceLink(host, port, scope, knownGood = knownGood, open = { h, p ->pending?.also { pending = null } ?: Connector.connect(h, p)@@ -138,6 +142,15 @@ class AdbDeviceSource(context: Context) : DeviceSource {if (st != null && lastKnown(st, kept) != kept) remember(host)}}+ launch {+ link.loggedOutAt.collect { at ->+ val d = saved[host] ?: return@collect+ if (d.loggedOutAt != at) {+ saved[host] = d.copy(loggedOutAt = at)+ persist()+ }+ }+ }link.state.collect { st ->if (st == AdbState.ONLINE) {restoring -= host@@ -147,7 +160,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {if (st == AdbState.ONLINE || st == AdbState.OFFLINE) remember(host)}})?.cancel()- link.connect()+ if (loggedOutAt != null) link.holdLoggedOut(loggedOutAt) else link.connect()}private fun remember(host: String) {@@ -165,6 +178,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {lastSeen = link.lastSeenMillis ?: old?.lastSeen ?: System.currentTimeMillis(),historyKey = keys[host] ?: old?.historyKey,lastKnown = link.stats.value?.let { lastKnown(it, kept) } ?: kept,+ loggedOutAt = link.loggedOutAt.value,)persist()}@@ -191,7 +205,14 @@ class AdbDeviceSource(context: Context) : DeviceSource {override suspend fun reconnect(deviceId: String) {restored.await()- links[deviceId]?.connect()+ links[deviceId]?.connect(asked = true)+ }++ override suspend fun cancelReconnect(deviceId: String) {+ restored.await()+ val link = links[deviceId] ?: return+ // Connect again after a logout goes back to it, with its time; any other attempt just stops.+ link.loggedOutAt.value?.let { link.holdLoggedOut(it) } ?: link.disconnect()}override suspend fun rename(deviceId: String, name: String?) {@@ -771,6 +792,8 @@ class AdbDeviceSource(context: Context) : DeviceSource {nickname = names[keys[id] ?: id],brand = stats?.brand ?: saved[id]?.lastKnown?.brand,lastKnown = saved[id]?.lastKnown,+ // Read after state: the link writes it first, so a fresh refusal never shows an old logout.+ loggedOutAt = link?.loggedOutAt?.value?.takeIf { state == AdbState.NOT_ALLOWED },)}diff --git a/app/src/main/java/app/tellyscope/data/DeviceSource.kt b/app/src/main/java/app/tellyscope/data/DeviceSource.ktindex b412614..df86787 100644--- a/app/src/main/java/app/tellyscope/data/DeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceSource.kt@@ -42,9 +42,15 @@ interface DeviceSource {/** Previously paired devices, including offline ones. */suspend fun known(): List<Device>- /** Try a known TV again after it stopped at "not allowed": the TV shows its Allow prompt. */+ /**+ * Try a known TV again after it stopped at "not allowed": the TV shows its Allow prompt. Clears+ * [Device.loggedOutAt]; a refusal now is a plain "not allowed", not another logout.+ */suspend fun reconnect(deviceId: String)+ /** Cancel on the Allow step: stops the attempt, and a TV that had logged this phone out goes back to that. */+ suspend fun cancelReconnect(deviceId: String)+/** The user's own name for a TV; blank goes back to the network name. Kept per [historyKey]. */suspend fun rename(deviceId: String, name: String?)diff --git a/app/src/main/java/app/tellyscope/data/DeviceStore.kt b/app/src/main/java/app/tellyscope/data/DeviceStore.ktindex 1e9929a..b768236 100644--- a/app/src/main/java/app/tellyscope/data/DeviceStore.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceStore.kt@@ -17,6 +17,8 @@ data class SavedDevice(val historyKey: String? = null,/** Cleared only by Forget, which drops the whole line. */val lastKnown: LastKnown? = null,+ /** Epoch millis the TV took this phone's key back; null while it hasn't, or once it lets it in again. */+ val loggedOutAt: Long? = null,)/**@@ -48,13 +50,14 @@ class DeviceStore(private val file: File) {clean(d.lastKnown?.manufacturer), clean(d.lastKnown?.brand), clean(d.lastKnown?.android),d.lastKnown?.softwareMonth?.toString().orEmpty(),d.lastKnown?.storageUsedGb?.toString().orEmpty(), d.lastKnown?.storageTotalGb?.toString().orEmpty(),+ d.loggedOutAt?.toString().orEmpty(),).joinToString("\t")private fun parse(line: String): SavedDevice? {val f = line.split('\t')- // 7 fields: written before the history key existed; 8 before the last-known facts.- if (f.size !in setOf(7, 8, 14) || f[0] != VERSION) return null- val lastKnown = if (f.size == 14 && f.subList(8, 14).any { it.isNotEmpty() }) {+ // 7 fields: written before the history key existed; 8 before the last-known facts; 14 before logout.+ if (f.size !in setOf(7, 8, 14, 15) || f[0] != VERSION) return null+ val lastKnown = if (f.size >= 14 && f.subList(8, 14).any { it.isNotEmpty() }) {LastKnown(manufacturer = f[8].ifEmpty { null },brand = f[9].ifEmpty { null },@@ -73,6 +76,7 @@ class DeviceStore(private val file: File) {lastSeen = f[6].toLongOrNull(),historyKey = f.getOrNull(7)?.ifEmpty { null },lastKnown = lastKnown,+ loggedOutAt = f.getOrNull(14)?.toLongOrNull(),)}diff --git a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.ktindex 4148083..575bfa4 100644--- a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt@@ -124,6 +124,7 @@ class FakeDeviceSource(}override suspend fun reconnect(deviceId: String) = Unit+ override suspend fun cancelReconnect(deviceId: String) = Unitoverride suspend fun rename(deviceId: String, name: String?) {remembered[deviceId]?.let { remembered[deviceId] = it.copy(nickname = name?.trim()?.ifEmpty { null }) }diff --git a/app/src/main/java/app/tellyscope/data/Model.kt b/app/src/main/java/app/tellyscope/data/Model.ktindex ced25e9..c0ce4b8 100644--- a/app/src/main/java/app/tellyscope/data/Model.kt+++ b/app/src/main/java/app/tellyscope/data/Model.kt@@ -51,6 +51,11 @@ data class Device(val brand: String? = null,/** What the TV last reported, kept until Forget; as of [lastSeen]. Null before it ever answered. */val lastKnown: LastKnown? = null,+ /**+ * Epoch millis the TV took back a key it had allowed: this phone is logged out and stops asking+ * (state stays [DeviceState.NotAllowed]). Null otherwise; cleared by a reconnect.+ */+ val loggedOutAt: Long? = null,)/**diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex b6f08d5..415ee3b 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -521,6 +521,14 @@ class TellyscopeViewModel(}}+ /** Cancel on the Allow step after Connect again: a logged-out TV shows its logout page again. */+ fun cancelReconnect(id: String) {+ viewModelScope.launch {+ source.cancelReconnect(id)+ refreshDevices()+ }+ }+fun rename(id: String, name: String?) {viewModelScope.launch {source.rename(id, name)diff --git a/app/src/test/java/app/tellyscope/DeviceStoreTest.kt b/app/src/test/java/app/tellyscope/DeviceStoreTest.ktindex 3d56e26..e205458 100644--- a/app/src/test/java/app/tellyscope/DeviceStoreTest.kt+++ b/app/src/test/java/app/tellyscope/DeviceStoreTest.kt@@ -57,11 +57,26 @@ class DeviceStoreTest {assertEquals(listOf(tv.copy(historyKey = "sn:XK03H1234")), DeviceStore(file).load())}+ @Test fun keepsTheLogout() {+ val file = tmp.root.resolve("devices.tsv")+ DeviceStore(file).save(listOf(tv.copy(loggedOutAt = 1_761_475_500_000), stick))+ assertEquals(listOf(tv.copy(loggedOutAt = 1_761_475_500_000), stick), DeviceStore(file).load())+ }++ @Test fun readsFilesFromBeforeTheLogout() {+ val file = tmp.root.resolve("devices.tsv")+ DeviceStore(file).save(listOf(tv))+ // The older format stopped at the last-known facts.+ file.writeText(file.readText().replace("\t\n", "\n"))+ assertEquals(14, file.readLines().single().split('\t').size)+ assertEquals(listOf(tv), DeviceStore(file).load())+ }+@Test fun readsFilesFromBeforeTheHistoryKey() {val file = tmp.root.resolve("devices.tsv")DeviceStore(file).save(listOf(tv))// The older format had no eighth field at all.- file.writeText(file.readText().replace("\t".repeat(7) + "\n", "\n"))+ file.writeText(file.readText().replace("\t".repeat(8) + "\n", "\n"))assertEquals(7, file.readLines().single().split('\t').size)assertEquals(listOf(tv), DeviceStore(file).load())}@@ -78,7 +93,7 @@ class DeviceStoreTest {val keyed = tv.copy(historyKey = "sn:XK03H1234")DeviceStore(file).save(listOf(keyed))// The older format stopped at the history key.- file.writeText(file.readText().replace("\t".repeat(6) + "\n", "\n"))+ file.writeText(file.readText().replace("\t".repeat(7) + "\n", "\n"))assertEquals(8, file.readLines().single().split('\t').size)assertEquals(listOf(keyed), DeviceStore(file).load())}