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.
Key history to the TV's serial; mark and report restores
jesse-agent-2325bd73dac64c3
diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex 899f831..8ba46e7 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -15,6 +15,7 @@ import app.tellyscope.adb.Protectedimport app.tellyscope.adb.ProtectedReasonimport com.flyfishxu.kadb.exception.AdbPairAuthExceptionimport com.flyfishxu.kadb.mdns.KadbMdnsAndroid+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Job@@ -49,6 +50,8 @@ class AdbDeviceSource(context: Context) : DeviceSource {/** Remembered TVs that haven't answered since launch: shown offline, not "connecting". */private val restoring = ConcurrentHashMap.newKeySet<String>()private val watchers = ConcurrentHashMap<String, Job>()+ /** Address → [historyKey], so history follows a TV across DHCP changes. */+ private val keys = ConcurrentHashMap<String, String>()/** Wireless debugging advertises pairing and connect on different ports. */private val pairingPorts = ConcurrentHashMap<String, Int>()private val book = HistoryBook(File(appContext.filesDir, "history.tsv"))@@ -61,6 +64,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {private val restored = scope.async(Dispatchers.IO) {store.load().forEach { d ->saved[d.host] = d+ d.historyKey?.let { keys[d.host] = it }hits[d.host] = ScanHit(d.host, d.port, d.kind, d.name, null)restoring += d.hostlink(d.host, d.port, first = null, knownGood = true)@@ -76,7 +80,11 @@ class AdbDeviceSource(context: Context) : DeviceSource {links.put(host, link)?.disconnect()watchers.put(host, scope.launch {link.state.collect { st ->- if (st == AdbState.ONLINE) restoring -= host+ if (st == AdbState.ONLINE) {+ restoring -= host+ // Read again on every connect: a new TV may have taken over a saved address.+ launch { readKey(host) }+ }if (st == AdbState.ONLINE || st == AdbState.OFFLINE) remember(host)}})?.cancel()@@ -94,6 +102,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {name = hit.hostname,model = link.stats.value?.model ?: old?.model,lastSeen = link.lastSeenMillis ?: old?.lastSeen ?: System.currentTimeMillis(),+ historyKey = keys[host] ?: old?.historyKey,)persist()}@@ -250,11 +259,12 @@ class AdbDeviceSource(context: Context) : DeviceSource {override suspend fun act(deviceId: String, action: Action, packageName: String, undoing: Long?): HistoryEntry {val shell = session(deviceId)// Before the first change on a TV, note what was already off: Restore must leave those alone.- if (!book.hasBaseline(deviceId)) book.setBaseline(deviceId, disabledPackages(deviceId))+ val key = key(deviceId)+ if (!book.hasBaseline(key)) book.setBaseline(key, disabledPackages(deviceId))val r = Actions(shell).run(AdbAction.valueOf(action.name.uppercase()), packageName)return when (r) {is ActionResult.Done -> book.record(- deviceId = deviceId,+ deviceId = key,at = System.currentTimeMillis(),action = action,packageName = packageName,@@ -267,12 +277,39 @@ class AdbDeviceSource(context: Context) : DeviceSource {}}- override suspend fun history(deviceId: String): List<HistoryEntry> = book.entries(deviceId)+ override suspend fun history(deviceId: String): List<HistoryEntry> = book.entries(key(deviceId))override suspend fun restoreAll(deviceId: String): List<HistoryEntry> {// Only what is still off now: the user may have turned some back on from the TV itself.val off = disabledPackages(deviceId)- return book.restorable(deviceId).filter { it in off }.map { act(deviceId, Action.Enable, it) }+ val key = key(deviceId)+ return restoreEach(book.restorable(key).filter { it in off }) { pkg ->+ act(deviceId, Action.Enable, pkg, undoing = book.openDisable(key, pkg))+ }+ }++ /**+ * The history key for a TV, read from it once connected and saved with it. Until it has+ * answered (offline since install) the address stands in, and that history moves over when+ * the key is learned.+ */+ private suspend fun key(deviceId: String): String = keys[deviceId] ?: readKey(deviceId)++ private suspend fun readKey(deviceId: String): String {+ val shell = links[deviceId]?.session ?: return keys[deviceId] ?: deviceId+ suspend fun prop(cmd: String) = shell.shell(cmd).takeIf { it.exitCode == 0 }?.output+ val key = try {+ historyKey(prop("getprop ro.serialno"), prop("settings get secure android_id"), deviceId)+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ return keys[deviceId] ?: deviceId+ }+ if (keys.put(deviceId, key) != key) {+ book.rekey(deviceId, key)+ remember(deviceId)+ }+ return key}private suspend fun disabledPackages(deviceId: String) =diff --git a/app/src/main/java/app/tellyscope/data/DeviceStore.kt b/app/src/main/java/app/tellyscope/data/DeviceStore.ktindex f84213c..ed485e2 100644--- a/app/src/main/java/app/tellyscope/data/DeviceStore.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceStore.kt@@ -12,6 +12,8 @@ data class SavedDevice(val name: String?,val model: String?,val lastSeen: Long?,+ /** [historyKey] once the TV has answered; null before that. */+ val historyKey: String? = null,)/**@@ -39,11 +41,13 @@ class DeviceStore(private val file: File) {private fun format(d: SavedDevice) = listOf(VERSION, d.host, d.port.toString(), d.kind.name, clean(d.name), clean(d.model), d.lastSeen?.toString().orEmpty(),+ clean(d.historyKey),).joinToString("\t")private fun parse(line: String): SavedDevice? {val f = line.split('\t')- if (f.size != 7 || f[0] != VERSION) return null+ // 7 fields: written before the history key existed.+ if (f.size !in 7..8 || f[0] != VERSION) return nullreturn SavedDevice(host = f[1].ifEmpty { return null },port = f[2].toIntOrNull() ?: return null,@@ -51,6 +55,7 @@ class DeviceStore(private val file: File) {name = f[4].ifEmpty { null },model = f[5].ifEmpty { null },lastSeen = f[6].toLongOrNull(),+ historyKey = f.getOrNull(7)?.ifEmpty { null },)}diff --git a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.ktindex e8658e7..71352d0 100644--- a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt@@ -186,7 +186,9 @@ class FakeDeviceSource(override suspend fun restoreAll(deviceId: String): List<HistoryEntry> {val off = appsFor(deviceId).filter { !it.enabled }.map { it.packageName }.toSet()- return book.restorable(deviceId).filter { it in off }.map { act(deviceId, Action.Enable, it) }+ return restoreEach(book.restorable(deviceId).filter { it in off }) { pkg ->+ act(deviceId, Action.Enable, pkg, undoing = book.openDisable(deviceId, pkg))+ }}private companion object {diff --git a/app/src/main/java/app/tellyscope/data/HistoryBook.kt b/app/src/main/java/app/tellyscope/data/HistoryBook.ktindex 3894e80..558ce95 100644--- a/app/src/main/java/app/tellyscope/data/HistoryBook.kt+++ b/app/src/main/java/app/tellyscope/data/HistoryBook.kt@@ -62,6 +62,25 @@ class HistoryBook(private val file: File? = null) {return leftDisabled(entries.filter { it.deviceId == deviceId }).filter { it !in before }}+ /** The newest disable of [packageName] that nothing has undone yet: what Restore reverses. */+ @Synchronized+ fun openDisable(deviceId: String, packageName: String): Long? = entries+ .filter { it.deviceId == deviceId && it.packageName == packageName && it.action == Action.Disable && it.undoneAt == null }+ .maxOfOrNull { it.id }++ /**+ * Moves history recorded under [from] (a TV's address, before its serial was known) to [to].+ * A baseline already under [to] wins: it was taken earlier, before any change.+ */+ @Synchronized+ fun rekey(from: String, to: String) {+ if (from == to) return+ var changed = false+ entries.replaceAll { if (it.deviceId == from) it.copy(deviceId = to).also { changed = true } else it }+ baselines.remove(from)?.let { old -> baselines.putIfAbsent(to, old); changed = true }+ if (changed) save()+ }+companion object {/** Packages whose last disable/enable in [history] was a disable. */fun leftDisabled(history: List<HistoryEntry>): List<String> =@@ -117,3 +136,38 @@ class HistoryBook(private val file: File? = null) {}private const val VERSION = "v1"++/**+ * Turns apps back on one at a time and stops at the first refusal, saying how far it got so the+ * user knows what already changed. [enable] records each step.+ */+suspend fun restoreEach(packages: List<String>, enable: suspend (String) -> HistoryEntry): List<HistoryEntry> {+ val done = mutableListOf<HistoryEntry>()+ for (pkg in packages) {+ try {+ done += enable(pkg)+ } catch (e: IllegalStateException) {+ val why = e.message ?: "the TV refused"+ throw IllegalStateException(+ if (done.isEmpty()) "couldn't turn apps back on: $why"+ else "turned ${done.size} ${if (done.size == 1) "app" else "apps"} back on, then stopped: $why",+ e,+ )+ }+ }+ return done+}++/**+ * Which TV a history belongs to, stable across DHCP changes: the serial number, or the Android ID+ * when the serial is missing or one of the placeholders cheap boxes ship; the address otherwise.+ */+fun historyKey(serial: String?, androidId: String?, address: String): String {+ val sn = serial?.trim().orEmpty()+ if (sn.isNotEmpty() && sn.lowercase() !in PLACEHOLDER_SERIALS) return "sn:$sn"+ val id = androidId?.trim().orEmpty()+ if (id.isNotEmpty() && id != "null" && id.any { it != '0' }) return "id:$id"+ return address+}++private val PLACEHOLDER_SERIALS = setOf("unknown", "0123456789abcdef", "0000000000000000", "123456789", "null")diff --git a/app/src/test/java/app/tellyscope/DeviceStoreTest.kt b/app/src/test/java/app/tellyscope/DeviceStoreTest.ktindex dad5e4b..0d24031 100644--- a/app/src/test/java/app/tellyscope/DeviceStoreTest.kt+++ b/app/src/test/java/app/tellyscope/DeviceStoreTest.kt@@ -48,4 +48,19 @@ class DeviceStoreTest {file.appendText("v1\t192.168.1.88\tnot-a-port\tClassic\t\t\t\n")assertEquals(listOf(tv), DeviceStore(file).load())}++ @Test fun keepsTheHistoryKey() {+ val file = tmp.root.resolve("devices.tsv")+ DeviceStore(file).save(listOf(tv.copy(historyKey = "sn:XK03H1234")))+ assertEquals(listOf(tv.copy(historyKey = "sn:XK03H1234")), 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\n", "\n"))+ assertEquals(7, file.readLines().single().split('\t').size)+ assertEquals(listOf(tv), DeviceStore(file).load())+ }}diff --git a/app/src/test/java/app/tellyscope/HistoryBookTest.kt b/app/src/test/java/app/tellyscope/HistoryBookTest.ktindex b5a3a0e..d1348bc 100644--- a/app/src/test/java/app/tellyscope/HistoryBookTest.kt+++ b/app/src/test/java/app/tellyscope/HistoryBookTest.kt@@ -5,6 +5,9 @@ package app.tellyscopeimport app.tellyscope.data.Actionimport app.tellyscope.data.FakeDeviceSourceimport app.tellyscope.data.HistoryBook+import app.tellyscope.data.HistoryEntry+import app.tellyscope.data.historyKey+import app.tellyscope.data.restoreEachimport kotlinx.coroutines.test.runTestimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalse@@ -86,4 +89,48 @@ class HistoryBookTest {assertFalse(apps.getValue("com.google.android.tvrecommendations").enabled)assertEquals(emptyList<String>(), source.restoreAll(id).map { it.packageName })}++ @Test fun historyFollowsTheSerialNotTheAddress() {+ assertEquals("sn:XK03H1234", historyKey(" XK03H1234\n", "a1b2", "tv-1"))+ // Placeholder serials some boxes ship would mix up every TV of that model.+ assertEquals("id:a1b2c3", historyKey("0123456789ABCDEF", "a1b2c3", "tv-1"))+ assertEquals("id:a1b2c3", historyKey("unknown", "a1b2c3\n", "tv-1"))+ assertEquals("tv-1", historyKey("", "0000000000000000", "tv-1"))+ assertEquals("tv-1", historyKey(null, null, "tv-1"))+ }++ @Test fun historyRecordedBeforeTheKeyMovesOverToIt() {+ val file = tmp.root.resolve("history.tsv")+ val book = HistoryBook(file)+ book.setBaseline(tv, setOf("com.old.off"))+ book.record(tv, 1, Action.Disable, "com.netflix.ninja", "Netflix", Action.Enable)+ book.rekey(tv, "sn:XK03H1234")++ val after = HistoryBook(file)+ assertEquals(emptyList<Any>(), after.entries(tv))+ assertEquals(listOf("com.netflix.ninja"), after.entries("sn:XK03H1234").map { it.packageName })+ assertEquals(listOf("com.netflix.ninja"), after.restorable("sn:XK03H1234"))+ assertFalse(after.hasBaseline(tv))+ }++ @Test fun restoreMarksTheDisablesItReversed() = runTest {+ val source = FakeDeviceSource()+ val id = source.known().first().id+ source.act(id, Action.Disable, "com.netflix.ninja")+ source.restoreAll(id)+ val disable = source.history(id).single { it.action == Action.Disable }+ // Already back on: no Undo left to offer.+ assertTrue(disable.undoneAt != null)+ }++ @Test fun aStoppedRestoreSaysHowFarItGot() = runTest {+ var calls = 0+ val e = runCatching {+ restoreEach(listOf("a", "b", "c")) { pkg ->+ if (++calls == 3) throw IllegalStateException("the TV refused")+ HistoryEntry(calls.toLong(), tv, 0, Action.Enable, pkg, pkg, Action.Disable, null)+ }+ }.exceptionOrNull()+ assertEquals("turned 2 apps back on, then stopped: the TV refused", e?.message)+ }}