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.

Suggest what to disable from the TV's device list

jesse-agent-3626c9a3a1197d6
diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.kt
index 1ed2191..e19411f 100644
--- a/app/src/main/java/app/tellyscope/MainActivity.kt
+++ b/app/src/main/java/app/tellyscope/MainActivity.kt
@@ -183,6 +183,8 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {
pickFile = { folder -> vm.folder(folder); pickFile.launch(arrayOf("*/*")) },
saveFile = { f -> vm.saving(f); saveFile.launch(f.name) },
cancelTransfer = vm::cancelTransfer,
+ pickList = vm::pickList,
+ disableSuggested = vm::disableSuggested,
),
)
}
diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
index ceb7240..26c4b3e 100644
--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt
@@ -71,6 +71,9 @@ class AdbDeviceSource(context: Context) : DeviceSource {
private val labels = ConcurrentHashMap<String, String>()
private val helperDex by lazy { appContext.assets.open("label-helper.jar").use { it.readBytes() } }
private val appNames = AppNames(File(appContext.filesDir, "app-names"))
+ private val lists = DeviceLists(File(appContext.filesDir, "lists"))
+ /** [historyKey] → the keep entries of that TV's list, once it has been looked up. */
+ private val keep = ConcurrentHashMap<String, Set<String>>()
init {
Connector.init(File(appContext.filesDir, "adbkey.pem"))
@@ -251,6 +254,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {
.ifEmpty { Parsers.packages(shell.shell("pm list packages").output) }
// Same key as history: a placeholder serial must not give two boxes one cache.
val names = appNames.names(key(deviceId), listed, LabelHelper(shell, helperDex)::describe)
+ val keep = keep[key(deviceId)].orEmpty()
return listed.map { p ->
val name = names.getValue(p.name)
labels[p.name] = name.label
@@ -262,11 +266,14 @@ class AdbDeviceSource(context: Context) : DeviceSource {
enabled = p.name !in disabled,
// Same rule as Actions.run: no known launcher, nothing can be stopped or disabled.
// A disabled app stays unprotected so Enable (always allowed) still shows.
- protectedReason = when {
- home.isNotEmpty() -> Protected.reason(p.name, home)
- p.name in disabled -> null
- else -> ProtectedReason.UNKNOWN_HOME
- }?.let(::reasonText),
+ protectedReason = withKeep(
+ when {
+ home.isNotEmpty() -> Protected.reason(p.name, home)
+ p.name in disabled -> null
+ else -> ProtectedReason.UNKNOWN_HOME
+ }?.let(::reasonText),
+ p.name, enabled = p.name !in disabled, keep,
+ ),
version = "",
icon = name.icon,
)
@@ -290,6 +297,12 @@ class AdbDeviceSource(context: Context) : DeviceSource {
// Before the first change on a TV, note what was already off: Restore must leave those alone.
val key = key(deviceId)
if (!book.hasBaseline(key)) book.setBaseline(key, disabledPackages(deviceId))
+ // The list's keep entries add to the built-in protection in Actions.run; look it up if not yet.
+ if (action == Action.Stop || action == Action.Disable) {
+ if (keepRefuses(action, packageName, keep[key] ?: resolve(deviceId).list?.keep.orEmpty())) {
+ throw IllegalStateException(KEEP_REASON)
+ }
+ }
val r = Actions(shell).run(AdbAction.valueOf(action.name.uppercase()), packageName)
return when (r) {
is ActionResult.Done -> book.record(
@@ -317,6 +330,42 @@ class AdbDeviceSource(context: Context) : DeviceSource {
}
}
+ override suspend fun suggestions(deviceId: String): Suggestions = try {
+ val r = resolve(deviceId)
+ when {
+ r.index == null -> Suggestions.Unavailable
+ r.entry == null -> Suggestions.Pick(r.index.commit, r.index.devices)
+ r.list == null -> Suggestions.Unavailable
+ else -> Suggestions.Ready(r.index.commit, r.list, r.sdk, suggest(r.list, apps(deviceId), r.sdk), r.index.devices)
+ }
+ } catch (e: CancellationException) {
+ throw e
+ } catch (_: Exception) {
+ Suggestions.Unavailable // the TV dropped mid-read
+ }
+
+ override suspend fun pickList(deviceId: String, listId: String) {
+ val key = key(deviceId)
+ lists.pick(key, listId)
+ keep.remove(key)
+ }
+
+ private class Resolved(val index: ListIndex?, val entry: ListEntry?, val list: DeviceList?, val sdk: Int?)
+
+ /** This TV's list (picked, else matched), with its keep entries recorded for [apps] and [act]. */
+ private suspend fun resolve(deviceId: String): Resolved {
+ val index = lists.index() ?: return Resolved(null, null, null, null)
+ val out = session(deviceId).shell(
+ (MATCH_KEYS.map { "ro.product.$it" } + "ro.build.version.sdk").joinToString("; ") { "getprop $it" },
+ ).output.lines().map { it.trim().ifEmpty { null } }
+ val props = MATCH_KEYS.withIndex().associate { (i, k) -> k to out.getOrNull(i) }
+ val key = key(deviceId)
+ val entry = lists.entryFor(index, key, props)
+ val list = entry?.let { lists.list(it) }
+ keep[key] = list?.keep.orEmpty()
+ return Resolved(index, entry, list, out.getOrNull(MATCH_KEYS.size)?.toIntOrNull())
+ }
+
/**
* 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
diff --git a/app/src/main/java/app/tellyscope/data/DeviceLists.kt b/app/src/main/java/app/tellyscope/data/DeviceLists.kt
new file mode 100644
index 0000000..61ff4c0
--- /dev/null
+++ b/app/src/main/java/app/tellyscope/data/DeviceLists.kt
@@ -0,0 +1,256 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope.data
+
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
+import org.json.JSONArray
+import org.json.JSONObject
+import java.io.File
+import java.net.HttpURLConnection
+import java.net.URL
+import java.security.MessageDigest
+
+/** Where the per-TV debloat lists live: the tellyscope-devices repo, built from cleanyourtv. */
+const val LISTS_BASE = "https://raw.githubusercontent.com/man15h/tellyscope-devices/main/"
+
+/** One row of `index.json`. [match] is null for lists nobody has matched to a TV yet. */
+data class ListEntry(
+ val id: String,
+ val name: String,
+ val match: Map<String, List<String>>?,
+ val sdk: Int?,
+ val file: String,
+ val sha256: String,
+)
+
+data class ListIndex(val commit: String?, val devices: List<ListEntry>)
+
+data class ListPackage(val pkg: String, val note: String?, val optional: Boolean)
+
+data class ListGroup(val title: String, val packages: List<ListPackage>)
+
+data class DeviceList(
+ val id: String,
+ val name: String,
+ val testedOs: String?,
+ val sdk: Int?,
+ /** Packages the list says must stay on. They can only add protection. */
+ val keep: Set<String>,
+ val groups: List<ListGroup>,
+)
+
+data class Suggested(val pkg: String, val label: String, val note: String?, val optional: Boolean, val ticked: Boolean)
+
+data class SuggestedGroup(val title: String, val packages: List<Suggested>)
+
+/** What the "Suggested for this TV" card shows. */
+sealed interface Suggestions {
+ /** No index (offline and nothing cached), or the chosen list failed its checksum. */
+ data object Unavailable : Suggestions
+
+ /** No list matches this TV and none was picked: ask which TV it is. */
+ data class Pick(val commit: String?, val devices: List<ListEntry>) : Suggestions
+
+ data class Ready(
+ val commit: String?,
+ val list: DeviceList,
+ /** The TV's SDK; ticks only when it equals [DeviceList.sdk]. */
+ val sdk: Int?,
+ val groups: List<SuggestedGroup>,
+ /** Every list, for "Not this TV?". */
+ val devices: List<ListEntry>,
+ ) : Suggestions {
+ val sdkMatches get() = sdk != null && sdk == list.sdk
+ }
+}
+
+/** Same rule tellyscope-devices checks; a name goes into a `pm` shell line. */
+private val PACKAGE = Regex("[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+")
+private val FILE = Regex("devices/[A-Za-z0-9][A-Za-z0-9._-]*\\.json")
+private val SHA256 = Regex("[0-9a-f]{64}")
+private const val SCHEMA = 1
+
+/** The props a match rule may name, read from `ro.product.*`. */
+val MATCH_KEYS = listOf("manufacturer", "model", "device")
+
+/** A rule matches when every key in it equals one of its values, ignoring case. An empty rule never does. */
+fun matches(rule: Map<String, List<String>>?, props: Map<String, String?>): Boolean =
+ !rule.isNullOrEmpty() && rule.all { (key, values) ->
+ val actual = props[key] ?: return@all false
+ 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. */
+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 ->
+ ListEntry(
+ id = d.getString("id"),
+ name = d.getString("name"),
+ match = d.optJSONObject("match")?.let { m ->
+ m.keys().asSequence().associateWith { k -> m.getJSONArray(k).strings() }
+ },
+ sdk = d.optIntOrNull("sdk"),
+ file = d.getString("file"),
+ sha256 = d.getString("sha256"),
+ ).takeIf { FILE.matches(it.file) && SHA256.matches(it.sha256) }
+ },
+ )
+} catch (_: org.json.JSONException) {
+ null
+}
+
+/** Null unless it is a schema 1 device file for [id]. 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) }
+ 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 ->
+ ListGroup(g.optString("title"), packages(g.optJSONArray("packages")))
+ }.filter { it.packages.isNotEmpty() },
+ )
+} catch (_: org.json.JSONException) {
+ null
+}
+
+/**
+ * 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.
+ */
+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 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) }
+ })
+ }.filter { it.packages.isNotEmpty() }
+}
+
+const val KEEP_REASON = "this TV's list says it must stay on"
+
+/**
+ * The list's keep entries add a reason; they never clear a built-in one. A keep entry that is
+ * already off stays unprotected, so Enable still shows.
+ */
+fun withKeep(builtIn: String?, pkg: String, enabled: Boolean, keep: Set<String>): String? =
+ builtIn ?: KEEP_REASON.takeIf { enabled && pkg in keep }
+
+/** Stop and Disable are refused for keep entries; Enable and Open always run. */
+fun keepRefuses(action: Action, pkg: String, keep: Set<String>) =
+ (action == Action.Stop || action == Action.Disable) && pkg in keep
+
+/**
+ * Fetches and caches the index and device files under [dir]. A failed fetch falls back to the
+ * cache; a device file is only used (and cached) when its sha256 matches the index. Hand picks
+ * are remembered per [historyKey].
+ */
+class DeviceLists(
+ private val dir: File,
+ private val fetch: suspend (String) -> ByteArray = ::download,
+) {
+ private val lock = Mutex()
+ private var index: ListIndex? = null
+ private val picks = File(dir, "picks.tsv")
+
+ /**
+ * Fetched once per process; later calls reuse it. Offline, the cached copy is returned and the
+ * next call tries the network again. Null when offline with no cache.
+ */
+ suspend fun index(): ListIndex? = lock.withLock {
+ index ?: withContext(Dispatchers.IO) {
+ dir.mkdirs()
+ val cache = File(dir, "index.json")
+ val text = attempt { fetch(LISTS_BASE + "index.json") }?.decodeToString()
+ text?.let(::parseIndex)?.also { cache.writeText(text); index = it }
+ ?: cache.takeIf { it.exists() }?.readText()?.let(::parseIndex)
+ }
+ }
+
+ /** The device file for [entry], from cache or the network. Null when the bytes don't match its sha256. */
+ suspend fun list(entry: ListEntry): DeviceList? = withContext(Dispatchers.IO) {
+ val cache = File(dir, entry.file.substringAfter('/'))
+ val bytes = cache.takeIf { it.exists() }?.readBytes()?.takeIf { sha256(it) == entry.sha256 }
+ ?: attempt { fetch(LISTS_BASE + entry.file) }?.takeIf { sha256(it) == entry.sha256 }
+ ?.also { dir.mkdirs(); cache.writeBytes(it) }
+ bytes?.let { parseList(it.decodeToString(), entry.id) }
+ }
+
+ /**
+ * The list for a TV: the one picked by hand for [key], else the first whose rule matches
+ * [props], else null for "Pick your TV".
+ */
+ fun entryFor(index: ListIndex, key: String, props: Map<String, String?>): ListEntry? =
+ picked(key)?.let { id -> index.devices.firstOrNull { it.id == id } }
+ ?: index.devices.firstOrNull { matches(it.match, props) }
+
+ @Synchronized
+ fun picked(key: String): String? = readPicks()[key]
+
+ @Synchronized
+ fun pick(key: String, id: String) {
+ dir.mkdirs()
+ val all = readPicks() + (key to id)
+ val tmp = File(dir, "picks.tsv.tmp")
+ tmp.writeText(all.entries.joinToString("") { (k, v) -> "$k\t$v\n" })
+ tmp.renameTo(picks)
+ }
+
+ private fun readPicks(): Map<String, String> = if (!picks.exists()) emptyMap() else
+ picks.readLines().mapNotNull { l -> l.split('\t').takeIf { it.size == 2 }?.let { it[0] to it[1] } }.toMap()
+
+ private suspend fun <T> attempt(block: suspend () -> T): T? = try {
+ block()
+ } catch (e: CancellationException) {
+ throw e
+ } catch (_: Exception) {
+ null
+ }
+}
+
+private const val MAX_BYTES = 2 shl 20 // 2 MiB; the index is ~60 KB
+
+/** Plain GET with short timeouts, so a slow network falls back to the cache rather than hanging. */
+private suspend fun download(url: String): ByteArray = withContext(Dispatchers.IO) {
+ val c = URL(url).openConnection() as HttpURLConnection
+ c.connectTimeout = 10_000
+ c.readTimeout = 10_000
+ try {
+ check(c.responseCode == 200) { "HTTP ${c.responseCode}" }
+ c.inputStream.use { s ->
+ val out = java.io.ByteArrayOutputStream()
+ val buf = ByteArray(8192)
+ while (true) {
+ val n = s.read(buf).takeIf { it >= 0 } ?: break
+ out.write(buf, 0, n)
+ check(out.size() <= MAX_BYTES) { "too large" }
+ }
+ out.toByteArray()
+ }
+ } finally {
+ c.disconnect()
+ }
+}
+
+private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }
+
+private fun JSONArray.objects() = (0 until length()).map { getJSONObject(it) }
+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/DeviceSource.kt b/app/src/main/java/app/tellyscope/data/DeviceSource.kt
index b97aef2..8ac2915 100644
--- a/app/src/main/java/app/tellyscope/data/DeviceSource.kt
+++ b/app/src/main/java/app/tellyscope/data/DeviceSource.kt
@@ -79,4 +79,13 @@ interface DeviceSource {
suspend fun push(deviceId: String, folder: TvFolder, name: String, size: Long?, source: Source, onProgress: (Progress) -> Unit): String
suspend fun pull(deviceId: String, folder: TvFolder, file: TvFile, sink: Sink, onProgress: (Progress) -> Unit)
+
+ /**
+ * What the TV's list from tellyscope-devices suggests turning off. Never throws; offline it
+ * uses the cached lists, or answers [Suggestions.Unavailable].
+ */
+ suspend fun suggestions(deviceId: String): Suggestions
+
+ /** "Pick your TV": use list [listId] for this TV from now on. */
+ suspend fun pickList(deviceId: String, listId: String)
}
diff --git a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt
index f51b477..e976772 100644
--- a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt
+++ b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt
@@ -264,7 +264,31 @@ class FakeDeviceSource(
TvFile("subtitles.srt", 61_000, clock() - 40 * 60_000L),
)
+ override suspend fun suggestions(deviceId: String): Suggestions {
+ delay(600)
+ val all = listOf(ListEntry(fakeList.id, fakeList.name, null, fakeList.sdk, "devices/${fakeList.id}.json", "0".repeat(64)))
+ return Suggestions.Ready(null, fakeList, 30, suggest(fakeList, appsFor(deviceId), 30), all)
+ }
+
+ override suspend fun pickList(deviceId: String, listId: String) = Unit
+
private companion object {
+ val fakeList = DeviceList(
+ id = "xgimi-horizon-pro",
+ name = "XGIMI Horizon Pro",
+ testedOs = "Android TV 11",
+ sdk = 30,
+ keep = emptySet(),
+ groups = listOf(
+ ListGroup("Extras", listOf(
+ ListPackage("com.xgimi.assistant", "voice assistant", optional = false),
+ ListPackage("com.google.android.tvrecommendations", null, optional = false),
+ ListPackage("com.netflix.ninja", null, optional = true),
+ )),
+ ),
+ )
+
+
val baseApps = listOf(
AppInfo("com.spocky.projengmenu", "Projectivy Launcher", 0xFF3D5AFE, false, true, "this is your home screen", "4.52"),
AppInfo("com.google.android.youtube.tv", "YouTube", 0xFFC4302B, false, true, null, "4.40.303"),
diff --git a/app/src/main/java/app/tellyscope/ui/Copy.kt b/app/src/main/java/app/tellyscope/ui/Copy.kt
index 15f80ed..99f1363 100644
--- a/app/src/main/java/app/tellyscope/ui/Copy.kt
+++ b/app/src/main/java/app/tellyscope/ui/Copy.kt
@@ -75,6 +75,12 @@ object Copy {
fun mb(v: Int) = if (v >= 1024) "%.1f GB".format(v / 1024.0) else "$v MB"
+ fun disabledSuggested(done: Int, of: Int) = when {
+ done == of -> "Disabled $done ${if (done == 1) "app" else "apps"}. Undo any of them from History."
+ done == 0 -> "The TV didn't disable any of them."
+ else -> "Disabled $done of $of apps; the TV refused the rest. Undo any of them from History."
+ }
+
const val ANDROID_SYSTEM = "Android system"
/** The word next to the status dot, so the state never rests on colour alone. */
diff --git a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt
index e35abad..a2a26fb 100644
--- a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt
+++ b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt
@@ -90,6 +90,7 @@ import app.tellyscope.data.HistoryEntry
import app.tellyscope.data.NetworkInfo
import app.tellyscope.data.Proc
import app.tellyscope.data.Snapshot
+import app.tellyscope.data.Suggestions
import app.tellyscope.ui.theme.SmallNumber
import app.tellyscope.ui.theme.StatNumber
@@ -118,6 +119,8 @@ data class DeviceActions(
/** Asks where to save [TvFile] on the phone, then copies it. */
val saveFile: (TvFile) -> Unit = {},
val cancelTransfer: () -> Unit = {},
+ val pickList: (String) -> Unit = {},
+ val disableSuggested: (List<String>) -> Unit = {},
)
@OptIn(ExperimentalMaterial3Api::class)
@@ -213,6 +216,12 @@ fun DeviceScreen(
// The :adb source has no per-process list yet; no bars beats an empty card.
if (q.isEmpty() && it.procs.isNotEmpty() && !offline) item { UsageCard(it, ui.apps) }
}
+ if (!offline && q.isEmpty()) {
+ val count = (ui.lists as? Suggestions.Ready)?.groups?.sumOf { it.packages.size } ?: 0
+ section("lists", "Suggested for this TV", count) {
+ SuggestionsBlock(ui.lists, ui.busy == DISABLING, actions.pickList, actions.disableSuggested)
+ }
+ }
// An offline TV can't list anything: sections with nothing in them stay out of the way.
if (!offline || ui.apps.isNotEmpty()) section(
key = "apps",
@@ -252,9 +261,18 @@ private fun DevicePicker(state: UiState, actions: DeviceActions) {
var open by remember { mutableStateOf(false) }
var forgetting by remember { mutableStateOf(false) }
var renaming by remember { mutableStateOf(false) }
+ var about by remember { mutableStateOf(false) }
val device = state.selected ?: return
if (forgetting) ForgetDialog(name(device), onForget = { forgetting = false; actions.forget(device.id) }, onDismiss = { forgetting = false })
if (renaming) RenameDialog(device.nickname.orEmpty(), networkName(device), onSave = { renaming = false; actions.rename(device.id, it) }, onDismiss = { renaming = false })
+ if (about) AboutDialog(
+ when (val l = state.device.lists) {
+ is Suggestions.Pick -> l.commit
+ is Suggestions.Ready -> l.commit
+ else -> null
+ },
+ onDismiss = { about = false },
+ )
val offlineCount = state.devices.count { it.state != DeviceState.Online }
Box {
Row(
@@ -310,6 +328,11 @@ private fun DevicePicker(state: UiState, actions: DeviceActions) {
leadingIcon = { Icon(Icons.Default.Delete, null) },
onClick = { open = false; forgetting = true },
)
+ DropdownMenuItem(
+ text = { Text("About & licences") },
+ leadingIcon = { Icon(Icons.Default.Info, null) },
+ onClick = { open = false; about = true },
+ )
}
}
}
diff --git a/app/src/main/java/app/tellyscope/ui/ListsCard.kt b/app/src/main/java/app/tellyscope/ui/ListsCard.kt
new file mode 100644
index 0000000..14af2d4
--- /dev/null
+++ b/app/src/main/java/app/tellyscope/ui/ListsCard.kt
@@ -0,0 +1,173 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope.ui
+
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.Button
+import androidx.compose.material3.Checkbox
+import androidx.compose.material3.FilledTonalButton
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+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.unit.dp
+import app.tellyscope.data.ListEntry
+import app.tellyscope.data.Suggestions
+
+/** Body of the "Suggested for this TV" section: the TV's list, cut down to what it has. */
+@Composable
+fun SuggestionsBlock(
+ lists: Suggestions?,
+ disabling: Boolean,
+ onPick: (String) -> Unit,
+ onDisable: (List<String>) -> Unit,
+) {
+ var picking by remember { mutableStateOf(false) }
+ var confirming by remember { mutableStateOf(false) }
+ // Ticks start from the list and reset whenever it reloads.
+ var ticked by remember(lists) {
+ mutableStateOf((lists as? Suggestions.Ready)?.groups.orEmpty().flatMap { it.packages }.filter { it.ticked }.map { it.pkg }.toSet())
+ }
+ val devices = when (lists) {
+ is Suggestions.Pick -> lists.devices
+ is Suggestions.Ready -> lists.devices
+ else -> emptyList()
+ }
+ if (picking) PickDialog(devices, onPick = { picking = false; onPick(it) }, onDismiss = { picking = false })
+ if (confirming) DisableDialog(ticked.size, onDisable = { confirming = false; onDisable(ticked.toList()) }, onDismiss = { confirming = false })
+
+ when (lists) {
+ null -> Muted("Looking up this TV's list…")
+ Suggestions.Unavailable -> Muted(
+ "Couldn't load the device lists. They download the first time you open a TV; check the phone's internet and open this TV again.",
+ )
+ is Suggestions.Pick -> {
+ Text("Tellyscope doesn't know this model yet. Pick your TV to see what's usually safe to turn off.", style = MaterialTheme.typography.bodyMedium)
+ FilledTonalButton(onClick = { picking = true }) { Text("Pick your TV") }
+ }
+ is Suggestions.Ready -> {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text("From the list for ${lists.list.name}.", Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium)
+ TextButton(onClick = { picking = true }) { Text("Not this TV?") }
+ }
+ if (!lists.sdkMatches) Muted(
+ lists.list.testedOs?.let { "Tested on $it, not this TV's Android version, so nothing is ticked. Tick only what you know you don't use." }
+ ?: "This list doesn't say which Android it was tested on, so nothing is ticked. Tick only what you know you don't use.",
+ )
+ if (lists.groups.isEmpty()) Muted("Nothing on the list is still on here.")
+ lists.groups.forEach { g ->
+ Text(g.title, style = MaterialTheme.typography.titleSmall, modifier = Modifier.padding(top = 8.dp))
+ g.packages.forEach { p ->
+ Row(
+ Modifier.fillMaxWidth().clickable(enabled = !disabling) { ticked = if (p.pkg in ticked) ticked - p.pkg else ticked + p.pkg },
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Checkbox(p.pkg in ticked, onCheckedChange = null, enabled = !disabling)
+ Spacer(Modifier.width(8.dp))
+ Column(Modifier.weight(1f)) {
+ Text(p.label, style = MaterialTheme.typography.bodyLarge)
+ Text(
+ listOfNotNull(p.pkg, p.note, "optional".takeIf { p.optional }).joinToString(" · "),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ }
+ }
+ }
+ if (lists.groups.isNotEmpty()) {
+ Button(onClick = { confirming = true }, enabled = ticked.isNotEmpty() && !disabling, modifier = Modifier.padding(top = 8.dp)) {
+ Text(if (disabling) "Disabling…" else "Disable ${ticked.size} selected")
+ }
+ }
+ }
+ }
+ if (lists is Suggestions.Pick || lists is Suggestions.Ready) Muted("Lists adapted from cleanyourtv (MIT).")
+}
+
+@Composable
+private fun Muted(text: String) {
+ Text(text, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+}
+
+/** Searchable "Pick your TV". The choice is remembered for this TV. */
+@Composable
+fun PickDialog(devices: List<ListEntry>, onPick: (String) -> Unit, onDismiss: () -> Unit) {
+ var q by rememberSaveable { mutableStateOf("") }
+ val shown = devices.filter { q.isBlank() || it.name.contains(q.trim(), ignoreCase = true) }.sortedBy { it.name.lowercase() }
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text("Pick your TV") },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ OutlinedTextField(q, { q = it }, placeholder = { Text("Brand or model") }, singleLine = true, modifier = Modifier.fillMaxWidth())
+ if (shown.isEmpty()) Muted("No list matches \"${q.trim()}\".")
+ LazyColumn(Modifier.heightIn(max = 360.dp)) {
+ items(shown, key = { it.id }) { d ->
+ Text(
+ d.name,
+ Modifier.fillMaxWidth().clickable { onPick(d.id) }.padding(vertical = 12.dp),
+ style = MaterialTheme.typography.bodyLarge,
+ )
+ }
+ }
+ }
+ },
+ confirmButton = {},
+ dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
+ )
+}
+
+@Composable
+private fun DisableDialog(count: Int, onDisable: () -> Unit, onDismiss: () -> Unit) {
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text("Disable $count ${if (count == 1) "app" else "apps"}?") },
+ text = { Text("Each one is hidden and stops running. Nothing is deleted; every one shows in History, where you can turn it back on.") },
+ confirmButton = { Button(onClick = onDisable) { Text("Yes, disable them") } },
+ dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
+ )
+}
+
+/** About and licences; [commit] is the cleanyourtv commit the downloaded lists were built from. */
+@Composable
+fun AboutDialog(commit: String?, onDismiss: () -> Unit) {
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text("About Tellyscope") },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text("Free software under the GNU GPL v3.", style = MaterialTheme.typography.bodyMedium)
+ Text(
+ "Device lists are adapted from cleanyourtv by Gathin (MIT licence), " +
+ (commit?.let { "commit ${it.take(12)}." } ?: "once they have downloaded."),
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ Text(
+ "Uses Kadb (Apache 2.0) and spake2-java (GPL v3). Full licence texts are in the NOTICE file.",
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ }
+ },
+ confirmButton = { TextButton(onClick = onDismiss) { Text("Close") } },
+ )
+}
diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
index debb7b2..cbd9ad1 100644
--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt
@@ -27,6 +27,7 @@ import app.tellyscope.data.ScanEvent
import app.tellyscope.data.ScanHit
import app.tellyscope.data.ScanProgress
import app.tellyscope.data.Snapshot
+import app.tellyscope.data.Suggestions
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
@@ -68,6 +69,8 @@ data class DeviceUi(
val files: FilesUi = FilesUi(),
/** A file copy in progress; its dialog stays up until it finishes or Cancel is tapped. */
val transfer: TransferUi? = null,
+ /** The TV's debloat list; null while it loads. */
+ val lists: Suggestions? = null,
)
data class SideloadUi(
@@ -111,6 +114,9 @@ data class UiState(
/** [DeviceUi.busy] value while "Restore everything" runs. */
const val RESTORING = "restore"
+/** [DeviceUi.busy] value while the ticked suggestions are being disabled. */
+const val DISABLING = "lists"
+
class TellyscopeViewModel(
private val source: DeviceSource,
private val storage: PhoneStorage? = null,
@@ -137,6 +143,7 @@ class TellyscopeViewModel(
private var transferJob: Job? = null
private var liveJob: Job? = null
private var mediumJob: Job? = null
+ private var listsJob: Job? = null
init {
viewModelScope.launch {
@@ -244,6 +251,7 @@ class TellyscopeViewModel(
fun select(id: String?) {
liveJob?.cancel()
mediumJob?.cancel()
+ listsJob?.cancel()
_state.update { it.copy(selectedId = id, device = DeviceUi(snapshot = id?.let(lastSnapshot::get)), 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.
@@ -258,6 +266,8 @@ class TellyscopeViewModel(
_state.update { it.copy(device = it.device.copy(snapshot = snap)) }
}
}
+ // Its own job: the list download never holds up apps or stats.
+ listsJob = viewModelScope.launch { loadLists(id!!) }
mediumJob = viewModelScope.launch {
// A TV that drops mid-read throws; the live flow ends and the offline card takes over.
try {
@@ -549,6 +559,52 @@ class TellyscopeViewModel(
}
}
+ private suspend fun loadLists(id: String) {
+ val lists = source.suggestions(id)
+ // Once the list is known its keep entries show as protected.
+ val apps = if (lists is Suggestions.Ready) runCatching { source.apps(id) }.getOrNull() else null
+ _state.update { s ->
+ if (s.selectedId != id) s else s.copy(device = s.device.copy(lists = lists, apps = apps ?: s.device.apps))
+ }
+ }
+
+ /** "Pick your TV": remember the choice for this TV and show its list. */
+ fun pickList(listId: String) {
+ val id = _state.value.selectedId ?: return
+ _state.update { it.copy(device = it.device.copy(lists = null)) }
+ listsJob?.cancel()
+ listsJob = viewModelScope.launch {
+ source.pickList(id, listId)
+ loadLists(id)
+ }
+ }
+
+ /** Disables the ticked suggestions one by one, each recorded in History with its own undo. */
+ fun disableSuggested(packages: List<String>) {
+ val id = _state.value.selectedId ?: return
+ _state.update { it.copy(device = it.device.copy(busy = DISABLING)) }
+ viewModelScope.launch {
+ var done = 0
+ for (pkg in packages) {
+ try {
+ source.act(id, Action.Disable, pkg)
+ done++
+ } catch (e: CancellationException) {
+ throw e
+ } catch (_: Exception) {
+ // The TV refused this one or dropped; the count says so.
+ }
+ }
+ _notice.value = Copy.disabledSuggested(done, packages.size)
+ val apps = runCatching { source.apps(id) }.getOrNull()
+ val history = source.history(id)
+ _state.update { s ->
+ s.copy(device = s.device.copy(apps = apps ?: s.device.apps, busy = null, history = history))
+ }
+ loadLists(id)
+ }
+ }
+
private fun setRow(ip: String, row: RowState) =
_state.update { it.copy(scan = it.scan.copy(rows = it.scan.rows + (ip to row))) }
diff --git a/app/src/test/java/app/tellyscope/DeviceListsTest.kt b/app/src/test/java/app/tellyscope/DeviceListsTest.kt
new file mode 100644
index 0000000..b38b0cd
--- /dev/null
+++ b/app/src/test/java/app/tellyscope/DeviceListsTest.kt
@@ -0,0 +1,160 @@
+// SPDX-License-Identifier: GPL-3.0-only
+
+package app.tellyscope
+
+import app.tellyscope.data.Action
+import app.tellyscope.data.AppInfo
+import app.tellyscope.data.DeviceList
+import app.tellyscope.data.DeviceLists
+import app.tellyscope.data.KEEP_REASON
+import app.tellyscope.data.LISTS_BASE
+import app.tellyscope.data.ListGroup
+import app.tellyscope.data.ListPackage
+import app.tellyscope.data.keepRefuses
+import app.tellyscope.data.matches
+import app.tellyscope.data.parseIndex
+import app.tellyscope.data.suggest
+import app.tellyscope.data.withKeep
+import kotlinx.coroutines.test.runTest
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import java.io.IOException
+import java.security.MessageDigest
+
+/** org.json is Android's, so this runs under Robolectric. */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35])
+class DeviceListsTest {
+ @get:Rule val tmp = TemporaryFolder()
+
+ private val device = """
+ {"schema": 1, "id": "acme-55", "name": "Acme 55", "tested": {"os": "Android TV 11", "sdk": 30, "build": null},
+ "launcher": null, "keep": [{"pkg": "com.acme.hdmi"}],
+ "groups": [{"title": "Junk", "packages": [
+ {"pkg": "com.acme.reporter", "note": "usage reporter"},
+ {"pkg": "com.acme.updater", "optional": true},
+ {"pkg": "com.acme.gone"},
+ {"pkg": "com.acme.bad;reboot"}]}],
+ "source": {"repo": "Gathin23/cleanyourtv", "path": "examples/acme-55/debloat.txt", "commit": "abc"}}
+ """.trimIndent().toByteArray()
+
+ private fun index(sha: String = sha256(device), schema: Int = 1) = """
+ {"schema": $schema, "source": {"repo": "Gathin23/cleanyourtv", "commit": "30626a8e4714"},
+ "devices": [
+ {"id": "acme-55", "name": "Acme 55", "match": {"manufacturer": ["Acme"], "model": ["A55", "A55X"]},
+ "sdk": 30, "file": "devices/acme-55.json", "sha256": "$sha"},
+ {"id": "other", "name": "Other TV", "match": null, "sdk": null, "file": "devices/other.json", "sha256": "${"0".repeat(64)}"}]}
+ """.trimIndent().toByteArray()
+
+ private fun app(pkg: String, enabled: Boolean = true, protectedReason: String? = null) =
+ AppInfo(pkg, pkg.substringAfterLast('.'), null, true, enabled, protectedReason, "")
+
+ private fun served(vararg files: Pair<String, ByteArray>): suspend (String) -> ByteArray {
+ val map = files.associate { (path, bytes) -> LISTS_BASE + path to bytes }
+ return { url -> map[url] ?: throw IOException("404 $url") }
+ }
+
+ @Test fun everyKeyInTheRuleMustMatchOneOfItsValues() {
+ val rule = mapOf("manufacturer" to listOf("Acme"), "model" to listOf("A55", "A55X"))
+ assertTrue(matches(rule, mapOf("manufacturer" to "ACME", "model" to "a55x", "device" to "whatever")))
+ assertFalse(matches(rule, mapOf("manufacturer" to "Acme", "model" to "A65")))
+ assertFalse(matches(rule, mapOf("manufacturer" to "Acme"))) // model unknown
+ assertFalse(matches(rule + ("device" to listOf("acmeone")), mapOf("manufacturer" to "Acme", "model" to "A55", "device" to "acmetwo")))
+ assertFalse(matches(null, mapOf("manufacturer" to "Acme")))
+ assertFalse(matches(emptyMap(), mapOf("manufacturer" to "Acme")))
+ }
+
+ @Test fun onlySchemaOneIsAccepted() {
+ assertNotNull(parseIndex(index().decodeToString()))
+ assertNull(parseIndex(index(schema = 2).decodeToString()))
+ assertNull(parseIndex("not json"))
+ }
+
+ @Test fun aDeviceFileWithTheWrongSha256IsRejectedAndNotCached() = runTest {
+ val lists = DeviceLists(tmp.root, served("index.json" to index(sha = "f".repeat(64)), "devices/acme-55.json" to device))
+ val entry = lists.index()!!.devices.first()
+ assertNull(lists.list(entry))
+ assertFalse(tmp.root.resolve("acme-55.json").exists())
+
+ val good = DeviceLists(tmp.newFolder(), served("index.json" to index(), "devices/acme-55.json" to device))
+ assertEquals("Acme 55", good.list(good.index()!!.devices.first())?.name)
+ }
+
+ @Test fun offlineFallsBackToTheCachedIndexAndLists() = runTest {
+ DeviceLists(tmp.root, served("index.json" to index(), "devices/acme-55.json" to device)).let {
+ it.list(it.index()!!.devices.first())
+ }
+ val offline = DeviceLists(tmp.root) { throw IOException("offline") }
+ val index = offline.index()
+ assertEquals("30626a8e4714", index?.commit)
+ assertNotNull(offline.list(index!!.devices.first()))
+ assertNull(DeviceLists(tmp.newFolder()) { throw IOException("offline") }.index())
+ }
+
+ @Test fun aPickIsRememberedPerTvAndBeatsAMatch() = runTest {
+ val index = parseIndex(index().decodeToString())!!
+ val props = mapOf("manufacturer" to "Acme", "model" to "A55")
+ DeviceLists(tmp.root).pick("sn:one", "other")
+ val lists = DeviceLists(tmp.root)
+ assertEquals("other", lists.entryFor(index, "sn:one", props)?.id)
+ assertEquals("acme-55", lists.entryFor(index, "sn:two", props)?.id)
+ assertNull(lists.entryFor(index, "sn:two", mapOf("manufacturer" to "Zeta", "model" to "Z1")))
+ }
+
+ @Test fun onlyPackagesTheTvHasAndStillHasOnAreSuggested() = runTest {
+ val lists = DeviceLists(tmp.root, served("index.json" to index(), "devices/acme-55.json" to device))
+ val list = lists.list(lists.index()!!.devices.first())!!
+ // The shell-metacharacter name never made it past parsing.
+ assertEquals(listOf("com.acme.reporter", "com.acme.updater", "com.acme.gone"), list.groups.single().packages.map { it.pkg })
+
+ val apps = listOf(app("com.acme.reporter"), app("com.acme.updater", enabled = false), app("com.netflix.ninja"))
+ val shown = suggest(list, apps, sdk = 30).flatMap { it.packages }.map { it.pkg }
+ assertEquals(listOf("com.acme.reporter"), shown)
+ }
+
+ @Test fun ticksOnlyNonOptionalEntriesAndOnlyOnTheTestedSdk() {
+ val list = DeviceList(
+ "acme-55", "Acme 55", "Android TV 11", 30, emptySet(),
+ listOf(ListGroup("Junk", listOf(ListPackage("com.a.one", null, false), ListPackage("com.a.two", null, true)))),
+ )
+ val apps = listOf(app("com.a.one"), app("com.a.two"))
+ fun ticks(sdk: Int?) = suggest(list, apps, sdk).flatMap { it.packages }.associate { it.pkg to it.ticked }
+ assertEquals(mapOf("com.a.one" to true, "com.a.two" to false), ticks(30))
+ assertEquals(mapOf("com.a.one" to false, "com.a.two" to false), ticks(31))
+ assertEquals(mapOf("com.a.one" to false, "com.a.two" to false), ticks(null))
+ 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 keepOnlyAddsProtection() {
+ val keep = setOf("com.acme.hdmi")
+ assertEquals(KEEP_REASON, withKeep(null, "com.acme.hdmi", enabled = true, keep))
+ // A built-in reason always survives, list or no list.
+ assertEquals("this is your home screen", withKeep("this is your home screen", "com.acme.launcher", enabled = true, keep))
+ assertEquals("this is your home screen", withKeep("this is your home screen", "com.acme.launcher", enabled = true, emptySet()))
+ // Already off: Enable must still be offered.
+ assertNull(withKeep(null, "com.acme.hdmi", enabled = false, keep))
+
+ assertTrue(keepRefuses(Action.Disable, "com.acme.hdmi", keep))
+ assertTrue(keepRefuses(Action.Stop, "com.acme.hdmi", keep))
+ assertFalse(keepRefuses(Action.Enable, "com.acme.hdmi", keep))
+ assertFalse(keepRefuses(Action.Disable, "com.acme.reporter", keep))
+
+ // A list that names a package in both keep and a group never suggests it.
+ val list = DeviceList("x", "X", null, 30, keep, listOf(ListGroup("Junk", listOf(ListPackage("com.acme.hdmi", null, false)))))
+ assertTrue(suggest(list, listOf(app("com.acme.hdmi")), 30).isEmpty())
+ // Nor one the app already protects.
+ val builtIn = list.copy(keep = emptySet())
+ assertTrue(suggest(builtIn, listOf(app("com.acme.hdmi", protectedReason = "your remote or HDMI inputs could stop working")), 30).isEmpty())
+ }
+
+ private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }
+}