Skip to content

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.

Fix five bugs from the code rescan

jesse-agent-36268efc3e3037f
diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Files.kt b/adb/src/main/kotlin/app/tellyscope/adb/Files.kt
index 71fa823..adc208a 100644
--- a/adb/src/main/kotlin/app/tellyscope/adb/Files.kt
+++ b/adb/src/main/kotlin/app/tellyscope/adb/Files.kt
@@ -35,7 +35,9 @@ class Files(private val session: AdbSession) {
folder: TvFolder,
onProgress: (Progress) -> Unit = {},
): String {
- val target = uniqueName(safeName(name), list(folder).map { it.name }.toSet())
+ // Every entry counts as taken, hidden files and folders too, not just what [list] shows.
+ val taken = runTransfer { _ -> session.list(folder.path).map { it.name }.toSet() }
+ val target = uniqueName(safeName(name), taken)
val path = "${folder.path}/$target"
runTransfer(cleanUp = { runCatching { session.shell("rm -f ${shellQuote(path)}") } }) { stopped ->
session.push(source.counting(size, stopped, onProgress), path, FILE_MODE, System.currentTimeMillis())
diff --git a/adb/src/test/kotlin/app/tellyscope/adb/FilesTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/FilesTest.kt
index bc50f8b..340e832 100644
--- a/adb/src/test/kotlin/app/tellyscope/adb/FilesTest.kt
+++ b/adb/src/test/kotlin/app/tellyscope/adb/FilesTest.kt
@@ -30,6 +30,14 @@ class FilesTest {
assertContentEquals(byteArrayOf(1), sh.transfer.files["/sdcard/Download/clip.mp4"])
}
+ @Test fun pushNeverOverwritesAHiddenFile() = runTest {
+ val sh = FakeShell()
+ sh.transfer.files["/sdcard/Download/.config"] = byteArrayOf(1)
+ val name = Files(sh).push(Buffer().write(data), data.size.toLong(), ".config", TvFolder.DOWNLOAD)
+ assertEquals(".config (1)", name)
+ assertContentEquals(byteArrayOf(1), sh.transfer.files["/sdcard/Download/.config"])
+ }
+
@Test fun pushReportsProgressToTheEnd() = runTest {
val sh = FakeShell()
val seen = mutableListOf<Progress>()
diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
index e2bd4c7..16770e3 100644
--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
@@ -553,25 +553,18 @@ class AdbDeviceSource(context: Context) : DeviceSource {
val t = Tweaks(session(deviceId))
val strictDns = tweak == Tweak.PRIVATE_DNS && values["private_dns_mode"] == "hostname"
if (strictDns && (sdk(deviceId) ?: TvSettings.DNS_SDK) < TvSettings.DNS_SDK) throw IllegalStateException(TvSettings.DNS_TOO_OLD)
- // Only the keys being written: Undo must not touch the ones this change left alone.
- val before = t.read(tweak).filterKeys { it in values }
- if (!t.write(tweak, values)) throw IllegalStateException("the TV didn't accept the change")
- // Strict Private DNS fails closed: a provider the network can't reach takes the TV
- // offline. Put it back on the spot; ADB stays up, it's the LAN by address.
- if (strictDns && !t.resolves()) {
- t.write(tweak, before)
- throw IllegalStateException(TvSettings.dnsUnreachable(values["private_dns_specifier"]))
+ return applyTweak(t, tweak, values, strictDns) { label, previous ->
+ book.record(
+ deviceId = key(deviceId),
+ at = System.currentTimeMillis(),
+ action = Action.Change,
+ packageName = tweak.name,
+ label = label,
+ undo = Action.Change,
+ undoing = undoing,
+ previous = previous,
+ )
}
- return book.record(
- deviceId = key(deviceId),
- at = System.currentTimeMillis(),
- action = Action.Change,
- packageName = tweak.name,
- label = TvSettings.label(tweak, t.read(tweak)),
- undo = Action.Change,
- undoing = undoing,
- previous = before,
- )
}
override suspend fun clearCaches(deviceId: String): Long? {
@@ -687,3 +680,34 @@ class AdbDeviceSource(context: Context) : DeviceSource {
ProtectedReason.CAME_WITH_TV -> "it came with the TV, so it can only be disabled"
}
}
+
+/**
+ * Writes [values] and hands [record] the label and the old values for History. Strict Private DNS
+ * fails closed: a provider the network can't reach takes the TV offline, so it's put back on the
+ * spot (ADB stays up, it's the LAN by address). If putting it back fails too, the change is still
+ * recorded, so Undo in History can take the TV back.
+ */
+internal suspend fun applyTweak(
+ t: Tweaks,
+ tweak: Tweak,
+ values: Map<String, String?>,
+ strictDns: Boolean,
+ record: suspend (label: String, previous: Map<String, String?>) -> HistoryEntry,
+): HistoryEntry {
+ // Only the keys being written: Undo must not touch the ones this change left alone.
+ val before = t.read(tweak).filterKeys { it in values }
+ if (!t.write(tweak, values)) throw IllegalStateException("the TV didn't accept the change")
+ if (strictDns && !t.resolves()) {
+ val restored = try {
+ t.write(tweak, before)
+ } catch (e: CancellationException) {
+ throw e
+ } catch (_: Exception) {
+ false
+ }
+ if (restored) throw IllegalStateException(TvSettings.dnsUnreachable(values["private_dns_specifier"]))
+ record(TvSettings.label(tweak, values), before)
+ throw IllegalStateException(TvSettings.dnsStuck(values["private_dns_specifier"]))
+ }
+ return record(TvSettings.label(tweak, t.read(tweak)), before)
+}
diff --git a/app/src/main/java/app/tellyscope/data/DeviceLists.kt b/app/src/main/java/app/tellyscope/data/DeviceLists.kt
index 21edc99..64ee29c 100644
--- a/app/src/main/java/app/tellyscope/data/DeviceLists.kt
+++ b/app/src/main/java/app/tellyscope/data/DeviceLists.kt
@@ -154,12 +154,12 @@ fun matches(rule: Map<String, List<String>>?, props: Map<String, String?>): Bool
values.any { it.equals(actual, ignoreCase = true) }
}
-/** Null unless it is a schema 1 index. Entries with a bad file name or checksum are dropped. */
+/** Null unless it is a schema 1 index. Entries with a missing field, bad file name or checksum are dropped. */
fun parseIndex(text: String): ListIndex? = try {
val o = jsonObject(text)
if (o.optInt("schema") != SCHEMA) null else ListIndex(
commit = o.optJSONObject("source")?.optStringOrNull("commit"),
- devices = o.getJSONArray("devices").objects().mapNotNull { d ->
+ devices = o.getJSONArray("devices").objectsOrSkip { d ->
ListEntry(
id = d.getString("id"),
name = d.getString("name"),
@@ -176,20 +176,22 @@ fun parseIndex(text: String): ListIndex? = try {
null
}
-/** Null unless it is a schema 1 device file for [id]. Names that aren't package names are dropped. */
+/**
+ * Null unless it is a schema 1 device file for [id]. Entries that can't be read and names that
+ * aren't package names are dropped.
+ */
fun parseList(text: String, id: String): DeviceList? = try {
val o = jsonObject(text)
val tested = o.optJSONObject("tested")
- fun packages(a: JSONArray?) = a?.objects().orEmpty()
- .map { ListPackage(it.getString("pkg"), it.optStringOrNull("note"), it.optBoolean("optional")) }
- .filter { PACKAGE.matches(it.pkg) }
+ fun packages(a: JSONArray?) = a?.objectsOrSkip { ListPackage(it.getString("pkg"), it.optStringOrNull("note"), it.optBoolean("optional")) }
+ .orEmpty().filter { PACKAGE.matches(it.pkg) }
if (o.optInt("schema") != SCHEMA || o.optString("id") != id) null else DeviceList(
id = id,
name = o.getString("name"),
testedOs = tested?.optStringOrNull("os"),
sdk = tested?.optIntOrNull("sdk"),
keep = packages(o.optJSONArray("keep")).map { it.pkg }.toSet(),
- groups = o.getJSONArray("groups").objects().map { g ->
+ groups = o.getJSONArray("groups").objectsOrSkip { g ->
ListGroup(g.optString("title"), packages(g.optJSONArray("packages")))
}.filter { it.packages.isNotEmpty() },
)
@@ -200,15 +202,17 @@ fun parseList(text: String, id: String): DeviceList? = try {
/**
* The list cut down to this TV: only apps it actually has, still on, and not protected (built in
* or by the list's keep). Pre-ticked only for non-optional entries on a TV with the SDK the list
- * was tested on.
+ * was tested on. Groups with the same title become one, and an app shows once, in its first group,
+ * since the screen keys rows by title and package.
*/
fun suggest(list: DeviceList, apps: List<AppInfo>, sdk: Int?): List<SuggestedGroup> {
val installed = apps.associateBy { it.packageName }
val tick = sdk != null && sdk == list.sdk
- return list.groups.map { g ->
- SuggestedGroup(g.title, g.packages.mapNotNull { p ->
+ val seen = mutableSetOf<String>()
+ return list.groups.groupBy { it.title }.map { (title, gs) ->
+ SuggestedGroup(title, gs.flatMap { it.packages }.mapNotNull { p ->
val app = installed[p.pkg]?.takeIf { it.enabled && it.protectedReason == null && p.pkg !in list.keep }
- app?.let { Suggested(p.pkg, it.label, p.note, p.optional, ticked = tick && !p.optional) }
+ app?.takeIf { seen.add(p.pkg) }?.let { Suggested(p.pkg, it.label, p.note, p.optional, ticked = tick && !p.optional) }
})
}.filter { it.packages.isNotEmpty() }
}
@@ -409,7 +413,14 @@ internal fun depth(text: String): Int {
return max
}
-private fun JSONArray.objects() = (0 until length()).map { getJSONObject(it) }
+/** [f] over each element, leaving out any that isn't an object or that [f] can't read. */
+private fun <T : Any> JSONArray.objectsOrSkip(f: (JSONObject) -> T?): List<T> = (0 until length()).mapNotNull {
+ try {
+ f(getJSONObject(it))
+ } catch (_: org.json.JSONException) {
+ null
+ }
+}
private fun JSONArray.strings() = (0 until length()).map { getString(it) }
private fun JSONObject.optStringOrNull(k: String) = if (isNull(k)) null else optString(k)
private fun JSONObject.optIntOrNull(k: String) = if (isNull(k)) null else optInt(k)
diff --git a/app/src/main/java/app/tellyscope/data/TvSettings.kt b/app/src/main/java/app/tellyscope/data/TvSettings.kt
index 4f59c81..f9d03d0 100644
--- a/app/src/main/java/app/tellyscope/data/TvSettings.kt
+++ b/app/src/main/java/app/tellyscope/data/TvSettings.kt
@@ -46,4 +46,8 @@ object TvSettings {
fun dnsUnreachable(host: String?) =
"the TV couldn't look anything up through $host, so Private DNS was put back. The network may block encrypted DNS (port 853)"
+
+ fun dnsStuck(host: String?) =
+ "the TV couldn't look anything up through $host, and putting the old Private DNS back failed. " +
+ "The TV may be offline until you undo it in History"
}
diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
index 4d79aa3..8165d49 100644
--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
@@ -238,27 +238,28 @@ class TellyscopeViewModel(
fun rescan() {
if (scanJob?.isActive == true) return
scanJob = viewModelScope.launch {
- _state.update { it.copy(scan = it.scan.copy(scanning = true, noLan = false)) }
- source.scan().collect { e ->
- when (e) {
- is ScanEvent.Progress -> _state.update { it.copy(scan = it.scan.copy(progress = e.progress)) }
- is ScanEvent.Found -> _state.update { s ->
- val known = s.devices.any { it.hit.ip == e.hit.ip }
- if (known || s.scan.hits.any { it.ip == e.hit.ip }) s
- else s.copy(scan = s.scan.copy(
- hits = (s.scan.hits + e.hit).sortedWith(compareBy({ it.maker == null }, { ipKey(it.ip) })),
- rows = s.scan.rows + (e.hit.ip to RowState.Found),
- ))
+ // Empty scan with no TV open: the guide is on screen; keep looking so the user never has to
+ // press anything. The retry stays in this job, as rescan() from here would see it still active.
+ while (true) {
+ _state.update { it.copy(scan = it.scan.copy(scanning = true, noLan = false)) }
+ source.scan().collect { e ->
+ when (e) {
+ is ScanEvent.Progress -> _state.update { it.copy(scan = it.scan.copy(progress = e.progress)) }
+ is ScanEvent.Found -> _state.update { s ->
+ val known = s.devices.any { it.hit.ip == e.hit.ip }
+ if (known || s.scan.hits.any { it.ip == e.hit.ip }) s
+ else s.copy(scan = s.scan.copy(
+ hits = (s.scan.hits + e.hit).sortedWith(compareBy({ it.maker == null }, { ipKey(it.ip) })),
+ rows = s.scan.rows + (e.hit.ip to RowState.Found),
+ ))
+ }
+ ScanEvent.NoLan -> _state.update { it.copy(scan = it.scan.copy(noLan = true)) }
+ ScanEvent.Done -> Unit
}
- ScanEvent.NoLan -> _state.update { it.copy(scan = it.scan.copy(noLan = true)) }
- ScanEvent.Done -> Unit
}
- }
- _state.update { it.copy(scan = it.scan.copy(scanning = false)) }
- // Empty scan: the guide is on screen; keep looking so the user never has to press anything.
- if (_state.value.scan.hits.isEmpty()) {
+ _state.update { it.copy(scan = it.scan.copy(scanning = false)) }
+ if (_state.value.let { it.scan.hits.isNotEmpty() || it.selected != null }) break
delay(15_000)
- rescan()
}
}
}
@@ -446,7 +447,9 @@ class TellyscopeViewModel(
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
- updateDevice(id) { it.copy(busy = null) }
+ // A change can fail after it was recorded (a rollback that didn't take), so History is reread.
+ val history = source.history(id)
+ updateDevice(id) { it.copy(busy = null, history = history) }
_notice.value = e.message?.replaceFirstChar(Char::uppercase) ?: "That didn't work."
return@launch
}
diff --git a/app/src/test/java/app/tellyscope/DeviceListsTest.kt b/app/src/test/java/app/tellyscope/DeviceListsTest.kt
index 0aa3850..1e94f87 100644
--- a/app/src/test/java/app/tellyscope/DeviceListsTest.kt
+++ b/app/src/test/java/app/tellyscope/DeviceListsTest.kt
@@ -204,6 +204,43 @@ class DeviceListsTest {
assertEquals(mapOf("com.a.one" to false, "com.a.two" to false), suggest(list.copy(sdk = null), apps, null).flatMap { it.packages }.associate { it.pkg to it.ticked })
}
+ @Test fun anAppInTwoGroupsOrTwoGroupsWithOneTitleShowOnce() {
+ fun p(pkg: String) = ListPackage(pkg, null, false)
+ val list = DeviceList(
+ "x", "X", null, 30, emptySet(),
+ listOf(
+ ListGroup("Junk", listOf(p("com.a.one"), p("com.a.two"))),
+ ListGroup("Ads", listOf(p("com.a.one"), p("com.a.three"))),
+ ListGroup("Junk", listOf(p("com.a.four"), p("com.a.two"))),
+ ),
+ )
+ val groups = suggest(list, listOf("one", "two", "three", "four").map { app("com.a.$it") }, 30)
+ // The screen keys rows by group title and by package, so a repeat of either crashes it.
+ assertEquals(listOf("Junk", "Ads"), groups.map { it.title })
+ assertEquals(listOf("com.a.one", "com.a.two", "com.a.four"), groups[0].packages.map { it.pkg })
+ assertEquals(listOf("com.a.three"), groups[1].packages.map { it.pkg })
+ }
+
+ @Test fun oneBadEntryIsDroppedNotTheWholeIndex() {
+ val text = """
+ {"schema": 1, "devices": [
+ {"id": "no-sha", "name": "No sha", "file": "devices/no-sha.json"},
+ "not an object",
+ {"id": "good", "name": "Good", "file": "devices/good.json", "sha256": "${"0".repeat(64)}"}]}
+ """.trimIndent()
+ assertEquals(listOf("good"), parseIndex(text)?.devices?.map { it.id })
+ }
+
+ @Test fun oneBadPackageOrGroupIsDroppedNotTheWholeList() {
+ val text = """
+ {"schema": 1, "id": "x", "name": "X", "keep": [{"note": "no pkg"}, {"pkg": "com.a.keep"}],
+ "groups": [7, {"title": "Junk", "packages": [{"note": "no pkg"}, {"pkg": "com.a.one"}]}]}
+ """.trimIndent()
+ val list = parseList(text, "x")
+ assertEquals(setOf("com.a.keep"), list?.keep)
+ assertEquals(listOf("com.a.one"), list?.groups?.flatMap { g -> g.packages.map { it.pkg } })
+ }
+
@Test fun keepIsNeverSuggested() {
val keep = setOf("com.acme.hdmi")
// A list that names a package in both keep and a group never suggests it.
diff --git a/app/src/test/java/app/tellyscope/DnsRollbackTest.kt b/app/src/test/java/app/tellyscope/DnsRollbackTest.kt
new file mode 100644
index 0000000..bc56c3a
--- /dev/null
+++ b/app/src/test/java/app/tellyscope/DnsRollbackTest.kt
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope
+
+import app.tellyscope.adb.AdbSession
+import app.tellyscope.adb.RemoteEntry
+import app.tellyscope.adb.ShellResult
+import app.tellyscope.adb.Tweak
+import app.tellyscope.adb.Tweaks
+import app.tellyscope.data.Action
+import app.tellyscope.data.HistoryBook
+import app.tellyscope.data.applyTweak
+import java.io.File
+import java.io.IOException
+import kotlinx.coroutines.test.runTest
+import okio.Sink
+import okio.Source
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** A TV whose DNS never resolves; [writes] counts `settings put` lines, and the ones in [failing] are refused. */
+private class NoDnsTv(private val failing: Set<Int>) : AdbSession {
+ var writes = 0
+
+ override suspend fun shell(command: String): ShellResult = when {
+ command.startsWith("ping") -> ShellResult("ping: unknown host", 2)
+ command.startsWith("settings get") -> ShellResult("null\noff\n", 0)
+ command.startsWith("settings") -> if (++writes in failing) throw IOException("link gone") else ShellResult("", 0)
+ else -> ShellResult("", 0)
+ }
+
+ override suspend fun push(bytes: ByteArray, remotePath: String) = Unit
+ override suspend fun reboot() = Unit
+ override fun install(source: Source, size: Long, vararg options: String) = Unit
+ override fun installMultiple(apks: List<File>, vararg options: String) = Unit
+ override fun push(source: Source, remotePath: String, mode: Int, lastModifiedMs: Long) = Unit
+ override fun pull(sink: Sink, remotePath: String) = Unit
+ override fun list(remoteDir: String) = emptyList<RemoteEntry>()
+ override fun close() = Unit
+}
+
+class DnsRollbackTest {
+ private val dns = mapOf("private_dns_specifier" to "dns.example", "private_dns_mode" to "hostname")
+
+ private suspend fun run(tv: NoDnsTv, book: HistoryBook): String = try {
+ applyTweak(Tweaks(tv), Tweak.PRIVATE_DNS, dns, strictDns = true) { label, previous ->
+ book.record("tv", 0, Action.Change, Tweak.PRIVATE_DNS.name, label, Action.Change, previous = previous)
+ }
+ error("should have thrown")
+ } catch (e: IllegalStateException) {
+ e.message.orEmpty()
+ }
+
+ @Test fun aProviderThatDoesntResolveIsPutBackAndNotRecorded() = runTest {
+ val book = HistoryBook()
+ val tv = NoDnsTv(failing = emptySet())
+ assertTrue(run(tv, book).contains("was put back"))
+ assertEquals(2, tv.writes)
+ assertTrue(book.entries("tv").isEmpty())
+ }
+
+ @Test fun aFailedPutBackSaysSoAndLeavesAnUndoInHistory() = runTest {
+ val book = HistoryBook()
+ val message = run(NoDnsTv(failing = setOf(2)), book)
+ assertTrue(message, message.contains("putting the old Private DNS back failed"))
+ val entry = book.entries("tv").single()
+ assertEquals(Action.Change, entry.undo)
+ assertEquals(mapOf("private_dns_specifier" to null, "private_dns_mode" to "off"), entry.previous)
+ }
+}
diff --git a/app/src/test/java/app/tellyscope/OffWifiTest.kt b/app/src/test/java/app/tellyscope/OffWifiTest.kt
index 3d0f938..8f6fdea 100644
--- a/app/src/test/java/app/tellyscope/OffWifiTest.kt
+++ b/app/src/test/java/app/tellyscope/OffWifiTest.kt
@@ -24,6 +24,7 @@ import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.test.StandardTestDispatcher
+import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runCurrent
@@ -110,4 +111,24 @@ class OffWifiTest {
Dispatchers.resetMain()
}
}
+
+ @Test fun anEmptyScanTriesAgainEvery15Seconds() {
+ val dispatcher = StandardTestDispatcher()
+ Dispatchers.setMain(dispatcher)
+ val source = JoinsWifi()
+ val vm = TellyscopeViewModel(source, clock = { 0L })
+ try {
+ with(TestScope(dispatcher)) {
+ runCurrent()
+ assertEquals(1, source.scans)
+ advanceTimeBy(15_001)
+ assertEquals(2, source.scans)
+ advanceTimeBy(15_001)
+ assertEquals(3, source.scans)
+ }
+ } finally {
+ vm.viewModelScope.cancel()
+ Dispatchers.resetMain()
+ }
+ }
}