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.
Warn when another computer has ADB access; list connected devices
jesse-agent-23294da6f68c52f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8543c97..777a600 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,8 @@ until this file has a section for its version.- **Fixed:** Apps show their real icon, not a banner strip or letter. [#136](../../pull/136)- **Improved:** The dock picker leaves out built-in phone-style apps like Camera. [#138](../../pull/138)+- **New:** See who has ADB access to your TV, and remove it in one tap. [#PR](../../pull/PR)+- **New:** Connected devices shows what's paired or plugged into the TV. [#PR](../../pull/PR)## 0.8.1 — 2026-10-25diff --git a/NOTICE b/NOTICEindex a509d80..129c269 100644--- a/NOTICE+++ b/NOTICE@@ -31,6 +31,11 @@ restart, waiting, can't-reach and dock menu icons those of "restart_alt","hourglass_top", "link_off", "swap_horiz" and "remove_circle_outline".Report a problem, Help add this TV and Add the rest use those of"bug_report", "add_to_queue" and "content_copy".+The access warning, Who has access and Remove all other access use those+of "shield", "gpp_good", "gpp_maybe", "lock_reset", "smartphone", "lan",+"laptop", "desktop_windows" and "help_outline"; the Connected devices card+those of "bluetooth", "headphones", "keyboard", "mouse", "sports_esports",+"usb", "speaker" and "settings_input_hdmi".--------------------------------------------------------------------------------Store badges in docs/badges/ (README only, not in the app)diff --git a/README.md b/README.mdindex 0a128c1..e90d1d6 100644--- a/README.md+++ b/README.md@@ -41,6 +41,14 @@ Debloat your Android TV, install apps, and browse and transfer files on it, all<td align="center"><sub>Set default launcher</sub></td><td align="center"><sub>Move your setup to a new TV (coming in 0.9)</sub></td></tr>+ <tr>+ <td><img src="docs/screenshots/access-warning.png" alt="The TV's page warns that another computer is connected, above Connected devices: the remote, headphones and keyboard"></td>+ <td><img src="docs/screenshots/who-has-access.png" alt="Who has access: this phone and one other address connected now, then every computer the TV allows, each with its fingerprint and when it was last seen"></td>+ </tr>+ <tr>+ <td align="center"><sub>Know when another computer connects</sub></td>+ <td align="center"><sub>See who has access, remove it in one tap</sub></td>+ </tr></table><sub>Rendered from the app's screenshot tests with sample data, except the 0.9 preview.</sub>@@ -82,6 +90,8 @@ Tellyscope is a phone app that talks to your Android TV, Google TV or Fire TV ov- **History.** Every change is listed with an Undo, and **Restore everything** turns back on what Tellyscope turned off. Undoing a **Turn on** asks first, since it disables the app again. History is kept per TV, across restarts.- **Install apps.** Pick an APK, several split APKs or an `.apks`/`.xapk`/`.apkm` bundle on your phone. Before installing, Tellyscope shows the app's name, version and size and says whether it's new, an update, a reinstall or an older version. It won't install an older version over a newer one unless you tick the box. If the TV refuses, you get the reason in plain words.- **TV tweaks.** **Block ads with Private DNS** sends the TV's address lookups to an ad-blocking DNS provider (AdGuard by default, or any other you type in). Tellyscope then checks the TV can still look addresses up, and puts the old setting back if not. It needs Android 9 or newer. **Faster animations** makes menus move at twice the speed. Both land in History with an Undo. **Clear caches** frees space by clearing every app's temporary files; app data and sign-ins stay. **Take screenshot** saves what the TV shows to your phone.+- **Who has access.** ADB lets any allowed computer do everything Tellyscope can, so the TV's page warns when a computer other than this phone is connected, with **It's mine** for your own. **Who has access** in the **⋮** menu lists who is connected now and every computer the TV allows, with its key fingerprint and roughly when it was last seen. The TV doesn't say which key is behind which connection, so Tellyscope never pairs them up. **Remove all other access** clears the TV's allowed list in one tap, then reconnects so the TV asks to allow this phone again; on TVs that won't take the request, it opens Developer options and walks you through **Revoke USB debugging authorisations**. It says "Only this phone has access" only after checking the TV again.+- **Connected devices.** The Overview lists what's paired with or plugged into the TV: Bluetooth remotes and headphones, USB keyboards and drives with their free space, HDMI-CEC devices such as a soundbar, and where the sound goes now.- **Connection requests.** When another device asks to debug the TV, Tellyscope shows the TV's "Allow debugging?" prompt on your phone, with the device's key fingerprint, so you can **Allow** or **Deny** it without the remote. **Always allow this device** appears when the TV's own prompt offers it.- **Files.** Send a file from your phone into the TV's Download or Movies folder, or save one from there to your phone. Two buttons under the TV pick the folder, and stay pinned under the bar as you scroll. An empty folder says so in the middle of the page. A file with the same name gets a " (1)" instead of being overwritten, and a cancelled copy leaves nothing half-written behind.- **Remote.** A D-pad and icon keys for Back, Home, Menu, mute and volume, laid out like Google TV's phone remote, plus typing on the TV. Each key gives a short tick; **Vibrate on key press** in Settings turns it off. The D-pad's centre pauses a playing video. **Add to dock** puts up to four of the TV's apps under the volume keys, each one tap from opening on the TV. Long-press one to change or remove it, or keep holding and move it to reorder. An app uninstalled from the TV leaves the dock by itself, and a snackbar says so. The restart button in the top bar asks first, then waits for the TV to come back: **Hide** keeps the wait in the top bar, and after a minute **Retry** waits another one.diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Access.kt b/adb/src/main/kotlin/app/tellyscope/adb/Access.ktnew file mode 100644index 0000000..8d3db87--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/Access.kt@@ -0,0 +1,147 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import java.net.InetAddress+import java.security.MessageDigest+import java.util.Base64++/**+ * A computer the TV allows to use ADB: a key from its allowed list. [name] is the comment adb+ * keeps after the key, like `alex@laptop`; null when there is none. [lastSeen] is the TV's own+ * `lastConnection`, epoch millis; it is rough (keys seen together share one time), never a session.+ */+data class AllowedKey(val fingerprint: String, val name: String?, val lastSeen: Long?)++/** One open ADB connection to the TV, by the address it comes from. Nothing ties it to a key. */+data class AdbClient(val address: String, val port: Int) {+ /** From the TV itself, like an ADB app running on it. */+ val loopback get() = address == "127.0.0.1" || address == "::1"+}++/**+ * Who can use ADB on the TV, and who is connected now. Both come from places the shell user may+ * read; `/data/misc/adb` itself is not one of them. Each read answers null when the TV won't say,+ * which the screens show as "can't check", never as nobody.+ */+class Access(private val shell: AdbShell) {++ /** The allowed computers, from `dumpsys adb` (Android 11+); null when the TV won't say. */+ suspend fun keys(): List<AllowedKey>? = keys(shell.shell("dumpsys adb").output)++ /**+ * Open connections to adbd: on 5555, [port] (the one Tellyscope uses) and the+ * wireless-debugging port when one is set. Null when the TV won't list them.+ */+ suspend fun clients(port: Int): List<AdbClient>? {+ val tls = shell.shell("getprop service.adb.tls.port").output.trim().toIntOrNull()+ val ports = setOfNotNull(CLASSIC_PORT, port, tls?.takeIf { it > 0 })+ return clients(shell.shell("cat /proc/net/tcp6 /proc/net/tcp 2>/dev/null").output, ports)+ }++ /**+ * The TV's own "Revoke USB debugging authorisations": IAdbManager.clearDebuggingKeys, which the+ * shell user may call. Every allowed computer goes, this phone too; open connections may stay+ * up until they reconnect. False when the TV refused the call, and without calling anything+ * on an Android whose transaction code isn't in [CLEAR_KEYS]: the manual guide covers those.+ */+ suspend fun revokeAll(): Boolean {+ val sdk = shell.shell("getprop ro.build.version.sdk").output.trim().toIntOrNull()+ val code = CLEAR_KEYS[sdk] ?: return false+ val r = shell.shell("service call adb $code 2>&1")+ return r.exitCode == 0 && r.output.contains("Parcel(00000000")+ }++ /** Opens Developer options on the TV, where "Revoke USB debugging authorisations" is. False when nothing opened. */+ suspend fun openDeveloperOptions(): Boolean {+ val r = shell.shell("am start -a android.settings.APPLICATION_DEVELOPMENT_SETTINGS 2>&1")+ return r.exitCode == 0 && "Error" !in r.output+ }++ companion object {+ const val CLASSIC_PORT = 5555++ /**+ * clearDebuggingKeys' binder transaction by API level: its 1-based place in IAdbManager.aidl,+ * read from each AOSP release branch (android11 to android16). A level not listed is never+ * called, since the same number may be another method there.+ */+ val CLEAR_KEYS = (30..36).associateWith { 3 }++ /** adb writes keys base64; the struct starts with its word count, 64, so every one begins `QAAAA`. */+ private val KEY = Regex("(QAAAA[A-Za-z0-9+/]+={0,2})(?:[ \\t]+([^\\r\\n\"]*))?")+ private val ADB_KEY_TAG = Regex("<adbKey\\b[^>]*>")+ private val ATTR = Regex("([\\w-]+)=\"([^\"]*)\"")+ /** Where the next field of `dumpsys adb` starts, so `user_keys` ends before it. */+ private val NEXT_FIELD = Regex("^\\s*(?:[a-z_]+=|[{}])", RegexOption.MULTILINE)++ /**+ * `dumpsys adb` prints the allowed-keys file as `user_keys`, and the key store as+ * `keystore` with a `lastConnection` per key. No `user_keys` under a readable debugging+ * manager means the file is gone, as after a revoke: nobody is allowed.+ */+ fun keys(dumpsys: String): List<AllowedKey>? {+ if ("debugging_manager" !in dumpsys) return null+ // The key store's entries are the key and its comment, with when it was last used.+ val stored = ADB_KEY_TAG.findAll(dumpsys).mapNotNull { tag ->+ val attrs = ATTR.findAll(tag.value).associate { it.groupValues[1] to xml(it.groupValues[2]) }+ attrs["key"]?.trim()?.let { it to attrs["lastConnection"]?.toLongOrNull()?.takeIf { t -> t > 0 } }+ }.toList()+ val listed = dumpsys.indexOf("user_keys=").takeIf { it >= 0 }?.let { start ->+ val from = start + "user_keys=".length+ val end = NEXT_FIELD.find(dumpsys, from)?.range?.first ?: dumpsys.length+ dumpsys.substring(from, end).lines().map { it.trim() }+ }.orEmpty()+ val stamps = stored.mapNotNull { (line, at) -> KEY.matchEntire(line)?.let { it.groupValues[1] to at } }.toMap()+ // The file's keys first, in its order, then any only the key store knows.+ return (listed + stored.map { it.first }).mapNotNull { line ->+ val m = KEY.matchEntire(line) ?: return@mapNotNull null+ val fp = fingerprint(m.groupValues[1]) ?: return@mapNotNull null+ AllowedKey(fp, m.groupValues[2].trim().takeIf { it.isNotEmpty() }, stamps[m.groupValues[1]])+ }.distinctBy { it.fingerprint }+ }++ /** The MD5 the TV's "Allow debugging?" prompt shows for a base64 adb key; null if it isn't one. */+ fun fingerprint(base64: String): String? = runCatching {+ MessageDigest.getInstance("MD5").digest(Base64.getDecoder().decode(base64)).joinToString(":") { "%02X".format(it) }+ }.getOrNull()++ /**+ * ESTABLISHED connections whose local port is one of [ports], from `/proc/net/tcp6` and+ * `/proc/net/tcp` together. IPv4 clients of an IPv6 socket show as `::ffff:` addresses+ * and come back as plain IPv4. Null when neither table was there to read.+ */+ fun clients(proc: String, ports: Set<Int>): List<AdbClient>? {+ if ("local_address" !in proc) return null+ return proc.lines().mapNotNull { line ->+ val cols = line.trim().split(Regex("\\s+"))+ if (cols.size < 4 || !cols[0].endsWith(":") || cols[3] != ESTABLISHED) return@mapNotNull null+ val (localPort, remote) = endpoint(cols[1])?.second to endpoint(cols[2])+ if (localPort !in ports || remote == null) return@mapNotNull null+ AdbClient(remote.first, remote.second)+ }.distinct()+ }++ private const val ESTABLISHED = "01"++ private fun endpoint(s: String): Pair<String, Int>? {+ val (hex, port) = s.split(':').takeIf { it.size == 2 } ?: return null+ return address(hex)?.let { it to (port.toIntOrNull(16) ?: return null) }+ }++ /**+ * A kernel socket address: 8 or 32 hex digits in 32-bit words, each in the CPU's+ * little-endian order. `::ffff:a.b.c.d` comes back as `a.b.c.d`.+ */+ fun address(hex: String): String? {+ if (hex.length != 8 && hex.length != 32) return null+ val bytes = runCatching {+ hex.chunked(8).flatMap { word -> word.chunked(2).map { it.toInt(16).toByte() }.reversed() }.toByteArray()+ }.getOrNull() ?: return null+ val mapped = bytes.size == 16 && bytes.take(10).all { it == 0.toByte() } && bytes[10] == 0xFF.toByte() && bytes[11] == 0xFF.toByte()+ val raw = if (mapped) bytes.copyOfRange(12, 16) else bytes+ return InetAddress.getByAddress(raw).hostAddress?.let { if (it == "0:0:0:0:0:0:0:1") "::1" else it }+ }++ private fun xml(s: String) = s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("&", "&")+ }+}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Peripherals.kt b/adb/src/main/kotlin/app/tellyscope/adb/Peripherals.ktnew file mode 100644index 0000000..bdea2d4--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/Peripherals.kt@@ -0,0 +1,178 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++/** Something plugged into or paired with the TV, for the Connected devices card. */+data class Peripheral(+ val name: String,+ val group: Group,+ val kind: Kind,+ /** In use now; false for a paired Bluetooth device that isn't connected. */+ val live: Boolean,+ /** What the TV says about it, already in the card's words: "USB", "Paired", "On". */+ val status: String,+ /** Free bytes on a USB drive when `df` answered; the card shows it in place of [status]. */+ val free: Long? = null,+) {+ enum class Group { Bluetooth, Input, Storage, Hdmi, Audio }+ enum class Kind { Remote, Headphones, Speaker, Keyboard, Mouse, Controller, Bluetooth, Usb, Hdmi, Sound }+}++/**+ * Reads the TV's Bluetooth, input, USB storage, HDMI-CEC and audio reports. Each source that+ * fails or prints nothing just adds nothing, since output differs from build to build. Built-in+ * inputs (the IR receiver, the TV's own keys) are left out: only external Bluetooth and USB count.+ */+class Peripherals(private val shell: AdbShell) {++ suspend fun read(): List<Peripheral> {+ suspend fun out(cmd: String) = runCatching { shell.shell(cmd).output }.getOrDefault("")+ val inputs = inputs(out("dumpsys input | sed -n '/Event Hub State/,/Input Reader State/p'"))+ val paired = bluetooth(out("dumpsys bluetooth_manager | sed -n '/Bonded devices:/,/^\\s*\$/p'"), inputs)+ // A Bluetooth device that is also an input is listed once, under Bluetooth.+ val btNames = paired.map { it.name }.toSet()+ val storage = volumes(out("sm list-volumes public")).map { (_, uuid) ->+ val label = uuid?.let { labels(out("dumpsys mount | grep -F 'fsUuid=$it'"))[it] }+ val free = uuid?.let { free(out("df -k /storage/$it")) }+ Peripheral(label ?: "USB drive", Peripheral.Group.Storage, Peripheral.Kind.Usb, true, "Connected", free)+ }+ return paired + inputs.filter { it.name !in btNames } + storage + hdmi(out("dumpsys hdmi_control")) + listOfNotNull(audio(out("dumpsys audio")))+ }++ companion object {+ private val BONDED = Regex("^\\s*[0-9A-Fa-fX]{2}(?::[0-9A-Fa-fX]{2}){5}\\s+\\[\\s*[\\w/?]+\\s*]\\s+(.+)$")++ /**+ * The "Bonded devices" block of `dumpsys bluetooth_manager`: `<address> [<type>] <name>`.+ * One that is also among [inputs] is connected now, and takes its kind from it.+ */+ fun bluetooth(dumpsys: String, inputs: List<Peripheral> = emptyList()): List<Peripheral> {+ val block = dumpsys.substringAfter("Bonded devices:", "").lineSequence().drop(1).takeWhile { it.isNotBlank() }+ return block.mapNotNull { BONDED.matchEntire(it)?.groupValues?.get(1)?.trim() }.filter { it.isNotEmpty() }.distinct().map { name ->+ val input = inputs.firstOrNull { it.name == name }+ Peripheral(+ name, Peripheral.Group.Bluetooth, input?.kind ?: guess(name),+ live = input != null,+ status = if (input != null) "Connected" else "Paired",+ )+ }.toList()+ }++ /** Names only go so far: these are the usual words in a Bluetooth device's name. */+ private fun guess(name: String): Peripheral.Kind {+ val n = name.lowercase()+ return when {+ Regex("\\b(remote|rc)\\b").containsMatchIn(n) -> Peripheral.Kind.Remote+ listOf("headphone", "buds", "airpods", "wh-", "wf-", "earphone").any { it in n } -> Peripheral.Kind.Headphones+ listOf("speaker", "soundbar", "sound bar", "beam").any { it in n } -> Peripheral.Kind.Speaker+ listOf("controller", "gamepad", "xbox", "dualshock", "dualsense").any { it in n } -> Peripheral.Kind.Controller+ "keyboard" in n -> Peripheral.Kind.Keyboard+ "mouse" in n -> Peripheral.Kind.Mouse+ else -> Peripheral.Kind.Bluetooth+ }+ }++ private val DEVICE = Regex("^\\s*-?\\d+: (.+)$")+ private val BUS = Regex("bus=0x([0-9a-fA-F]+)")++ /**+ * External input devices from `dumpsys input`'s Event Hub: Bluetooth (bus 5) or USB+ * (bus 3). `Classes:` is a hex mask before Android 12 and a list of names after; both work.+ */+ fun inputs(dumpsys: String): List<Peripheral> {+ val found = mutableListOf<Pair<String, Pair<String, Int?>>>()+ var name: String? = null+ var classes = ""+ var bus: Int? = null+ fun flush() { name?.let { found += it to (classes to bus) } }+ for (line in dumpsys.substringAfter("Devices:", "").lines()) {+ val header = DEVICE.matchEntire(line)+ when {+ header != null && line.indexOf(header.groupValues[1]) <= 12 -> { flush(); name = header.groupValues[1].trim(); classes = ""; bus = null }+ line.trim().startsWith("Classes:") -> classes = line.substringAfter("Classes:").trim()+ line.trim().startsWith("Identifier:") -> bus = BUS.find(line)?.groupValues?.get(1)?.toIntOrNull(16)+ }+ }+ flush()+ return found.mapNotNull { (n, info) ->+ val via = when (info.second) { BT_BUS -> "Bluetooth"; USB_BUS -> "USB"; else -> return@mapNotNull null }+ Triple(n, kind(info.first), via)+ }.groupBy { it.first }.map { (n, rows) ->+ // One remote shows up as several devices; the strongest kind wins.+ val best = rows.maxBy { it.second.ordinal }+ Peripheral(n, Peripheral.Group.Input, best.second.kind, true, best.third)+ }+ }++ private const val USB_BUS = 0x03+ private const val BT_BUS = 0x05++ /** Weakest first, so a remote that also says keyboard counts as a keyboard. */+ private enum class InputKind(val kind: Peripheral.Kind) { Remote(Peripheral.Kind.Remote), Mouse(Peripheral.Kind.Mouse), Keyboard(Peripheral.Kind.Keyboard), Controller(Peripheral.Kind.Controller) }++ private fun kind(classes: String): InputKind {+ val mask = Regex("0x([0-9a-fA-F]+)").find(classes)?.groupValues?.get(1)?.toLongOrNull(16)+ fun has(bit: Long, word: String) = (mask != null && mask and bit != 0L) || Regex("\\b$word\\b").containsMatchIn(classes)+ return when {+ has(0x40, "GAMEPAD") || has(0x100, "JOYSTICK") -> InputKind.Controller+ has(0x2, "ALPHAKEY") -> InputKind.Keyboard+ has(0x8, "CURSOR") -> InputKind.Mouse+ else -> InputKind.Remote+ }+ }++ /** `sm list-volumes public`: `public:8,1 mounted 1A2B-3C4D`. The mounted ones, with their filesystem UUID. */+ fun volumes(sm: String): List<Pair<String, String?>> = sm.lines().mapNotNull { line ->+ val cols = line.trim().split(Regex("\\s+"))+ if (cols.size < 2 || !cols[0].startsWith("public:") || cols[1] != "mounted") return@mapNotNull null+ cols[0] to cols.getOrNull(2)?.takeIf { it != "null" }+ }++ /** Drive labels by UUID from `dumpsys mount`'s VolumeInfo lines (`fsUuid=… fsLabel=…`). */+ fun labels(dumpsys: String): Map<String, String> = dumpsys.lines().mapNotNull { line ->+ val uuid = Regex("fsUuid=(\\S+)").find(line)?.groupValues?.get(1) ?: return@mapNotNull null+ val label = Regex("fsLabel=(.*?)(?:\\s+\\w+=|$)").find(line)?.groupValues?.get(1)?.trim()?.takeIf { it.isNotEmpty() && it != "null" } ?: return@mapNotNull null+ uuid to label+ }.toMap()++ /** Free bytes from `df -k <path>`'s one data row; null when it didn't answer. */+ fun free(df: String): Long? = df.lines().drop(1).firstNotNullOfOrNull { line ->+ line.trim().split(Regex("\\s+")).getOrNull(3)?.toLongOrNull()?.times(1024)+ }++ private val CEC = Regex("logical_address: 0x([0-9a-fA-F]+).*?device_type: (\\d+).*?display_name: (.*?) power_status: (\\d+)")++ /**+ * Other devices on HDMI-CEC from `dumpsys hdmi_control`, by their CEC name. The TV itself+ * (logical address 0) is left out. A power status of 0 is on.+ */+ fun hdmi(dumpsys: String): List<Peripheral> = CEC.findAll(dumpsys).mapNotNull { m ->+ val (addr, type, name, power) = m.destructured+ if (addr.toInt(16) == 0 || name.isBlank()) return@mapNotNull null+ Triple(addr, name.trim(), type.toInt() to (power == "0"))+ }.distinctBy { it.first }.map { (_, name, info) ->+ val (type, on) = info+ Peripheral(name, Peripheral.Group.Hdmi, if (type == AUDIO_SYSTEM) Peripheral.Kind.Speaker else Peripheral.Kind.Hdmi, on, if (on) "On" else "Standby")+ }.toList()++ private const val AUDIO_SYSTEM = 5++ /** Where the TV's sound goes now: the `Devices:` line under STREAM_MUSIC in `dumpsys audio`. */+ fun audio(dumpsys: String): Peripheral? {+ val music = dumpsys.substringAfter("- STREAM_MUSIC:", "").takeIf { it.isNotEmpty() } ?: return null+ val devices = Regex("Devices:\\s*(\\S[^\\r\\n]*)").find(music)?.groupValues?.get(1)?.trim() ?: return null+ val first = devices.split(Regex("[\\s,|]+")).firstOrNull { it.isNotBlank() } ?: return null+ val to = when {+ first == "speaker" -> "TV speakers"+ first.startsWith("hdmi_earc") -> "HDMI eARC"+ first.startsWith("hdmi_arc") -> "HDMI ARC"+ first.startsWith("hdmi") -> "HDMI"+ first.startsWith("bt_") || first.startsWith("ble_") -> "Bluetooth"+ first.startsWith("usb") -> "USB audio"+ first.startsWith("wired_") || first == "line" || first.startsWith("headphone") -> "Headphone jack"+ first == "spdif" -> "Optical"+ else -> first+ }+ return Peripheral("Sound output", Peripheral.Group.Audio, Peripheral.Kind.Sound, true, to)+ }+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/AccessTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/AccessTest.ktnew file mode 100644index 0000000..580a7bd--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/AccessTest.kt@@ -0,0 +1,140 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.test.runTest+import java.security.KeyPairGenerator+import java.security.MessageDigest+import java.security.interfaces.RSAPublicKey+import java.util.Base64+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class AccessTest {+ private fun key(): String {+ val pub = KeyPairGenerator.getInstance("RSA").apply { initialize(2048) }.generateKeyPair().public as RSAPublicKey+ return Base64.getEncoder().encodeToString(Connector.adbPublicKey(pub))+ }++ private val laptop = key()+ private val studio = key()+ private val phone = key()++ /** Android 11's `dumpsys adb`, trimmed to what [Access.keys] reads. */+ private fun dumpsys(userKeys: String?, keystore: String = "") = buildString {+ appendLine("ADB MANAGER STATE (dumpsys adb):")+ appendLine("{")+ appendLine(" debugging_manager={")+ appendLine(" connected_to_adb=true")+ appendLine(" last_key_received=$laptop")+ if (userKeys != null) appendLine(" user_keys=$userKeys")+ appendLine(" system_keys=")+ appendLine(" keystore=<?xml version='1.0' encoding='utf-8' standalone='yes' ?>")+ appendLine("<keyStore version=\"1\">")+ append(keystore)+ appendLine("</keyStore>")+ appendLine(" }")+ appendLine("}")+ }++ @Test fun readsTheAllowedListWithNamesAndLastSeen() {+ val out = dumpsys(+ userKeys = "$laptop alex@laptop\n$studio studio-pc\n$phone",+ keystore = "<adbKey key=\"$laptop alex@laptop\" lastConnection=\"1793000000000\" />\n" ++ "<adbKey key=\"$studio studio-pc\" lastConnection=\"0\" />\n",+ )+ val keys = Access.keys(out)!!+ assertEquals(listOf("alex@laptop", "studio-pc", null), keys.map { it.name })+ assertEquals(listOf(1793000000000L, null, null), keys.map { it.lastSeen })+ assertEquals(Access.fingerprint(laptop), keys[0].fingerprint)+ }++ @Test fun aKeyOnlyTheKeyStoreKnowsStillCounts() {+ val out = dumpsys(userKeys = laptop, keystore = "<adbKey key=\"$studio studio-pc & co\" lastConnection=\"5\" />\n")+ assertEquals(listOf(null, "studio-pc & co"), Access.keys(out)!!.map { it.name })+ }++ @Test fun afterARevokeNobodyIsAllowed() {+ assertEquals(emptyList(), Access.keys(dumpsys(userKeys = null)))+ assertEquals(emptyList(), Access.keys(dumpsys(userKeys = "")))+ }++ @Test fun deniedOrOldTvsCantSay() {+ assertNull(Access.keys("Permission Denial: can't dump adb from pid=1234"))+ assertNull(Access.keys(""))+ }++ @Test fun fingerprintIsWhatThisPhoneShows() {+ val pub = KeyPairGenerator.getInstance("RSA").apply { initialize(2048) }.generateKeyPair().public as RSAPublicKey+ val bytes = Connector.adbPublicKey(pub)+ val expected = MessageDigest.getInstance("MD5").digest(bytes).joinToString(":") { "%02X".format(it) }+ assertEquals(expected, Access.fingerprint(Base64.getEncoder().encodeToString(bytes)))+ assertNull(Access.fingerprint("not base64!"))+ }++ private val header = " sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode"++ @Test fun ipv4MappedClientsComeBackAsIpv4() {+ // 192.0.2.47:51234 into :5555, established; one listening socket; one on another port.+ val tcp6 = """+ $header+ 0: 00000000000000000000000000000000:15B3 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 2000 0 1+ 1: 0000000000000000FFFF00000A0200C0:15B3 0000000000000000FFFF00002F0200C0:C822 01 00000000:00000000 00:00000000 00000000 2000 0 2+ 2: 0000000000000000FFFF00000A0200C0:15B3 0000000000000000FFFF00002F0200C0:C823 01 00000000:00000000 00:00000000 00000000 2000 0 3+ 3: 0000000000000000FFFF00000A0200C0:1F90 0000000000000000FFFF0000330200C0:C824 01 00000000:00000000 00:00000000 00000000 1000 0 4+ """.trimIndent()+ assertEquals(+ listOf(AdbClient("192.0.2.47", 0xC822), AdbClient("192.0.2.47", 0xC823)),+ Access.clients(tcp6, setOf(5555)),+ )+ }++ @Test fun plainIpv4AndLoopback() {+ val tcp = """+ $header+ 0: 0A0200C0:15B3 0A0200C0:D000 01 00000000:00000000 00:00000000 00000000 2000 0 1+ 1: 0100007F:15B3 0100007F:D001 01 00000000:00000000 00:00000000 00000000 2000 0 2+ 2: 0A0200C0:15B3 0B0200C0:D002 06 00000000:00000000 00:00000000 00000000 2000 0 3+ """.trimIndent()+ val clients = Access.clients(tcp, setOf(5555))!!+ assertEquals(listOf("192.0.2.10", "127.0.0.1"), clients.map { it.address })+ assertTrue(clients[1].loopback)+ assertFalse(clients[0].loopback)+ }++ @Test fun ipv6LoopbackAndNative() {+ assertEquals("::1", Access.address("00000000000000000000000001000000"))+ assertEquals("2001:db8:0:0:0:0:0:1", Access.address("B80D01200000000000000000" + "01000000"))+ assertNull(Access.address("XYZ"))+ }++ @Test fun noOneConnectedIsEmptyNoTableIsNull() {+ assertEquals(emptyList(), Access.clients(header, setOf(5555)))+ assertNull(Access.clients("cat: /proc/net/tcp6: Permission denied", setOf(5555)))+ assertNull(Access.clients("", setOf(5555)))+ }++ @Test fun clientsAlsoWatchTheWirelessDebuggingPort() = runTest {+ val tcp = "$header\n 0: 0A0200C0:9C40 2F0200C0:D000 01 00000000:00000000 00:00000000 00000000 2000 0 1"+ val sh = FakeShell(mapOf("getprop service.adb.tls.port" to ok("40000\n"), "cat /proc/net" to ok(tcp)))+ assertEquals(listOf(AdbClient("192.0.2.47", 0xD000)), Access(sh).clients(5555))+ }++ private fun tv(sdk: String, call: ShellResult) = FakeShell(mapOf("getprop ro.build.version.sdk" to ok("$sdk\n"), "service call adb 3" to call))++ @Test fun revokeIsTheBinderCallAndChecksItsReply() = runTest {+ assertTrue(Access(tv("30", ok("Result: Parcel(00000000 '....')"))).revokeAll())+ assertFalse(Access(tv("30", ok("Result: Parcel(fffffffc ffffffff '........')"))).revokeAll())+ assertFalse(Access(tv("34", ShellResult("service: not found", 127))).revokeAll())+ }++ @Test fun anUnlistedAndroidIsNeverCalled() = runTest {+ for (sdk in listOf("29", "37", "")) {+ val sh = tv(sdk, ok("Result: Parcel(00000000 '....')"))+ assertFalse(Access(sh).revokeAll())+ assertFalse(sh.ran.any { it.startsWith("service call") }, sdk)+ }+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/PeripheralsTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/PeripheralsTest.ktnew file mode 100644index 0000000..47f8db2--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/PeripheralsTest.kt@@ -0,0 +1,121 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import app.tellyscope.adb.Peripheral.Group+import app.tellyscope.adb.Peripheral.Kind+import kotlinx.coroutines.test.runTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class PeripheralsTest {+ private val input11 = """+ Event Hub State:+ BuiltInKeyboardId: -2+ Devices:+ -1: Virtual+ Classes: 0x40000023+ Identifier: bus=0x0000, vendor=0x0000, product=0x0000, version=0x0000+ 3: sunxi-ir+ Classes: 0x00000001+ Identifier: bus=0x0019, vendor=0x0001, product=0x0001, version=0x0100+ 5: Xbox Wireless Controller+ Classes: 0x80000141+ Identifier: bus=0x0005, vendor=0x045e, product=0x0b13, version=0x0509+ 6: Logitech K400+ Classes: 0x80000003+ Identifier: bus=0x0003, vendor=0x046d, product=0x4024, version=0x0111+ 7: Logitech K400+ Classes: 0x80000008+ Identifier: bus=0x0003, vendor=0x046d, product=0x4024, version=0x0111+ Input Reader State:+ """.trimIndent()++ @Test fun externalInputsOnlyStrongestKindWins() {+ val got = Peripherals.inputs(input11)+ assertEquals(+ listOf(+ Peripheral("Xbox Wireless Controller", Group.Input, Kind.Controller, true, "Bluetooth"),+ Peripheral("Logitech K400", Group.Input, Kind.Keyboard, true, "USB"),+ ),+ got,+ )+ }++ @Test fun android12ClassNamesWork() {+ val out = """+ Event Hub State:+ Devices:+ 9: MX Master+ Classes: CURSOR | EXTERNAL+ Identifier: bus=0x0005, vendor=0x046d, product=0xb019, version=0x0002+ """.trimIndent()+ assertEquals(Kind.Mouse, Peripherals.inputs(out).single().kind)+ }++ private val bluetooth = """+ Bonded devices:+ AA:BB:CC:DD:EE:01 [ DUAL ] Xbox Wireless Controller+ AA:BB:CC:DD:EE:02 [BR/EDR] Sony WH-1000XM4+ XX:XX:XX:XX:EE:03 [ LE ] Remote Control 2.4G++ Connected profiles:+ """.trimIndent()++ @Test fun bondedDevicesConnectedWhenAlsoAnInput() {+ val got = Peripherals.bluetooth(bluetooth, Peripherals.inputs(input11))+ assertEquals(listOf("Xbox Wireless Controller", "Sony WH-1000XM4", "Remote Control 2.4G"), got.map { it.name })+ assertEquals(listOf(Kind.Controller, Kind.Headphones, Kind.Remote), got.map { it.kind })+ assertEquals(listOf("Connected", "Paired", "Paired"), got.map { it.status })+ assertEquals(listOf(true, false, false), got.map { it.live })+ }++ @Test fun noBluetoothNoRows() {+ assertEquals(emptyList(), Peripherals.bluetooth(""))+ assertEquals(emptyList(), Peripherals.bluetooth("Bluetooth Status\n enabled: false\n"))+ }++ @Test fun usbVolumesLabelsAndFreeSpace() {+ assertEquals(+ listOf("public:8,1" to "1A2B-3C4D", "public:8,17" to null),+ Peripherals.volumes("public:8,1 mounted 1A2B-3C4D\npublic:8,17 mounted null\npublic:8,33 unmounted 9999-0000\n"),+ )+ val mount = " VolumeInfo{public:8,1}:\n type=PUBLIC diskId=disk:8,0 partGuid=null mountFlags=VISIBLE \n fsType=vfat fsUuid=1A2B-3C4D fsLabel=Movies 2 internalPath=/mnt/media_rw/1A2B-3C4D"+ assertEquals(mapOf("1A2B-3C4D" to "Movies 2"), Peripherals.labels(mount))+ assertEquals(41L * 1024, Peripherals.free("Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/fuse 62000 21000 41 34% /storage/1A2B-3C4D\n"))+ assertNull(Peripherals.free("df: /storage/x: No such file or directory"))+ }++ @Test fun usbDriveFallsBackToPlainWords() = runTest {+ val sh = FakeShell(mapOf("sm list-volumes" to ok("public:8,1 mounted 1A2B-3C4D\n")))+ assertEquals(listOf(Peripheral("USB drive", Group.Storage, Kind.Usb, true, "Connected")), Peripherals(sh).read())+ }++ @Test fun hdmiCecSkipsTheTvItself() {+ val out = """+ mDeviceInfos:+ Device: logical_address: 0x00 device_type: 0 vendor_id: 0 display_name: TV power_status: 0 physical_address: 0x0000 port_id: 0+ Device: logical_address: 0x04 device_type: 4 vendor_id: 0 display_name: Chromecast power_status: 0 physical_address: 0x1000 port_id: 1+ Device: logical_address: 0x05 device_type: 5 vendor_id: 0 display_name: Sonos Beam power_status: 1 physical_address: 0x2000 port_id: 2+ """.trimIndent()+ assertEquals(+ listOf(+ Peripheral("Chromecast", Group.Hdmi, Kind.Hdmi, true, "On"),+ Peripheral("Sonos Beam", Group.Hdmi, Kind.Speaker, false, "Standby"),+ ),+ Peripherals.hdmi(out),+ )+ }++ @Test fun audioOutputFromStreamMusic() {+ val out = "- STREAM_RING:\n Devices: speaker\n- STREAM_MUSIC:\n Muted: false\n Devices: hdmi_arc\n- STREAM_ALARM:\n"+ assertEquals(Peripheral("Sound output", Group.Audio, Kind.Sound, true, "HDMI ARC"), Peripherals.audio(out))+ assertEquals("TV speakers", Peripherals.audio("- STREAM_MUSIC:\n Devices: speaker\n")?.status)+ assertNull(Peripherals.audio("Can't find service: audio"))+ }++ @Test fun aSourceThatFailsAddsNothing() = runTest {+ val sh = FakeShell(mapOf("dumpsys audio" to ok("- STREAM_MUSIC:\n Devices: speaker\n")))+ assertEquals(listOf("TV speakers"), Peripherals(sh).read().map { it.status })+ }+}diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.ktindex b90c0e3..ba11cda 100644--- a/app/src/main/java/app/tellyscope/MainActivity.kt+++ b/app/src/main/java/app/tellyscope/MainActivity.kt@@ -45,6 +45,8 @@ import app.tellyscope.data.FakeDeviceSourceimport app.tellyscope.data.FoldBookimport app.tellyscope.data.KeyHapticsimport app.tellyscope.data.UpdateCheck+import app.tellyscope.ui.AccessActions+import app.tellyscope.ui.AccessScreenimport app.tellyscope.ui.AdvancedScreenimport app.tellyscope.ui.Copyimport app.tellyscope.ui.DebloatScreen@@ -172,6 +174,7 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {var advanced by rememberSaveable { mutableStateOf(false) }var debloat by rememberSaveable { mutableStateOf(false) }var settings by rememberSaveable { mutableStateOf(false) }+ var access by rememberSaveable { mutableStateOf(false) }// "*/*": file managers label .apks and .xapk bundles inconsistently, so a narrower type would grey them out.val pickApp = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { vm.pickedApp(it) }@@ -189,7 +192,7 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {Snackbars(snackbar, vm.done, vm.notice, vm::doneShown, vm::noticeShown) { vm.undo(it.entry, it.deviceId) }// A newly connected TV becomes the selection; leave the add flow then, not on tap.- LaunchedEffect(state.selectedId) { adding = false; remote = false; advanced = false; debloat = false; settings = false }+ LaunchedEffect(state.selectedId) { adding = false; remote = false; advanced = false; debloat = false; settings = false; access = false }if (state.selected == null || adding) {BackHandler(enabled = adding) { adding = false }@@ -232,6 +235,10 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {onDispose { vm.showStats(StatsProfile.OTHER) }}AdvancedScreen(state, back = { advanced = false }, snackbar = snackbar)+ } else if (access || state.device.removal != null) {+ // A removal started from the warning opens this screen too, and back steps out of it first.+ BackHandler { if (state.device.removal != null) vm.closeRemoval() else access = false }+ AccessScreen(state, accessActions(vm) { access = false }, snackbar = snackbar)} else if (settings) {BackHandler { settings = false }SettingsScreen(@@ -303,6 +310,8 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {dismissRequest = vm::dismissRequest,foldSystem = vm::foldSystem,showStats = vm::showStats,+ whoHasAccess = { access = true },+ access = accessActions(vm) { access = false },),)}@@ -346,3 +355,15 @@ private fun Context.openWifiSettings() {runCatching { startActivity(Intent(panel)) }.recoverCatching { startActivity(Intent(Settings.ACTION_WIFI_SETTINGS)) }}++private fun accessActions(vm: TellyscopeViewModel, back: () -> Unit) = AccessActions(+ back = back,+ markMine = vm::markMine,+ askRemove = vm::askRemoveAccess,+ close = vm::closeRemoval,+ remove = vm::removeAccess,+ openDeveloperOptions = vm::openDeveloperOptions,+ revokedByHand = vm::revokedByHand,+ askAgain = vm::askTvAgain,+ retry = vm::retryRemoval,+)diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex 34824ca..3bf59f3 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -7,6 +7,7 @@ import android.net.ConnectivityManagerimport android.net.LinkPropertiesimport android.net.Networkimport android.net.NetworkCapabilities+import app.tellyscope.adb.Accessimport app.tellyscope.adb.ActionResultimport app.tellyscope.adb.ApkInfoimport app.tellyscope.adb.Files@@ -28,6 +29,7 @@ import app.tellyscope.adb.LabelHelperimport app.tellyscope.adb.LanScannerimport app.tellyscope.adb.NetworkStatsimport app.tellyscope.adb.Parsers+import app.tellyscope.adb.Peripheralsimport app.tellyscope.adb.Protectedimport app.tellyscope.adb.ProtectedReasonimport app.tellyscope.adb.Remote@@ -59,6 +61,7 @@ import okio.Sinkimport okio.Sourceimport java.io.Fileimport java.net.Inet4Address+import java.net.NetworkInterfaceimport java.util.concurrent.ConcurrentHashMapimport app.tellyscope.adb.Action as AdbActionimport app.tellyscope.adb.ConnectResult as AdbConnectResult@@ -93,6 +96,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {private val book = HistoryBook(File(appContext.filesDir, "history.tsv"))private val names = NameBook(File(appContext.filesDir, "names.tsv"))private val docks = DockBook(File(appContext.filesDir, "docks.tsv"))+ private val mine = MineBook(File(appContext.filesDir, "mine.tsv"))/** Last label seen per package, so history entries read like the app list. */private val labels = ConcurrentHashMap<String, String>()/** The remote's key helper on each TV, while the remote is open. */@@ -660,6 +664,33 @@ class AdbDeviceSource(context: Context) : DeviceSource {override suspend fun facts(deviceId: String) = TvFacts.read(session(deviceId))+ override suspend fun access(deviceId: String): TvAccess {+ val a = Access(session(deviceId))+ val port = links[deviceId]?.port ?: Access.CLASSIC_PORT+ return TvAccess.of(a.clients(port), a.keys(), phoneAddresses(), deviceId, mine[key(deviceId)], phoneFingerprint())+ }++ override suspend fun markMine(deviceId: String, address: String) {+ restored.await()+ mine.add(key(deviceId), address)+ }++ override suspend fun peripherals(deviceId: String) = Peripherals(session(deviceId)).read()++ override suspend fun revokeAll(deviceId: String) = Access(session(deviceId)).revokeAll()++ override suspend fun openDeveloperOptions(deviceId: String) = Access(session(deviceId)).openDeveloperOptions()++ @Volatile private var fingerprint: String? = null++ override fun phoneFingerprint(): String? = fingerprint ?: Connector.fingerprint().also { fingerprint = it }++ /** Every address this phone has now, so its own connection to the TV is recognised. */+ private fun phoneAddresses(): Set<String> = runCatching {+ NetworkInterface.getNetworkInterfaces().toList().flatMap { it.inetAddresses.toList() }+ .mapNotNull { it.hostAddress?.substringBefore('%') }.toSet()+ }.getOrDefault(emptySet())+/*** 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@@ -681,6 +712,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {book.rekey(deviceId, key)names.rekey(deviceId, key)docks.rekey(deviceId, key)+ mine.rekey(deviceId, key)remember(deviceId)}return keydiff --git a/app/src/main/java/app/tellyscope/data/DeviceSource.kt b/app/src/main/java/app/tellyscope/data/DeviceSource.ktindex 6eda182..697de0c 100644--- a/app/src/main/java/app/tellyscope/data/DeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceSource.kt@@ -7,6 +7,7 @@ import app.tellyscope.adb.ApkInfoimport app.tellyscope.adb.ConnectionRequestimport app.tellyscope.adb.InstallResultimport app.tellyscope.adb.InstalledVersion+import app.tellyscope.adb.Peripheralimport app.tellyscope.adb.Progressimport app.tellyscope.adb.RemoteKeyimport app.tellyscope.adb.TvFacts@@ -160,4 +161,25 @@ interface DeviceSource {/** What a report says about the TV: model, Android, the apps it came with. Throws if it's gone. */suspend fun facts(deviceId: String): TvFacts++ /** Who may use ADB on the TV and who is connected now. Throws if it's gone. */+ suspend fun access(deviceId: String): TvAccess = TvAccess()++ /** "It's mine": connections from [address] stop counting toward the warning on this TV. */+ suspend fun markMine(deviceId: String, address: String) {}++ /** Bluetooth, input, USB storage, HDMI-CEC and audio, for the Connected devices card. */+ suspend fun peripherals(deviceId: String): List<Peripheral> = emptyList()++ /**+ * Clears every allowed key on the TV, this phone's too. False when the TV refused, or its+ * Android isn't one the call is known for: the manual guide takes over.+ */+ suspend fun revokeAll(deviceId: String): Boolean = false++ /** Opens Developer options on the TV, for the manual guide. False when nothing opened. */+ suspend fun openDeveloperOptions(deviceId: String): Boolean = false++ /** This phone's key as the TV's Allow prompt shows it. */+ fun phoneFingerprint(): String? = null}diff --git a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.ktindex 66b3198..8e138c5 100644--- a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt@@ -2,10 +2,13 @@package app.tellyscope.data+import app.tellyscope.adb.AdbClient+import app.tellyscope.adb.AllowedKeyimport app.tellyscope.adb.ApkInfoimport app.tellyscope.adb.ConnectionRequestimport app.tellyscope.adb.InstallResultimport app.tellyscope.adb.InstalledVersion+import app.tellyscope.adb.Peripheralimport app.tellyscope.adb.Progressimport app.tellyscope.adb.RemoteKeyimport app.tellyscope.adb.TvFacts@@ -366,12 +369,54 @@ class FakeDeviceSource(override suspend fun answerRequest(deviceId: String, request: ConnectionRequest, allow: Boolean, always: Boolean) = false+ /** Addresses marked "It's mine", and TVs whose access was cleared, so the demo flow ends on Done. */+ private val mine = mutableSetOf<String>()+ private val revoked = mutableSetOf<String>()++ override suspend fun access(deviceId: String): TvAccess {+ val clients = listOf(AdbClient(PHONE, 40112)) ++ if (deviceId in revoked) emptyList() else listOf(AdbClient(OTHER, 51234), AdbClient(OTHER, 51240))+ val keys = listOf(AllowedKey(PHONE_FINGERPRINT, "tellyscope@phone", clock() - 60_000)) + if (deviceId in revoked) emptyList() else listOf(+ AllowedKey("9B:21:6E:F0:3A:7C:11:58:D4:02:BE:93:6F:A1:C8:E5", "alex@laptop", clock() - 2 * 3_600_000),+ AllowedKey("C4:0E:63:19:B2:7D:45:E8:0A:91:3C:F6:28:D7:A2:5B", "studio-pc", clock() - 3 * 86_400_000),+ AllowedKey("71:D5:08:AE:42:9F:C3:16:7B:E0:54:2A:D9:83:3C:E9", null, null),+ )+ return TvAccess.of(clients, keys, setOf(PHONE), deviceId, mine, PHONE_FINGERPRINT)+ }++ override suspend fun markMine(deviceId: String, address: String) {+ mine += address+ }++ override suspend fun peripherals(deviceId: String) = listOf(+ Peripheral("XGIMI remote", Peripheral.Group.Bluetooth, Peripheral.Kind.Remote, true, "Connected"),+ Peripheral("Sony WH-1000XM4", Peripheral.Group.Bluetooth, Peripheral.Kind.Headphones, false, "Paired"),+ Peripheral("Logitech K400", Peripheral.Group.Input, Peripheral.Kind.Keyboard, true, "USB"),+ Peripheral("SanDisk 64 GB", Peripheral.Group.Storage, Peripheral.Kind.Usb, true, "Connected", free = 41L shl 30),+ Peripheral("Sonos Beam", Peripheral.Group.Hdmi, Peripheral.Kind.Speaker, true, "On"),+ Peripheral("Sound output", Peripheral.Group.Audio, Peripheral.Kind.Sound, true, "HDMI ARC"),+ )++ override suspend fun revokeAll(deviceId: String): Boolean {+ delay(600)+ revoked += deviceId+ return true+ }++ override suspend fun openDeveloperOptions(deviceId: String) = true++ override fun phoneFingerprint() = PHONE_FINGERPRINT+override suspend fun facts(deviceId: String) = TvFacts(manufacturer = "XGIMI", model = "Horizon Pro", device = "XK03H", androidVersion = "11", sdk = 30,build = "RTT1.230922.001", stockPackages = fakeStock, userApps = 7, identifiers = emptySet(),)private companion object {+ const val PHONE = "192.0.2.10"+ const val OTHER = "192.0.2.47"+ const val PHONE_FINGERPRINT = "3F:9A:1C:5D:E0:42:B7:19:8C:6A:F3:21:0D:94:7E:C2"+/** Enough stock apps that a cleanyourtv report spills into "Add the rest". */val fakeStock = listOf("com.google.android.youtube.tv", "com.netflix.ninja", "com.amazon.amazonvideo.livingroom", "com.xgimi.ota",diff --git a/app/src/main/java/app/tellyscope/data/TvAccess.kt b/app/src/main/java/app/tellyscope/data/TvAccess.ktnew file mode 100644index 0000000..b3597e0--- /dev/null+++ b/app/src/main/java/app/tellyscope/data/TvAccess.kt@@ -0,0 +1,111 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope.data++import app.tellyscope.adb.AdbClient+import app.tellyscope.adb.AllowedKey+import java.io.File++/**+ * Who can use ADB on a TV ([allowed]) and who is connected now ([connected]). Either is null+ * when the TV wouldn't say, which reads as "can't check", never as nobody. The two lists are+ * never tied together: the TV doesn't say which key is behind which connection.+ */+data class TvAccess(+ val connected: List<AccessClient>? = null,+ val allowed: List<AccessKey>? = null,+) {+ /** Connections the warning is about: neither this phone nor an address the user said is theirs. */+ val others: List<AccessClient> get() = connected.orEmpty().filter { it.who == AccessClient.Who.Other || it.who == AccessClient.Who.OnTv }++ val warning: Boolean get() = others.isNotEmpty()++ /** Checked, not assumed: both lists read, no other connection, and no allowed key but this phone's. */+ val onlyThisPhone: Boolean get() = connected != null && allowed != null && others.isEmpty() && allowed.none { !it.phone }++ companion object {+ /**+ * Sorts the TV's open connections into this phone, the user's own and the rest. A+ * loopback connection is this phone only when Tellyscope itself reaches the TV over+ * loopback ([tvHost], as through an emulator's forward); otherwise it is an app on the TV.+ */+ fun of(+ clients: List<AdbClient>?,+ keys: List<AllowedKey>?,+ phoneAddresses: Set<String>,+ tvHost: String,+ mine: Set<String>,+ phoneFingerprint: String?,+ ): TvAccess {+ val tvLoopback = tvHost == "localhost" || AdbClient(tvHost, 0).loopback+ val connected = clients?.groupBy { it.address }?.map { (address, rows) ->+ val loopback = rows.first().loopback+ val phone = if (loopback) tvLoopback else address in phoneAddresses+ val who = when {+ phone -> AccessClient.Who.Phone+ address in mine -> AccessClient.Who.Mine+ loopback -> AccessClient.Who.OnTv+ else -> AccessClient.Who.Other+ }+ AccessClient(address, rows.size, who)+ }?.sortedBy { it.who.ordinal }+ val allowed = keys?.map { AccessKey(it.fingerprint, it.name, it.lastSeen, phone = it.fingerprint == phoneFingerprint) }+ ?.sortedByDescending { it.phone }+ return TvAccess(connected, allowed)+ }+ }+}++data class AccessClient(val address: String, val connections: Int, val who: Who) {+ enum class Who { Phone, Mine, Other, OnTv }+}++/** An allowed computer. [lastSeen] is rough: the TV stamps keys, not sessions. */+data class AccessKey(val fingerprint: String, val name: String?, val lastSeen: Long?, val phone: Boolean = false)++/**+ * Addresses the user marked "It's mine" on each TV, keyed like [NameBook]. `key \t address` per+ * line; null file keeps it in memory (tests, the fake source).+ */+class MineBook(private val file: File? = null) {+ private val mine = linkedMapOf<String, Set<String>>()++ init {+ file?.takeIf { it.exists() }?.let { f ->+ runCatching { f.readLines() }.getOrDefault(emptyList()).forEach { line ->+ val (k, a) = line.split('\t').takeIf { it.size == 2 && it.none(String::isBlank) } ?: return@forEach+ mine[k] = mine[k].orEmpty() + a+ }+ }+ }++ @Synchronized+ operator fun get(key: String): Set<String> = mine[key].orEmpty()++ @Synchronized+ fun add(key: String, address: String) {+ val clean = address.trim().takeIf { it.isNotEmpty() && '\t' !in it && '\n' !in it } ?: return+ mine[key] = mine[key].orEmpty() + clean+ save()+ }++ /** The address stood in until the TV said who it is; the marks move to the real key. */+ @Synchronized+ fun rekey(from: String, to: String) {+ if (from == to) return+ val moved = mine.remove(from) ?: return+ mine[to] = mine[to].orEmpty() + moved+ save()+ }++ private fun save() {+ val f = file ?: return+ f.parentFile?.mkdirs()+ val tmp = File(f.path + ".tmp")+ tmp.writeText(mine.entries.joinToString("") { (k, set) -> set.joinToString("") { "$k\t$it\n" } })+ if (!tmp.renameTo(f)) {+ f.delete()+ tmp.renameTo(f)+ }+ }+}diff --git a/app/src/main/java/app/tellyscope/ui/AccessUi.kt b/app/src/main/java/app/tellyscope/ui/AccessUi.ktnew file mode 100644index 0000000..3cd8c72--- /dev/null+++ b/app/src/main/java/app/tellyscope/ui/AccessUi.kt@@ -0,0 +1,589 @@+// SPDX-License-Identifier: GPL-3.0-only+// Icons here use Material Icons path data (Apache-2.0), see NOTICE.++package app.tellyscope.ui++import androidx.compose.animation.animateContentSize+import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ExperimentalLayoutApi+import androidx.compose.foundation.layout.FlowRow+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyListScope+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.filled.ArrowBack+import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight+import androidx.compose.material.icons.filled.KeyboardArrowDown+import androidx.compose.material.icons.filled.KeyboardArrowUp+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.Button+import androidx.compose.material3.ButtonDefaults+import androidx.compose.material3.Card+import androidx.compose.material3.CardDefaults+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi+import androidx.compose.material3.FilledTonalButton+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.LoadingIndicator+import androidx.compose.material3.MaterialShapes+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedButton+import androidx.compose.material3.Scaffold+import androidx.compose.material3.SnackbarHost+import androidx.compose.material3.SnackbarHostState+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.material3.TopAppBar+import androidx.compose.material3.toShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.PathFillType+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.graphics.vector.PathParser+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.text.SpanStyle+import androidx.compose.ui.text.buildAnnotatedString+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.text.withStyle+import androidx.compose.ui.unit.dp+import app.tellyscope.adb.Peripheral+import app.tellyscope.data.AccessClient+import app.tellyscope.data.AccessKey+import app.tellyscope.data.DeviceState+import app.tellyscope.data.TvAccess++/** What the Who has access screen and the warning can do. */+data class AccessActions(+ val back: () -> Unit = {},+ val markMine: (String) -> Unit = {},+ val askRemove: () -> Unit = {},+ val close: () -> Unit = {},+ val remove: () -> Unit = {},+ val openDeveloperOptions: () -> Unit = {},+ val revokedByHand: () -> Unit = {},+ val askAgain: () -> Unit = {},+ val retry: () -> Unit = {},+)++internal object AccessIcons {+ val Shield = icon("Shield", "M12 1 3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4z")+ val ShieldOk = icon("ShieldOk", "M12 2 4 5v6.09c0 5.05 3.41 9.76 8 10.91 4.59-1.15 8-5.86 8-10.91V5l-8-3zM10.94 15.54 7.4 12l1.41-1.41 2.12 2.12 4.24-4.24 1.41 1.41-5.64 5.66z")+ val ShieldNote = icon("ShieldNote", "M12 2 4 5v6.09c0 5.05 3.41 9.76 8 10.91 4.59-1.15 8-5.86 8-10.91V5l-8-3zM13 16h-2v-2h2v2zM13 12h-2V7h2v5z")+ val LockReset = icon(+ "LockReset",+ "M13 3a9 9 0 0 0-9 9H1l4 4 4-4H6c0-3.86 3.14-7 7-7s7 3.14 7 7-3.14 7-7 7c-1.9 0-3.62-.76-4.88-1.99L6.7 18.42A8.982 8.982 0 0 0 13 21a9 9 0 0 0 0-18z" ++ "M15 11v-1c0-1.1-.9-2-2-2s-2 .9-2 2v1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1h4c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1z" ++ "M14 11h-2v-1c0-.55.45-1 1-1s1 .45 1 1v1z",+ )+ val Phone = icon("Phone", "M17 1.01 7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z")+ val Lan = icon("Lan", "M13 22h8v-7h-3v-4h-5V9h3V2H8v7h3v2H6v4H3v7h8v-7H8v-2h8v2h-3z")+ val Laptop = icon("Laptop", "M20 18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2h-4zM4 6h16v10H4V6z")+ val Desktop = icon("Desktop", "M20 3H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h6v2H8v2h8v-2h-2v-2h6c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM20 15H4V5h16v10z")+ val Unknown = icon(+ "Unknown",+ "M11 18h2v-2h-2v2zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM12 20c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" ++ "M12 6c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z",+ )+ val Bluetooth = icon("Bluetooth", "M17.71 7.71 12 2h-1v7.59L6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 5.83l1.88 1.88L13 9.59V5.83zM14.88 16.29 13 18.17v-3.76l1.88 1.88z")+ val Headphones = icon("Headphones", "M12 3a9 9 0 0 0-9 9v7c0 1.1.9 2 2 2h4v-8H5v-1c0-3.87 3.13-7 7-7s7 3.13 7 7v1h-4v8h4c1.1 0 2-.9 2-2v-7a9 9 0 0 0-9-9z")+ val Keyboard = icon(+ "Keyboard",+ "M20 5H4c-1.1 0-1.99.9-1.99 2L2 17c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2z" ++ "M11 8h2v2h-2zM11 11h2v2h-2zM8 8h2v2H8zM8 11h2v2H8zM5 11h2v2H5zM5 8h2v2H5zM8 15h8v2H8zM14 11h2v2h-2zM14 8h2v2h-2zM17 11h2v2h-2zM17 8h2v2h-2z",+ )+ val Mouse = icon("Mouse", "M13 1.07V9h7c0-4.08-3.05-7.44-7-7.93zM4 15c0 4.42 3.58 8 8 8s8-3.58 8-8v-4H4v4zM11 1.07C7.05 1.56 4 4.92 4 9h7V1.07z")+ val Controller = icon(+ "Controller",+ "M21.58 16.09l-1.09-7.66A3.996 3.996 0 0 0 16.53 5H7.47C5.48 5 3.79 6.46 3.51 8.43l-1.09 7.66a2.545 2.545 0 0 0 4.32 2.16L9 16h6l2.25 2.25c.48.48 1.13.75 1.8.75 1.56 0 2.75-1.37 2.53-2.91z" ++ "M11 11H9v2H8v-2H6v-1h2V8h1v2h2v1zM15 8a1 1 0 1 0 0 2 1 1 0 1 0 0-2zM17 11a1 1 0 1 0 0 2 1 1 0 1 0 0-2z",+ )+ val Usb = icon(+ "Usb",+ "M15 7v4h1v2h-3V5h2l-3-4-3 4h2v8H8v-2.07c.7-.37 1.2-1.08 1.2-1.93 0-1.21-.99-2.2-2.2-2.2-1.21 0-2.2.99-2.2 2.2 0 .85.5 1.56 1.2 1.93V13c0 1.11.89 2 2 2h3v3.05c-.71.37-1.2 1.1-1.2 1.95a2.2 2.2 0 0 0 4.4 0c0-.85-.49-1.58-1.2-1.95V15h3c1.11 0 2-.89 2-2v-2h1V7h-4z",+ )+ val Speaker = icon(+ "Speaker",+ "M17 2H7c-1.1 0-2 .9-2 2v16c0 1.1.9 1.99 2 1.99L17 22c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z" ++ "M12 4a2 2 0 1 0 0 4 2 2 0 1 0 0-4zM12 10a5 5 0 1 0 0 10 5 5 0 1 0 0-10zM12 12a3 3 0 1 0 0 6 3 3 0 1 0 0-6z",+ )+ val Hdmi = icon("Hdmi", "M18 7V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v3H5v6l3 6v3h8v-3l3-6V7h-1zM8 4h8v3h-2V5h-1v2h-2V5h-1v2H8V4z")++ private fun icon(name: String, path: String) = ImageVector.Builder(name, 24.dp, 24.dp, 24f, 24f)+ .addPath(PathParser().parsePathString(path).toNodes(), pathFillType = PathFillType.EvenOdd, fill = SolidColor(Color.Black))+ .build()++ fun of(kind: Peripheral.Kind) = when (kind) {+ Peripheral.Kind.Remote -> TileIcons.Remote+ Peripheral.Kind.Headphones -> Headphones+ Peripheral.Kind.Speaker, Peripheral.Kind.Sound -> Speaker+ Peripheral.Kind.Keyboard -> Keyboard+ Peripheral.Kind.Mouse -> Mouse+ Peripheral.Kind.Controller -> Controller+ Peripheral.Kind.Bluetooth -> Bluetooth+ Peripheral.Kind.Usb -> Usb+ Peripheral.Kind.Hdmi -> Hdmi+ }+}++/**+ * C1: another computer is connected. A red card, collapsed by default with the whole card as the+ * toggle; open, it says where the connections come from and links to Who has access. "It's mine"+ * marks the address when there is one; with several, it opens Who has access to pick.+ */+@OptIn(ExperimentalLayoutApi::class)+@Composable+fun AccessWarning(access: TvAccess, actions: AccessActions, onWho: () -> Unit, startOpen: Boolean = false) {+ val c = MaterialTheme.colorScheme+ var open by rememberSaveable { mutableStateOf(startOpen) }+ val others = access.others+ Card(+ onClick = { open = !open },+ colors = CardDefaults.cardColors(containerColor = c.errorContainer, contentColor = c.onErrorContainer),+ shape = MaterialTheme.shapes.large,+ modifier = Modifier.fillMaxWidth().animateContentSize().testTag("accessWarning"),+ ) {+ Column(Modifier.padding(start = 16.dp, end = 12.dp, top = 16.dp, bottom = 16.dp)) {+ Row {+ Icon(AccessIcons.Shield, contentDescription = null, Modifier.padding(top = 2.dp).size(24.dp))+ Spacer(Modifier.width(16.dp))+ Column(Modifier.weight(1f)) {+ Text(Copy.WARNING_TITLE, style = MaterialTheme.typography.titleMedium)+ Text(Copy.WARNING_TEXT, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(top = 4.dp))+ }+ Icon(+ if (open) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,+ contentDescription = if (open) "Show less" else "Show more",+ Modifier.padding(start = 8.dp),+ )+ }+ if (open) {+ Column(Modifier.padding(start = 40.dp, top = 12.dp, end = 4.dp)) {+ HorizontalDivider(color = c.onErrorContainer.copy(alpha = 0.2f))+ Text(Copy.CONNECTED_NOW, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(top = 12.dp))+ others.forEach { o ->+ Text(Copy.connectedFrom(if (o.who == AccessClient.Who.OnTv) Copy.ON_TV.lowercase() else o.address, o.connections), style = MaterialTheme.typography.bodyLarge)+ }+ Row(+ Modifier.padding(top = 8.dp).clip(RoundedCornerShape(8.dp)).clickable(onClick = onWho).padding(vertical = 4.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(Copy.WHO_HAS_ACCESS, style = MaterialTheme.typography.labelLarge)+ Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null, Modifier.size(18.dp))+ }+ }+ }+ FlowRow(Modifier.padding(top = 12.dp, start = 12.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ val border = BorderStroke(1.dp, c.onErrorContainer)+ val colors = ButtonDefaults.outlinedButtonColors(contentColor = c.onErrorContainer)+ OutlinedButton(onClick = { others.singleOrNull()?.let { actions.markMine(it.address) } ?: onWho() }, border = border, colors = colors) {+ Text(Copy.ITS_MINE)+ }+ OutlinedButton(onClick = actions.askRemove, border = border, colors = colors, contentPadding = ButtonDefaults.ButtonWithIconContentPadding) {+ Icon(AccessIcons.LockReset, contentDescription = null, Modifier.size(18.dp))+ Spacer(Modifier.width(8.dp))+ Text(Copy.REMOVE_ACCESS)+ }+ }+ }+ }+}++/**+ * What's plugged in or paired. Three rows and Show all; open, it grows in place into labelled+ * groups with Show less at the end. Teal for in use, grey for paired but off.+ */+@Composable+fun ConnectedDevicesCard(peripherals: List<Peripheral>, startOpen: Boolean = false) {+ val c = MaterialTheme.colorScheme+ var open by rememberSaveable { mutableStateOf(startOpen) }+ Card(+ colors = CardDefaults.cardColors(containerColor = c.surfaceContainerLow),+ shape = MaterialTheme.shapes.large,+ modifier = Modifier.fillMaxWidth().animateContentSize().testTag("connectedDevices"),+ ) {+ Column(Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 8.dp)) {+ Text(Copy.DEVICES_TITLE, style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(bottom = 4.dp))+ if (peripherals.isEmpty()) {+ Text(Copy.NO_DEVICES, style = MaterialTheme.typography.bodyMedium, color = c.onSurfaceVariant, modifier = Modifier.padding(vertical = 8.dp))+ } else if (open) {+ peripherals.groupBy { it.group }.forEach { (group, rows) ->+ Text(Copy.group(group), style = MaterialTheme.typography.labelLarge, color = c.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp, bottom = 2.dp))+ rows.forEach { PeripheralRow(it, grouped = true) }+ }+ } else {+ peripherals.take(COLLAPSED_ROWS).forEach { PeripheralRow(it, grouped = false) }+ }+ if (peripherals.size > COLLAPSED_ROWS) {+ TextButton(onClick = { open = !open }, contentPadding = PaddingValues(horizontal = 0.dp, vertical = 8.dp)) {+ Text(if (open) Copy.SHOW_LESS else Copy.showAll(peripherals.size))+ }+ }+ }+ }+}++private const val COLLAPSED_ROWS = 3++@Composable+private fun PeripheralRow(p: Peripheral, grouped: Boolean) {+ val c = MaterialTheme.colorScheme+ Row(Modifier.fillMaxWidth().height(56.dp), verticalAlignment = Alignment.CenterVertically) {+ Icon(AccessIcons.of(p.kind), contentDescription = null, tint = if (p.live) c.primary else c.onSurfaceVariant)+ Spacer(Modifier.width(16.dp))+ Text(p.name, Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Spacer(Modifier.width(8.dp))+ Text(Copy.peripheralStatus(p, grouped), style = MaterialTheme.typography.bodySmall, color = c.onSurfaceVariant)+ }+}++/**+ * Who has access (C3) and, once started, Remove all other access (C4–C6). The list is the+ * screen until a removal starts; C4 is a dialog over it, and every later step has the screen.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun AccessScreen(state: UiState, actions: AccessActions, snackbar: SnackbarHostState = remember { SnackbarHostState() }) {+ val device = state.selected ?: return+ val ui = state.device+ val removal = ui.removal+ val flow = removal != null && removal.step != Removal.Step.Confirm+ Scaffold(+ snackbarHost = { SnackbarHost(snackbar) },+ topBar = {+ TopAppBar(+ title = {+ Column {+ Text(if (flow) Copy.REMOVE_TITLE else Copy.WHO_HAS_ACCESS)+ Text(name(device), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+ },+ navigationIcon = {+ IconButton(onClick = if (flow) actions.close else actions.back) {+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = if (flow) Copy.WHO_HAS_ACCESS else "Back to the TV's page")+ }+ },+ )+ },+ ) { pad ->+ val body = Modifier.fillMaxSize().padding(pad)+ when (removal?.step) {+ null, Removal.Step.Confirm -> AccessList(ui.access, state.now, device.state == DeviceState.Online, actions, body)+ Removal.Step.Revoking -> Waiting(Copy.REVOKING, body)+ Removal.Step.Checking -> Waiting(Copy.CHECKING, body)+ Removal.Step.Manual -> ManualGuide(actions, body)+ Removal.Step.Allow -> AllowPhone(removal, actions, body)+ Removal.Step.Done -> Outcome(+ body, Verdict.Done, Copy.DONE_TITLE, Copy.DONE_TEXT,+ trust = true,+ ) { Button(onClick = { actions.close(); actions.back() }) { Text(Copy.backTo(name(device))) } }+ Removal.Step.StillConnected -> Outcome(body, Verdict.Still, Copy.STILL_TITLE, Copy.stillText(removal.still ?: Copy.UNNAMED_COMPUTER, name(device))) {+ OutlinedButton(onClick = actions.close) { Text(Copy.WHO_HAS_ACCESS) }+ Button(onClick = actions.retry) { Text(Copy.TRY_AGAIN) }+ }+ Removal.Step.Unconfirmed -> Outcome(body, Verdict.Unknown, Copy.UNCONFIRMED_TITLE, Copy.UNCONFIRMED_TEXT) {+ Button(onClick = actions.close) { Text(Copy.DONE) }+ }+ }+ }+ if (removal?.step == Removal.Step.Confirm) ConfirmRemoval(actions)+}++/** C4: the one warning before every key on the TV goes, this phone's included. */+@Composable+private fun ConfirmRemoval(actions: AccessActions) {+ val c = MaterialTheme.colorScheme+ AlertDialog(+ onDismissRequest = actions.close,+ icon = { Icon(AccessIcons.LockReset, contentDescription = null, tint = c.error) },+ title = { Text(Copy.CONFIRM_TITLE, textAlign = TextAlign.Center) },+ text = {+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Text(Copy.CONFIRM_TEXT)+ Text(Copy.CONFIRM_REMOTE)+ }+ },+ confirmButton = { TextButton(onClick = actions.remove, colors = ButtonDefaults.textButtonColors(contentColor = c.error)) { Text(Copy.CONFIRM_BUTTON) } },+ dismissButton = { TextButton(onClick = actions.close) { Text(Copy.CANCEL) } },+ )+}++/** C3: who is connected now and which computers are allowed, never tied together. */+@Composable+private fun AccessList(access: TvAccess?, now: Long, online: Boolean, actions: AccessActions, modifier: Modifier) {+ val c = MaterialTheme.colorScheme+ LazyColumn(modifier, contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 32.dp)) {+ item { Text(Copy.ACCESS_INTRO, style = MaterialTheme.typography.bodyMedium, color = c.onSurfaceVariant, modifier = Modifier.padding(bottom = 16.dp)) }+ section(Copy.CONNECTED_NOW)+ when (val list = access?.connected) {+ null -> item { Muted(if (access == null) "Checking…" else Copy.CANT_CHECK_CONNECTED) }+ else -> segmented(list) { ConnectedRow(it, actions) }+ }+ item { Spacer(Modifier.height(24.dp)) }+ section(Copy.ALLOWED_COMPUTERS)+ when (val list = access?.allowed) {+ null -> item { Muted(if (access == null) "Checking…" else Copy.CANT_CHECK_ALLOWED) }+ emptyList<AccessKey>() -> item { Muted(Copy.NOBODY_ALLOWED) }+ else -> segmented(list) { AllowedRow(it, now) }+ }+ item {+ Column(Modifier.padding(top = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text(Copy.ACCESS_FOOT_LINK, style = MaterialTheme.typography.bodySmall, color = c.onSurfaceVariant)+ Text(Copy.ACCESS_FOOT_ALL, style = MaterialTheme.typography.bodySmall, color = c.onSurfaceVariant)+ OutlinedButton(+ onClick = actions.askRemove,+ enabled = online,+ colors = ButtonDefaults.outlinedButtonColors(contentColor = c.error),+ contentPadding = ButtonDefaults.ButtonWithIconContentPadding,+ modifier = Modifier.padding(top = 8.dp),+ ) {+ Icon(AccessIcons.LockReset, contentDescription = null, Modifier.size(18.dp))+ Spacer(Modifier.width(8.dp))+ Text(Copy.REMOVE_ACCESS)+ }+ }+ }+ }+}++private fun LazyListScope.section(title: String) = item {+ Text(title, style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary, modifier = Modifier.padding(bottom = 8.dp))+}++/** An MD3 segmented list: 2 dp apart, 16 dp outer corners and 4 dp inner ones. */+private fun <T> LazyListScope.segmented(rows: List<T>, row: @Composable (T) -> Unit) {+ rows.forEachIndexed { i, r ->+ item {+ val top = if (i == 0) 16.dp else 4.dp+ val bottom = if (i == rows.lastIndex) 16.dp else 4.dp+ Surface(+ shape = RoundedCornerShape(topStart = top, topEnd = top, bottomStart = bottom, bottomEnd = bottom),+ color = MaterialTheme.colorScheme.surfaceContainerHigh,+ modifier = Modifier.fillMaxWidth().padding(bottom = 2.dp),+ ) { row(r) }+ }+ }+}++@Composable+private fun ConnectedRow(client: AccessClient, actions: AccessActions) {+ val c = MaterialTheme.colorScheme+ val phone = client.who == AccessClient.Who.Phone+ AccessRow(+ icon = if (phone) AccessIcons.Phone else AccessIcons.Lan,+ title = when (client.who) {+ AccessClient.Who.Phone -> Copy.THIS_PHONE+ AccessClient.Who.OnTv -> Copy.ON_TV+ else -> client.address+ },+ chip = phone,+ ) {+ if (phone || client.who == AccessClient.Who.OnTv) Sub(client.address)+ Sub(Copy.connections(client.connections))+ when (client.who) {+ AccessClient.Who.Other, AccessClient.Who.OnTv -> {+ Text(Copy.NOT_THIS_PHONE, style = MaterialTheme.typography.bodyMedium, color = c.error)+ Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) {+ FilledTonalButton(onClick = { actions.markMine(client.address) }) { Text(Copy.ITS_MINE) }+ }+ }+ AccessClient.Who.Mine -> Sub(Copy.YOURS)+ AccessClient.Who.Phone -> {}+ }+ }+}++@Composable+private fun AllowedRow(key: AccessKey, now: Long) {+ val name = key.name+ AccessRow(+ icon = when {+ key.phone -> AccessIcons.Phone+ name == null -> AccessIcons.Unknown+ "laptop" in name.lowercase() || "book" in name.lowercase() -> AccessIcons.Laptop+ else -> AccessIcons.Desktop+ },+ title = if (key.phone) Copy.THIS_PHONE else name ?: Copy.UNNAMED_COMPUTER,+ chip = key.phone,+ ) {+ Text(Copy.shortFingerprint(key.fingerprint), style = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace), color = MaterialTheme.colorScheme.onSurfaceVariant)+ Sub(Copy.lastSeen(key.lastSeen, now))+ }+}++@Composable+private fun AccessRow(icon: ImageVector, title: String, chip: Boolean, lines: @Composable () -> Unit) {+ Row(Modifier.padding(16.dp)) {+ Icon(icon, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant)+ Spacer(Modifier.width(16.dp))+ Column(Modifier.weight(1f)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(title, style = MaterialTheme.typography.titleMedium)+ if (chip) {+ Spacer(Modifier.width(8.dp))+ Surface(shape = RoundedCornerShape(8.dp), color = MaterialTheme.colorScheme.secondaryContainer) {+ Text(Copy.TELLYSCOPE, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp))+ }+ }+ }+ lines()+ }+ }+}++@Composable+private fun Sub(text: String) = Text(text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)++@Composable+private fun Muted(text: String) = Text(text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 8.dp))++@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+private fun Waiting(text: String, modifier: Modifier) {+ Column(modifier.padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {+ LoadingIndicator(Modifier.size(96.dp))+ Text(text, style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(top = 24.dp))+ }+}++/** C5: the TV is asking about this phone. Its fingerprint wraps at the colons, to compare pair by pair. */+@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+private fun AllowPhone(removal: Removal, actions: AccessActions, modifier: Modifier) {+ val c = MaterialTheme.colorScheme+ Column(+ modifier.verticalScroll(rememberScrollState()).padding(horizontal = 24.dp, vertical = 32.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ LoadingIndicator(Modifier.size(96.dp))+ Text(Copy.ALLOW_TITLE, style = MaterialTheme.typography.headlineSmall, textAlign = TextAlign.Center, modifier = Modifier.padding(top = 32.dp))+ Text(+ buildAnnotatedString {+ append(Copy.ALLOW_TEXT_A)+ withStyle(SpanStyle(fontWeight = FontWeight.SemiBold)) { append(Copy.ALLOW_ALWAYS) }+ append(Copy.ALLOW_TEXT_B)+ withStyle(SpanStyle(fontWeight = FontWeight.SemiBold)) { append(Copy.ALLOW_BUTTON) }+ append(".")+ },+ style = MaterialTheme.typography.bodyLarge, color = c.onSurfaceVariant, textAlign = TextAlign.Center,+ modifier = Modifier.padding(top = 12.dp),+ )+ if (removal.refused) {+ Text(Copy.REFUSED, style = MaterialTheme.typography.bodyLarge, color = c.error, textAlign = TextAlign.Center, modifier = Modifier.padding(top = 16.dp))+ Button(onClick = actions.askAgain, Modifier.padding(top = 8.dp)) { Text(Copy.ASK_AGAIN) }+ }+ removal.fingerprint?.let { fp ->+ Surface(shape = MaterialTheme.shapes.large, color = c.surfaceContainerHigh, modifier = Modifier.fillMaxWidth().padding(top = 24.dp)) {+ Column(Modifier.padding(16.dp)) {+ Text(Copy.FINGERPRINT_LABEL, style = MaterialTheme.typography.labelLarge, color = c.onSurfaceVariant)+ Text(+ fp.replace(":", ":"),+ style = MaterialTheme.typography.titleMedium.copy(fontFamily = FontFamily.Monospace),+ modifier = Modifier.padding(vertical = 8.dp),+ )+ Text(Copy.FINGERPRINT_HINT, style = MaterialTheme.typography.bodySmall, color = c.onSurfaceVariant)+ }+ }+ }+ TextButton(onClick = actions.close, Modifier.padding(top = 16.dp)) { Text(Copy.STOP_WAITING) }+ }+}++/** The fallback when the TV won't take the call: revoke in Developer options, then allow again. */+@Composable+private fun ManualGuide(actions: AccessActions, modifier: Modifier) {+ val c = MaterialTheme.colorScheme+ Column(modifier.verticalScroll(rememberScrollState()).padding(horizontal = 24.dp, vertical = 16.dp)) {+ Text(Copy.MANUAL_INTRO, style = MaterialTheme.typography.bodyLarge, color = c.onSurfaceVariant)+ Step(1, Copy.MANUAL_STEP_1, Copy.MANUAL_STEP_1_TEXT) {+ Button(onClick = actions.openDeveloperOptions, contentPadding = ButtonDefaults.ButtonWithIconContentPadding) {+ Icon(OpenInNew, contentDescription = null, Modifier.size(18.dp))+ Spacer(Modifier.width(8.dp))+ Text(Copy.OPEN_ON_TV)+ }+ }+ Step(2, Copy.MANUAL_STEP_2, Copy.MANUAL_STEP_2_TEXT) {+ OutlinedButton(onClick = actions.revokedByHand) { Text(Copy.MANUAL_DONE) }+ }+ }+}++@Composable+private fun Step(n: Int, title: String, text: String, button: @Composable () -> Unit) {+ val c = MaterialTheme.colorScheme+ Row(Modifier.padding(top = 24.dp)) {+ Box(Modifier.size(32.dp).clip(RoundedCornerShape(16.dp)).background(c.primary), contentAlignment = Alignment.Center) {+ Text("$n", style = MaterialTheme.typography.titleSmall, color = c.onPrimary)+ }+ Spacer(Modifier.width(16.dp))+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text(title, style = MaterialTheme.typography.titleMedium)+ Text(text, style = MaterialTheme.typography.bodyMedium, color = c.onSurfaceVariant)+ button()+ }+ }+}++private enum class Verdict { Done, Still, Unknown }++/** C6, C6b and C6c: a cookie badge, what Tellyscope found, and where to go next. */+@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+private fun Outcome(modifier: Modifier, kind: Verdict, title: String, text: String, trust: Boolean = false, buttons: @Composable () -> Unit) {+ val c = MaterialTheme.colorScheme+ val (bg, fg) = when (kind) {+ Verdict.Done -> c.primaryContainer to c.onPrimaryContainer+ Verdict.Still -> c.surfaceContainerHighest to c.error+ Verdict.Unknown -> c.surfaceContainerHighest to c.onSurfaceVariant+ }+ Column(+ modifier.verticalScroll(rememberScrollState()).padding(horizontal = 24.dp, vertical = 32.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Box(Modifier.size(96.dp).clip(MaterialShapes.Cookie9Sided.toShape()).background(bg), contentAlignment = Alignment.Center) {+ Icon(if (kind == Verdict.Done) AccessIcons.ShieldOk else AccessIcons.Shield, contentDescription = null, Modifier.size(44.dp), tint = fg)+ }+ Text(title, style = MaterialTheme.typography.headlineSmall, textAlign = TextAlign.Center, modifier = Modifier.padding(top = 32.dp))+ Text(text, style = MaterialTheme.typography.bodyLarge, color = c.onSurfaceVariant, textAlign = TextAlign.Center, modifier = Modifier.padding(top = 12.dp))+ if (trust) {+ Surface(shape = MaterialTheme.shapes.large, color = c.surfaceContainerHigh, modifier = Modifier.fillMaxWidth().padding(top = 24.dp)) {+ Row(Modifier.padding(16.dp)) {+ Icon(AccessIcons.ShieldNote, contentDescription = null, tint = c.onSurfaceVariant)+ Spacer(Modifier.width(16.dp))+ Text(Copy.TRUST_WARNING, style = MaterialTheme.typography.bodyLarge)+ }+ }+ }+ Row(Modifier.padding(top = 24.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { buttons() }+ }+}diff --git a/app/src/main/java/app/tellyscope/ui/Copy.kt b/app/src/main/java/app/tellyscope/ui/Copy.ktindex e7acb6d..1be9edc 100644--- a/app/src/main/java/app/tellyscope/ui/Copy.kt+++ b/app/src/main/java/app/tellyscope/ui/Copy.kt@@ -4,6 +4,7 @@ package app.tellyscope.uiimport app.tellyscope.adb.InstallKindimport app.tellyscope.adb.InstallRefusal+import app.tellyscope.adb.Peripheralimport app.tellyscope.adb.TvFolderimport app.tellyscope.data.Actionimport app.tellyscope.data.AppNames@@ -407,4 +408,102 @@ object Copy {const val REQUEST_ALLOWED = "Allowed. That device can control the TV now."const val REQUEST_DENIED = "Denied. That device can't connect."const val REQUEST_GONE = "The TV's prompt had closed or changed, so nothing was pressed."++ // Who has access+ const val WARNING_TITLE = "Another computer is connected to this TV"+ const val WARNING_TEXT = "It can do everything Tellyscope can: install or remove apps, read files and control the screen."+ const val ITS_MINE = "It's mine"+ const val REMOVE_ACCESS = "Remove all other access…"+ const val CONNECTED_NOW = "Connected now"+ const val WHO_HAS_ACCESS = "Who has access"+ fun connections(n: Int) = if (n == 1) "1 connection" else "$n connections"+ fun connectedFrom(address: String, n: Int) = "From $address · ${connections(n)}"+ const val ON_TV = "An app on this TV"+ const val ACCESS_INTRO = "Each computer allowed to use ADB can install or remove apps, read files and control the screen."+ const val THIS_PHONE = "This phone"+ const val TELLYSCOPE = "Tellyscope"+ const val NOT_THIS_PHONE = "Not this phone"+ const val YOURS = "Yours"+ const val ALLOWED_COMPUTERS = "Allowed computers"+ const val UNNAMED_COMPUTER = "Unnamed computer"+ const val CANT_CHECK_CONNECTED = "This TV doesn't say who is connected."+ const val CANT_CHECK_ALLOWED = "This TV doesn't list its allowed computers."+ const val NOBODY_ALLOWED = "No computer is allowed. The next one to connect has to be allowed on the TV."+ const val ACCESS_FOOT_LINK = "The TV doesn't say which allowed computer is behind a connection. If you don't recognise an address, remove all other access."+ const val ACCESS_FOOT_ALL = "Android can't remove one computer on its own: this clears every computer, then you allow Tellyscope again."+ /** Rough on purpose: the TV stamps a key when any connection uses it, not per session. */+ fun lastSeen(at: Long?, now: Long): String {+ if (at == null) return "Never seen"+ val days = ((now - at) / 86_400_000).coerceAtLeast(0)+ return when {+ now - at < 5 * 60_000 -> "Last seen just now"+ days == 0L -> "Last seen today, " + SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(at))+ days == 1L -> "Last seen yesterday"+ days < 30 -> "Last seen $days days ago"+ else -> "Last seen over a month ago"+ }+ }+ /** Enough of a fingerprint to tell keys apart: the first three and last two pairs. */+ fun shortFingerprint(fp: String): String {+ val parts = fp.split(':')+ return if (parts.size <= 5) fp else (parts.take(3) + "…" + parts.takeLast(2)).joinToString(":")+ }++ // Remove all other access+ const val REMOVE_TITLE = "Remove all other access"+ const val CONFIRM_TITLE = "Remove all other access?"+ const val CONFIRM_TEXT = "Every computer this TV has allowed loses access, your own computers too: they'll need allowing again."+ const val CONFIRM_REMOTE = "Tellyscope reconnects straight away. Keep the TV remote handy: the TV asks you to allow this phone."+ const val CONFIRM_BUTTON = "Remove access"+ const val CANCEL = "Cancel"+ const val REVOKING = "Removing access…"+ const val ALLOW_TITLE = "Allow this phone on the TV"+ const val ALLOW_TEXT_A = "Other access is removed. The TV now asks “Allow USB debugging?”. Tick "+ const val ALLOW_ALWAYS = "Always allow from this computer"+ const val ALLOW_TEXT_B = ", then choose "+ const val ALLOW_BUTTON = "Allow"+ const val FINGERPRINT_LABEL = "The TV should show this fingerprint"+ const val FINGERPRINT_HINT = "If it shows a different one, choose Cancel on the TV."+ const val STOP_WAITING = "Stop waiting"+ const val REFUSED = "The TV didn't allow this phone. It may have timed out, or Cancel was chosen."+ const val ASK_AGAIN = "Ask the TV again"+ const val CHECKING = "Checking the TV…"+ const val DONE_TITLE = "Only this phone has access"+ const val DONE_TEXT = "Tellyscope checked the TV again: this phone is the only allowed computer, and nothing else is connected."+ const val TRUST_WARNING = "Only allow computers and apps you trust. Anything you allow can install apps, read files and control the TV."+ fun backTo(tv: String) = "Back to $tv"+ const val STILL_TITLE = "Another computer is still connected"+ fun stillText(who: String, tv: String) =+ "Tellyscope still sees $who on $tv. It may have connected again straight away. Turn it off or unplug it from the network, then try again."+ fun connectionFrom(address: String) = "a connection from $address"+ const val TRY_AGAIN = "Try again"+ const val UNCONFIRMED_TITLE = "Revoked on the TV"+ const val UNCONFIRMED_TEXT = "Tellyscope can't check the list on this TV. Look under Developer options to confirm."+ const val DONE = "Done"+ const val MANUAL_INTRO = "This TV didn't take Tellyscope's request, so it's two steps on the TV. Afterwards only this phone can use ADB on it; your own computers will need allowing again."+ const val MANUAL_STEP_1 = "Open Developer options on the TV"+ const val MANUAL_STEP_1_TEXT = "Tellyscope opens it for you. If nothing happens on the TV, go to Settings → Device Preferences → Developer options."+ const val OPEN_ON_TV = "Open on TV"+ const val MANUAL_STEP_2 = "Choose “Revoke USB debugging authorisations”"+ const val MANUAL_STEP_2_TEXT = "Then come back here, and Tellyscope asks the TV to allow this phone again."+ const val MANUAL_DONE = "I've revoked it"+ const val DEV_OPTIONS_FAILED = "Couldn't open Developer options on the TV. Go to Settings → Device Preferences → Developer options."++ // Connected devices+ const val DEVICES_TITLE = "Connected devices"+ fun showAll(n: Int) = "Show all ($n)"+ const val SHOW_LESS = "Show less"+ const val NO_DEVICES = "Nothing plugged in or paired."+ fun group(g: Peripheral.Group) = when (g) {+ Peripheral.Group.Bluetooth -> "Bluetooth"+ Peripheral.Group.Input -> "Input"+ Peripheral.Group.Storage -> "USB storage"+ Peripheral.Group.Hdmi -> "HDMI-CEC"+ Peripheral.Group.Audio -> "Audio output"+ }+ /** The row's right-hand words. Collapsed rows have no group label, so Bluetooth says so there. */+ fun peripheralStatus(p: Peripheral, grouped: Boolean): String {+ val status = p.free?.let { "${bytes(it).replace(".0 ", " ")} free" } ?: p.status+ return if (!grouped && p.group == Peripheral.Group.Bluetooth) "Bluetooth · ${status.lowercase()}" else status+ }}diff --git a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt b/app/src/main/java/app/tellyscope/ui/DeviceScreen.ktindex cb51397..5ae6e0e 100644--- a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt+++ b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt@@ -114,6 +114,10 @@ data class DeviceActions(val foldSystem: (AppsTab, Boolean) -> Unit = { _, _ -> },/** The open tab's refresh rates; the TV's stats reads follow them. */val showStats: (StatsProfile) -> Unit = {},+ /** Opens Who has access. */+ val whoHasAccess: () -> Unit = {},+ /** The access warning's buttons, shared with Who has access. */+ val access: AccessActions = AccessActions(),)/**diff --git a/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt b/app/src/main/java/app/tellyscope/ui/DeviceTabs.ktindex 0d0ee27..9053a44 100644--- a/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt+++ b/app/src/main/java/app/tellyscope/ui/DeviceTabs.kt@@ -37,6 +37,8 @@ import androidx.compose.material.icons.filled.MoreVertimport androidx.compose.material.icons.filled.Searchimport androidx.compose.material.icons.filled.Settingsimport androidx.compose.material3.AssistChip+import androidx.compose.material3.Badge+import androidx.compose.material3.BadgedBoximport androidx.compose.material3.Cardimport androidx.compose.material3.CardDefaultsimport androidx.compose.material3.DropdownMenu@@ -289,6 +291,9 @@ fun DeviceTabsScreen(}item { SectionTitle("Suggested for this TV") }item { SuggestedCard(ui.lists, debloat, offline, onChanges = { toChanges = true; tab = TvTab.Tweaks }) }+ // The warning first, then what's plugged in, then Android.+ ui.access?.takeIf { it.warning && !offline }?.let { a -> item(key = "accessWarning") { AccessWarning(a, actions.access, onWho = actions.whoHasAccess) } }+ ui.peripherals?.takeIf { !offline }?.let { p -> item(key = "connectedDevices") { ConnectedDevicesCard(p) } }item { AndroidCard(state, snap, offline, onUpdates = actions.checkUpdates) }}TvTab.Apps -> {@@ -421,6 +426,13 @@ private fun AppMenu(state: UiState, actions: DeviceActions) {MenuBlock {DropdownMenuItem(text = { Text("Rename this TV") }, leadingIcon = { Icon(Icons.Default.Edit, null) }, onClick = { open = false; renaming = true })DropdownMenuItem(text = { Text("Forget this TV") }, leadingIcon = { Icon(Icons.Default.Delete, null) }, onClick = { open = false; forgetting = true })+ DropdownMenuItem(+ text = { Text(Copy.WHO_HAS_ACCESS) },+ leadingIcon = {+ BadgedBox(badge = { if (state.device.access?.warning == true) Badge() }) { Icon(AccessIcons.Shield, null) }+ },+ onClick = { open = false; actions.whoHasAccess() },+ )DropdownMenuItem(text = { Text("Advanced") }, leadingIcon = { Icon(Icons.Default.List, null) }, onClick = { open = false; actions.advanced() })}Spacer(Modifier.height(4.dp))@@ -594,7 +606,7 @@ private fun StatusRow(icon: ImageVector, title: String, sub: String?, button: St}-private object TileIcons {+internal object TileIcons {// Absolute commands only: Compose's path parser misplaces a relative move after a close.val Upload = icon("Upload", "M9 16H15V10H19L12 3L5 10H9ZM5 18H19V20H5Z")// Material's settings_remote: a remote with a ring button and two signal arcs.diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex f53bd3d..a2e5180 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -11,6 +11,7 @@ import app.tellyscope.adb.InstallKindimport app.tellyscope.adb.StatsProfileimport app.tellyscope.adb.InstallResultimport app.tellyscope.adb.InstalledVersion+import app.tellyscope.adb.Peripheralimport app.tellyscope.adb.Progressimport app.tellyscope.adb.Remoteimport app.tellyscope.adb.RemoteKey@@ -41,6 +42,7 @@ import app.tellyscope.data.ScanKindimport app.tellyscope.data.ScanProgressimport app.tellyscope.data.Snapshotimport app.tellyscope.data.Suggestions+import app.tellyscope.data.TvAccessimport app.tellyscope.data.TvSettingsimport app.tellyscope.data.TvTweaksimport app.tellyscope.data.Update@@ -105,8 +107,33 @@ data class DeviceUi(val request: ConnectionRequest? = null,/** The Remote's app shortcuts, in order. */val dock: List<Docked> = emptyList(),+ /** Who may use ADB on the TV and who is connected; null until first read. */+ val access: TvAccess? = null,+ /** What's plugged in or paired; null until first read. */+ val peripherals: List<Peripheral>? = null,+ /** "Remove all other access", while it runs; null otherwise. */+ val removal: Removal? = null,)+/**+ * "Remove all other access", one step at a time. The TV's keys are cleared ([Step.Revoking], or+ * by hand in Developer options when the call isn't available: [Step.Manual]); Tellyscope then+ * reconnects and the TV asks to allow this phone ([Step.Allow]). [Step.Done] only after a re-read+ * shows nobody else; [Step.StillConnected] names who is left, [Step.Unconfirmed] means the TV+ * wouldn't say.+ */+data class Removal(+ val step: Step,+ /** This phone's fingerprint, to compare with the TV's prompt. */+ val fingerprint: String? = null,+ /** The TV said no to this phone (Cancel, or the prompt timed out): offer to ask again. */+ val refused: Boolean = false,+ /** Who is still there, for [Step.StillConnected]: "a connection from …", or a computer's name. */+ val still: String? = null,+) {+ enum class Step { Confirm, Revoking, Manual, Allow, Checking, Done, StillConnected, Unconfirmed }+}+data class SideloadUi(val step: Step = Step.Reading,/** Null while the picked file is still being read. */@@ -221,6 +248,20 @@ const val SCREENSHOT = "screenshot"/** [DeviceUi.busy] value while the TV's connection prompt is being answered. */const val ANSWERING = "request"+/** How long a removal waits to see the link drop before checking a link that stayed up. */+const val RELINK_GRACE_MS = 5_000L++/** Where a removal ends, from the re-read after it: never Done on a guess. */+fun outcome(access: TvAccess?): Removal = when {+ access?.connected == null || access.allowed == null -> Removal(Removal.Step.Unconfirmed)+ access.onlyThisPhone -> Removal(Removal.Step.Done)+ else -> Removal(+ Removal.Step.StillConnected,+ still = access.others.firstOrNull()?.let { Copy.connectionFrom(it.address) }+ ?: access.allowed.firstOrNull { !it.phone }?.let { it.name ?: Copy.UNNAMED_COMPUTER },+ )+}+class TellyscopeViewModel(private val source: DeviceSource,private val storage: PhoneStorage? = null,@@ -264,6 +305,9 @@ class TellyscopeViewModel(private var mediumJob: Job? = nullprivate var listsJob: Job? = nullprivate var requestJob: Job? = null+ private var accessJob: Job? = null+ /** Runs the removal across the reconnect it causes, so [select] doesn't stop it. */+ private var removalJob: Job? = nullprivate var updateJob: Job? = null/** The fingerprint the user waved away on the phone; its prompt stays hidden while the TV shows it. */private var dismissedRequest: String? = null@@ -410,9 +454,14 @@ class TellyscopeViewModel(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)- _state.update { it.copy(selectedId = id, device = DeviceUi(snapshot = id?.let(lastSnapshot::get), transfer = transfer), query = "") }+ // A removal survives the reconnect it causes; the TV coming back reselects it.+ _state.update {+ val removal = it.device.removal.takeIf { _ -> it.selectedId == id }+ it.copy(selectedId = id, device = DeviceUi(snapshot = id?.let(lastSnapshot::get), transfer = transfer, removal = removal), query = "")+ }val device = _state.value.selected ?: return// History lives on the phone, so it shows (and undo is offered) even while the TV is off.viewModelScope.launch {@@ -430,6 +479,7 @@ class TellyscopeViewModel(// 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!!) }mediumJob = viewModelScope.launch {// A TV that drops mid-read throws; the live flow ends and the offline card takes over.try {@@ -906,6 +956,112 @@ class TellyscopeViewModel(}}+ /**+ * Who has access every 10 s while the TV's page is open, and what's plugged in every 30 s.+ * A failed read keeps the last answer; a removal in progress does its own reads.+ */+ private suspend fun watchAccess(id: String) {+ var tick = 0+ while (true) {+ if (_state.value.device.removal == null) readAccess(id)+ if (tick++ % 3 == 0) {+ val found = try { source.peripherals(id) } catch (e: CancellationException) { throw e } catch (_: Exception) { null }+ found?.let { p -> updateDevice(id) { it.copy(peripherals = p) } }+ }+ delay(10_000)+ }+ }++ private suspend fun readAccess(id: String): TvAccess? {+ val access = try { source.access(id) } catch (e: CancellationException) { throw e } catch (_: Exception) { null }+ access?.let { a -> updateDevice(id) { it.copy(access = a) } }+ return access+ }++ /** "It's mine": that address stops raising the warning on this TV. */+ fun markMine(address: String) {+ val id = _state.value.selectedId ?: return+ viewModelScope.launch {+ source.markMine(id, address)+ readAccess(id)+ }+ }++ private fun setRemoval(id: String, removal: Removal?) = updateDevice(id) { it.copy(removal = removal) }++ /** "Remove all other access…": asks first. */+ fun askRemoveAccess() {+ val id = _state.value.selectedId ?: return+ setRemoval(id, Removal(Removal.Step.Confirm))+ }++ /** Cancel, Stop waiting or Done: the flow closes. Keys already cleared stay cleared. */+ fun closeRemoval() {+ removalJob?.cancel()+ val id = _state.value.selectedId ?: return+ setRemoval(id, null)+ viewModelScope.launch { readAccess(id) }+ }++ /** Clears every key on the TV, or opens the manual guide when the TV won't take the call. */+ fun removeAccess() {+ val id = _state.value.selectedId ?: return+ removalJob?.cancel()+ removalJob = viewModelScope.launch {+ setRemoval(id, Removal(Removal.Step.Revoking))+ val ok = try { source.revokeAll(id) } catch (e: CancellationException) { throw e } catch (_: Exception) { false }+ if (ok) relink(id) else setRemoval(id, Removal(Removal.Step.Manual))+ }+ }++ /** The manual guide's first step: Developer options open on the TV. */+ fun openDeveloperOptions() {+ val id = _state.value.selectedId ?: return+ viewModelScope.launch {+ val ok = try { source.openDeveloperOptions(id) } catch (e: CancellationException) { throw e } catch (_: Exception) { false }+ if (!ok) _notice.value = Copy.DEV_OPTIONS_FAILED+ }+ }++ /** The user revoked on the TV by hand: reconnect and allow this phone, as after the call. */+ fun revokedByHand() {+ val id = _state.value.selectedId ?: return+ removalJob?.cancel()+ removalJob = viewModelScope.launch { relink(id) }+ }++ /** The TV refused this phone: show its prompt again. */+ fun askTvAgain() {+ val id = _state.value.selectedId ?: return+ updateDevice(id) { it.copy(removal = it.removal?.copy(refused = false)) }+ viewModelScope.launch { source.reconnect(id) }+ }++ /**+ * Reconnects so the TV asks to allow this phone, waits for it to be back, then checks. A link+ * that stays up through the revoke didn't need allowing again, and is checked straight away.+ */+ private suspend fun relink(id: String) {+ setRemoval(id, Removal(Removal.Step.Allow, fingerprint = source.phoneFingerprint()))+ source.reconnect(id)+ suspend fun state() = source.known().firstOrNull { it.id == id }?.state+ var dropped = false+ var waited = 0L+ while (true) {+ val st = state()+ if (st != DeviceState.Online) dropped = true+ if (st == DeviceState.Online && (dropped || waited >= RELINK_GRACE_MS)) break+ if (st == DeviceState.NotAllowed) updateDevice(id) { it.copy(removal = it.removal?.copy(refused = true)) }+ delay(1_000)+ waited += 1_000+ }+ setRemoval(id, Removal(Removal.Step.Checking))+ setRemoval(id, outcome(readAccess(id)))+ }++ /** "Try again" after another computer was still there: clear again, no need to ask twice. */+ fun retryRemoval() = removeAccess()+/** "Pick your TV": remember the choice for this TV and show its list. */fun pickList(listId: String) {val id = _state.value.selectedId ?: returndiff --git a/app/src/test/java/app/tellyscope/RemoveAccessTest.kt b/app/src/test/java/app/tellyscope/RemoveAccessTest.ktnew file mode 100644index 0000000..d2946e7--- /dev/null+++ b/app/src/test/java/app/tellyscope/RemoveAccessTest.kt@@ -0,0 +1,149 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope++import androidx.lifecycle.viewModelScope+import app.tellyscope.data.Device+import app.tellyscope.data.DeviceSource+import app.tellyscope.data.DeviceState+import app.tellyscope.data.FakeDeviceSource+import app.tellyscope.data.ScanHit+import app.tellyscope.data.ScanKind+import app.tellyscope.data.Snapshot+import app.tellyscope.data.TvAccess+import app.tellyscope.ui.Removal+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.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.Assert.assertTrue+import org.junit.Before+import org.junit.Test++/** A TV whose access, revoke answer and link state the test sets. */+private class AccessTv : DeviceSource by FakeDeviceSource(FakeDeviceSource.Scenario.Empty, clock = { 0L }) {+ var state = DeviceState.Online+ var revokes = true+ var revoked = 0+ var reconnects = 0+ var devOptions = 0+ var after = TvAccess()++ override suspend fun known() = listOf(Device("tv", ScanHit("tv", 5555, ScanKind.Classic, "tv", null), state, null, null, null, 0L))+ override fun live(deviceId: String) = emptyFlow<Snapshot>()+ override suspend fun apps(deviceId: String) = emptyList<app.tellyscope.data.AppInfo>()+ override suspend fun access(deviceId: String) = if (state == DeviceState.Online) after else throw IllegalStateException("offline")+ override suspend fun revokeAll(deviceId: String): Boolean { revoked++; return revokes }+ override suspend fun reconnect(deviceId: String) { reconnects++ }+ override suspend fun openDeveloperOptions(deviceId: String): Boolean { devOptions++; return true }+ override fun phoneFingerprint() = "AA:BB"+}++@OptIn(ExperimentalCoroutinesApi::class)+class RemoveAccessTest {+ private val dispatcher = StandardTestDispatcher()+ private val test = TestScope(dispatcher)+ private val tv = AccessTv()+ private lateinit var vm: TellyscopeViewModel++ private val onlyPhone = TvAccess(listOf(app.tellyscope.data.AccessClient("192.0.2.10", 1, app.tellyscope.data.AccessClient.Who.Phone)), emptyList())++ @Before fun setUp() = Dispatchers.setMain(dispatcher)++ @After fun tearDown() {+ if (::vm.isInitialized) vm.viewModelScope.cancel()+ Dispatchers.resetMain()+ }++ private fun start() = with(test) {+ vm = TellyscopeViewModel(tv, clock = { 0L })+ runCurrent()+ }++ private val step get() = vm.state.value.device.removal?.step++ @Test fun confirmThenRevokeThenAllowOnTheTvThenDone() = with(test) {+ start()+ vm.askRemoveAccess()+ assertEquals(Removal.Step.Confirm, step)+ vm.removeAccess()+ runCurrent()+ assertEquals(1, tv.revoked)+ assertEquals(Removal.Step.Allow, step)+ assertEquals("AA:BB", vm.state.value.device.removal?.fingerprint)+ assertEquals(1, tv.reconnects)+ // The link drops while the TV asks; the user allows; it's back.+ tv.state = DeviceState.Waiting+ advanceTimeBy(3_100)+ assertEquals(Removal.Step.Allow, step)+ tv.after = onlyPhone+ tv.state = DeviceState.Online+ advanceTimeBy(3_100)+ assertEquals(Removal.Step.Done, step)+ }++ @Test fun aTvThatRefusesTheCallGetsTheManualGuide() = with(test) {+ tv.revokes = false+ start()+ vm.askRemoveAccess()+ vm.removeAccess()+ runCurrent()+ assertEquals(Removal.Step.Manual, step)+ assertEquals(0, tv.reconnects)+ vm.openDeveloperOptions()+ runCurrent()+ assertEquals(1, tv.devOptions)+ vm.revokedByHand()+ runCurrent()+ assertEquals(Removal.Step.Allow, step)+ assertEquals(1, tv.reconnects)+ }++ @Test fun refusedOnTheTvOffersToAskAgain() = with(test) {+ start()+ vm.askRemoveAccess()+ vm.removeAccess()+ runCurrent()+ tv.state = DeviceState.NotAllowed+ advanceTimeBy(1_100)+ assertTrue(vm.state.value.device.removal!!.refused)+ vm.askTvAgain()+ runCurrent()+ assertEquals(2, tv.reconnects)+ assertEquals(false, vm.state.value.device.removal!!.refused)+ }++ @Test fun aLinkThatStaysUpIsCheckedAfterTheGraceAndAnotherComputerIsNamed() = with(test) {+ tv.after = TvAccess(onlyPhone.connected!! + app.tellyscope.data.AccessClient("192.0.2.47", 2, app.tellyscope.data.AccessClient.Who.Other), emptyList())+ start()+ vm.askRemoveAccess()+ vm.removeAccess()+ advanceTimeBy(6_100)+ assertEquals(Removal.Step.StillConnected, step)+ vm.closeRemoval()+ runCurrent()+ assertNull(step)+ }++ @Test fun stopWaitingLeavesTheFlow() = with(test) {+ start()+ vm.askRemoveAccess()+ vm.removeAccess()+ runCurrent()+ tv.state = DeviceState.Waiting+ vm.closeRemoval()+ tv.state = DeviceState.Online+ advanceTimeBy(5_000)+ assertNull(step)+ }+}diff --git a/app/src/test/java/app/tellyscope/ScreenshotTest.kt b/app/src/test/java/app/tellyscope/ScreenshotTest.ktindex 6f4b071..01e4afd 100644--- a/app/src/test/java/app/tellyscope/ScreenshotTest.kt+++ b/app/src/test/java/app/tellyscope/ScreenshotTest.kt@@ -63,6 +63,11 @@ import app.tellyscope.data.SuggestedGroupimport app.tellyscope.data.Procimport app.tellyscope.data.Suggestionsimport app.tellyscope.ui.AboutDialog+import app.tellyscope.ui.Removal+import app.tellyscope.ui.ConnectedDevicesCard+import app.tellyscope.ui.AccessWarning+import app.tellyscope.ui.AccessScreen+import app.tellyscope.ui.AccessActionsimport app.tellyscope.ui.AdvancedScreenimport app.tellyscope.ui.AppsTabimport app.tellyscope.ui.ConnectScreen@@ -1420,4 +1425,56 @@ class ScreenshotTest {val t = TransferUi("family-trip-2025.mp4", toTv = true, folder = TvFolder.MOVIES, progress = Progress(486_000_000, 812_000_000))DeviceTabsScreen(deviceState { copy(transfer = t) }, DeviceActions())}++ // Connected devices and the access warning (0.9): the cards on their own, then the TV page with+ // both, then Who has access and each step of Remove all other access.+ private fun accessState(removal: Removal? = null) = runBlocking {+ md3State().let { it.copy(device = it.device.copy(access = fake.access(it.selectedId!!), peripherals = fake.peripherals(it.selectedId!!), removal = removal)) }+ }++ private fun card(name: String, dark: Boolean, content: @Composable () -> Unit) = shot(name, dark) {+ Surface { Column(Modifier.padding(16.dp)) { content() } }+ }++ @Test fun access_warning() = card("90_access_warning", false) { AccessWarning(accessState().device.access!!, AccessActions(), onWho = {}) }+ @Test fun access_warning_dark() = card("90_access_warning", true) { AccessWarning(accessState().device.access!!, AccessActions(), onWho = {}) }+ @Test fun access_warning_open() = card("91_access_warning_open", false) { AccessWarning(accessState().device.access!!, AccessActions(), onWho = {}, startOpen = true) }+ @Test fun access_warning_open_dark() = card("91_access_warning_open", true) { AccessWarning(accessState().device.access!!, AccessActions(), onWho = {}, startOpen = true) }+ @Test fun devices_card() = card("92_connected_devices", false) { ConnectedDevicesCard(accessState().device.peripherals!!) }+ @Test fun devices_card_dark() = card("92_connected_devices", true) { ConnectedDevicesCard(accessState().device.peripherals!!) }+ @Test fun devices_card_open() = card("93_connected_devices_open", false) { ConnectedDevicesCard(accessState().device.peripherals!!, startOpen = true) }+ @Test fun devices_card_open_dark() = card("93_connected_devices_open", true) { ConnectedDevicesCard(accessState().device.peripherals!!, startOpen = true) }++ /** The Overview with both cards, scrolled to them: warning first, then devices, then Android. */+ private fun accessOverview(dark: Boolean) {+ // By key: scrolling to a node by tag never stops with the clock held.+ val scroll = { compose.onNode(hasScrollAction()).performScrollToKey("accessWarning"); Unit }+ // Built once: a fresh state on every recomposition would never let the page settle.+ val state = accessState()+ shot("94_overview_access", dark, before = scroll) { DeviceTabsScreen(state, DeviceActions()) }+ compose.onNodeWithTag("accessWarning").assertExists()+ }+ @Test fun access_overview() = accessOverview(false)+ @Test fun access_overview_dark() = accessOverview(true)++ private fun accessScreen(name: String, dark: Boolean, removal: Removal?) {+ val state = accessState(removal)+ shot(name, dark, screen = removal?.step == Removal.Step.Confirm) { AccessScreen(state, AccessActions()) }+ }+ @Test fun access_list() = accessScreen("95_who_has_access", false, null)+ @Test fun access_list_dark() = accessScreen("95_who_has_access", true, null)+ @Test fun access_confirm() = accessScreen("96_remove_confirm", false, Removal(Removal.Step.Confirm))+ @Test fun access_confirm_dark() = accessScreen("96_remove_confirm", true, Removal(Removal.Step.Confirm))+ private val allow = Removal(Removal.Step.Allow, fingerprint = "3F:9A:1C:5D:E0:42:B7:19:8C:6A:F3:21:0D:94:7E:C2")+ @Test fun access_allow() = accessScreen("97_remove_allow", false, allow)+ @Test fun access_allow_dark() = accessScreen("97_remove_allow", true, allow)+ @Test fun access_done() = accessScreen("98_remove_done", false, Removal(Removal.Step.Done))+ @Test fun access_done_dark() = accessScreen("98_remove_done", true, Removal(Removal.Step.Done))+ private val still = Removal(Removal.Step.StillConnected, still = Copy.connectionFrom("192.0.2.47"))+ @Test fun access_still() = accessScreen("99_remove_still", false, still)+ @Test fun access_still_dark() = accessScreen("99_remove_still", true, still)+ @Test fun access_unconfirmed() = accessScreen("99_remove_unconfirmed", false, Removal(Removal.Step.Unconfirmed))+ @Test fun access_unconfirmed_dark() = accessScreen("99_remove_unconfirmed", true, Removal(Removal.Step.Unconfirmed))+ @Test fun access_manual() = accessScreen("99_remove_manual", false, Removal(Removal.Step.Manual))+ @Test fun access_manual_dark() = accessScreen("99_remove_manual", true, Removal(Removal.Step.Manual))}diff --git a/app/src/test/java/app/tellyscope/TvAccessTest.kt b/app/src/test/java/app/tellyscope/TvAccessTest.ktnew file mode 100644index 0000000..f871685--- /dev/null+++ b/app/src/test/java/app/tellyscope/TvAccessTest.kt@@ -0,0 +1,89 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope++import app.tellyscope.adb.AdbClient+import app.tellyscope.adb.AllowedKey+import app.tellyscope.data.AccessClient.Who+import app.tellyscope.data.MineBook+import app.tellyscope.data.TvAccess+import app.tellyscope.ui.Copy+import app.tellyscope.ui.Removal+import app.tellyscope.ui.outcome+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Rule+import org.junit.Test+import org.junit.rules.TemporaryFolder++/** When "another computer is connected" shows, and when Remove all other access may say Done. */+class TvAccessTest {+ @get:Rule val tmp = TemporaryFolder()++ private val phone = "192.0.2.10"+ private val other = "192.0.2.47"+ private val phoneKey = AllowedKey("AA", "tellyscope@phone", 1)+ private val laptop = AllowedKey("BB", "alex@laptop", 2)++ private fun access(vararg clients: AdbClient, keys: List<AllowedKey>? = listOf(phoneKey), mine: Set<String> = emptySet(), tv: String = "192.0.2.20") =+ TvAccess.of(clients.toList(), keys, setOf(phone, "fe80::1"), tv, mine, phoneFingerprint = "AA")++ @Test fun onlyThisPhoneConnectedIsNoWarning() {+ val a = access(AdbClient(phone, 40000))+ assertFalse(a.warning)+ assertEquals(listOf(Who.Phone), a.connected!!.map { it.who })+ }++ @Test fun anotherAddressIsAWarningWithItsConnectionsCounted() {+ val a = access(AdbClient(phone, 40000), AdbClient(other, 51234), AdbClient(other, 51240))+ assertTrue(a.warning)+ assertEquals(other, a.others.single().address)+ assertEquals(2, a.others.single().connections)+ }++ @Test fun itsMineSilencesThatAddressOnly() {+ val a = access(AdbClient(other, 1), AdbClient("192.0.2.99", 2), mine = setOf(other))+ assertEquals(listOf("192.0.2.99"), a.others.map { it.address })+ assertEquals(Who.Mine, a.connected!!.first { it.address == other }.who)+ }++ @Test fun loopbackIsAnAppOnTheTvUnlessTellyscopeItselfUsesLoopback() {+ assertEquals(Who.OnTv, access(AdbClient("127.0.0.1", 1)).others.single().who)+ assertFalse(access(AdbClient("127.0.0.1", 1), tv = "127.0.0.1").warning)+ assertFalse(access(AdbClient("::1", 1), tv = "localhost").warning)+ }++ @Test fun cantReadTheTableIsNotNobody() {+ val a = TvAccess.of(null, null, setOf(phone), "tv", emptySet(), "AA")+ assertFalse(a.warning)+ assertFalse(a.onlyThisPhone)+ assertNull(a.connected)+ }++ @Test fun thisPhonesKeyIsMarkedAndFirst() {+ val a = access(keys = listOf(laptop, phoneKey))+ assertEquals(listOf(true, false), a.allowed!!.map { it.phone })+ }++ @Test fun doneOnlyAfterACheckThatFindsNobodyElse() {+ assertEquals(Removal.Step.Done, outcome(access(AdbClient(phone, 1))).step)+ // Not ticking "Always allow" leaves the list empty: still nobody else.+ assertEquals(Removal.Step.Done, outcome(access(AdbClient(phone, 1), keys = emptyList())).step)+ val still = outcome(access(AdbClient(phone, 1), AdbClient(other, 2)))+ assertEquals(Removal.Step.StillConnected, still.step)+ assertEquals(Copy.connectionFrom(other), still.still)+ assertEquals("alex@laptop", outcome(access(AdbClient(phone, 1), keys = listOf(phoneKey, laptop))).still)+ assertEquals(Removal.Step.Unconfirmed, outcome(null).step)+ assertEquals(Removal.Step.Unconfirmed, outcome(access(AdbClient(phone, 1), keys = null)).step)+ }++ @Test fun mineBookPersistsAndFollowsTheTv() {+ val f = tmp.newFile("mine.tsv")+ MineBook(f).apply { add("192.0.2.20", other); add("192.0.2.20", "bad\taddress"); rekey("192.0.2.20", "serial-1") }+ val book = MineBook(f)+ assertEquals(setOf(other), book["serial-1"])+ assertTrue(book["192.0.2.20"].isEmpty())+ }+}diff --git a/docs/screenshots/access-warning.png b/docs/screenshots/access-warning.pngnew file mode 100644index 0000000..07a9799Binary files /dev/null and b/docs/screenshots/access-warning.png differdiff --git a/docs/screenshots/frame.py b/docs/screenshots/frame.pyindex 124987f..4d47895 100644--- a/docs/screenshots/frame.py+++ b/docs/screenshots/frame.py@@ -26,6 +26,8 @@ SHOTS = {"send": "25_readme_send","tweaks": "29_readme_tweaks","home": "30_readme_home",+ "access-warning": "94_overview_access",+ "who-has-access": "95_who_has_access",}DP = 3 # the tests render at xxhdpidiff --git a/docs/screenshots/who-has-access.png b/docs/screenshots/who-has-access.pngnew file mode 100644index 0000000..87c2d2cBinary files /dev/null and b/docs/screenshots/who-has-access.png differ