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.
Show real app names and icons from the TV
jesse-agent-23245f286397bd1
diff --git a/README.md b/README.mdindex 1b6dc43..7c14286 100644--- a/README.md+++ b/README.md@@ -23,6 +23,7 @@ Debloating a TV can break it if done carelessly. Tellyscope is built around thes2. **Backup first.** Before the first change on a TV, Tellyscope records the list of enabled packages, so every change can be undone, even after an app reinstall.3. **Protected list.** Packages the TV needs to boot, update, show the launcher or accept input are on a protected list. Tellyscope refuses to disable them, and there is no override in the app.4. **No root, no exploits.** Only what ADB allows on a stock TV.+5. **Nothing left on the TV.** To show real app names and icons, Tellyscope copies a small helper to `/data/local/tmp`, runs it once and deletes it. The helper only reads through PackageManager: no writes, no permissions, no network.## Project layout@@ -30,6 +31,7 @@ Debloating a TV can break it if done carelessly. Tellyscope is built around thes|---|---|| `:app` | The Android phone app. Kotlin, Jetpack Compose, Material 3 Expressive. Package `app.tellyscope`. || `:adb` | Pure Kotlin/JVM library on top of [Kadb](https://github.com/flyfishxu/Kadb): connecting, pairing and running commands on a TV. Unit-testable without a device. |+| `app/src/helper` | The label helper: plain Java, built into a dex in the app's assets and run on the TV with `app_process`. || `:cli` | Desktop smoke test for `:adb` against a real TV (`./gradlew :cli:run --args="stats <tv-ip>"`). Not shipped. |## Buildingdiff --git a/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt b/adb/src/main/kotlin/app/tellyscope/adb/Actions.ktindex 95d1380..41cf01c 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/Actions.kt@@ -60,7 +60,7 @@ class Actions(private val shell: AdbShell) {return if (r.exitCode == 0 && ok(r.output)) ActionResult.Done(undo) else ActionResult.Failed(r.output.trim())}- private companion object {+ internal companion object {val PACKAGE = Regex("[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)+|android")}}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt b/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.ktindex 0552d04..774f88f 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt@@ -10,4 +10,7 @@ fun interface AdbShell {data class ShellResult(val output: String, val exitCode: Int)/** An open connection to one device. */-interface AdbSession : AdbShell, AutoCloseable+interface AdbSession : AdbShell, AutoCloseable {+ /** Writes [bytes] to [remotePath] on the device, mode 0644. Throws [java.io.IOException] if the link is gone. */+ suspend fun push(bytes: ByteArray, remotePath: String)+}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt b/adb/src/main/kotlin/app/tellyscope/adb/Connector.ktindex e19cdf6..65ea533 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt@@ -9,6 +9,7 @@ import com.flyfishxu.kadb.exception.AdbPairAuthExceptionimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.runInterruptible+import okio.Bufferimport okio.Path.Companion.toPathimport java.io.Fileimport java.io.IOException@@ -96,5 +97,9 @@ internal class KadbSession(private val kadb: Kadb) : AdbSession {return ShellResult(r.output, r.exitCode)}+ override suspend fun push(bytes: ByteArray, remotePath: String) = runInterruptible(Dispatchers.IO) {+ kadb.push(Buffer().write(bytes), remotePath, "644".toInt(8), System.currentTimeMillis())+ }+override fun close() = kadb.close()}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/LabelHelper.kt b/adb/src/main/kotlin/app/tellyscope/adb/LabelHelper.ktnew file mode 100644index 0000000..1e00d5e--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/LabelHelper.kt@@ -0,0 +1,131 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.NonCancellable+import kotlinx.coroutines.withContext+import kotlinx.coroutines.withTimeoutOrNull+import java.util.Base64+import kotlin.time.Duration.Companion.seconds++/** One app as the TV's PackageManager describes it. */+class AppLabel(val packageName: String, val label: String, val versionCode: Long, val iconPng: ByteArray?)++/**+ * Real app names and icons, read on the TV by the helper dex (`app/src/helper`): push it, run it+ * once with `app_process` as the shell user, delete it whatever happens. The helper only reads+ * through PackageManager. [dex] is the helper jar bundled in the app's assets.+ */+class LabelHelper(private val session: AdbSession, private val dex: ByteArray) {++ /**+ * Describes [packages], or every installed app past [MAX_ARGS] so the shell line stays short+ * on old adbd. Null when the helper couldn't run at all (push refused, `app_process` blocked by+ * the OEM, a dropped link, a run past [TIMEOUT], no usable output): the caller falls back to its+ * name table.+ */+ suspend fun describe(packages: Collection<String>): List<AppLabel>? {+ val names = packages.filter { Actions.PACKAGE.matches(it) } // they go into a shell line+ if (names.isEmpty()) return emptyList()+ val args = if (names.size > MAX_ARGS) "--all" else names.joinToString(" ")+ return try {+ session.push(dex, PATH)+ // A hung helper must not hold up the app list; a timeout counts as "couldn't run".+ val out = withTimeoutOrNull(TIMEOUT) {+ session.shell("CLASSPATH=$PATH app_process / $MAIN $args 2>/dev/null; rm -f $PATH").output+ }+ out?.let(::parse)?.ifEmpty { null }+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ null+ } finally {+ // The shell line removes it too; this covers a run that never got that far.+ withContext(NonCancellable) { runCatching { session.shell("rm -f $PATH") } }+ }+ }++ companion object {+ const val PATH = "/data/local/tmp/tellyscope-label-helper.jar"+ const val MAIN = "app.tellyscope.helper.Labels"+ const val MAX_ARGS = 40+ /** Every icon on a slow TV fits in this; past it, the fallback names are better than a spinner. */+ val TIMEOUT = 60.seconds++ /** The helper's output: one flat JSON object per line. Lines that don't parse are skipped. */+ fun parse(output: String): List<AppLabel> = output.lineSequence().mapNotNull { line ->+ val o = FlatJson.parse(line.trim()) ?: return@mapNotNull null+ val pkg = o["p"] as? String ?: return@mapNotNull null+ val label = (o["l"] as? String)?.trim()?.takeIf { it.isNotEmpty() } ?: return@mapNotNull null+ val version = (o["v"] as? Long) ?: return@mapNotNull null+ val icon = (o["i"] as? String)?.let { runCatching { Base64.getDecoder().decode(it) }.getOrNull() }+ AppLabel(pkg, label, version, icon)+ }.toList()+ }+}++/** Just enough JSON for the helper's lines: one object, string and integer values, no nesting. */+internal object FlatJson {+ fun parse(s: String): Map<String, Any>? = runCatching { Reader(s).obj() }.getOrNull()++ private class Reader(val s: String) {+ var i = 0++ fun obj(): Map<String, Any> {+ val out = mutableMapOf<String, Any>()+ expect('{')+ ws()+ if (peek() == '}') { i++; return end(out) }+ while (true) {+ ws()+ val key = string()+ ws(); expect(':'); ws()+ out[key] = if (peek() == '"') string() else number()+ ws()+ when (s[i++]) {+ ',' -> continue+ '}' -> return end(out)+ else -> error("bad separator at $i")+ }+ }+ }++ private fun end(out: Map<String, Any>): Map<String, Any> {+ ws()+ require(i == s.length) { "trailing data" }+ return out+ }++ private fun string(): String {+ expect('"')+ val b = StringBuilder()+ while (true) {+ when (val c = s[i++]) {+ '"' -> return b.toString()+ '\\' -> when (val e = s[i++]) {+ 'u' -> { b.append(s.substring(i, i + 4).toInt(16).toChar()); i += 4 }+ 'n' -> b.append('\n')+ 't' -> b.append('\t')+ 'r' -> b.append('\r')+ 'b' -> b.append('\b')+ 'f' -> b.append('\u000c')+ '"', '\\', '/' -> b.append(e)+ else -> error("bad escape \\$e")+ }+ else -> b.append(c)+ }+ }+ }++ private fun number(): Long {+ val start = i+ if (peek() == '-') i+++ while (i < s.length && s[i].isDigit()) i+++ return s.substring(start, i).toLong()+ }++ private fun peek() = s[i]+ private fun ws() { while (i < s.length && s[i].isWhitespace()) i++ }+ private fun expect(c: Char) { require(s[i++] == c) { "expected $c at ${i - 1}" } }+ }+}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Parsers.kt b/adb/src/main/kotlin/app/tellyscope/adb/Parsers.ktindex 0240514..fafb5b3 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/Parsers.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/Parsers.kt@@ -65,15 +65,19 @@ object Parsers {return (cpu.ifEmpty { zones }).maxOf { it.second }}- data class Package(val name: String, val uid: Int?)+ data class Package(val name: String, val uid: Int?, val versionCode: Long? = null)- /** `pm list packages -U`: `package:com.foo uid:10023` (uid list may be comma-separated). */+ /**+ * `pm list packages [--show-versioncode] [-U]`: `package:com.foo versionCode:42 uid:10023`+ * (uid list may be comma-separated).+ */fun packages(pmList: String): List<Package> = pmList.lineSequence().mapNotNull { line ->val l = line.trim()if (!l.startsWith("package:")) return@mapNotNull nullval name = l.removePrefix("package:").substringBefore(' ')val uid = l.substringAfter(" uid:", "").substringBefore(',').toIntOrNull()- Package(name, uid).takeIf { name.isNotEmpty() }+ val version = l.substringAfter(" versionCode:", "").substringBefore(' ').toLongOrNull()+ Package(name, uid, version).takeIf { name.isNotEmpty() }}.toList()data class Process(val pid: Int, val user: String, val rssKb: Long, val cpuPercent: Double, val name: String)diff --git a/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.kt b/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.ktindex fb7222b..d2d791c 100644--- a/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.kt+++ b/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.kt@@ -13,6 +13,14 @@ class FakeShell(private val answers: Map<String, ShellResult> = emptyMap()) : Adreturn answers.entries.firstOrNull { command.startsWith(it.key) }?.value ?: ShellResult("", 0)}+ val pushed = mutableMapOf<String, ByteArray>()+ var failPush: Exception? = null++ override suspend fun push(bytes: ByteArray, remotePath: String) {+ failPush?.let { throw it }+ pushed[remotePath] = bytes+ }+override fun close() { closed = true }}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/LabelHelperTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/LabelHelperTest.ktnew file mode 100644index 0000000..9bbc30f--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/LabelHelperTest.kt@@ -0,0 +1,101 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.awaitCancellation+import kotlinx.coroutines.test.runTest+import java.io.IOException+import java.util.Base64+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class LabelHelperTest {+ private val dex = byteArrayOf(1, 2, 3)+ private val png = byteArrayOf(0x89.toByte(), 'P'.code.toByte(), 'N'.code.toByte(), 'G'.code.toByte())+ private val b64 = Base64.getEncoder().encodeToString(png)++ @Test fun parsesHelperLines() {+ val out = """+ {"p":"com.netflix.ninja","l":"Netflix","v":62174,"i":"$b64"}+ {"p":"com.example.cafe","l":"Café \"TV\" \\ guide","v":3}+ """.trimIndent()+ val apps = LabelHelper.parse(out)+ assertEquals(listOf("com.netflix.ninja", "com.example.cafe"), apps.map { it.packageName })+ assertEquals("Netflix", apps[0].label)+ assertEquals(62174L, apps[0].versionCode)+ assertContentEquals(png, apps[0].iconPng)+ assertEquals("Café \"TV\" \\ guide", apps[1].label)+ assertNull(apps[1].iconPng)+ }++ @Test fun skipsLinesThatDontParse() {+ val out = """+ Exception in thread "main" java.lang.SecurityException+ {"p":"com.a","l":"A","v":1}+ {"p":"com.b","l":"","v":1}+ {"p":"com.c","l":"C"}+ {"p":"com.d","l":"D","v":1,"i":"not base64!"}+ {"p":"com.e","l":"E","v":1+ """.trimIndent()+ val apps = LabelHelper.parse(out)+ assertEquals(listOf("com.a", "com.d"), apps.map { it.packageName })+ assertNull(apps[1].iconPng)+ }++ @Test fun pushesRunsAndDeletes() = runTest {+ val sh = FakeShell(mapOf("CLASSPATH=" to ok("""{"p":"com.a","l":"A","v":7}""" + "\n")))+ val apps = LabelHelper(sh, dex).describe(listOf("com.a", "com.b"))+ assertEquals(listOf("com.a"), apps?.map { it.packageName })+ assertContentEquals(dex, sh.pushed[LabelHelper.PATH])+ val run = sh.ran.single { it.startsWith("CLASSPATH=") }+ assertTrue(run.contains("app_process / ${LabelHelper.MAIN} com.a com.b "))+ assertTrue(run.endsWith("rm -f ${LabelHelper.PATH}"))+ assertEquals("rm -f ${LabelHelper.PATH}", sh.ran.last())+ }++ @Test fun manyAppsAskForAll() = runTest {+ val sh = FakeShell(mapOf("CLASSPATH=" to ok("""{"p":"com.a","l":"A","v":7}""")))+ LabelHelper(sh, dex).describe((1..41).map { "com.app$it" })+ assertTrue(sh.ran.single { it.startsWith("CLASSPATH=") }.contains("${LabelHelper.MAIN} --all 2>"))+ }++ @Test fun refusedPushIsNullAndStillCleansUp() = runTest {+ val sh = FakeShell().apply { failPush = IOException("read-only file system") }+ assertNull(LabelHelper(sh, dex).describe(listOf("com.a")))+ assertEquals(listOf("rm -f ${LabelHelper.PATH}"), sh.ran)+ }++ @Test fun noOutputIsNull() = runTest {+ // An OEM that blocks app_process for the shell user: the run "succeeds" and prints nothing.+ val sh = FakeShell(mapOf("CLASSPATH=" to ShellResult("", 1)))+ assertNull(LabelHelper(sh, dex).describe(listOf("com.a")))+ assertEquals("rm -f ${LabelHelper.PATH}", sh.ran.last())+ }++ @Test fun hungHelperTimesOutToNull() = runTest {+ val sh = object : AdbSession by FakeShell() {+ val ran = mutableListOf<String>()+ override suspend fun shell(command: String): ShellResult {+ ran += command+ if (command.startsWith("CLASSPATH=")) awaitCancellation()+ return ok("")+ }+ }+ assertNull(LabelHelper(sh, dex).describe(listOf("com.a")))+ assertEquals("rm -f ${LabelHelper.PATH}", sh.ran.last())+ }++ @Test fun packageNamesNeverReachTheShellUnchecked() = runTest {+ val sh = FakeShell(mapOf("CLASSPATH=" to ok("""{"p":"com.a","l":"A","v":7}""")))+ LabelHelper(sh, dex).describe(listOf("com.a", "com.b; reboot"))+ assertTrue(sh.ran.none { "reboot" in it })+ }++ @Test fun versionCodeFromPmList() {+ val pkgs = Parsers.packages("package:com.a versionCode:42 uid:10023\npackage:com.b uid:10024\n")+ assertEquals(listOf(42L, null), pkgs.map { it.versionCode })+ assertEquals(listOf(10023, 10024), pkgs.map { it.uid })+ }+}diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 5861755..9ce2811 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -1,5 +1,9 @@// SPDX-License-Identifier: GPL-3.0-only+import com.android.tools.r8.D8+import com.android.tools.r8.D8Command+import com.android.tools.r8.OutputMode+plugins {alias(libs.plugins.android.application)alias(libs.plugins.kotlin.compose)@@ -74,6 +78,48 @@ android {}}+// The label helper (src/helper): plain Java against android.jar, dexed on its own and shipped as+// an asset. It runs on the TV through app_process, so it must not touch app code or libraries.+val compileLabelHelper by tasks.registering(JavaCompile::class) {+ source = fileTree("src/helper/java")+ classpath = files(androidComponents.sdkComponents.bootClasspath)+ destinationDirectory = layout.buildDirectory.dir("intermediates/labelHelper/classes")+ sourceCompatibility = "17"+ targetCompatibility = "17"+}++/** D8 ships inside AGP, so this needs no build-tools version of its own. */+abstract class DexLabelHelper : DefaultTask() {+ @get:InputFiles abstract val classes: ConfigurableFileCollection+ @get:InputFiles abstract val androidJar: ConfigurableFileCollection+ @get:OutputDirectory abstract val outputDir: DirectoryProperty++ @TaskAction fun dex() {+ val out = outputDir.get().asFile.also { it.deleteRecursively(); it.mkdirs() }+ D8.run(+ D8Command.builder()+ .addProgramFiles(classes.asFileTree.matching { include("**/*.class") }.files.map { it.toPath() })+ .addLibraryFiles(androidJar.files.map { it.toPath() })+ // Old TVs too: the fallback covers OEM blocks, not a dex the TV can't load.+ .setMinApiLevel(21)+ .setOutput(out.resolve("label-helper.jar").toPath(), OutputMode.DexIndexed)+ .build(),+ )+ }+}++val dexLabelHelper by tasks.registering(DexLabelHelper::class) {+ classes.from(compileLabelHelper)+ androidJar.from(androidComponents.sdkComponents.bootClasspath)+ outputDir = layout.buildDirectory.dir("generated/labelHelper/assets")+}++androidComponents {+ onVariants { variant ->+ variant.sources.assets?.addGeneratedSourceDirectory(dexLabelHelper, DexLabelHelper::outputDir)+ }+}+dependencies {implementation(project(":adb"))diff --git a/app/src/helper/java/app/tellyscope/helper/Labels.java b/app/src/helper/java/app/tellyscope/helper/Labels.javanew file mode 100644index 0000000..84945d6--- /dev/null+++ b/app/src/helper/java/app/tellyscope/helper/Labels.java@@ -0,0 +1,116 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.helper;++import android.content.Context;+import android.content.pm.ApplicationInfo;+import android.content.pm.PackageInfo;+import android.content.pm.PackageManager;+import android.graphics.Bitmap;+import android.graphics.Canvas;+import android.graphics.drawable.Drawable;+import android.os.Build;+import android.os.Looper;+import android.util.Base64;++import java.io.ByteArrayOutputStream;+import java.io.PrintStream;+import java.lang.reflect.Field;+import java.lang.reflect.Method;+import java.util.ArrayList;+import java.util.List;++/**+ * Runs on the TV as the shell user, through {@code app_process}, and prints one JSON object per+ * app: {@code {"p":package,"l":label,"v":versionCode,"i":base64 PNG}}. Arguments are the packages+ * to describe, or {@code --all}. It only reads through PackageManager: no writes, no permissions,+ * no network. The app pushes it, runs it once and deletes it.+ */+public final class Labels {+ private static final int ICON_PX = 96;++ public static void main(String[] args) throws Exception {+ Looper.prepareMainLooper();+ PackageManager pm = systemContext().getPackageManager();+ PrintStream out = new PrintStream(System.out, false, "UTF-8");++ List<String> names = new ArrayList<>();+ if (args.length == 1 && args[0].equals("--all")) {+ for (PackageInfo p : pm.getInstalledPackages(0)) names.add(p.packageName);+ } else {+ for (String a : args) names.add(a);+ }+ for (String name : names) {+ try {+ PackageInfo p = pm.getPackageInfo(name, 0);+ ApplicationInfo ai = p.applicationInfo;+ if (ai == null) continue;+ out.print("{\"p\":");+ string(out, name);+ out.print(",\"l\":");+ string(out, ai.loadLabel(pm).toString());+ out.print(",\"v\":");+ out.print(versionCode(p));+ String icon = icon(ai.loadIcon(pm));+ if (icon != null) {+ out.print(",\"i\":\"");+ out.print(icon);+ out.print('"');+ }+ out.print("}\n");+ } catch (Exception e) {+ // One unreadable app (gone since the list, broken resources) doesn't stop the rest.+ }+ }+ out.flush();+ }++ /** No Context in a bare app_process; build the system one the way the framework does for itself. */+ private static Context systemContext() throws Exception {+ Class<?> at = Class.forName("android.app.ActivityThread");+ java.lang.reflect.Constructor<?> ctor = at.getDeclaredConstructor();+ ctor.setAccessible(true);+ Object thread = ctor.newInstance();+ Field current = at.getDeclaredField("sCurrentActivityThread");+ current.setAccessible(true);+ current.set(null, thread);+ Method get = at.getDeclaredMethod("getSystemContext");+ return (Context) get.invoke(thread);+ }++ @SuppressWarnings("deprecation")+ private static long versionCode(PackageInfo p) {+ return Build.VERSION.SDK_INT >= 28 ? p.getLongVersionCode() : p.versionCode;+ }++ private static String icon(Drawable d) {+ if (d == null) return null;+ try {+ Bitmap b = Bitmap.createBitmap(ICON_PX, ICON_PX, Bitmap.Config.ARGB_8888);+ d.setBounds(0, 0, ICON_PX, ICON_PX);+ d.draw(new Canvas(b));+ ByteArrayOutputStream png = new ByteArrayOutputStream();+ b.compress(Bitmap.CompressFormat.PNG, 100, png);+ b.recycle();+ return Base64.encodeToString(png.toByteArray(), Base64.NO_WRAP);+ } catch (Exception e) {+ return null; // the label is still worth sending+ }+ }++ /** JSON string, ASCII only: anything outside printable ASCII is a \\u escape. */+ private static void string(PrintStream out, String s) {+ out.print('"');+ for (int i = 0; i < s.length(); i++) {+ char c = s.charAt(i);+ if (c == '"' || c == '\\') {+ out.print('\\');+ out.print(c);+ } else if (c < 0x20 || c > 0x7e) {+ out.print(String.format("\\u%04x", (int) c));+ } else {+ out.print(c);+ }+ }+ out.print('"');+ }+}diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex 8ba46e7..47b82aa 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -9,6 +9,7 @@ import app.tellyscope.adb.ActionResultimport app.tellyscope.adb.Actionsimport app.tellyscope.adb.Connectorimport app.tellyscope.adb.DeviceLink+import app.tellyscope.adb.LabelHelperimport app.tellyscope.adb.LanScannerimport app.tellyscope.adb.Parsersimport app.tellyscope.adb.Protected@@ -38,7 +39,8 @@ import app.tellyscope.adb.ScanHit as AdbHit/*** [DeviceSource] on real TVs through `:adb`. Device id is the TV's IP. Known devices live for the* app process only (persisting them is a later slice), and `procs` / network details beyond the- * IP are empty for now: slice 1 is scan → connect → live CPU/RAM.+ * IP are empty for now: slice 1 is scan → connect → live CPU/RAM. App names and icons come from+ * the label helper through [AppNames].*/class AdbDeviceSource(context: Context) : DeviceSource {private val appContext = context.applicationContext@@ -55,6 +57,10 @@ class AdbDeviceSource(context: Context) : DeviceSource {/** Wireless debugging advertises pairing and connect on different ports. */private val pairingPorts = ConcurrentHashMap<String, Int>()private val book = HistoryBook(File(appContext.filesDir, "history.tsv"))+ /** Last label seen per package, so history entries read like the app list. */+ 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"))init {Connector.init(File(appContext.filesDir, "adbkey.pem"))@@ -225,10 +231,17 @@ class AdbDeviceSource(context: Context) : DeviceSource {val home = Actions(shell).homePackages()val system = Parsers.packages(shell.shell("pm list packages -s").output).map { it.name }.toSet()val disabled = Parsers.packages(shell.shell("pm list packages -d").output).map { it.name }.toSet()- return Parsers.packages(shell.shell("pm list packages").output).map { p ->+ // Older pm rejects --show-versioncode and prints no packages; list again without it.+ val listed = Parsers.packages(shell.shell("pm list packages --show-versioncode").output)+ .ifEmpty { Parsers.packages(shell.shell("pm list packages").output) }+ val serial = shell.shell("getprop ro.serialno").output.trim()+ val names = appNames.names(serial.ifEmpty { deviceId }, listed, LabelHelper(shell, helperDex)::describe)+ return listed.map { p ->+ val name = names.getValue(p.name)+ labels[p.name] = name.labelAppInfo(packageName = p.name,- label = humanise(p.name),+ label = name.label,iconColor = null,system = p.name in system,enabled = p.name !in disabled,@@ -240,6 +253,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {else -> ProtectedReason.UNKNOWN_HOME}?.let(::reasonText),version = "",+ icon = name.icon,)}.sortedBy { it.label.lowercase() }}@@ -268,7 +282,7 @@ class AdbDeviceSource(context: Context) : DeviceSource {at = System.currentTimeMillis(),action = action,packageName = packageName,- label = humanise(packageName),+ label = labels[packageName] ?: AppNames.fallback(packageName),undo = r.undo?.let { Action.valueOf(it.name.lowercase().replaceFirstChar(Char::uppercase)) },undoing = undoing,)@@ -343,12 +357,6 @@ class AdbDeviceSource(context: Context) : DeviceSource {)}- /** `com.google.android.youtube.tv` → "Youtube". Real APK labels come with the apps slice. */- private fun humanise(pkg: String): String {- val parts = pkg.split('.').filter { it !in setOf("com", "android", "google", "tv", "app", "apps", "org") }- return (parts.lastOrNull() ?: pkg).replaceFirstChar(Char::uppercase)- }-/** Copy from the protected-apps table in the UX copy doc. */private fun reasonText(r: ProtectedReason) = when (r) {ProtectedReason.HOME_SCREEN -> "this is your home screen"diff --git a/app/src/main/java/app/tellyscope/data/AppNames.kt b/app/src/main/java/app/tellyscope/data/AppNames.ktnew file mode 100644index 0000000..a17bed9--- /dev/null+++ b/app/src/main/java/app/tellyscope/data/AppNames.kt@@ -0,0 +1,96 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope.data++import app.tellyscope.adb.AppLabel+import app.tellyscope.adb.Parsers+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import java.io.File+import java.util.Base64++/** What the app list shows for one package. [icon] is a PNG; null means a letter avatar. */+class AppName(val label: String, val icon: ByteArray?)++/**+ * Real app names and icons per TV. The TV's own labels come from `describe` (the label helper) and+ * are cached in [dir], one file per TV, so the helper only runs again for new or updated apps. When+ * the helper can't run, [KnownLabels] and then a humanised package id stand in, with no icon, and+ * that TV isn't asked again until the app restarts.+ */+class AppNames(private val dir: File) {+ /** One helper run at a time; a second caller then finds the first one's results cached. */+ private val lock = Mutex()+ private val refused = mutableSetOf<String>()+ /** Asked for and not described (no readable app info): don't run the helper again just for these. */+ private val unanswered = mutableSetOf<Pair<String, String>>()++ /**+ * [tv] identifies the TV (its serial); [packages] is `pm list packages --show-versioncode`.+ * [describe] runs the helper on that TV for the packages it's given, null if it couldn't.+ */+ suspend fun names(+ tv: String,+ packages: List<Parsers.Package>,+ describe: suspend (List<String>) -> List<AppLabel>?,+ ): Map<String, AppName> = lock.withLock {+ val file = File(dir, fileName(tv))+ val cache = load(file).toMutableMap()+ val stale = packages.filter { p ->+ val hit = cache[p.name]+ // Without a versionCode (an older pm) a cached label is as good as it gets.+ (hit == null || (p.versionCode != null && p.versionCode != hit.versionCode)) && (tv to p.name) !in unanswered+ }+ if (stale.isNotEmpty() && tv !in refused) {+ val fresh = describe(stale.map { it.name })+ if (fresh == null) {+ refused += tv+ } else {+ fresh.forEach { cache[it.packageName] = it }+ stale.filter { s -> fresh.none { it.packageName == s.name } }.forEach { unanswered += tv to it.name }+ save(file, cache.values)+ }+ }+ packages.associate { p ->+ p.name to (cache[p.name]?.let { AppName(it.label, it.iconPng) } ?: AppName(fallback(p.name), null))+ }+ }++ companion object {+ /** Bundled table first, then `com.google.android.youtube.tv` → "Youtube". */+ fun fallback(pkg: String): String = KnownLabels[pkg] ?: humanise(pkg)++ private fun humanise(pkg: String): String {+ val parts = pkg.split('.').filter { it !in setOf("com", "android", "google", "tv", "app", "apps", "org") }+ return (parts.lastOrNull() ?: pkg).replaceFirstChar(Char::uppercase)+ }++ private fun fileName(tv: String) = tv.replace(Regex("[^A-Za-z0-9._-]"), "_") + ".tsv"++ /** `package \t versionCode \t label \t base64 PNG`. A damaged line costs that app, not the file. */+ private fun load(file: File): Map<String, AppLabel> {+ if (!file.exists()) return emptyMap()+ return runCatching { file.readLines() }.getOrDefault(emptyList()).mapNotNull { line ->+ val f = line.split('\t')+ if (f.size != 4) return@mapNotNull null+ val version = f[1].toLongOrNull() ?: return@mapNotNull null+ if (f[0].isEmpty() || f[2].isEmpty()) return@mapNotNull null+ val icon = f[3].takeIf { it.isNotEmpty() }?.let { runCatching { Base64.getDecoder().decode(it) }.getOrNull() }+ AppLabel(f[0], f[2], version, icon)+ }.associateBy { it.packageName }+ }++ private fun save(file: File, labels: Collection<AppLabel>) {+ file.parentFile?.mkdirs()+ val tmp = File(file.path + ".tmp")+ tmp.writeText(+ labels.joinToString("") { a ->+ val label = a.label.replace(Regex("[\t\r\n]"), " ")+ val icon = a.iconPng?.let { Base64.getEncoder().encodeToString(it) }.orEmpty()+ "${a.packageName}\t${a.versionCode}\t$label\t$icon\n"+ },+ )+ if (!tmp.renameTo(file)) tmp.delete()+ }+ }+}diff --git a/app/src/main/java/app/tellyscope/data/KnownLabels.kt b/app/src/main/java/app/tellyscope/data/KnownLabels.ktnew file mode 100644index 0000000..e876cb7--- /dev/null+++ b/app/src/main/java/app/tellyscope/data/KnownLabels.kt@@ -0,0 +1,53 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope.data++/**+ * Display names for common TV packages, used when the label helper can't run on a TV (old+ * Android, an OEM block). Names only: no brand icons ship with the app, so these get a letter+ * avatar. Add a package only with the name its own APK shows.+ */+object KnownLabels {+ operator fun get(pkg: String): String? = names[pkg]++ private val names = mapOf(+ // Android and Google TV system apps+ "android" to "Android System",+ "com.android.systemui" to "System UI",+ "com.android.tv.settings" to "Settings",+ "com.android.vending" to "Google Play Store",+ "com.android.chrome" to "Chrome",+ "com.android.bluetooth" to "Bluetooth",+ "com.android.shell" to "Shell",+ "com.android.providers.downloads" to "Download Manager",+ "com.android.packageinstaller" to "Package installer",+ "com.google.android.packageinstaller" to "Package installer",+ "com.google.android.gms" to "Google Play services",+ "com.google.android.gsf" to "Google Services Framework",+ "com.google.android.tvlauncher" to "Android TV Home",+ "com.google.android.apps.tv.launcherx" to "Google TV Home",+ "com.google.android.apps.mediashell" to "Chromecast built-in",+ "com.google.android.tv.remote.service" to "Android TV Remote Service",+ "com.google.android.inputmethod.latin" to "Gboard",+ "com.google.android.tts" to "Speech Services by Google",+ "com.google.android.play.games" to "Google Play Games",+ "com.google.android.youtube.tv" to "YouTube",+ "com.google.android.youtube.tvmusic" to "YouTube Music",+ "com.google.android.youtube.tvkids" to "YouTube Kids",+ // Streaming and media apps+ "com.netflix.ninja" to "Netflix",+ "com.amazon.amazonvideo.livingroom" to "Prime Video",+ "com.disney.disneyplus" to "Disney+",+ "com.apple.atve.androidtv.appletv" to "Apple TV",+ "com.spotify.tv.android" to "Spotify",+ "com.plexapp.android" to "Plex",+ "org.jellyfin.androidtv" to "Jellyfin",+ "org.xbmc.kodi" to "Kodi",+ "org.videolan.vlc" to "VLC",+ "tv.twitch.android.app" to "Twitch",+ "com.crunchyroll.crunchyroid" to "Crunchyroll",+ "com.teamsmart.videomanager.tv" to "SmartTube",+ // Launchers+ "com.spocky.projengmenu" to "Projectivy Launcher",+ )+}diff --git a/app/src/main/java/app/tellyscope/data/Model.kt b/app/src/main/java/app/tellyscope/data/Model.ktindex 9078e8d..668bc89 100644--- a/app/src/main/java/app/tellyscope/data/Model.kt+++ b/app/src/main/java/app/tellyscope/data/Model.kt@@ -81,13 +81,15 @@ data class AppInfo(val packageName: String,/** Human label from the APK. Never the package id; the source falls back to a humanised id. */val label: String,- /** ARGB of the icon tile until real icons are wired; null = neutral tile. */+ /** ARGB of the letter avatar; null = neutral tile. Unused when [icon] is set. */val iconColor: Long?,val system: Boolean,val enabled: Boolean,/** Why this app can't be touched, in user words; null when actions are allowed. */val protectedReason: String?,val version: String,+ /** The app's own icon as a PNG, from the TV; null shows the letter avatar. */+ val icon: ByteArray? = null,)data class Socket(val app: String, val remote: String, val state: String)diff --git a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt b/app/src/main/java/app/tellyscope/ui/DeviceScreen.ktindex 919fdc8..e8b3052 100644--- a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt+++ b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt@@ -2,9 +2,11 @@package app.tellyscope.ui+import android.graphics.BitmapFactoryimport androidx.compose.animation.AnimatedVisibilityimport androidx.compose.animation.animateContentSizeimport androidx.compose.animation.core.animateFloatAsState+import androidx.compose.foundation.Imageimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Arrangement@@ -65,6 +67,7 @@ import androidx.compose.ui.draw.alphaimport androidx.compose.ui.draw.clipimport androidx.compose.ui.draw.rotateimport androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.asImageBitmapimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport app.tellyscope.data.Action@@ -438,6 +441,11 @@ private fun EmptyLine(q: String) {@Composablefun AppIcon(app: AppInfo, modifier: Modifier = Modifier) {+ val image = remember(app.icon) { app.icon?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() } }+ if (image != null) {+ Image(image, contentDescription = null, modifier.size(40.dp).clip(MaterialTheme.shapes.medium))+ return+ }val bg = app.iconColor?.let { Color(it) } ?: MaterialTheme.colorScheme.secondaryContainerval fg = if (app.iconColor != null) Color.White else MaterialTheme.colorScheme.onSecondaryContainerBox(modifier.size(40.dp).clip(MaterialTheme.shapes.medium).background(bg), contentAlignment = Alignment.Center) {diff --git a/app/src/test/java/app/tellyscope/AppNamesTest.kt b/app/src/test/java/app/tellyscope/AppNamesTest.ktnew file mode 100644index 0000000..8f4d709--- /dev/null+++ b/app/src/test/java/app/tellyscope/AppNamesTest.kt@@ -0,0 +1,92 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope++import app.tellyscope.adb.AppLabel+import app.tellyscope.adb.Parsers+import app.tellyscope.data.AppNames+import java.io.File+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertArrayEquals+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Rule+import org.junit.Test+import org.junit.rules.TemporaryFolder++class AppNamesTest {+ @get:Rule val tmp = TemporaryFolder()++ private val icon = byteArrayOf(1, 2, 3)+ private val netflix = Parsers.Package("com.netflix.ninja", null, 10)+ private val odd = Parsers.Package("com.example.weatherbox", null, 3)++ /** Answers like the helper would, from the TV's current versions, and records each run. */+ private class Helper(val fail: Boolean = false) {+ val runs = mutableListOf<List<String>>()+ var versions = mutableMapOf<String, Long>()+ suspend fun describe(packages: List<String>): List<AppLabel>? {+ runs += packages+ if (fail) return null+ return packages.map { AppLabel(it, "Real ${it.substringAfterLast('.')}", versions[it] ?: 0, byteArrayOf(1, 2, 3)) }+ }+ }++ @Test fun helperNamesAndIcons() = runBlocking {+ val helper = Helper()+ val names = AppNames(tmp.root).names("SN1", listOf(netflix, odd), helper::describe)+ assertEquals("Real ninja", names.getValue("com.netflix.ninja").label)+ assertArrayEquals(icon, names.getValue("com.netflix.ninja").icon)+ }++ @Test fun fallbackWhenTheHelperFails() = runBlocking {+ val helper = Helper(fail = true)+ val appNames = AppNames(tmp.root)+ val names = appNames.names("SN1", listOf(netflix, odd), helper::describe)+ assertEquals("Netflix", names.getValue("com.netflix.ninja").label) // bundled table+ assertEquals("Weatherbox", names.getValue("com.example.weatherbox").label) // humanised id+ assertNull(names.getValue("com.netflix.ninja").icon) // letter avatar+ // A refusal isn't retried on every open; the next app start tries again.+ appNames.names("SN1", listOf(netflix, odd), helper::describe)+ assertEquals(1, helper.runs.size)+ }++ @Test fun helperRunsAgainOnlyForNewOrUpdatedApps() = runBlocking {+ val helper = Helper().apply { versions = mutableMapOf(netflix.name to 10, odd.name to 3) }+ AppNames(tmp.root).names("SN1", listOf(netflix, odd), helper::describe)+ // A fresh instance reads the cache from disk, as after an app restart.+ val later = AppNames(tmp.root)+ later.names("SN1", listOf(netflix, odd), helper::describe)+ assertEquals(1, helper.runs.size)++ val youtube = Parsers.Package("com.google.android.youtube.tv", null, 5)+ helper.versions[netflix.name] = 11+ later.names("SN1", listOf(netflix.copy(versionCode = 11), odd, youtube), helper::describe)+ assertEquals(listOf("com.netflix.ninja", "com.google.android.youtube.tv"), helper.runs.last())+ }++ @Test fun cacheIsPerTv() = runBlocking {+ val helper = Helper()+ val appNames = AppNames(tmp.root)+ appNames.names("SN1", listOf(netflix), helper::describe)+ appNames.names("SN2", listOf(netflix), helper::describe)+ assertEquals(2, helper.runs.size)+ }++ @Test fun appsTheHelperSkipsArentAskedForAgain() = runBlocking {+ var runs = 0+ val appNames = AppNames(tmp.root)+ repeat(2) {+ appNames.names("SN1", listOf(netflix, odd), { runs++; listOf(AppLabel("com.netflix.ninja", "Netflix", 10, null)) })+ }+ assertEquals(1, runs)+ }++ @Test fun damagedCacheLinesCostOnlyThatApp() = runBlocking {+ File(tmp.root, "SN1.tsv").writeText("com.netflix.ninja\t10\tNetflix\t\ngarbage line\ncom.example.weatherbox\tx\tW\t\n")+ val helper = Helper()+ val names = AppNames(tmp.root).names("SN1", listOf(netflix, odd), helper::describe)+ assertEquals("Netflix", names.getValue("com.netflix.ninja").label)+ assertEquals(listOf("com.example.weatherbox"), helper.runs.single())+ }+}diff --git a/app/src/test/java/app/tellyscope/ScreenshotTest.kt b/app/src/test/java/app/tellyscope/ScreenshotTest.ktindex 1f58a69..59a2cb8 100644--- a/app/src/test/java/app/tellyscope/ScreenshotTest.kt+++ b/app/src/test/java/app/tellyscope/ScreenshotTest.kt@@ -2,6 +2,9 @@package app.tellyscope+import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.Paintimport androidx.compose.runtime.Composableimport androidx.compose.ui.test.junit4.v2.createComposeRuleimport androidx.compose.ui.test.onNodeWithText@@ -9,6 +12,8 @@ import androidx.compose.ui.test.onRootimport androidx.compose.ui.test.performClickimport androidx.compose.ui.test.performScrollToimport app.tellyscope.data.Action+import app.tellyscope.data.AppInfo+import app.tellyscope.data.AppNamesimport app.tellyscope.data.Deviceimport app.tellyscope.data.DeviceStateimport app.tellyscope.data.FakeDeviceSource@@ -28,6 +33,7 @@ import app.tellyscope.ui.ScanUiimport app.tellyscope.ui.UiStateimport app.tellyscope.ui.theme.TellyscopeThemeimport com.github.takahirom.roborazzi.captureRoboImage+import java.io.ByteArrayOutputStreamimport kotlin.random.Randomimport kotlinx.coroutines.runBlockingimport org.junit.Rule@@ -148,6 +154,45 @@ class ScreenshotTest {shot("07_device_history", before = openHistory) { DeviceScreen(deviceState { copy(history = history) }, DeviceActions()) }}+ /** A real TV's app list: no per-process stats yet, so the apps sit right under the stat grid. */+ private fun appsState(apps: List<AppInfo>): UiState {+ val base = deviceState()+ return base.copy(device = base.device.copy(snapshot = base.device.snapshot?.copy(procs = emptyList()), apps = apps))+ }++ private val tvApps = listOf(+ "com.google.android.youtube.tv" to 0xFFE53935,+ "com.netflix.ninja" to 0xFF212121,+ "org.jellyfin.androidtv" to 0xFF7B5EA7,+ "com.example.weatherbox" to 0xFF0288D1,+ "com.xgimi.assistant" to 0xFF00897B,+ )++ /** Stand-ins for the PNGs the helper reads off the TV: no brand artwork in the repo. */+ private fun iconPng(argb: Long): ByteArray {+ val b = Bitmap.createBitmap(96, 96, Bitmap.Config.ARGB_8888)+ Canvas(b).apply {+ drawColor(argb.toInt())+ drawCircle(48f, 48f, 24f, Paint().apply { color = android.graphics.Color.WHITE; isAntiAlias = true })+ }+ return ByteArrayOutputStream().also { b.compress(Bitmap.CompressFormat.PNG, 100, it) }.toByteArray()+ }++ private fun app(pkg: String, label: String, icon: ByteArray?) =+ AppInfo(pkg, label, null, pkg.startsWith("com.xgimi"), true, null, "", icon)++ @Test fun apps_helperNames() {+ val labels = listOf("YouTube", "Netflix", "Jellyfin", "Weather Box", "XGIMI Assistant")+ val apps = tvApps.zip(labels) { (pkg, color), label -> app(pkg, label, iconPng(color)) }+ shot("09_apps_helper_names") { DeviceScreen(appsState(apps), DeviceActions()) }+ }++ @Test fun apps_fallbackNames() {+ // The helper was refused: bundled names where known, a humanised id otherwise, letter avatars.+ val apps = tvApps.map { (pkg, _) -> app(pkg, AppNames.fallback(pkg), null) }+ shot("10_apps_fallback_names") { DeviceScreen(appsState(apps), DeviceActions()) }+ }+@Test fun permission() = shot("08_permission") { PermissionScreen(denied = false, canAsk = true, {}, {}) }@Test fun permission_denied() = shot("08_permission_denied") { PermissionScreen(denied = true, canAsk = true, {}, {}) }