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.
Remember TVs across restarts; add Forget
jesse-agent-23292ef82f90389
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt b/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.ktindex 56c9ca8..a0ef5fe 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/DeviceLink.kt@@ -16,7 +16,8 @@ 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 keeps retrying instead, since a TV- * waking up can stall the handshake exactly like an unanswered prompt.+ * waking up can stall the handshake exactly like an unanswered prompt. [knownGood] marks a device+ * remembered from an earlier launch, which counts as online before.*/class DeviceLink(val host: String,@@ -25,6 +26,7 @@ class DeviceLink(private val retryEvery: Duration = 5.seconds,private val monitorFor: (AdbShell) -> MonitorSource = { DeviceMonitor(it) },private val open: suspend (String, Int) -> ConnectResult = { h, p -> Connector.connect(h, p) },+ private val knownGood: Boolean = false,) {private val _state = MutableStateFlow(DeviceState.FOUND)val state: StateFlow<DeviceState> = _state.asStateFlow()@@ -53,7 +55,7 @@ class DeviceLink(private suspend fun loop() {_state.value = _state.value.on(DeviceEvent.Connect)- var wasOnline = false+ var wasOnline = knownGoodwhile (true) {when (val r = open(host, port)) {is ConnectResult.NotAllowed -> if (!wasOnline) {diff --git a/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.ktindex 020a6f2..3044656 100644--- a/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt+++ b/adb/src/test/kotlin/app/tellyscope/adb/DeviceLinkTest.kt@@ -24,6 +24,16 @@ class DeviceLinkTest {assertEquals(1, calls)}+ @Test fun rememberedDeviceKeepsRetryingThroughNotAllowed() = runTest {+ // After an app restart the TV may still be waking up: a stalled handshake isn't a refusal.+ var calls = 0+ val link = DeviceLink("tv", 5555, backgroundScope, open = { _, _ -> calls++; ConnectResult.NotAllowed }, knownGood = true)+ link.connect(); runCurrent()+ advanceTimeBy(20_001)+ assertEquals(DeviceState.WAITING, link.state.value)+ assertTrue(calls >= 4)+ }+@Test fun dropsToOfflineThenReconnects() = runTest {val sessions = mutableListOf<FakeShell>()var reachable = truediff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 012c89c..55eacd9 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -93,6 +93,7 @@ dependencies {testImplementation(platform(libs.compose.bom))testImplementation(libs.compose.ui.test.junit4)testImplementation(libs.junit)+ testImplementation(libs.kotlinx.coroutines.test)testImplementation(libs.robolectric)testImplementation(libs.roborazzi)testImplementation(libs.roborazzi.compose)diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.ktindex f4793af..e008b86 100644--- a/app/src/main/java/app/tellyscope/MainActivity.kt+++ b/app/src/main/java/app/tellyscope/MainActivity.kt@@ -162,6 +162,7 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {cancel = vm::cancel,undo = vm::undo,reconnect = { state.selectedId?.let(vm::select) },+ forget = vm::forget,),)}diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex ab76678..bc38ca0 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -16,12 +16,16 @@ import app.tellyscope.adb.ProtectedReasonimport com.flyfishxu.kadb.exception.AdbPairAuthExceptionimport com.flyfishxu.kadb.mdns.KadbMdnsAndroidimport kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Jobimport kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.asyncimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.combineimport kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.flow.transformWhile+import kotlinx.coroutines.launchimport java.io.Fileimport java.net.Inet4Addressimport java.util.concurrent.ConcurrentHashMap@@ -40,6 +44,11 @@ class AdbDeviceSource(context: Context) : DeviceSource {private val scope = CoroutineScope(SupervisorJob())private val links = ConcurrentHashMap<String, DeviceLink>()private val hits = ConcurrentHashMap<String, ScanHit>()+ private val store = DeviceStore(File(appContext.filesDir, "devices.tsv"))+ private val saved = ConcurrentHashMap<String, SavedDevice>()+ /** Remembered TVs that haven't answered since launch: shown offline, not "connecting". */+ private val restoring = ConcurrentHashMap.newKeySet<String>()+ private val watchers = ConcurrentHashMap<String, Job>()/** Wireless debugging advertises pairing and connect on different ports. */private val pairingPorts = ConcurrentHashMap<String, Int>()private var historyId = 0L@@ -48,6 +57,61 @@ class AdbDeviceSource(context: Context) : DeviceSource {Connector.init(File(appContext.filesDir, "adbkey.pem"))}+ /** Remembered TVs reconnect in the background from launch; [known] waits for the file read. */+ private val restored = scope.async(Dispatchers.IO) {+ store.load().forEach { d ->+ saved[d.host] = d+ 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)+ }+ }++ /** 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) {+ var pending = first+ val link = DeviceLink(host, port, scope, knownGood = knownGood, open = { h, p ->+ pending?.also { pending = null } ?: Connector.connect(h, p)+ })+ links.put(host, link)?.disconnect()+ watchers.put(host, scope.launch {+ link.state.collect { st ->+ if (st == AdbState.ONLINE) restoring -= host+ if (st == AdbState.ONLINE || st == AdbState.OFFLINE) remember(host)+ }+ })?.cancel()+ link.connect()+ }++ private fun remember(host: String) {+ val link = links[host] ?: return+ val hit = hits[host] ?: return+ val old = saved[host]+ saved[host] = SavedDevice(+ host = host,+ port = link.port,+ kind = hit.kind,+ name = hit.hostname,+ model = link.stats.value?.model ?: old?.model,+ lastSeen = link.lastSeenMillis ?: old?.lastSeen ?: System.currentTimeMillis(),+ )+ persist()+ }++ /** Reads the map at write time, so whichever save runs last writes the newest list. */+ private fun persist() {+ scope.launch(Dispatchers.IO) { synchronized(store) { store.save(saved.values.sortedBy { it.host }) } }+ }++ override suspend fun forget(deviceId: String) {+ restored.await()+ watchers.remove(deviceId)?.cancel()+ links.remove(deviceId)?.disconnect()+ hits.remove(deviceId)+ restoring -= deviceId+ if (saved.remove(deviceId) != null) persist()+ }+/*** The subnet of the active network if it's Wi-Fi or Ethernet. On mobile data or a VPN there is* no sweep, so we never probe a carrier's or VPN's neighbours; mDNS and add-by-IP still work.@@ -66,7 +130,9 @@ class AdbDeviceSource(context: Context) : DeviceSource {}override fun scan(): Flow<ScanEvent> = flow {- LanScanner(KadbMdnsAndroid(appContext)).scan(lanHosts()).collect { h ->+ val hosts = lanHosts()+ if (hosts.isEmpty()) emit(ScanEvent.NoLan)+ LanScanner(KadbMdnsAndroid(appContext)).scan(hosts).collect { h ->if (h.kind == AdbHit.Kind.PAIRING) {pairingPorts[h.host] = h.portif (hits.containsKey(h.host)) return@collect@@ -87,13 +153,9 @@ class AdbDeviceSource(context: Context) : DeviceSource {override suspend fun connect(hit: ScanHit): ConnectResult = when (val r = Connector.connect(hit.ip, hit.port)) {is AdbConnectResult.Online -> {hits[hit.ip] = hit+ restoring -= hit.ip// Hand the open session to a link, which reconnects on its own from here on.- var first: AdbConnectResult? = r- val link = DeviceLink(hit.ip, hit.port, scope, open = { h, p ->- first?.also { first = null } ?: Connector.connect(h, p)- })- links.put(hit.ip, link)?.disconnect()- link.connect()+ link(hit.ip, hit.port, first = r, knownGood = false)ConnectResult.Online(device(hit.ip))}AdbConnectResult.NotAllowed -> ConnectResult.NotAllowed@@ -114,7 +176,10 @@ class AdbDeviceSource(context: Context) : DeviceSource {return connect(connectHit)}- override suspend fun known(): List<Device> = links.keys.map(::device)+ override suspend fun known(): List<Device> {+ restored.await()+ return links.keys.map(::device)+ }override fun live(deviceId: String): Flow<Snapshot> {val link = links[deviceId] ?: return flow {}@@ -201,10 +266,11 @@ class AdbDeviceSource(context: Context) : DeviceSource {private fun device(id: String): Device {val link = links[id]val stats = link?.stats?.value+ val state = link?.state?.valuereturn Device(id = id,hit = hits.getValue(id),- state = when (link?.state?.value) {+ state = if (id in restoring && state != AdbState.ONLINE) DeviceState.Offline else when (state) {AdbState.WAITING -> DeviceState.WaitingAdbState.ONLINE -> DeviceState.OnlineAdbState.OFFLINE -> DeviceState.Offline@@ -212,10 +278,10 @@ class AdbDeviceSource(context: Context) : DeviceSource {AdbState.NEEDS_PAIRING -> DeviceState.NeedsPairingAdbState.FOUND, null -> DeviceState.Found},- model = stats?.model,+ model = stats?.model ?: saved[id]?.model,manufacturer = stats?.manufacturer,android = stats?.androidVersion,- lastSeen = link?.lastSeenMillis,+ lastSeen = link?.lastSeenMillis ?: saved[id]?.lastSeen,)}diff --git a/app/src/main/java/app/tellyscope/data/DeviceSource.kt b/app/src/main/java/app/tellyscope/data/DeviceSource.ktindex 409b70e..e37b3ba 100644--- a/app/src/main/java/app/tellyscope/data/DeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceSource.kt@@ -23,6 +23,9 @@ interface DeviceSource {/** Previously paired devices, including offline ones. */suspend fun known(): List<Device>+ /** Stop reconnecting to a TV and drop it from the remembered list. */+ suspend fun forget(deviceId: String)+/** Fast-tier stats. Completes when the device goes offline. */fun live(deviceId: String): Flow<Snapshot>diff --git a/app/src/main/java/app/tellyscope/data/DeviceStore.kt b/app/src/main/java/app/tellyscope/data/DeviceStore.ktnew file mode 100644index 0000000..f84213c--- /dev/null+++ b/app/src/main/java/app/tellyscope/data/DeviceStore.kt@@ -0,0 +1,63 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope.data++import java.io.File++/** What Tellyscope remembers about a TV between launches. */+data class SavedDevice(+ val host: String,+ val port: Int,+ val kind: ScanKind,+ val name: String?,+ val model: String?,+ val lastSeen: Long?,+)++/**+ * Remembered TVs, one tab-separated line each. Plain text so it needs no library and a damaged+ * line costs one device, not the list. Writes go to a temp file and are renamed into place.+ */+class DeviceStore(private val file: File) {++ @Synchronized+ fun load(): List<SavedDevice> {+ if (!file.exists()) return emptyList()+ return file.readLines().mapNotNull(::parse)+ }++ @Synchronized+ fun save(devices: List<SavedDevice>) {+ file.parentFile?.mkdirs()+ val tmp = File(file.path + ".tmp")+ tmp.writeText(devices.joinToString("") { format(it) + "\n" })+ if (!tmp.renameTo(file)) {+ file.delete()+ tmp.renameTo(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(),+ ).joinToString("\t")++ private fun parse(line: String): SavedDevice? {+ val f = line.split('\t')+ if (f.size != 7 || f[0] != VERSION) return null+ return SavedDevice(+ host = f[1].ifEmpty { return null },+ port = f[2].toIntOrNull() ?: return null,+ kind = ScanKind.entries.firstOrNull { it.name == f[3] } ?: return null,+ name = f[4].ifEmpty { null },+ model = f[5].ifEmpty { null },+ lastSeen = f[6].toLongOrNull(),+ )+ }++ /** Names come from the network (mDNS, reverse DNS): keep them on one field. */+ private fun clean(s: String?) = s.orEmpty().replace(Regex("[\\t\\r\\n]"), " ")++ private companion object {+ const val VERSION = "v1"+ }+}diff --git a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.ktindex 785248f..2be2a6c 100644--- a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt@@ -77,21 +77,30 @@ class FakeDeviceSource(return ConnectResult.Online(device(hit))}- override suspend fun known(): List<Device> = listOf(- Device(- id = "192.168.1.64",- hit = ScanHit("192.168.1.64", 5555, ScanKind.Classic, "bedroom-firetv", "Amazon"),- state = DeviceState.Offline,- model = "Fire TV Stick 4K",- manufacturer = "Amazon",- android = "9",- lastSeen = clock() - 14 * 60_000,- ),- )+ /** Connected or remembered TVs, keyed by id; starts with one offline TV to show that state. */+ private val remembered = linkedMapOf<String, Device>().apply {+ listOf(+ Device(+ id = "192.168.1.64",+ hit = ScanHit("192.168.1.64", 5555, ScanKind.Classic, "bedroom-firetv", "Amazon"),+ state = DeviceState.Offline,+ model = "Fire TV Stick 4K",+ manufacturer = "Amazon",+ android = "9",+ lastSeen = clock() - 14 * 60_000,+ ),+ ).takeIf { scenario == Scenario.Normal }.orEmpty().forEach { put(it.id, it) }+ }++ override suspend fun known(): List<Device> = remembered.values.toList()++ override suspend fun forget(deviceId: String) {+ remembered.remove(deviceId)+ }private fun device(hit: ScanHit): Device {val (model, maker, android) = models[hit.maker] ?: Triple("Android TV box", hit.maker, "10")- return Device(hit.ip, hit, DeviceState.Online, model, maker, android, clock())+ return Device(hit.ip, hit, DeviceState.Online, model, maker, android, clock()).also { remembered[it.id] = it }}override fun live(deviceId: String): Flow<Snapshot> = flow {diff --git a/app/src/main/java/app/tellyscope/data/Model.kt b/app/src/main/java/app/tellyscope/data/Model.ktindex b9c53f1..9078e8d 100644--- a/app/src/main/java/app/tellyscope/data/Model.kt+++ b/app/src/main/java/app/tellyscope/data/Model.kt@@ -20,6 +20,8 @@ data class ScanProgress(val probed: Int, val total: Int, val subnet: String)sealed interface ScanEvent {data class Found(val hit: ScanHit) : ScanEventdata class Progress(val progress: ScanProgress) : ScanEvent+ /** Not on Wi-Fi or Ethernet: only TVs that announce themselves (or add-by-IP) can be found. */+ data object NoLan : ScanEventdata object Done : ScanEvent}diff --git a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt b/app/src/main/java/app/tellyscope/ui/DeviceScreen.ktindex ee46638..62d14f3 100644--- a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt+++ b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt@@ -27,8 +27,10 @@ import androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.Addimport androidx.compose.material.icons.filled.ArrowDropDownimport androidx.compose.material.icons.filled.Close+import androidx.compose.material.icons.filled.Deleteimport androidx.compose.material.icons.filled.KeyboardArrowDownimport androidx.compose.material.icons.filled.Search+import androidx.compose.material3.AlertDialogimport androidx.compose.material3.Buttonimport androidx.compose.material3.Cardimport androidx.compose.material3.CardDefaults@@ -86,6 +88,7 @@ data class DeviceActions(val cancel: () -> Unit = {},val undo: (HistoryEntry) -> Unit = {},val reconnect: () -> Unit = {},+ val forget: (String) -> Unit = {},)@OptIn(ExperimentalMaterial3Api::class)@@ -186,7 +189,9 @@ fun DeviceScreen(@Composableprivate fun DevicePicker(state: UiState, actions: DeviceActions) {var open by remember { mutableStateOf(false) }+ var forgetting by remember { mutableStateOf(false) }val device = state.selected ?: return+ if (forgetting) ForgetDialog(name(device), onForget = { forgetting = false; actions.forget(device.id) }, onDismiss = { forgetting = false })val offlineCount = state.devices.count { it.state != DeviceState.Online }Box {Row(@@ -195,7 +200,7 @@ private fun DevicePicker(state: UiState, actions: DeviceActions) {) {StateDot(device.state)Spacer(Modifier.width(8.dp))- Text(device.hit.hostname ?: device.model ?: device.hit.ip, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Text(name(device), maxLines = 1, overflow = TextOverflow.Ellipsis)Icon(Icons.Default.ArrowDropDown, contentDescription = "Switch TV")}DropdownMenu(open, onDismissRequest = { open = false }) {@@ -203,7 +208,7 @@ private fun DevicePicker(state: UiState, actions: DeviceActions) {.filter { state.showOffline || it.state == DeviceState.Online || it.id == state.selectedId }.forEach { d ->DropdownMenuItem(- text = { Text(d.hit.hostname ?: d.model ?: d.hit.ip) },+ text = { Text(name(d)) },leadingIcon = { StateDot(d.state) },trailingIcon = {if (d.state != DeviceState.Online) Text(@@ -225,10 +230,29 @@ private fun DevicePicker(state: UiState, actions: DeviceActions) {leadingIcon = { Icon(Icons.Default.Add, null) },onClick = { open = false; actions.addDevice() },)+ DropdownMenuItem(+ text = { Text("Forget this TV") },+ leadingIcon = { Icon(Icons.Default.Delete, null) },+ onClick = { open = false; forgetting = true },+ )}}}+private fun name(d: Device) = d.hit.hostname ?: d.model ?: d.hit.ip++/** Forgetting only touches this phone; the TV keeps its own list of allowed computers. */+@Composable+fun ForgetDialog(name: String, onForget: () -> Unit, onDismiss: () -> Unit) {+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text("Forget $name?") },+ text = { Text("Tellyscope stops reconnecting to it and removes it from this phone. Nothing on the TV changes. You can add it again from a scan.") },+ confirmButton = { Button(onClick = onForget) { Text("Forget") } },+ dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },+ )+}+@Composableprivate fun StateDot(state: DeviceState) {val c = when (state) {diff --git a/app/src/main/java/app/tellyscope/ui/ScanScreen.kt b/app/src/main/java/app/tellyscope/ui/ScanScreen.ktindex fdfbbaa..ee22c8f 100644--- a/app/src/main/java/app/tellyscope/ui/ScanScreen.kt+++ b/app/src/main/java/app/tellyscope/ui/ScanScreen.kt@@ -116,7 +116,7 @@ private fun ScanStatus(scan: ScanUi) {Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {if (scan.scanning) {Text(- "Looking for TVs on your Wi-Fi… ${p?.probed ?: 0}/${p?.total ?: 254}",+ "Looking for TVs${if (scan.noLan) "" else " on your Wi-Fi"}… ${p?.probed ?: 0}/${p?.total ?: 254}",style = MaterialTheme.typography.labelLarge,)LinearWavyProgressIndicator(@@ -126,10 +126,17 @@ private fun ScanStatus(scan: ScanUi) {} else {val n = scan.hits.sizeText(- if (n == 0) "No TVs found yet" else "Found $n ${if (n == 1) "TV" else "TVs"} on your Wi-Fi",+ if (n == 0) "No TVs found yet" else "Found $n ${if (n == 1) "TV" else "TVs"}${if (scan.noLan) "" else " on your Wi-Fi"}",style = MaterialTheme.typography.labelLarge,)}+ if (scan.noLan) {+ Text(+ "You're not on Wi-Fi, so only TVs that announce themselves show up. Join the TV's Wi-Fi, or add it by IP address.",+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }}}diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex 502e29b..6dd5d11 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -37,6 +37,8 @@ sealed interface RowState {data class ScanUi(val scanning: Boolean = false,val progress: ScanProgress? = null,+ /** Not on Wi-Fi or Ethernet, so there was no sweep. */+ val noLan: Boolean = false,val hits: List<ScanHit> = emptyList(),val rows: Map<String, RowState> = emptyMap(),)@@ -85,11 +87,18 @@ class TellyscopeViewModel(private var mediumJob: Job? = nullinit {- viewModelScope.launch { _state.update { it.copy(devices = source.known()) } }viewModelScope.launch {+ // Remembered TVs open straight to their page (offline until they answer).+ val known = source.known()+ _state.update { it.copy(devices = known) }+ if (_state.value.selectedId == null) known.firstOrNull()?.let { select(it.id) }+ }+ viewModelScope.launch {+ var tick = 0while (true) {delay(1_000)_state.update { it.copy(now = clock()) }+ if (++tick % 3 == 0) refreshDevices()}}rescan()@@ -98,7 +107,7 @@ class TellyscopeViewModel(fun rescan() {if (scanJob?.isActive == true) returnscanJob = viewModelScope.launch {- _state.update { it.copy(scan = it.scan.copy(scanning = true)) }+ _state.update { it.copy(scan = it.scan.copy(scanning = true, noLan = false)) }source.scan().collect { e ->when (e) {is ScanEvent.Progress -> _state.update { it.copy(scan = it.scan.copy(progress = e.progress)) }@@ -110,6 +119,7 @@ class TellyscopeViewModel(rows = s.scan.rows + (e.hit.ip to RowState.Found),))}+ ScanEvent.NoLan -> _state.update { it.copy(scan = it.scan.copy(noLan = true)) }ScanEvent.Done -> Unit}}@@ -205,6 +215,25 @@ class TellyscopeViewModel(}}+ /** Remembered TVs reconnect on their own; pick up their state and restart stats when one comes back. */+ private suspend fun refreshDevices() {+ val known = source.known()+ val before = _state.value.selected?.state+ _state.update { it.copy(devices = known) }+ val now = _state.value.selected ?: return+ if (now.state == DeviceState.Online && before != DeviceState.Online) select(now.id)+ }++ fun forget(id: String) {+ viewModelScope.launch {+ source.forget(id)+ val known = source.known()+ _state.update { it.copy(devices = known) }+ // Next TV, online ones first; none left means back to the scan screen.+ select((known.firstOrNull { it.state == DeviceState.Online } ?: known.firstOrNull())?.id)+ }+ }+fun showOffline(show: Boolean) = _state.update { it.copy(showOffline = show) }fun query(q: String) = _state.update { it.copy(query = q) }diff --git a/app/src/test/java/app/tellyscope/DeviceStoreTest.kt b/app/src/test/java/app/tellyscope/DeviceStoreTest.ktnew file mode 100644index 0000000..dad5e4b--- /dev/null+++ b/app/src/test/java/app/tellyscope/DeviceStoreTest.kt@@ -0,0 +1,51 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope++import app.tellyscope.data.DeviceStore+import app.tellyscope.data.SavedDevice+import app.tellyscope.data.ScanKind+import org.junit.Assert.assertEquals+import org.junit.Rule+import org.junit.Test+import org.junit.rules.TemporaryFolder++class DeviceStoreTest {+ @get:Rule val tmp = TemporaryFolder()++ private val tv = SavedDevice("192.168.1.23", 5555, ScanKind.Classic, "xgimi-projector", "XGIMI Horizon Pro", 1_760_000_000_000)+ private val stick = SavedDevice("192.168.1.57", 37211, ScanKind.Wireless, null, null, null)++ @Test fun missingFileIsEmpty() {+ assertEquals(emptyList<SavedDevice>(), DeviceStore(tmp.root.resolve("devices.tsv")).load())+ }++ @Test fun survivesARestart() {+ val file = tmp.root.resolve("devices.tsv")+ DeviceStore(file).save(listOf(tv, stick))+ // A new store on the same file is what the next launch sees.+ assertEquals(listOf(tv, stick), DeviceStore(file).load())+ }++ @Test fun saveReplacesTheList() {+ val store = DeviceStore(tmp.root.resolve("devices.tsv"))+ store.save(listOf(tv, stick))+ store.save(listOf(stick))+ assertEquals(listOf(stick), store.load())+ }++ @Test fun networkNamesCannotBreakTheFormat() {+ val store = DeviceStore(tmp.root.resolve("devices.tsv"))+ store.save(listOf(tv.copy(name = "living\troom\nTV")))+ assertEquals(listOf(tv.copy(name = "living room TV")), store.load())+ }++ @Test fun damagedLinesCostOnlyThemselves() {+ val file = tmp.root.resolve("devices.tsv")+ DeviceStore(file).save(listOf(tv))+ file.appendText("v1\tbroken\n")+ file.appendText("v9\t192.168.1.88\t5555\tClassic\t\t\t\n")+ file.appendText("v1\t192.168.1.88\tnot-a-port\tClassic\t\t\t\n")+ assertEquals(listOf(tv), DeviceStore(file).load())+ }+}diff --git a/app/src/test/java/app/tellyscope/RememberedDevicesTest.kt b/app/src/test/java/app/tellyscope/RememberedDevicesTest.ktnew file mode 100644index 0000000..5471c93--- /dev/null+++ b/app/src/test/java/app/tellyscope/RememberedDevicesTest.kt@@ -0,0 +1,58 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope++import androidx.lifecycle.viewModelScope+import app.tellyscope.data.DeviceState+import app.tellyscope.data.FakeDeviceSource+import app.tellyscope.ui.TellyscopeViewModel+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.cancel+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.assertNull+import org.junit.Before+import org.junit.Test++@OptIn(ExperimentalCoroutinesApi::class)+class RememberedDevicesTest {+ private val dispatcher = StandardTestDispatcher()+ private val test = TestScope(dispatcher)+ private lateinit var vm: TellyscopeViewModel++ @Before fun setUp() = Dispatchers.setMain(dispatcher)++ @After fun tearDown() {+ vm.viewModelScope.cancel()+ Dispatchers.resetMain()+ }++ @Test fun rememberedTvOpensOfflineThenForgetReturnsToScan() = with(test) {+ vm = TellyscopeViewModel(FakeDeviceSource(clock = { 0L }), clock = { 0L })+ runCurrent()+ // The fake remembers one TV that is off: the app opens on its page, not the scan.+ val tv = vm.state.value.selected!!+ assertEquals(DeviceState.Offline, tv.state)++ vm.forget(tv.id)+ runCurrent()+ assertNull(vm.state.value.selectedId)+ assertEquals(emptyList<String>(), vm.state.value.devices.map { it.id })+ // The periodic refresh must not bring it back.+ advanceTimeBy(10_000)+ assertEquals(emptyList<String>(), vm.state.value.devices.map { it.id })+ }++ @Test fun freshInstallStartsOnTheScan() = with(test) {+ vm = TellyscopeViewModel(FakeDeviceSource(FakeDeviceSource.Scenario.Empty, clock = { 0L }), clock = { 0L })+ runCurrent()+ assertNull(vm.state.value.selectedId)+ }+}diff --git a/app/src/test/java/app/tellyscope/ScreenshotTest.kt b/app/src/test/java/app/tellyscope/ScreenshotTest.ktindex 6f06425..e063a52 100644--- a/app/src/test/java/app/tellyscope/ScreenshotTest.kt+++ b/app/src/test/java/app/tellyscope/ScreenshotTest.kt@@ -16,6 +16,7 @@ import app.tellyscope.data.ScanProgressimport app.tellyscope.ui.DeviceActionsimport app.tellyscope.ui.DeviceScreenimport app.tellyscope.ui.DeviceUi+import app.tellyscope.ui.ForgetDialogimport app.tellyscope.ui.PermissionScreenimport app.tellyscope.ui.RowStateimport app.tellyscope.ui.ScanScreen@@ -139,4 +140,11 @@ class ScreenshotTest {@Test fun permission() = shot("08_permission") { PermissionScreen(denied = false, canAsk = true, {}, {}) }@Test fun permission_denied() = shot("08_permission_denied") { PermissionScreen(denied = true, canAsk = true, {}, {}) }++ @Test fun forget() = shot("09_forget") { ForgetDialog("xgimi-projector", {}, {}) }++ @Test fun scan_offWifi() = scan(+ ScanUi(scanning = false, noLan = true, hits = listOf(chromecast), rows = mapOf(chromecast.ip to RowState.Found)),+ name = "10_scan_off_wifi",+ )}