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.
Read the app list once per TV open, in one shell line
jesse-agent-821155d5c032169
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/BatchedShell.kt b/adb/src/main/kotlin/app/tellyscope/adb/BatchedShell.ktnew file mode 100644index 0000000..4e69fdd--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/BatchedShell.kt@@ -0,0 +1,53 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++/**+ * Runs a set of commands as one shell line, then answers them from that read; any other command+ * goes to the TV. Each command keeps its own output and exit code. A line cut short leaves the+ * commands after the cut unanswered, so those run on their own when asked.+ */+class BatchedShell private constructor(+ private val shell: AdbShell,+ private val answers: Map<String, ShellResult>,+) : AdbShell {+ override suspend fun shell(command: String): ShellResult = answers[command] ?: shell.shell(command)++ companion object {+ /** Everything an app list reads through [Actions] and `pm`, in one round trip instead of up to ten. */+ suspend fun appList(shell: AdbShell) = of(+ shell,+ listOf(+ Commands.HOME_ACTIVITY,+ Commands.HOME_ACTIVITIES,+ Commands.SYSTEM_PACKAGES,+ "pm list packages -d",+ Commands.USER_PACKAGES,+ Commands.LAUNCHABLE,+ "${Commands.TV_LAUNCHABLE} 2>/dev/null",+ "pm list packages --show-versioncode",+ Commands.A11Y_SERVICES,+ Commands.A11Y_ON,+ ),+ )++ suspend fun of(shell: AdbShell, commands: List<String>): BatchedShell {+ val distinct = commands.distinct()+ // `{ }` keeps a command's own `;` and redirects inside its section.+ val line = distinct.joinToString("; ") { "{ $it; }; echo \"${Commands.SEP}$?\"" }+ return BatchedShell(shell, split(shell.shell(line).output, distinct))+ }++ internal fun split(output: String, commands: List<String>): Map<String, ShellResult> {+ val answers = mutableMapOf<String, ShellResult>()+ var from = 0+ for (command in commands) {+ val end = END.find(output, from) ?: break+ answers[command] = ShellResult(output.substring(from, end.range.first), end.groupValues[1].toInt())+ from = end.range.last + 1+ }+ return answers+ }++ private val END = Regex("${Regex.escape(Commands.SEP)}(\\d+)\\r?\\n?")+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/BatchedShellTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/BatchedShellTest.ktnew file mode 100644index 0000000..1396cd7--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/BatchedShellTest.kt@@ -0,0 +1,51 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.test.runTest+import org.junit.Assert.assertEquals+import org.junit.Test++class BatchedShellTest {+ private val sep = Commands.SEP++ @Test fun eachCommandGetsItsOwnOutputAndExitCode() {+ val answers = BatchedShell.split("package:a\npackage:b\n${sep}0\n${sep}0\nError\n${sep}255\n", listOf("one", "two", "three"))+ assertEquals(ShellResult("package:a\npackage:b\n", 0), answers["one"])+ assertEquals(ShellResult("", 0), answers["two"])+ assertEquals(ShellResult("Error\n", 255), answers["three"])+ }++ @Test fun aLineCutShortLeavesTheRestUnanswered() {+ val answers = BatchedShell.split("package:a\n${sep}0\npackage:", listOf("one", "two"))+ assertEquals(setOf("one"), answers.keys)+ }++ @Test fun oneRoundTripThenAnswersFromIt() = runTest {+ val tv = FakeShell()+ tv.answer = { if (it.startsWith("{ pm list packages -s; }")) ShellResult("package:sys\n${sep}0\npackage:off\n${sep}0\n", 0) else null }+ val shell = BatchedShell.of(tv, listOf("pm list packages -s", "pm list packages -d", "pm list packages -s"))+ assertEquals(1, tv.ran.size)+ assertEquals("{ pm list packages -s; }; echo \"${sep}$?\"; { pm list packages -d; }; echo \"${sep}$?\"", tv.ran.single())+ assertEquals("package:off\n", shell.shell("pm list packages -d").output)+ assertEquals(1, tv.ran.size)+ // Anything not in the batch still goes to the TV.+ shell.shell("pm list packages")+ assertEquals(listOf("pm list packages"), tv.ran.drop(1))+ }++ @Test fun theAppListsReadsAreOneLine() = runTest {+ val tv = FakeShell()+ tv.answer = { if (it.startsWith("{ ")) ShellResult("${sep}0\n".repeat(10), 0) else null }+ val shell = BatchedShell.appList(tv)+ Actions(shell).homePackages()+ Actions(shell).homeOptions()+ Actions(shell).launchable()+ Actions(shell).tvLaunchable()+ shell.shell(Commands.SYSTEM_PACKAGES)+ shell.shell("pm list packages -d")+ shell.shell(Commands.USER_PACKAGES)+ shell.shell("pm list packages --show-versioncode")+ Actions(shell).serviceOn("a/b")+ assertEquals(1, tv.ran.size)+ }+}diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex 5bea30e..2b3ad99 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -10,6 +10,7 @@ import android.net.NetworkCapabilitiesimport app.tellyscope.adb.Accessimport app.tellyscope.adb.ActionResultimport app.tellyscope.adb.ApkInfo+import app.tellyscope.adb.BatchedShellimport app.tellyscope.adb.Filesimport app.tellyscope.adb.HomeOptionsimport app.tellyscope.adb.HomeResult@@ -366,7 +367,8 @@ class AdbDeviceSource(context: Context) : DeviceSource {links[deviceId]?.gate?.during(block) ?: block()override suspend fun apps(deviceId: String): List<AppInfo> {- val shell = session(deviceId)+ val session = session(deviceId)+ val shell = BatchedShell.appList(session)val home = Actions(shell).homePackages()val homeOptions = Actions(shell).homeOptions()val system = Parsers.packages(shell.shell("pm list packages -s").output).map { it.name }.toSet()@@ -379,7 +381,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {val listed = Parsers.packages(shell.shell("pm list packages --show-versioncode").output).ifEmpty { Parsers.packages(shell.shell("pm list packages").output) }// Same key as history: a placeholder serial must not give two boxes one cache.- val names = appNames.names(key(deviceId), listed, LabelHelper(shell, helperDex)::describe)+ val names = appNames.names(key(deviceId), listed, LabelHelper(session, helperDex)::describe)val keep = keep[key(deviceId)].orEmpty()// On a launcher the user added, offer the way back to the one it replaced.val back = homeOptions?.current?.takeIf { it !in system }@@ -635,14 +637,14 @@ class AdbDeviceSource(context: Context) : DeviceSource {}}- override suspend fun suggestions(deviceId: String): Suggestions = try {+ override suspend fun suggestions(deviceId: String, apps: suspend () -> List<AppInfo>): Suggestions = try {val r = resolve(deviceId)when {r.index == null -> Suggestions.Unavailabler.match == ListMatch.None -> Suggestions.NoList(r.index.commit, r.index.devices)r.list == null -> Suggestions.Unavailableelse -> Suggestions.Ready(- r.index.commit, r.list, r.sdk, suggest(r.list, apps(deviceId), r.sdk), r.index.devices,+ r.index.commit, r.list, r.sdk, suggest(r.list, apps(), r.sdk), r.index.devices,byMaker = r.match is ListMatch.Maker,)}diff --git a/app/src/main/java/app/tellyscope/data/DeviceSource.kt b/app/src/main/java/app/tellyscope/data/DeviceSource.ktindex 9521699..df3f009 100644--- a/app/src/main/java/app/tellyscope/data/DeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceSource.kt@@ -127,9 +127,10 @@ interface DeviceSource {/*** What the TV's list from tellyscope-devices suggests turning off. Never throws; offline it- * uses the cached lists, or answers [Suggestions.Unavailable].+ * uses the cached lists, or answers [Suggestions.Unavailable]. [apps] is the TV's app list,+ * asked for only once a list is found.*/- suspend fun suggestions(deviceId: String): Suggestions+ suspend fun suggestions(deviceId: String, apps: suspend () -> List<AppInfo>): Suggestions/** "Pick your TV": use list [listId] for this TV from now on. */suspend fun pickList(deviceId: String, listId: String)diff --git a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.ktindex feeb61b..a5a67f0 100644--- a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt@@ -288,10 +288,10 @@ class FakeDeviceSource(TvFile("subtitles.srt", 61_000, clock() - 40 * 60_000L),)- override suspend fun suggestions(deviceId: String): Suggestions {+ override suspend fun suggestions(deviceId: String, apps: suspend () -> List<AppInfo>): Suggestions {delay(600)val all = listOf(ListEntry(fakeList.id, fakeList.name, null, fakeList.sdk, "devices/${fakeList.id}.json", "0".repeat(64)))- return Suggestions.Ready(null, fakeList, 30, suggest(fakeList, appsFor(deviceId), 30), all)+ return Suggestions.Ready(null, fakeList, 30, suggest(fakeList, apps(), 30), all)}override suspend fun pickList(deviceId: String, listId: String) = Unitdiff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex 0170903..11fbea8 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -50,6 +50,7 @@ import app.tellyscope.data.Updateimport app.tellyscope.data.FoldBookimport app.tellyscope.data.UpdateCheckimport kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Jobimport kotlinx.coroutines.delay@@ -551,17 +552,25 @@ class TellyscopeViewModel(_state.update { it.copy(device = it.device.copy(snapshot = snap)) }}}- // Its own job: the list download never holds up apps or stats.- listsJob = viewModelScope.launch { loadLists(id) }+ // One read of the app list per open: Apps and the TV's list both use it. The list+ // download runs in its own job, so it never holds up apps or stats.+ val apps = CompletableDeferred<List<AppInfo>>()+ listsJob = viewModelScope.launch { loadLists(id) { apps.await() } }requestJob = viewModelScope.launch { watchRequests(id) }accessJob = viewModelScope.launch { watchAccess(id) }mediumJob = viewModelScope.launch {// A TV that drops mid-read throws; the live flow ends and the offline card takes over.try {// Read first: update {} may run its block again, and must never call the TV.- val apps = source.apps(id)- updateDevice(id) { it.copy(apps = apps) }- pruneDock(id, apps)+ val read = try {+ source.apps(id)+ } catch (e: Exception) {+ apps.completeExceptionally(e)+ throw e+ }+ updateDevice(id) { it.copy(apps = read) }+ apps.complete(read)+ pruneDock(id, read)val tweaks = source.tweaks(id)updateDevice(id) { it.copy(tweaks = tweaks) }loadFiles()@@ -596,8 +605,8 @@ class TellyscopeViewModel(fun reconnect(id: String) {viewModelScope.launch {source.reconnect(id)- refreshDevices()- select(id)+ // A TV that came back is selected already; again would read it all twice.+ if (!refreshDevices() || _state.value.selectedId != id) select(id)}}@@ -1150,15 +1159,20 @@ class TellyscopeViewModel(}}- private suspend fun loadLists(id: String) {- val lists = source.suggestions(id)- // Once the list is known its keep entries show as protected.- val apps = if (lists is Suggestions.Ready) runCatching { source.apps(id) }.getOrNull() else null+ private suspend fun loadLists(id: String, apps: suspend () -> List<AppInfo>) {+ val lists = source.suggestions(id, apps)+ // Once the list is known its keep entries show as protected, without reading the TV again.+ val keep = (lists as? Suggestions.Ready)?.list?.keep.orEmpty()_state.update { s ->- if (s.selectedId != id) s else s.copy(device = s.device.copy(lists = lists, apps = apps ?: s.device.apps))+ if (s.selectedId != id) s+ else s.copy(device = s.device.copy(lists = lists, apps = s.device.apps.map { it.copy(listKeep = it.packageName in keep) }))}}+ /** The app list on screen, or a fresh read when there's none yet. */+ private suspend fun shownApps(id: String): List<AppInfo> =+ _state.value.takeIf { it.selectedId == id }?.device?.apps?.ifEmpty { null } ?: source.apps(id)+/*** Another device's "Allow debugging?" prompt, checked every few seconds while the TV's page* is open. A failed check just waits for the next one.@@ -1343,7 +1357,7 @@ class TellyscopeViewModel(listsJob?.cancel()listsJob = viewModelScope.launch {source.pickList(id, listId)- loadLists(id)+ loadLists(id) { shownApps(id) }}}@@ -1366,7 +1380,7 @@ class TellyscopeViewModel(val now = source.listSource()_state.update { it.copy(listSource = now, device = it.device.copy(lists = null)) }_notice.value = Copy.listSource(now)- if (id != null) loadLists(id)+ if (id != null) loadLists(id) { shownApps(id) }}}@@ -1432,7 +1446,7 @@ class TellyscopeViewModel(val apps = runCatching { source.apps(id) }.getOrNull()val history = source.history(id)updateDevice(id) { it.copy(apps = apps ?: it.apps, busy = null, history = history) }- loadLists(id)+ loadLists(id) { apps ?: source.apps(id) }}}diff --git a/app/src/test/java/app/tellyscope/LauncherFlowTest.kt b/app/src/test/java/app/tellyscope/LauncherFlowTest.ktindex aa8791a..1ac3850 100644--- a/app/src/test/java/app/tellyscope/LauncherFlowTest.kt+++ b/app/src/test/java/app/tellyscope/LauncherFlowTest.kt@@ -72,7 +72,7 @@ private class StoreTv : DeviceSource by FakeDeviceSource(FakeDeviceSource.Scenaroverride suspend fun known() = listOf(Device("tv", ScanHit("tv", 5555, ScanKind.Classic, "tv", null), DeviceState.Online, null, null, null, 0L))override fun live(deviceId: String): Flow<Snapshot> = emptyFlow()- override suspend fun suggestions(deviceId: String) = Suggestions.Unavailable+ override suspend fun suggestions(deviceId: String, apps: suspend () -> List<AppInfo>) = Suggestions.Unavailableoverride suspend fun history(deviceId: String) = emptyList<HistoryEntry>()override suspend fun apps(deviceId: String) = listOf(store, stock) +diff --git a/app/src/test/java/app/tellyscope/ResultsLandOnTheirTvTest.kt b/app/src/test/java/app/tellyscope/ResultsLandOnTheirTvTest.ktindex eb8aba9..72b9c31 100644--- a/app/src/test/java/app/tellyscope/ResultsLandOnTheirTvTest.kt+++ b/app/src/test/java/app/tellyscope/ResultsLandOnTheirTvTest.kt@@ -7,6 +7,7 @@ import app.tellyscope.adb.RemoteKeyimport app.tellyscope.data.Actionimport app.tellyscope.data.AppInfoimport app.tellyscope.data.Device+import app.tellyscope.data.DeviceListimport app.tellyscope.data.DeviceSourceimport app.tellyscope.data.DeviceStateimport app.tellyscope.data.FakeDeviceSource@@ -35,6 +36,7 @@ import org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertNull+import org.junit.Assert.assertTrueimport org.junit.Beforeimport org.junit.Test@@ -52,7 +54,14 @@ private class TwoTvs : DeviceSource by FakeDeviceSource(FakeDeviceSource.Scenarioverride fun live(deviceId: String): Flow<Snapshot> = emptyFlow()- override suspend fun suggestions(deviceId: String) = Suggestions.Unavailable+ /** Set: a list found for every TV, keeping these packages. */+ var listKeep: Set<String>? = null++ override suspend fun suggestions(deviceId: String, apps: suspend () -> List<AppInfo>): Suggestions {+ val keep = listKeep ?: return Suggestions.Unavailable+ apps()+ return Suggestions.Ready(null, DeviceList(deviceId, deviceId, null, null, keep, emptyList()), null, emptyList(), emptyList())+ }override suspend fun apps(deviceId: String): List<AppInfo> {appsCalls++@@ -97,6 +106,17 @@ class ResultsLandOnTheirTvTest {assertEquals(listOf("app-on-tv-a"), vm.state.value.device.apps?.map { it.packageName })}+ @Test fun theTvsListUsesTheSameAppRead() = with(test) {+ source.appsDelayMs = 3_000+ source.listKeep = setOf("app-on-tv-a")+ vm = TellyscopeViewModel(source, clock = { 0L })+ advanceTimeBy(20_000)+ assertEquals(1, source.appsCalls)+ assertTrue(vm.state.value.device.lists is Suggestions.Ready)+ // The keep mark comes from the list, not a second read of the TV.+ assertEquals(listOf(true), vm.state.value.device.apps?.map { it.listKeep })+ }+@Test fun resultForAnotherTvLeavesTheShownPageAlone() = with(test) {vm = TellyscopeViewModel(source, clock = { 0L })runCurrent()diff --git a/app/src/test/java/app/tellyscope/ScreenshotTest.kt b/app/src/test/java/app/tellyscope/ScreenshotTest.ktindex 0a443d6..5e866af 100644--- a/app/src/test/java/app/tellyscope/ScreenshotTest.kt+++ b/app/src/test/java/app/tellyscope/ScreenshotTest.kt@@ -242,7 +242,7 @@ class ScreenshotTest {/** The fake's list, among a few other models so "Which TV is this?" has a choice. */private suspend fun lists(id: String): Suggestions.Ready {- val ready = fake.suggestions(id) as Suggestions.Ready+ val ready = fake.suggestions(id) { fake.apps(id) } as Suggestions.Readyval others = listOf("XGIMI MoGo 2 projector", "XGIMI MoGo 3 Pro projector", "Philips 55OLED708","Sony Bravia (Google TV)", "TCL C-series", "Xiaomi Mi Box S",