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.
Pause every TV and LAN read while the app is in the background
jesse-agent-232fdfeaf4cde0a
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt b/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.ktindex d30cece..8a9a7a6 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt@@ -92,6 +92,7 @@ class DeviceLink(private suspend fun loop() {while (true) {+ gate.awaitResumed()when (val r = open(host, port)) {is ConnectResult.NotAllowed -> {_loggedOutAt.value = if (allowedBefore) System.currentTimeMillis() else nulldiff --git a/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.kt b/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.ktindex d0234eb..7eaf6fb 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/DeviceMonitor.kt@@ -75,13 +75,16 @@ data class StatsProfile(val fastEvery: Duration, val processes: ProcessLevel, va/*** What the app tells one TV's stats loop. [during] pauses it while a change runs, so a slow read* never competes with `pm`, an install or a Home switch; [profile] is the open screen's refresh- * rates. Until a screen sets one, everything is read every 2 s.+ * rates. Until a screen sets one, everything is read every 2 s. [paused] is the app in the+ * background: no stats are read and a dropped link doesn't retry until it's false again.*/class StatsGate {private val running = MutableStateFlow(0)val profile = MutableStateFlow(StatsProfile.ADVANCED)+ val paused = MutableStateFlow(false)+val busy: Boolean get() = running.value > 0suspend fun <T> during(block: suspend () -> T): T {@@ -96,6 +99,10 @@ class StatsGate {internal suspend fun awaitIdle() {running.first { it == 0 }}++ internal suspend fun awaitResumed() {+ paused.first { !it }+ }}/**@@ -128,6 +135,11 @@ class DeviceMonitor(var prev: Fast? = nullwhile (true) {+ // Back from the background: CPU % and network speed start from fresh samples, not an average over the pause.+ if (gate.paused.value) {+ gate.awaitResumed()+ prev = null+ }val profile = gate.profile.value// Tiers are timed from the start of the round they ran in, so a 2 s tier runs every round.val started = clock.markNow()diff --git a/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.ktindex 7b33d25..899ded5 100644--- a/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt+++ b/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt@@ -60,6 +60,19 @@ class DeviceLinkTest {assertEquals(0, calls)}+ @Test fun pausedLinkDoesNotRetry() = runTest {+ var calls = 0+ val link = DeviceLink("tv", 5555, backgroundScope, open = { _, _ -> calls++; ConnectResult.Unreachable("asleep") })+ link.connect(); runCurrent()+ assertEquals(1, calls)+ link.gate.paused.value = true+ advanceTimeBy(10 * 60_000); runCurrent()+ assertEquals(1, calls)+ link.gate.paused.value = false+ runCurrent()+ assertEquals(2, calls)+ }+@Test fun dropsToOfflineThenReconnects() = runTest {val sessions = mutableListOf<FakeShell>()var reachable = truediff --git a/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.ktindex bcd448a..0bbd2a6 100644--- a/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.kt+++ b/adb/src/test/kotlin/app/tellyscope/adb/DeviceMonitorTest.kt@@ -145,6 +145,21 @@ class DeviceMonitorTest {assertTrue(readings.isNotEmpty())}+ @Test fun nothingIsReadWhilePaused() = runTest {+ var calls = 0+ val inner = device()+ val tv = AdbShell { cmd -> calls++; inner.shell(cmd) }+ val gate = StatsGate().apply { paused.value = true }+ val readings = mutableListOf<Stats>()+ backgroundScope.launch { DeviceMonitor(tv, gate = gate).stats().collect { readings += it } }+ advanceTimeBy(10 * 60_000); runCurrent()+ assertEquals(0, calls)+ gate.paused.value = false+ advanceTimeBy(5_000); runCurrent()+ assertTrue(calls > 0)+ assertTrue(readings.isNotEmpty())+ }+@Test fun aTvThatDiesMidChangeIsStillLost() = runTest {val gate = StatsGate()val ran = mutableListOf<String>()diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.ktindex 1dff39c..c9dd51a 100644--- a/app/src/main/java/app/tellyscope/MainActivity.kt+++ b/app/src/main/java/app/tellyscope/MainActivity.kt@@ -203,6 +203,9 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {// On every return to the app, not just a cold start; the check itself enforces the interval.LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { vm.checkForUpdate() }+ // In the background nothing reads the TVs or sweeps the LAN; back on screen, everything picks up again.+ LifecycleEventEffect(Lifecycle.Event.ON_STOP) { vm.pause() }+ LifecycleEventEffect(Lifecycle.Event.ON_START) { vm.resume() }Snackbars(snackbar, vm.done, vm.notice, vm::doneShown, vm::noticeShown) { vm.undo(it.entry, it.deviceId) }LoggedOutSnackbars(snackbar, { state.devices }, { state.selectedId }, onView = vm::select)diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex 48bc6cc..5bea30e 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -79,6 +79,8 @@ class AdbDeviceSource(context: Context) : DeviceSource {private val links = ConcurrentHashMap<String, DeviceLink>()/** The TV on screen and its screen's refresh rates; every other TV reads at [StatsProfile.OTHER]. */@Volatile private var statsFor: Pair<String, StatsProfile>? = null+ /** The app is in the background; see [pause]. */+ @Volatile private var paused = falseprivate val hits = ConcurrentHashMap<String, ScanHit>()private val store = DeviceStore(File(appContext.filesDir, "devices.tsv"))private val launchers by lazy { parseLaunchers(appContext.assets.open("launchers.json").bufferedReader().use { it.readText() }) }@@ -137,6 +139,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {pending?.also { pending = null } ?: Connector.connect(h, p)})link.gate.profile.value = statsFor?.takeIf { it.first == host }?.second ?: StatsProfile.OTHER+ link.gate.paused.value = pausedlinks.put(host, link)?.disconnect()watchers.put(host, scope.launch {// Save a fresh reading only when what's kept of it changed, not every 2 s.@@ -353,6 +356,11 @@ class AdbDeviceSource(context: Context) : DeviceSource {links.forEach { (host, link) -> link.gate.profile.value = if (host == deviceId) profile else StatsProfile.OTHER }}+ override fun pause(paused: Boolean) {+ this.paused = paused+ links.values.forEach { it.gate.paused.value = paused }+ }+/** Runs a change with that TV's stats paused, so a slow stats read can't compete with it or cut it off. */private suspend fun <T> busy(deviceId: String, block: suspend () -> T): T =links[deviceId]?.gate?.during(block) ?: block()diff --git a/app/src/main/java/app/tellyscope/data/DeviceSource.kt b/app/src/main/java/app/tellyscope/data/DeviceSource.ktindex 00ff155..9521699 100644--- a/app/src/main/java/app/tellyscope/data/DeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceSource.kt@@ -63,6 +63,12 @@ interface DeviceSource {/** Reads [deviceId] at its screen's [profile]; every other TV, or all of them for null, at the slowest. */fun showStats(deviceId: String?, profile: StatsProfile) {}+ /**+ * The app went to the background ([paused] true) or came back. While paused no TV's stats are+ * read and a dropped TV isn't retried; open connections stay, so a running copy or install goes on.+ */+ fun pause(paused: Boolean) {}+suspend fun apps(deviceId: String): List<AppInfo>suspend fun network(deviceId: String): NetworkInfodiff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex 1088f00..0170903 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -331,6 +331,12 @@ class TellyscopeViewModel(/** Watches the TV for a launcher's install from the Play Store. */private var launcherJob: Job? = nullprivate var updateJob: Job? = null+ /** The clock and the device refresh, every second. */+ private var tickJob: Job? = null+ /** In the background since [pause]; [resume] starts everything again. */+ private var paused = false+ /** The scan was running, or asked for, while in the background, so [resume] starts it. */+ private var scanOnResume = false/** The fingerprint the user waved away on the phone; its prompt stays hidden while the TV shows it. */private var dismissedRequest: String? = null@@ -342,14 +348,7 @@ class TellyscopeViewModel(_state.update { it.copy(devices = known, listSource = lists) }if (_state.value.selectedId == null) known.firstOrNull()?.let { select(it.id) }}- viewModelScope.launch {- var tick = 0- while (true) {- delay(1_000)- _state.update { it.copy(now = clock()) }- if (++tick % 3 == 0) refreshDevices()- }- }+ startTick()updates?.let { u ->viewModelScope.launch(Dispatchers.IO) { _state.update { it.copy(checkUpdates = u.enabled, alphaBuild = u.alpha) } }}@@ -375,7 +374,48 @@ class TellyscopeViewModel(}}+ private fun startTick() {+ tickJob = viewModelScope.launch {+ var tick = 0+ while (true) {+ delay(1_000)+ _state.update { it.copy(now = clock()) }+ if (++tick % 3 == 0) refreshDevices()+ }+ }+ }++ /**+ * The app went to the background: nothing reads the TVs or sweeps the LAN until [resume].+ * What the user started goes on: a copy, an install, an action, the Play Store wait, a removal.+ */+ fun pause() {+ if (paused) return+ paused = true+ tickJob?.cancel()+ scanOnResume = scanJob?.isActive == true+ scanJob?.cancel()+ stopWatching()+ source.pause(true)+ }++ /** Back in the foreground: the TVs are read again and the page on screen picks up where it was, dialogs and all. */+ fun resume() {+ if (!paused) return+ paused = false+ source.pause(false)+ startTick()+ if (scanOnResume) rescan()+ viewModelScope.launch {+ if (!refreshDevices()) _state.value.selected?.let(::watch)+ }+ }+fun rescan() {+ if (paused) {+ scanOnResume = true+ return+ }if (scanJob?.isActive == true) returnscanJob = viewModelScope.launch {// Empty scan with no TV open: the guide is on screen; keep looking so the user never has to@@ -472,12 +512,8 @@ class TellyscopeViewModel(fun showStats(profile: StatsProfile) = source.showStats(_state.value.selectedId, profile)fun select(id: String?) {- liveJob?.cancel()+ stopWatching()launcherJob?.cancel()- mediumJob?.cancel()- listsJob?.cancel()- requestJob?.cancel()- accessJob?.cancel()// A copy still running on this TV keeps its dialog, after a reconnect or a look at another TV.val transfer = id?.let(transfers::get)// A removal survives the reconnect it causes; the TV coming back reselects it.@@ -493,29 +529,44 @@ class TellyscopeViewModel(val hidden = source.launcherCardHidden(device.id)_state.update { if (it.selectedId == device.id) it.copy(device = it.device.copy(history = history, dock = dock, launcherCardHidden = hidden)) else it }}- if (device.state != DeviceState.Online) return+ watch(device)+ }++ /** Stops the reads of the TV on screen that [watch] started. */+ private fun stopWatching() {+ liveJob?.cancel()+ mediumJob?.cancel()+ listsJob?.cancel()+ requestJob?.cancel()+ accessJob?.cancel()+ }++ /** Reads the TV on screen while it's online: stats, apps, tweaks, files, lists, prompts, access. Not in the background. */+ private fun watch(device: Device) {+ if (paused || device.state != DeviceState.Online) return+ val id = device.idliveJob = viewModelScope.launch {- source.live(id!!).collect { snap ->+ source.live(id).collect { snap ->lastSnapshot[id] = snap_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!!) }- requestJob = viewModelScope.launch { watchRequests(id!!) }- accessJob = viewModelScope.launch { watchAccess(id!!) }+ listsJob = viewModelScope.launch { loadLists(id) }+ 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!!)+ val apps = source.apps(id)updateDevice(id) { it.copy(apps = apps) }pruneDock(id, apps)val tweaks = source.tweaks(id)updateDevice(id) { it.copy(tweaks = tweaks) }loadFiles()while (true) {- val net = source.network(id!!)+ val net = source.network(id)_state.update { it.copy(device = it.device.copy(network = net)) }delay(10_000)}@@ -527,13 +578,18 @@ class TellyscopeViewModel(}}- /** Remembered TVs reconnect on their own; pick up their state and restart stats when one comes back. */- private suspend fun refreshDevices() {+ /**+ * Remembered TVs reconnect on their own; pick up their state and restart stats when one comes back.+ * True when that reselected the TV on screen.+ */+ private suspend fun refreshDevices(): Boolean {val known = source.known()val before = _state.value.selected?.state_state.update { s -> s.copy(devices = known, restarting = restarts(s.restarting, known)) }- val now = _state.value.selected ?: return- if (now.state == DeviceState.Online && before != DeviceState.Online) select(now.id)+ val now = _state.value.selected ?: return false+ if (now.state != DeviceState.Online || before == DeviceState.Online) return false+ select(now.id)+ return true}/** Reconnect button: a TV stopped at "not allowed" asks again; an offline one restarts its stats. */diff --git a/app/src/test/java/app/tellyscope/PauseTest.kt b/app/src/test/java/app/tellyscope/PauseTest.ktnew file mode 100644index 0000000..23d123a--- /dev/null+++ b/app/src/test/java/app/tellyscope/PauseTest.kt@@ -0,0 +1,125 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope++import androidx.lifecycle.viewModelScope+import app.tellyscope.adb.ConnectionRequest+import app.tellyscope.data.AppInfo+import app.tellyscope.data.Device+import app.tellyscope.data.DeviceSource+import app.tellyscope.data.DeviceState+import app.tellyscope.data.FakeDeviceSource+import app.tellyscope.data.NetworkInfo+import app.tellyscope.data.ScanEvent+import app.tellyscope.data.ScanHit+import app.tellyscope.data.ScanKind+import app.tellyscope.data.Snapshot+import app.tellyscope.data.TvAccess+import app.tellyscope.ui.TellyscopeViewModel+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.emptyFlow+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.test.StandardTestDispatcher+import kotlinx.coroutines.test.TestScope+import kotlinx.coroutines.test.advanceTimeBy+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.runCurrent+import kotlinx.coroutines.test.setMain+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test++/** One TV, or none with [tvs] false; every read that would reach the TV or the LAN is counted by name. */+private class Counted(private val tvs: Boolean = true) : DeviceSource by FakeDeviceSource(FakeDeviceSource.Scenario.Empty, clock = { 0L }) {+ val reads = mutableListOf<String>()+ val paused = mutableListOf<Boolean>()++ override suspend fun known() = if (!tvs) emptyList() else listOf(+ Device("tv", ScanHit("tv", 5555, ScanKind.Classic, "tv", null), DeviceState.Online, null, null, null, 0L),+ ).also { reads += "known" }++ override fun live(deviceId: String) = emptyFlow<Snapshot>().also { reads += "live" }+ override suspend fun apps(deviceId: String) = emptyList<AppInfo>().also { reads += "apps" }+ override suspend fun network(deviceId: String) = NetworkInfo("wlan0", "192.0.2.5", null, null, null, null, emptyList(), emptyList()).also { reads += "network" }+ override suspend fun connectionRequest(deviceId: String): ConnectionRequest? = null.also { reads += "prompt" }+ override suspend fun access(deviceId: String) = TvAccess().also { reads += "access" }+ override fun scan() = flowOf<ScanEvent>(ScanEvent.Done).also { reads += "scan" }++ override fun pause(paused: Boolean) {+ this.paused += paused+ }+}++@OptIn(ExperimentalCoroutinesApi::class)+class PauseTest {+ private val dispatcher = StandardTestDispatcher()+ private val test = TestScope(dispatcher)+ private lateinit var vm: TellyscopeViewModel++ @Before fun setUp() = Dispatchers.setMain(dispatcher)++ @After fun tearDown() {+ if (::vm.isInitialized) vm.viewModelScope.cancel()+ Dispatchers.resetMain()+ }++ private fun open(tv: Counted) = with(test) {+ vm = TellyscopeViewModel(tv, clock = { 0L })+ advanceTimeBy(30_000)+ runCurrent()+ }++ @Test fun inTheBackgroundNothingReadsTheTv() = with(test) {+ val tv = Counted()+ open(tv)+ assertTrue(tv.reads.containsAll(listOf("apps", "network", "prompt", "access", "known")))+ vm.pause()+ runCurrent()+ tv.reads.clear()+ advanceTimeBy(10 * 60_000)+ runCurrent()+ assertEquals(emptyList<String>(), tv.reads)+ assertEquals(listOf(true), tv.paused)+ }++ @Test fun backOnScreenThePageReadsTheTvAgain() = with(test) {+ val tv = Counted()+ open(tv)+ vm.pause()+ runCurrent()+ tv.reads.clear()+ vm.resume()+ advanceTimeBy(1_000)+ runCurrent()+ assertTrue(tv.reads.containsAll(listOf("live", "apps", "network", "prompt", "access")))+ assertEquals(listOf(true, false), tv.paused)+ assertEquals("tv", vm.state.value.selectedId)+ }++ @Test fun startingTwiceStartsOnce() = with(test) {+ val tv = Counted()+ open(tv)+ vm.resume() // the first ON_START, with nothing paused+ runCurrent()+ assertEquals(emptyList<Boolean>(), tv.paused)+ }++ @Test fun theEmptyScanStopsInTheBackgroundAndStartsAgainAfter() = with(test) {+ val tv = Counted(tvs = false)+ open(tv)+ assertTrue("scan" in tv.reads) // no TV, nothing found: it keeps looking every 15 s+ vm.pause()+ runCurrent()+ tv.reads.clear()+ advanceTimeBy(5 * 60_000)+ runCurrent()+ assertEquals(emptyList<String>(), tv.reads)+ vm.resume()+ runCurrent()+ assertEquals(listOf("scan"), tv.reads)+ }+}