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.
Install APKs and copy files between the phone and the TV
jesse-agent-2326885a847fb24
diff --git a/README.md b/README.mdindex 7c14286..55a9d1b 100644--- a/README.md+++ b/README.md@@ -12,6 +12,8 @@ Tellyscope is a phone app that talks to your Android TV or Google TV over the ne- **Processes**: what's running and what's eating resources.- **Network**: interfaces, addresses and traffic.- **Debloat**: turn off preinstalled apps, ads and trackers you don't want, and turn them back on with one tap.+- **Install apps**: pick an APK, a set of split APKs or an `.apks`/`.xapk` bundle on your phone and install it on the TV. It tells you first whether it's new or an update, and won't put an older version over a newer one unless you tick the box.+- **Files**: send a file from your phone into the TV's Download or Movies folder, or save one from there to your phone. Nothing on the TV is overwritten.It connects either through classic network debugging (port 5555) or through Android 11+ wireless debugging with a pairing code.diff --git a/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt b/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.ktindex 774f88f..805495e 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/AdbShell.kt@@ -1,6 +1,10 @@// SPDX-License-Identifier: GPL-3.0-onlypackage app.tellyscope.adb+import okio.Sink+import okio.Source+import java.io.File+/** The one thing collectors and actions need from a connection. Faked in tests. */fun interface AdbShell {/** Runs [command] on the device and returns stdout. Throws [java.io.IOException] if the link is gone. */@@ -9,8 +13,22 @@ fun interface AdbShell {data class ShellResult(val output: String, val exitCode: Int)+/**+ * Kadb's install and sync calls, as they are: blocking, and throwing with the device's answer in+ * the message. [Sideload] and [Files] run them off the main thread. Faked in tests.+ */+interface AdbTransfer {+ fun install(source: Source, size: Long, vararg options: String)+ fun installMultiple(apks: List<File>, vararg options: String)+ fun push(source: Source, remotePath: String, mode: Int, lastModifiedMs: Long)+ fun pull(sink: Sink, remotePath: String)+ fun list(remoteDir: String): List<RemoteEntry>+}++data class RemoteEntry(val name: String, val mode: Int, val size: Long, val mtimeSec: Long)+/** An open connection to one device. */-interface AdbSession : AdbShell, AutoCloseable {+interface AdbSession : AdbShell, AdbTransfer, 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/ApkBundle.kt b/adb/src/main/kotlin/app/tellyscope/adb/ApkBundle.ktnew file mode 100644index 0000000..0d4a81f--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/ApkBundle.kt@@ -0,0 +1,48 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import java.io.File+import java.io.IOException+import java.util.zip.ZipFile++/**+ * Split apps come as several .apk files, or as one bundle (.apks, .xapk, .apkm) that is a zip of+ * them. Both end up here as a list of APK files, base first, ready for [Sideload.install].+ */+object ApkBundle {++ /** An APK is itself a zip with a manifest at the root; a bundle is a zip of APKs. */+ fun isApk(file: File): Boolean = zipEntries(file)?.contains("AndroidManifest.xml") == true++ /**+ * The APKs inside [bundle], extracted into [dir]. Only top-level `*.apk` entries count; OBB+ * data and metadata are skipped. Throws [IOException] when there are none.+ */+ fun unpack(bundle: File, dir: File): List<File> {+ dir.mkdirs()+ val out = ZipFile(bundle).use { zip ->+ zip.entries().asSequence()+ .filter { !it.isDirectory && '/' !in it.name && it.name.endsWith(".apk", ignoreCase = true) }+ .map { e ->+ // Names are flat (no '/' above), so nothing can land outside dir.+ File(dir, e.name).also { f -> zip.getInputStream(e).use { i -> f.outputStream().use(i::copyTo) } }+ }+ .toList()+ }+ if (out.isEmpty()) throw IOException("no APKs in ${bundle.name}")+ return baseFirst(out)+ }++ /** `base.apk` if there is one, else the largest file (splits are small config slices). */+ fun baseFirst(apks: List<File>): List<File> {+ val base = apks.firstOrNull { it.name.equals("base.apk", ignoreCase = true) } ?: apks.maxBy { it.length() }+ return listOf(base) + (apks - base)+ }++ private fun zipEntries(file: File): Set<String>? =+ try {+ ZipFile(file).use { z -> z.entries().asSequence().map { it.name }.toSet() }+ } catch (_: IOException) {+ null+ }+}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt b/adb/src/main/kotlin/app/tellyscope/adb/Connector.ktindex 65ea533..9829aee 100644--- a/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt+++ b/adb/src/main/kotlin/app/tellyscope/adb/Connector.kt@@ -11,6 +11,8 @@ import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.runInterruptibleimport okio.Bufferimport okio.Path.Companion.toPath+import okio.Sink+import okio.Sourceimport java.io.Fileimport java.io.IOExceptionimport java.io.InterruptedIOException@@ -101,5 +103,18 @@ internal class KadbSession(private val kadb: Kadb) : AdbSession {kadb.push(Buffer().write(bytes), remotePath, "644".toInt(8), System.currentTimeMillis())}+ override fun install(source: Source, size: Long, vararg options: String) = kadb.install(source, size, *options)++ override fun installMultiple(apks: List<File>, vararg options: String) = kadb.installMultiple(apks, *options)++ override fun push(source: Source, remotePath: String, mode: Int, lastModifiedMs: Long) =+ kadb.push(source, remotePath, mode, lastModifiedMs)++ override fun pull(sink: Sink, remotePath: String) = kadb.pull(sink, remotePath)++ override fun list(remoteDir: String): List<RemoteEntry> = kadb.openSync().use { sync ->+ sync.list(remoteDir).map { RemoteEntry(it.name, it.mode, it.size, it.mtimeSec) }+ }+override fun close() = kadb.close()}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Files.kt b/adb/src/main/kotlin/app/tellyscope/adb/Files.ktnew file mode 100644index 0000000..71fa823--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/Files.kt@@ -0,0 +1,72 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import okio.Sink+import okio.Source++/** The two shared folders Tellyscope reads and writes. Nothing outside them. */+enum class TvFolder(val path: String) {+ DOWNLOAD("/sdcard/Download"),+ MOVIES("/sdcard/Movies"),+}++data class TvFile(val name: String, val size: Long, val modifiedMillis: Long)++/** Phone ↔ TV file copies over the ADB sync service. */+class Files(private val session: AdbSession) {++ /** Plain files in [folder], newest first. A missing folder is an empty one. */+ suspend fun list(folder: TvFolder): List<TvFile> = runTransfer { _ ->+ session.list(folder.path)+ .filter { it.mode and S_IFMT == S_IFREG && !it.name.startsWith(".") }+ .map { TvFile(it.name, it.size, it.mtimeSec * 1000) }+ .sortedByDescending { it.modifiedMillis }+ }++ /**+ * Copies [source] into [folder] as [name], or "name (1).ext" if that's taken, so nothing on the+ * TV is ever overwritten. Returns the name it was saved under. A cancelled or failed copy deletes+ * the partial file, so a retry doesn't land as "name (1)" beside a truncated one.+ */+ suspend fun push(+ source: Source,+ size: Long?,+ name: String,+ folder: TvFolder,+ onProgress: (Progress) -> Unit = {},+ ): String {+ val target = uniqueName(safeName(name), list(folder).map { it.name }.toSet())+ 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())+ }+ return target+ }++ /** Copies [file] from [folder] into [sink]. On cancel the caller deletes what it was writing to. */+ suspend fun pull(folder: TvFolder, file: TvFile, sink: Sink, onProgress: (Progress) -> Unit = {}) {+ require(safeName(file.name) == file.name) { "not a plain file name: ${file.name}" }+ runTransfer { stopped -> session.pull(sink.counting(file.size, stopped, onProgress), "${folder.path}/${file.name}") }+ }++ companion object {+ private const val S_IFMT = 0xF000+ private const val S_IFREG = 0x8000+ private const val FILE_MODE = 420 // 0644++ /** One path segment: no separators, no control characters, never "." or "..". */+ fun safeName(name: String): String {+ val cleaned = name.map { if (it == '/' || it == '\\' || it.code < 0x20) '_' else it }.joinToString("").trim()+ return cleaned.takeUnless { it.isEmpty() || it.all { c -> c == '.' } } ?: "file"+ }++ /** "clip.mp4" → "clip (1).mp4" → "clip (2).mp4" until it's free. */+ fun uniqueName(name: String, taken: Set<String>): String {+ if (name !in taken) return name+ val dot = name.lastIndexOf('.').takeIf { it > 0 } ?: name.length+ val stem = name.substring(0, dot)+ val ext = name.substring(dot)+ return generateSequence(1) { it + 1 }.map { "$stem ($it)$ext" }.first { it !in taken }+ }+ }+}diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Progress.kt b/adb/src/main/kotlin/app/tellyscope/adb/Progress.ktnew file mode 100644index 0000000..68ea5d3--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/Progress.kt@@ -0,0 +1,78 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.NonCancellable+import kotlinx.coroutines.job+import kotlinx.coroutines.withContext+import okio.Buffer+import okio.ForwardingSink+import okio.ForwardingSource+import okio.Sink+import okio.Source+import java.io.InterruptedIOException++/** Bytes moved so far out of [total]. [total] is null when the size isn't known up front. */+data class Progress(val done: Long, val total: Long?) {+ val fraction: Float? get() = total?.takeIf { it > 0 }?.let { (done.toDouble() / it).toFloat().coerceIn(0f, 1f) }+}++/**+ * Runs a blocking Kadb [transfer] on the IO pool. Cancelling the coroutine doesn't interrupt the+ * thread (that would close the socket the stats share); the next chunk read or written through+ * [counting] sees it and stops the stream instead. [cleanUp] runs whenever the transfer doesn't+ * finish, cancelled or failed (a full disk, a dropped link), so nothing truncated is left behind.+ * A cancel then reaches the caller as [CancellationException], a failure as itself.+ */+internal suspend fun <T> runTransfer(cleanUp: suspend () -> Unit = {}, transfer: (stopped: () -> Boolean) -> T): T =+ withContext(Dispatchers.IO) {+ val job = coroutineContext.job+ try {+ transfer { !job.isActive }+ } catch (e: Exception) {+ withContext(NonCancellable) { cleanUp() }+ // Kadb may wrap our stop in its own exception; what matters is whether we asked to stop.+ if (job.isActive) throw e+ throw CancellationException("transfer cancelled").apply { initCause(e) }+ }+ }++/** Reports at most once per percent, so a 2 GB file doesn't flood the UI with updates. */+private class Reporter(private val total: Long?, private val onProgress: (Progress) -> Unit) {+ private var done = 0L+ private var last = -1L++ fun add(n: Long) {+ done += n+ val step = total?.let { if (it > 0) done * 100 / it else 100 } ?: (done shr 20)+ if (step != last) {+ last = step+ onProgress(Progress(done, total))+ }+ }+}++internal fun Source.counting(total: Long?, stopped: () -> Boolean, onProgress: (Progress) -> Unit): Source {+ val r = Reporter(total, onProgress)+ return object : ForwardingSource(this) {+ override fun read(sink: Buffer, byteCount: Long): Long {+ if (stopped()) throw InterruptedIOException("cancelled")+ return super.read(sink, byteCount).also { if (it > 0) r.add(it) }+ }+ }+}++internal fun Sink.counting(total: Long?, stopped: () -> Boolean, onProgress: (Progress) -> Unit): Sink {+ val r = Reporter(total, onProgress)+ return object : ForwardingSink(this) {+ override fun write(source: Buffer, byteCount: Long) {+ if (stopped()) throw InterruptedIOException("cancelled")+ super.write(source, byteCount)+ r.add(byteCount)+ }+ }+}++/** One shell word, single-quoted the way adb quotes arguments. */+internal fun shellQuote(s: String) = "'" + s.replace("'", "'\\''") + "'"diff --git a/adb/src/main/kotlin/app/tellyscope/adb/Sideload.kt b/adb/src/main/kotlin/app/tellyscope/adb/Sideload.ktnew file mode 100644index 0000000..086fd5e--- /dev/null+++ b/adb/src/main/kotlin/app/tellyscope/adb/Sideload.kt@@ -0,0 +1,149 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.CancellationException+import okio.source+import java.io.File++/** What the phone read from the APK before sending it. */+data class ApkInfo(val packageName: String, val versionCode: Long, val versionName: String?)++data class InstalledVersion(val versionCode: Long, val versionName: String?)++enum class InstallKind { NEW, UPDATE, REINSTALL, DOWNGRADE }++fun installKind(apk: ApkInfo, installed: InstalledVersion?): InstallKind = when {+ installed == null -> InstallKind.NEW+ apk.versionCode > installed.versionCode -> InstallKind.UPDATE+ apk.versionCode == installed.versionCode -> InstallKind.REINSTALL+ else -> InstallKind.DOWNGRADE+}++/** Why the TV wouldn't install. The app turns each one into a sentence. */+enum class InstallRefusal {+ /** Same package, signed by someone else: only an uninstall would let it in, and we never uninstall. */+ SIGNATURE,+ DOWNGRADE,+ NO_SPACE,+ /** A policy, a verifier or the TV's owner settings blocked it. */+ TV_SAID_NO,+ /** The app needs a newer Android than the TV has. */+ TV_TOO_OLD,+ /** Built for a different processor, e.g. an arm64-only app on a 32-bit TV. */+ WRONG_CPU,+ /** Targets an Android so old that the TV refuses it. */+ APP_TOO_OLD,+ /** Needs hardware the TV doesn't have (a touchscreen, a camera). */+ MISSING_FEATURE,+ /** A split app with a part missing. */+ MISSING_PARTS,+ TEST_ONLY,+ /** Another installed app already claims one of its permissions or providers. */+ CONFLICT,+ /** Not an APK, or a damaged one. */+ BROKEN,+ UNKNOWN,+}++sealed interface InstallResult {+ data object Done : InstallResult+ /** [detail] is the TV's own words, for the "details" line and bug reports. */+ data class Refused(val reason: InstallRefusal, val detail: String) : InstallResult+}++/**+ * Installs APKs from the phone. Every install replaces in place (`-r`); a downgrade happens only+ * when the caller passes `allowDowngrade`, which the UI sets only after the user asked for it.+ */+class Sideload(private val session: AdbSession) {++ /** The version on the TV, or null when it isn't installed. */+ suspend fun installed(pkg: String): InstalledVersion? {+ require(Actions.PACKAGE.matches(pkg)) { "not a package name: $pkg" }+ return parseInstalled(session.shell("dumpsys package $pkg").output, pkg)+ }++ /**+ * Installs [apks], the base first for a split app. One APK streams with byte progress; a split+ * set goes through Kadb's install session, which reports nothing until it finishes, so+ * [onProgress] then only sees an unknown total.+ */+ suspend fun install(+ apks: List<File>,+ apk: ApkInfo,+ allowDowngrade: Boolean,+ onProgress: (Progress) -> Unit = {},+ ): InstallResult {+ require(apks.isNotEmpty()) { "nothing to install" }+ val kind = installKind(apk, installed(apk.packageName))+ if (kind == InstallKind.DOWNGRADE && !allowDowngrade) {+ return InstallResult.Refused(InstallRefusal.DOWNGRADE, "the TV has a newer version")+ }+ val options = if (kind == InstallKind.DOWNGRADE) arrayOf("-r", "-d") else arrayOf("-r")+ return try {+ runTransfer { stopped ->+ if (apks.size == 1) {+ val f = apks.single()+ f.source().use { src ->+ session.install(src.counting(f.length(), stopped, onProgress), f.length(), *options)+ }+ } else {+ onProgress(Progress(0, null))+ session.installMultiple(apks, *options)+ }+ }+ InstallResult.Done+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ // Kadb throws IllegalStateException or IOException with "Failure [INSTALL_...]" in it.+ val out = e.message.orEmpty()+ InstallResult.Refused(refusal(out), out.substringAfter("Install failed: ").trim())+ }+ }++ companion object {+ /**+ * The version from `dumpsys package <pkg>`. Only the active entry counts: an updated+ * system app also lists its factory copy under "Hidden system packages".+ */+ fun parseInstalled(dumpsys: String, pkg: String): InstalledVersion? {+ val active = dumpsys.substringBefore("Hidden system packages:")+ val start = active.indexOf("Package [$pkg]")+ if (start < 0) return null+ val block = active.substring(start).lineSequence().drop(1).takeWhile { !it.trimStart().startsWith("Package [") }.joinToString("\n")+ val code = Regex("""versionCode=(\d+)""").find(block)?.groupValues?.get(1)?.toLongOrNull() ?: return null+ val name = Regex("""versionName=(\S+)""").find(block)?.groupValues?.get(1)+ return InstalledVersion(code, name)+ }++ fun refusal(output: String): InstallRefusal {+ val code = Regex("""INSTALL_[A-Z_]+""").find(output)?.value+ ?: return if ("not enough space" in output.lowercase()) InstallRefusal.NO_SPACE else InstallRefusal.UNKNOWN+ return when (code) {+ "INSTALL_FAILED_UPDATE_INCOMPATIBLE",+ "INSTALL_FAILED_SHARED_USER_INCOMPATIBLE",+ "INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES" -> InstallRefusal.SIGNATURE+ "INSTALL_FAILED_VERSION_DOWNGRADE" -> InstallRefusal.DOWNGRADE+ "INSTALL_FAILED_INSUFFICIENT_STORAGE" -> InstallRefusal.NO_SPACE+ "INSTALL_FAILED_USER_RESTRICTED",+ "INSTALL_FAILED_VERIFICATION_FAILURE",+ "INSTALL_FAILED_VERIFICATION_TIMEOUT",+ "INSTALL_FAILED_ABORTED" -> InstallRefusal.TV_SAID_NO+ "INSTALL_FAILED_OLDER_SDK" -> InstallRefusal.TV_TOO_OLD+ "INSTALL_FAILED_NO_MATCHING_ABIS",+ "INSTALL_FAILED_CPU_ABI_INCOMPATIBLE" -> InstallRefusal.WRONG_CPU+ "INSTALL_FAILED_DEPRECATED_SDK_VERSION" -> InstallRefusal.APP_TOO_OLD+ "INSTALL_FAILED_MISSING_FEATURE" -> InstallRefusal.MISSING_FEATURE+ "INSTALL_FAILED_MISSING_SPLIT" -> InstallRefusal.MISSING_PARTS+ "INSTALL_FAILED_TEST_ONLY" -> InstallRefusal.TEST_ONLY+ "INSTALL_FAILED_DUPLICATE_PERMISSION",+ "INSTALL_FAILED_CONFLICTING_PROVIDER",+ "INSTALL_FAILED_DUPLICATE_PACKAGE",+ "INSTALL_FAILED_ALREADY_EXISTS" -> InstallRefusal.CONFLICT+ "INSTALL_FAILED_INVALID_APK", "INSTALL_FAILED_INVALID_URI" -> InstallRefusal.BROKEN+ else -> if (code.startsWith("INSTALL_PARSE_FAILED")) InstallRefusal.BROKEN else InstallRefusal.UNKNOWN+ }+ }+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/ApkBundleTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/ApkBundleTest.ktnew file mode 100644index 0000000..f77622c--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/ApkBundleTest.kt@@ -0,0 +1,53 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import java.io.File+import java.io.IOException+import java.util.zip.ZipEntry+import java.util.zip.ZipOutputStream+import kotlin.io.path.createTempDirectory+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class ApkBundleTest {+ private val dir = createTempDirectory("bundle").toFile()++ private fun zip(name: String, entries: Map<String, Int>) = File(dir, name).also { f ->+ ZipOutputStream(f.outputStream()).use { z ->+ entries.forEach { (e, size) -> z.putNextEntry(ZipEntry(e)); z.write(ByteArray(size)); z.closeEntry() }+ }+ }++ @Test fun tellsAnApkFromABundle() {+ assertTrue(ApkBundle.isApk(zip("app.apk", mapOf("AndroidManifest.xml" to 10, "classes.dex" to 10))))+ assertFalse(ApkBundle.isApk(zip("app.apks", mapOf("base.apk" to 10))))+ assertFalse(ApkBundle.isApk(File(dir, "notes.txt").apply { writeText("hi") }))+ }++ @Test fun unpacksApksBaseFirstAndSkipsTheRest() {+ val b = zip("player.xapk", mapOf(+ "manifest.json" to 5,+ "config.arm64_v8a.apk" to 50,+ "com.example.player.apk" to 900,+ "Android/obb/com.example.player/main.1.obb" to 100,+ "icon.png" to 5,+ ))+ val out = ApkBundle.unpack(b, File(dir, "out"))+ assertEquals(listOf("com.example.player.apk", "config.arm64_v8a.apk"), out.map { it.name })+ assertEquals(900, out.first().length())+ }++ @Test fun baseApkWinsOverSize() {+ val b = zip("player.apks", mapOf("split_big.apk" to 900, "base.apk" to 100))+ assertEquals("base.apk", ApkBundle.unpack(b, File(dir, "o2")).first().name)+ }++ @Test fun nestedPathsNeverEscape() {+ val b = zip("evil.apks", mapOf("../../escape.apk" to 10))+ assertFailsWith<IOException> { ApkBundle.unpack(b, File(dir, "o3")) }+ assertFalse(File(dir, "escape.apk").exists())+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.kt b/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.ktindex d2d791c..d1b251f 100644--- a/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.kt+++ b/adb/src/test/kotlin/app/tellyscope/adb/FakeShell.kt@@ -1,8 +1,18 @@// SPDX-License-Identifier: GPL-3.0-onlypackage app.tellyscope.adb+import okio.Buffer+import okio.Sink+import okio.Source+import okio.buffer+import okio.source+import java.io.File+/** Answers by the first matching command prefix and records what ran. */-class FakeShell(private val answers: Map<String, ShellResult> = emptyMap()) : AdbSession {+class FakeShell(+ private val answers: Map<String, ShellResult> = emptyMap(),+ val transfer: FakeTransfer = FakeTransfer(),+) : AdbSession, AdbTransfer by transfer {val ran = mutableListOf<String>()var closed = falsevar failWith: Exception? = null@@ -24,4 +34,55 @@ class FakeShell(private val answers: Map<String, ShellResult> = emptyMap()) : Adoverride fun close() { closed = true }}+/** A TV filesystem in a map, plus the install calls it saw. */+class FakeTransfer : AdbTransfer {+ val files = mutableMapOf<String, ByteArray>()+ val installs = mutableListOf<Pair<List<String>, List<String>>>()+ /** Thrown by install calls, like Kadb does with the TV's "Failure [...]" answer. */+ var installFails: Exception? = null+ /** Runs between chunks, so a test can cancel mid-copy. */+ var onChunk: () -> Unit = {}++ override fun install(source: Source, size: Long, vararg options: String) {+ drain(source)+ installFails?.let { throw it }+ installs += listOf("stream:$size") to options.toList()+ }++ override fun installMultiple(apks: List<File>, vararg options: String) {+ installFails?.let { throw it }+ installs += apks.map { it.name } to options.toList()+ }++ override fun push(source: Source, remotePath: String, mode: Int, lastModifiedMs: Long) {+ files[remotePath] = drain(source)+ }++ override fun pull(sink: Sink, remotePath: String) {+ val bytes = files[remotePath] ?: throw java.io.IOException("Sync failed: No such file")+ val src = bytes.inputStream().source().buffer()+ while (!src.exhausted()) {+ val chunk = Buffer()+ src.read(chunk, CHUNK)+ sink.write(chunk, chunk.size)+ onChunk()+ }+ sink.flush()+ }++ override fun list(remoteDir: String): List<RemoteEntry> =+ files.filterKeys { it.substringBeforeLast('/') == remoteDir }+ .map { (path, bytes) -> RemoteEntry(path.substringAfterLast('/'), 0x81A4, bytes.size.toLong(), 1_700_000_000) }++ private fun drain(source: Source): ByteArray {+ val all = Buffer()+ while (source.read(all, CHUNK) != -1L) onChunk()+ return all.readByteArray()+ }++ private companion object {+ const val CHUNK = 8192L+ }+}+fun ok(output: String) = ShellResult(output, 0)diff --git a/adb/src/test/kotlin/app/tellyscope/adb/FilesTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/FilesTest.ktnew file mode 100644index 0000000..bc50f8b--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/FilesTest.kt@@ -0,0 +1,127 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withContext+import kotlinx.coroutines.test.runTest+import okio.Buffer+import java.io.IOException+import java.util.concurrent.CountDownLatch+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class FilesTest {+ private val data = ByteArray(300_000) { (it % 251).toByte() }++ @Test fun pushNeverOverwrites() = runTest {+ val sh = FakeShell()+ sh.transfer.files["/sdcard/Download/clip.mp4"] = byteArrayOf(1)+ sh.transfer.files["/sdcard/Download/clip (1).mp4"] = byteArrayOf(2)+ val name = Files(sh).push(Buffer().write(data), data.size.toLong(), "clip.mp4", TvFolder.DOWNLOAD)+ assertEquals("clip (2).mp4", name)+ assertContentEquals(data, sh.transfer.files["/sdcard/Download/clip (2).mp4"])+ assertContentEquals(byteArrayOf(1), sh.transfer.files["/sdcard/Download/clip.mp4"])+ }++ @Test fun pushReportsProgressToTheEnd() = runTest {+ val sh = FakeShell()+ val seen = mutableListOf<Progress>()+ Files(sh).push(Buffer().write(data), data.size.toLong(), "a.bin", TvFolder.MOVIES) { seen += it }+ assertEquals(Progress(data.size.toLong(), data.size.toLong()), seen.last())+ assertTrue(seen.zipWithNext().all { (a, b) -> b.done > a.done })+ }++ @Test fun pullCopiesTheFile() = runTest {+ val sh = FakeShell()+ sh.transfer.files["/sdcard/Movies/film.mkv"] = data+ val files = Files(sh)+ val f = files.list(TvFolder.MOVIES).single()+ val out = Buffer()+ files.pull(TvFolder.MOVIES, f, out)+ assertContentEquals(data, out.readByteArray())+ }++ @Test fun listShowsPlainVisibleFilesOnly() = runTest {+ val sh = FakeShell()+ sh.transfer.files["/sdcard/Download/a.txt"] = byteArrayOf(1)+ sh.transfer.files["/sdcard/Download/.nomedia"] = byteArrayOf()+ sh.transfer.files["/sdcard/Movies/b.mp4"] = byteArrayOf(1)+ assertEquals(listOf("a.txt"), Files(sh).list(TvFolder.DOWNLOAD).map { it.name })+ }++ @Test fun cancelledPushDeletesThePartialFile() = runBlocking {+ val sh = FakeShell()+ val started = CountDownLatch(1)+ val release = CountDownLatch(1)+ var chunks = 0+ sh.transfer.onChunk = { if (++chunks == 3) { started.countDown(); release.await() } }+ val job = async(Dispatchers.Default) {+ Files(sh).push(Buffer().write(data), data.size.toLong(), "big.bin", TvFolder.DOWNLOAD)+ }+ withContext(Dispatchers.IO) { started.await() }+ job.cancel()+ release.countDown()+ assertFailsWith<CancellationException> { job.await() }+ assertFalse("/sdcard/Download/big.bin" in sh.transfer.files)+ assertTrue(sh.ran.contains("rm -f '/sdcard/Download/big.bin'"), "ran: ${sh.ran}")+ }++ @Test fun failedPushDeletesThePartialFile() = runTest {+ val sh = FakeShell()+ var chunks = 0+ sh.transfer.onChunk = { if (++chunks == 3) throw IOException("Sync failed: No space left on device") }+ assertFailsWith<IOException> {+ Files(sh).push(Buffer().write(data), data.size.toLong(), "clip.mp4", TvFolder.DOWNLOAD)+ }+ assertTrue(sh.ran.contains("rm -f '/sdcard/Download/clip.mp4'"), "ran: ${sh.ran}")+ }++ @Test fun finishedPushDeletesNothing() = runTest {+ val sh = FakeShell()+ Files(sh).push(Buffer().write(data), data.size.toLong(), "clip.mp4", TvFolder.DOWNLOAD)+ assertTrue(sh.ran.none { it.startsWith("rm ") })+ }++ @Test fun cancelledPullStopsWriting() = runBlocking {+ val sh = FakeShell()+ sh.transfer.files["/sdcard/Movies/film.mkv"] = data+ val started = CountDownLatch(1)+ val release = CountDownLatch(1)+ var chunks = 0+ sh.transfer.onChunk = { if (++chunks == 2) { started.countDown(); release.await() } }+ val out = Buffer()+ val files = Files(sh)+ val f = files.list(TvFolder.MOVIES).single()+ val job = async(Dispatchers.Default) { files.pull(TvFolder.MOVIES, f, out) }+ withContext(Dispatchers.IO) { started.await() }+ job.cancel()+ release.countDown()+ assertFailsWith<CancellationException> { job.await() }+ assertTrue(out.size < data.size)+ }++ @Test fun namesStayInsideTheFolder() {+ assertEquals("_.._etc_passwd", Files.safeName("/../etc/passwd"))+ assertEquals("file", Files.safeName(".."))+ assertEquals("file", Files.safeName(" "))+ assertEquals("it's fine.mp4", Files.safeName("it's fine.mp4"))+ }++ @Test fun uniqueNames() {+ assertEquals("a.mp4", Files.uniqueName("a.mp4", setOf("b.mp4")))+ assertEquals("a (1).mp4", Files.uniqueName("a.mp4", setOf("a.mp4")))+ assertEquals("README (1)", Files.uniqueName("README", setOf("README")))+ assertEquals(".bashrc (1)", Files.uniqueName(".bashrc", setOf(".bashrc")))+ }++ @Test fun quotingSurvivesApostrophes() {+ assertEquals("'it'\\''s.mp4'", shellQuote("it's.mp4"))+ }+}diff --git a/adb/src/test/kotlin/app/tellyscope/adb/SideloadTest.kt b/adb/src/test/kotlin/app/tellyscope/adb/SideloadTest.ktnew file mode 100644index 0000000..c7f4794--- /dev/null+++ b/adb/src/test/kotlin/app/tellyscope/adb/SideloadTest.kt@@ -0,0 +1,125 @@+// SPDX-License-Identifier: GPL-3.0-only+package app.tellyscope.adb++import kotlinx.coroutines.test.runTest+import java.io.File+import java.io.IOException+import kotlin.io.path.createTempDirectory+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class SideloadTest {+ private val dir = createTempDirectory("sideload").toFile()+ private fun apk(name: String, size: Int = 20_000) = File(dir, name).apply { writeBytes(ByteArray(size)) }++ private val dumpsys = """+ Packages:+ Package [com.example.player] (3c1a2b):+ userId=10123+ versionCode=42 minSdk=24 targetSdk=34+ versionName=4.2.0+ Package [com.example.other] (77aa):+ versionCode=7 minSdk=21 targetSdk=33+ versionName=0.7+ Hidden system packages:+ Package [com.example.player] (1f00):+ versionCode=1 minSdk=24 targetSdk=34+ versionName=1.0-factory+ """.trimIndent()++ private val player = ApkInfo("com.example.player", 42, "4.2.0")++ @Test fun readsTheActiveVersionNotTheFactoryCopy() {+ assertEquals(InstalledVersion(42, "4.2.0"), Sideload.parseInstalled(dumpsys, "com.example.player"))+ assertEquals(InstalledVersion(7, "0.7"), Sideload.parseInstalled(dumpsys, "com.example.other"))+ assertNull(Sideload.parseInstalled(dumpsys, "com.example.absent"))+ assertNull(Sideload.parseInstalled("Unable to find package: com.example.absent\n", "com.example.absent"))+ }++ @Test fun kindComparesVersionCodes() {+ val on = InstalledVersion(42, "4.2.0")+ assertEquals(InstallKind.NEW, installKind(player, null))+ assertEquals(InstallKind.UPDATE, installKind(player.copy(versionCode = 43), on))+ assertEquals(InstallKind.REINSTALL, installKind(player, on))+ assertEquals(InstallKind.DOWNGRADE, installKind(player.copy(versionCode = 41), on))+ }++ @Test fun singleApkStreamsWithProgressAndReplaces() = runTest {+ val sh = FakeShell()+ val seen = mutableListOf<Progress>()+ val r = Sideload(sh).install(listOf(apk("app.apk")), player, allowDowngrade = false) { seen += it }+ assertEquals(InstallResult.Done, r)+ assertEquals(listOf("stream:20000") to listOf("-r"), sh.transfer.installs.single())+ assertEquals(1f, seen.last().fraction)+ assertTrue(seen.size in 2..101, "throttled to about one update per percent, got ${seen.size}")+ }++ @Test fun splitApkGoesThroughInstallMultiple() = runTest {+ val sh = FakeShell()+ val parts = listOf(apk("base.apk"), apk("split_config.arm64_v8a.apk", 500))+ val seen = mutableListOf<Progress>()+ assertEquals(InstallResult.Done, Sideload(sh).install(parts, player, allowDowngrade = false) { seen += it })+ assertEquals(listOf("base.apk", "split_config.arm64_v8a.apk") to listOf("-r"), sh.transfer.installs.single())+ assertNull(seen.single().fraction)+ }++ @Test fun downgradeIsRefusedBeforeAnythingIsSent() = runTest {+ val sh = FakeShell(mapOf("dumpsys package" to ok(dumpsys)))+ val r = Sideload(sh).install(listOf(apk("old.apk")), player.copy(versionCode = 40), allowDowngrade = false)+ assertEquals(InstallRefusal.DOWNGRADE, (r as InstallResult.Refused).reason)+ assertTrue(sh.transfer.installs.isEmpty())+ }++ @Test fun downgradeOnlyWhenAskedAddsDashD() = runTest {+ val sh = FakeShell(mapOf("dumpsys package" to ok(dumpsys)))+ Sideload(sh).install(listOf(apk("old.apk")), player.copy(versionCode = 40), allowDowngrade = true)+ assertEquals(listOf("-r", "-d"), sh.transfer.installs.single().second)+ }++ @Test fun allowDowngradeDoesNothingForAnUpdate() = runTest {+ val sh = FakeShell(mapOf("dumpsys package" to ok(dumpsys)))+ Sideload(sh).install(listOf(apk("new.apk")), player.copy(versionCode = 50), allowDowngrade = true)+ assertEquals(listOf("-r"), sh.transfer.installs.single().second)+ }++ @Test fun tvRefusalBecomesAReasonNotACrash() = runTest {+ val sh = FakeShell()+ sh.transfer.installFails = IllegalStateException(+ "Install failed: Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE: Package com.example.player signatures do not match previously installed version; ignoring!]",+ )+ val r = Sideload(sh).install(listOf(apk("app.apk")), player, allowDowngrade = false) as InstallResult.Refused+ assertEquals(InstallRefusal.SIGNATURE, r.reason)+ assertTrue(r.detail.startsWith("Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE"))+ }++ @Test fun splitSessionFailureIsMappedToo() = runTest {+ val sh = FakeShell()+ sh.transfer.installFails = IOException("Install failed: Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE]")+ val r = Sideload(sh).install(listOf(apk("base.apk"), apk("split.apk")), player, allowDowngrade = false)+ assertEquals(InstallRefusal.NO_SPACE, (r as InstallResult.Refused).reason)+ }++ @Test fun refusalCodes() {+ val cases = mapOf(+ "Failure [INSTALL_FAILED_VERSION_DOWNGRADE]" to InstallRefusal.DOWNGRADE,+ "Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE]" to InstallRefusal.NO_SPACE,+ "Failure [INSTALL_FAILED_USER_RESTRICTED: Install canceled by user]" to InstallRefusal.TV_SAID_NO,+ "Failure [INSTALL_FAILED_VERIFICATION_FAILURE]" to InstallRefusal.TV_SAID_NO,+ "Failure [INSTALL_FAILED_OLDER_SDK: Requires newer sdk version #34 (current version is #30)]" to InstallRefusal.TV_TOO_OLD,+ "Failure [INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]" to InstallRefusal.WRONG_CPU,+ "Failure [INSTALL_FAILED_DEPRECATED_SDK_VERSION: App package must target at least SDK version 23]" to InstallRefusal.APP_TOO_OLD,+ "Failure [INSTALL_FAILED_MISSING_FEATURE: Package requires unavailable feature android.hardware.touchscreen]" to InstallRefusal.MISSING_FEATURE,+ "Failure [INSTALL_FAILED_MISSING_SPLIT: Missing split for com.example.player]" to InstallRefusal.MISSING_PARTS,+ "Failure [INSTALL_FAILED_TEST_ONLY]" to InstallRefusal.TEST_ONLY,+ "Failure [INSTALL_FAILED_DUPLICATE_PERMISSION: ...]" to InstallRefusal.CONFLICT,+ "Failure [INSTALL_PARSE_FAILED_NOT_APK: Failed to parse /data/app/vmdl.tmp/base.apk]" to InstallRefusal.BROKEN,+ "Failure [INSTALL_FAILED_INVALID_APK]" to InstallRefusal.BROKEN,+ "Failure [INSTALL_FAILED_SOMETHING_NEW]" to InstallRefusal.UNKNOWN,+ "Error: java.io.IOException: Requested internal only, but not enough space" to InstallRefusal.NO_SPACE,+ "Kadb is closed" to InstallRefusal.UNKNOWN,+ )+ cases.forEach { (out, want) -> assertEquals(want, Sideload.refusal(out), out) }+ }+}diff --git a/app/src/main/java/app/tellyscope/MainActivity.kt b/app/src/main/java/app/tellyscope/MainActivity.ktindex 4e7f11a..1ed2191 100644--- a/app/src/main/java/app/tellyscope/MainActivity.kt+++ b/app/src/main/java/app/tellyscope/MainActivity.kt@@ -32,6 +32,7 @@ import androidx.lifecycle.viewmodel.compose.viewModelimport androidx.lifecycle.viewmodel.initializerimport androidx.lifecycle.viewmodel.viewModelFactoryimport app.tellyscope.data.AdbDeviceSource+import app.tellyscope.data.AndroidPhoneStorageimport app.tellyscope.data.FakeDeviceSourceimport app.tellyscope.ui.Copyimport app.tellyscope.ui.DeviceActions@@ -59,7 +60,10 @@ class MainActivity : ComponentActivity() {val vm: TellyscopeViewModel = viewModel(factory = viewModelFactory {initializer {- TellyscopeViewModel(scenario?.let(::FakeDeviceSource) ?: AdbDeviceSource(applicationContext))+ TellyscopeViewModel(+ scenario?.let(::FakeDeviceSource) ?: AdbDeviceSource(applicationContext),+ AndroidPhoneStorage(applicationContext),+ )}},)@@ -116,6 +120,11 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {val snackbar = remember { SnackbarHostState() }var adding by rememberSaveable { mutableStateOf(false) }+ // "*/*": file managers label .apks and .xapk bundles inconsistently, so a narrower type would grey them out.+ val pickApp = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { vm.pickedApp(it) }+ val pickFile = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> uri?.let(vm::push) }+ val saveFile = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream"), vm::saveTo)+LaunchedEffect(done) {val entry = done ?: return@LaunchedEffectvm.doneShown()@@ -165,6 +174,15 @@ fun TellyscopeApp(vm: TellyscopeViewModel) {forget = vm::forget,rename = vm::rename,restoreAll = vm::restoreAll,+ pickApp = { pickApp.launch(arrayOf("*/*")) },+ allowDowngrade = vm::allowDowngrade,+ install = vm::install,+ closeSideload = vm::closeSideload,+ openInstalled = vm::openInstalled,+ folder = vm::folder,+ pickFile = { folder -> vm.folder(folder); pickFile.launch(arrayOf("*/*")) },+ saveFile = { f -> vm.saving(f); saveFile.launch(f.name) },+ cancelTransfer = vm::cancelTransfer,),)}diff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex b2955ce..ceb7240 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -6,6 +6,13 @@ import android.content.Contextimport android.net.ConnectivityManagerimport android.net.NetworkCapabilitiesimport app.tellyscope.adb.ActionResult+import app.tellyscope.adb.ApkInfo+import app.tellyscope.adb.Files+import app.tellyscope.adb.InstallResult+import app.tellyscope.adb.Progress+import app.tellyscope.adb.Sideload+import app.tellyscope.adb.TvFile+import app.tellyscope.adb.TvFolderimport app.tellyscope.adb.Actionsimport app.tellyscope.adb.Connectorimport app.tellyscope.adb.DeviceLink@@ -28,6 +35,8 @@ import kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.flow.transformWhileimport kotlinx.coroutines.launch+import okio.Sink+import okio.Sourceimport java.io.Fileimport java.net.Inet4Addressimport java.util.concurrent.ConcurrentHashMap@@ -336,6 +345,24 @@ class AdbDeviceSource(context: Context) : DeviceSource {private suspend fun disabledPackages(deviceId: String) =Parsers.packages(session(deviceId).shell("pm list packages -d").output).map { it.name }.toSet()+ override suspend fun installed(deviceId: String, packageName: String) = Sideload(session(deviceId)).installed(packageName)++ override suspend fun install(+ deviceId: String,+ apks: List<File>,+ apk: ApkInfo,+ allowDowngrade: Boolean,+ onProgress: (Progress) -> Unit,+ ): InstallResult = Sideload(session(deviceId)).install(apks, apk, allowDowngrade, onProgress)++ override suspend fun files(deviceId: String, folder: TvFolder) = Files(session(deviceId)).list(folder)++ override suspend fun push(deviceId: String, folder: TvFolder, name: String, size: Long?, source: Source, onProgress: (Progress) -> Unit) =+ Files(session(deviceId)).push(source, size, name, folder, onProgress)++ override suspend fun pull(deviceId: String, folder: TvFolder, file: TvFile, sink: Sink, onProgress: (Progress) -> Unit) =+ Files(session(deviceId)).pull(folder, file, sink, onProgress)+private fun session(deviceId: String) =links[deviceId]?.session ?: throw IllegalStateException("$deviceId is offline")diff --git a/app/src/main/java/app/tellyscope/data/DeviceSource.kt b/app/src/main/java/app/tellyscope/data/DeviceSource.ktindex 03ee0ba..b97aef2 100644--- a/app/src/main/java/app/tellyscope/data/DeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceSource.kt@@ -2,7 +2,16 @@package app.tellyscope.data+import app.tellyscope.adb.ApkInfo+import app.tellyscope.adb.InstallResult+import app.tellyscope.adb.InstalledVersion+import app.tellyscope.adb.Progress+import app.tellyscope.adb.TvFile+import app.tellyscope.adb.TvFolderimport kotlinx.coroutines.flow.Flow+import okio.Sink+import okio.Source+import java.io.File/*** Everything the screens need from a TV. The UI only talks to this; an@@ -50,4 +59,24 @@ interface DeviceSource {/** Turns back on every app Tellyscope disabled, and nothing that was off before. */suspend fun restoreAll(deviceId: String): List<HistoryEntry>++ /** The version of [packageName] on the TV, or null when it isn't installed. */+ suspend fun installed(deviceId: String, packageName: String): InstalledVersion?++ /** Installs [apks] (base first). Refuses a downgrade unless [allowDowngrade]; refusals come back, never throw. */+ suspend fun install(+ deviceId: String,+ apks: List<File>,+ apk: ApkInfo,+ allowDowngrade: Boolean,+ onProgress: (Progress) -> Unit,+ ): InstallResult++ /** Files in one of the shared folders, newest first. */+ suspend fun files(deviceId: String, folder: TvFolder): List<TvFile>++ /** Copies a phone file to the TV without overwriting anything; returns the name it got. */+ 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)}diff --git a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.ktindex 5c37208..f51b477 100644--- a/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/FakeDeviceSource.kt@@ -2,12 +2,22 @@package app.tellyscope.data+import app.tellyscope.adb.ApkInfo+import app.tellyscope.adb.InstallResult+import app.tellyscope.adb.InstalledVersion+import app.tellyscope.adb.Progress+import app.tellyscope.adb.TvFile+import app.tellyscope.adb.TvFolder+import java.io.Fileimport kotlin.random.Randomimport kotlinx.coroutines.currentCoroutineContextimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.flowimport kotlinx.coroutines.isActive+import okio.Buffer+import okio.Sink+import okio.Source/*** Stand-in [DeviceSource] for building the screens before the ADB module exists.@@ -42,6 +52,7 @@ class FakeDeviceSource(private val apps = mutableMapOf<String, MutableList<AppInfo>>()private val book = HistoryBook()+ private val tvFiles = mutableMapOf<TvFolder, MutableList<TvFile>>()override fun scan(): Flow<ScanEvent> = flow {val subnet = "192.168.1.0/24"@@ -195,6 +206,64 @@ class FakeDeviceSource(}}+ override suspend fun installed(deviceId: String, packageName: String): InstalledVersion? =+ appsFor(deviceId).firstOrNull { it.packageName == packageName }?.let { InstalledVersion(1, it.version) }++ override suspend fun install(+ deviceId: String,+ apks: List<File>,+ apk: ApkInfo,+ allowDowngrade: Boolean,+ onProgress: (Progress) -> Unit,+ ): InstallResult {+ val total = apks.sumOf { it.length() }+ for (i in 0..20) {+ onProgress(Progress(total * i / 20, total))+ delay(100)+ }+ delay(1_200) // the TV unpacking it+ return InstallResult.Done+ }++ override suspend fun files(deviceId: String, folder: TvFolder): List<TvFile> = tvFiles.getOrPut(folder) {+ if (folder == TvFolder.DOWNLOAD) baseFiles.toMutableList() else mutableListOf()+ }.sortedByDescending { it.modifiedMillis }++ override suspend fun push(deviceId: String, folder: TvFolder, name: String, size: Long?, source: Source, onProgress: (Progress) -> Unit): String {+ var done = 0L+ val buf = Buffer()+ while (true) {+ val n = source.read(buf, 256 * 1024)+ if (n < 0) break+ buf.clear()+ done += n+ onProgress(Progress(done, size))+ delay(50)+ }+ files(deviceId, folder)+ tvFiles.getValue(folder) += TvFile(name, done, clock())+ return name+ }++ override suspend fun pull(deviceId: String, folder: TvFolder, file: TvFile, sink: Sink, onProgress: (Progress) -> Unit) {+ val chunk = ByteArray(64 * 1024)+ var done = 0L+ while (done < file.size) {+ val n = minOf(chunk.size.toLong(), file.size - done)+ sink.write(Buffer().write(chunk, 0, n.toInt()), n)+ done += n+ onProgress(Progress(done, file.size))+ delay(30)+ }+ sink.flush()+ }++ private val baseFiles get() = listOf(+ TvFile("holiday-2025.mp4", 812_000_000, clock() - 3 * 86_400_000L),+ TvFile("projectivy-backup.plbackup", 48_200, clock() - 26 * 3_600_000L),+ TvFile("subtitles.srt", 61_000, clock() - 40 * 60_000L),+ )+private companion object {val baseApps = listOf(AppInfo("com.spocky.projengmenu", "Projectivy Launcher", 0xFF3D5AFE, false, true, "this is your home screen", "4.52"),diff --git a/app/src/main/java/app/tellyscope/data/PhoneStorage.kt b/app/src/main/java/app/tellyscope/data/PhoneStorage.ktnew file mode 100644index 0000000..99e3668--- /dev/null+++ b/app/src/main/java/app/tellyscope/data/PhoneStorage.kt@@ -0,0 +1,116 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope.data++import android.content.Context+import android.net.Uri+import android.provider.DocumentsContract+import android.provider.OpenableColumns+import androidx.core.content.pm.PackageInfoCompat+import app.tellyscope.adb.ApkBundle+import app.tellyscope.adb.ApkInfo+import app.tellyscope.adb.Files+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import okio.Sink+import okio.Source+import okio.sink+import okio.source+import java.io.File+import java.io.IOException++/** An app the user picked on the phone, copied into the cache and read, ready to install. */+data class PickedApp(+ /** Base APK first, then any split parts. */+ val files: List<File>,+ val info: ApkInfo,+ /** The APK's own label; the package name when it has none. */+ val label: String,+) {+ val sizeBytes: Long get() = files.sumOf { it.length() }+}++/** The picked file wasn't an APK or a bundle of them. */+class NotAnApp : IOException("not an Android app")++class PhoneFile(val name: String, val size: Long?, val source: Source)++/** The phone's side of a copy, through the system file picker. Faked in screenshots. */+interface PhoneStorage {+ /** One .apk, several split .apk files, or one .apks/.xapk/.apkm bundle. Throws [NotAnApp]. */+ suspend fun readApp(uris: List<Uri>): PickedApp+ fun open(uri: Uri): PhoneFile+ fun create(uri: Uri): Sink+ /** Removes a half-written file after a cancelled save. */+ fun delete(uri: Uri)+ /** Drops the cached copy of the last picked app. */+ fun clearApp()+}++class AndroidPhoneStorage(context: Context) : PhoneStorage {+ private val ctx = context.applicationContext+ private val dir get() = File(ctx.cacheDir, "sideload")++ override suspend fun readApp(uris: List<Uri>): PickedApp = withContext(Dispatchers.IO) {+ clearApp()+ dir.mkdirs()+ val copies = uris.map { uri ->+ val f = File(dir, Files.safeName(displayName(uri) ?: "app.apk"))+ ctx.contentResolver.openInputStream(uri)?.use { i -> f.outputStream().use(i::copyTo) } ?: throw NotAnApp()+ f+ }+ val apks = when {+ copies.all(ApkBundle::isApk) -> ApkBundle.baseFirst(copies)+ copies.size == 1 -> try {+ ApkBundle.unpack(copies.single(), File(dir, "parts"))+ } catch (_: IOException) {+ throw NotAnApp()+ }+ else -> throw NotAnApp()+ }+ val base = apks.first()+ @Suppress("DEPRECATION") // the flags overload is API 33++ val pkg = ctx.packageManager.getPackageArchiveInfo(base.path, 0) ?: throw NotAnApp()+ val app = pkg.applicationInfo+ // An archive's label resolves only once its source path points at the file.+ val label = app?.let {+ it.sourceDir = base.path+ it.publicSourceDir = base.path+ it.loadLabel(ctx.packageManager).toString()+ }+ PickedApp(+ files = apks,+ info = ApkInfo(pkg.packageName, PackageInfoCompat.getLongVersionCode(pkg), pkg.versionName),+ label = label?.takeIf { it.isNotBlank() && it != pkg.packageName } ?: pkg.packageName,+ )+ }++ override fun open(uri: Uri): PhoneFile {+ var name: String? = null+ var size: Long? = null+ ctx.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->+ if (c.moveToFirst()) {+ name = c.getString(0)+ size = if (c.isNull(1)) null else c.getLong(1)+ }+ }+ val input = ctx.contentResolver.openInputStream(uri) ?: throw IOException("can't open the file")+ return PhoneFile(name ?: uri.lastPathSegment ?: "file", size, input.source())+ }++ override fun create(uri: Uri): Sink =+ ctx.contentResolver.openOutputStream(uri, "wt")?.sink() ?: throw IOException("can't write there")++ override fun delete(uri: Uri) {+ runCatching { DocumentsContract.deleteDocument(ctx.contentResolver, uri) }+ }++ override fun clearApp() {+ dir.deleteRecursively()+ }++ private fun displayName(uri: Uri): String? =+ ctx.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->+ if (c.moveToFirst()) c.getString(0) else null+ }+}diff --git a/app/src/main/java/app/tellyscope/ui/Copy.kt b/app/src/main/java/app/tellyscope/ui/Copy.ktindex 110d14f..15f80ed 100644--- a/app/src/main/java/app/tellyscope/ui/Copy.kt+++ b/app/src/main/java/app/tellyscope/ui/Copy.kt@@ -2,6 +2,9 @@package app.tellyscope.ui+import app.tellyscope.adb.InstallKind+import app.tellyscope.adb.InstallRefusal+import app.tellyscope.adb.TvFolderimport app.tellyscope.data.Actionimport app.tellyscope.data.DeviceStateimport app.tellyscope.data.Snapshot@@ -116,4 +119,83 @@ object Copy {const val FULL = 0.9private const val HOT_C = 80++ fun bytes(v: Long): String = when {+ v >= 1L shl 30 -> "%.1f GB".format(v / (1L shl 30).toDouble())+ v >= 1L shl 20 -> "%.1f MB".format(v / (1L shl 20).toDouble())+ v >= 1L shl 10 -> "${v shr 10} KB"+ else -> "$v bytes"+ }++ fun folder(f: TvFolder) = when (f) {+ TvFolder.DOWNLOAD -> "Download"+ TvFolder.MOVIES -> "Movies"+ }++ // Sideload++ fun installButton(kind: InstallKind) = when (kind) {+ InstallKind.NEW -> "Install"+ InstallKind.UPDATE -> "Update"+ InstallKind.REINSTALL -> "Reinstall"+ InstallKind.DOWNGRADE -> "Install older version"+ }++ fun installKind(kind: InstallKind, onTv: String?, picked: String?) = when (kind) {+ InstallKind.NEW -> "Not on this TV yet. This installs it."+ InstallKind.UPDATE -> "Updates the TV's copy" + versions(onTv, picked) + ". Its settings stay."+ InstallKind.REINSTALL -> "The TV already has this version" + (onTv?.let { " ($it)" } ?: "") + ". This installs it again over itself."+ InstallKind.DOWNGRADE -> "This is older than the one on the TV" ++ (if (onTv != null && picked != null) " ($picked here, $onTv on the TV)" else "") ++ ". Android normally refuses that, and the app's saved data may not work with the older version."+ }++ private fun versions(onTv: String?, picked: String?) =+ if (onTv != null && picked != null) " from $onTv to $picked" else ""++ const val ALLOW_DOWNGRADE = "Install the older version anyway"+ const val INSTALL_KEEP_OPEN = "Keep Tellyscope open until it's done."++ fun installed(kind: InstallKind, app: String) = when (kind) {+ InstallKind.UPDATE -> "Updated $app."+ InstallKind.REINSTALL -> "Reinstalled $app."+ InstallKind.NEW, InstallKind.DOWNGRADE -> "Installed $app."+ }++ fun installRefused(reason: InstallRefusal, app: String) = when (reason) {+ InstallRefusal.SIGNATURE ->+ "The $app on the TV comes from a different developer, so Android won't replace it. Tellyscope never uninstalls, so if you're sure, uninstall it on the TV first."+ InstallRefusal.DOWNGRADE -> "The TV has a newer $app and won't go back to an older one."+ InstallRefusal.NO_SPACE -> "The TV is out of space. Disable or uninstall something there, then try again."+ InstallRefusal.TV_SAID_NO ->+ "The TV blocked the install. Look in the TV's security settings for installing apps from unknown sources, or for app verification, then try again."+ InstallRefusal.TV_TOO_OLD -> "$app needs a newer version of Android than this TV has."+ InstallRefusal.WRONG_CPU ->+ "This $app is built for a different kind of processor. Look for a version made for this TV, often marked armeabi-v7a or arm64-v8a."+ InstallRefusal.APP_TOO_OLD -> "$app was made for a very old version of Android, and this TV won't install it."+ InstallRefusal.MISSING_FEATURE -> "$app needs something this TV doesn't have, like a touchscreen or a camera."+ InstallRefusal.MISSING_PARTS ->+ "$app comes in several parts and one is missing. Pick all of its .apk files together, or its .apks bundle."+ InstallRefusal.TEST_ONLY -> "This is a developer test build of $app, which the TV won't install."+ InstallRefusal.CONFLICT -> "Another app on the TV already uses something $app needs, so the TV refused it."+ InstallRefusal.BROKEN -> "This file isn't a working app. It may be damaged or only half downloaded; try getting it again."+ InstallRefusal.UNKNOWN -> "The TV didn't install $app."+ }++ const val NOT_AN_APP = "That file isn't an Android app. Pick an .apk, several split .apk files, or an .apks or .xapk bundle."+ const val SIDELOAD_LOST = "Lost the TV partway through. Check it's still on and connected, then try again."++ // Files++ fun sent(name: String, savedAs: String, f: TvFolder) =+ if (savedAs == name) "Sent $name to ${folder(f)}" else "Sent to ${folder(f)} as $savedAs, since $name was already there"++ fun saved(name: String) = "Saved $name to your phone"+ fun sendFailed(name: String) = "Couldn't send $name. Check the TV is still connected and has space."+ fun saveFailed(name: String) = "Couldn't save $name. Check the TV is still connected and the phone has space."++ const val CANCELLED_SEND = "Cancelled. Nothing was left on the TV."+ const val CANCELLED_SAVE = "Cancelled. Nothing was saved."+ const val CANT_READ = "Couldn't read that file on your phone."+ const val FILES_LOST = "Couldn't read this folder. Check the TV is still connected."}diff --git a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt b/app/src/main/java/app/tellyscope/ui/DeviceScreen.ktindex e0ea420..e35abad 100644--- a/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt+++ b/app/src/main/java/app/tellyscope/ui/DeviceScreen.kt@@ -78,6 +78,8 @@ import androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.asImageBitmapimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dp+import app.tellyscope.adb.TvFile+import app.tellyscope.adb.TvFolderimport app.tellyscope.data.Actionimport app.tellyscope.data.AppInfoimport app.tellyscope.data.AppNames@@ -104,6 +106,18 @@ data class DeviceActions(val forget: (String) -> Unit = {},val rename: (String, String?) -> Unit = { _, _ -> },val restoreAll: () -> Unit = {},+ /** Opens the system picker for an APK, split APKs or a bundle. */+ val pickApp: () -> Unit = {},+ val allowDowngrade: (Boolean) -> Unit = {},+ val install: () -> Unit = {},+ val closeSideload: () -> Unit = {},+ val openInstalled: () -> Unit = {},+ val folder: (TvFolder) -> Unit = {},+ /** Shows that folder, then opens the system picker for a file to send into it. */+ val pickFile: (TvFolder) -> Unit = {},+ /** Asks where to save [TvFile] on the phone, then copies it. */+ val saveFile: (TvFile) -> Unit = {},+ val cancelTransfer: () -> Unit = {},)@OptIn(ExperimentalMaterial3Api::class)@@ -194,6 +208,7 @@ fun DeviceScreen()}}+ if (!offline && q.isEmpty()) item { SendRow(actions) }snap?.let {// 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) }@@ -220,10 +235,15 @@ fun DeviceScreen(if (!offline || ui.network != null) section("net", "Network", ui.network?.sockets?.size ?: 0, forceOpen = q.isNotEmpty()) {ui.network?.let { NetworkBlock(it, q) }}+ if (!offline && q.isEmpty()) section("files", "Files on the TV", ui.files.list?.size ?: 0) {+ FilesBlock(ui.files, state.now, actions)+ }section("history", "History", ui.history.size) {HistoryList(ui.history, state.now, actions.undo, restoring = ui.busy == RESTORING, onRestoreAll = actions.restoreAll)}}+ ui.sideload?.let { SideloadDialog(it, actions) }+ ui.transfer?.let { TransferDialog(it, actions.cancelTransfer) }}}diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex 77e4a01..debb7b2 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -2,8 +2,16 @@package app.tellyscope.ui+import android.net.Uriimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScope+import app.tellyscope.adb.InstallKind+import app.tellyscope.adb.InstallResult+import app.tellyscope.adb.InstalledVersion+import app.tellyscope.adb.Progress+import app.tellyscope.adb.TvFile+import app.tellyscope.adb.TvFolder+import app.tellyscope.adb.installKindimport app.tellyscope.data.Actionimport app.tellyscope.data.AppInfoimport app.tellyscope.data.ConnectResult@@ -12,6 +20,9 @@ import app.tellyscope.data.DeviceSourceimport app.tellyscope.data.DeviceStateimport app.tellyscope.data.HistoryEntryimport app.tellyscope.data.NetworkInfo+import app.tellyscope.data.NotAnApp+import app.tellyscope.data.PhoneStorage+import app.tellyscope.data.PickedAppimport app.tellyscope.data.ScanEventimport app.tellyscope.data.ScanHitimport app.tellyscope.data.ScanProgress@@ -52,8 +63,39 @@ data class DeviceUi(/** Package whose action row is open, and the action awaiting confirmation. */val pending: Pair<String, Action>? = null,val busy: String? = null,+ /** The install dialog; null when it's closed. */+ val sideload: SideloadUi? = null,+ val files: FilesUi = FilesUi(),+ /** A file copy in progress; its dialog stays up until it finishes or Cancel is tapped. */+ val transfer: TransferUi? = null,)+data class SideloadUi(+ val step: Step = Step.Reading,+ /** Null while the picked file is still being read. */+ val app: PickedApp? = null,+ val installed: InstalledVersion? = null,+ /** Set only by the user's own tick on the downgrade warning. */+ val allowDowngrade: Boolean = false,+ val progress: Progress? = null,+ val error: String? = null,+ /** The TV's own words for a refusal, shown small under the explanation. */+ val detail: String? = null,+) {+ enum class Step { Reading, Ready, Installing, Installed, Failed }++ val kind: InstallKind? get() = app?.let { installKind(it.info, installed) }+}++data class FilesUi(+ val folder: TvFolder = TvFolder.DOWNLOAD,+ /** Null while loading. */+ val list: List<TvFile>? = null,+ val error: String? = null,+)++data class TransferUi(val name: String, val toTv: Boolean, val folder: TvFolder, val progress: Progress? = null)+data class UiState(val scan: ScanUi = ScanUi(),val devices: List<Device> = emptyList(),@@ -71,6 +113,7 @@ const val RESTORING = "restore"class TellyscopeViewModel(private val source: DeviceSource,+ private val storage: PhoneStorage? = null,private val allowTimeoutMs: Long = 60_000,private val clock: () -> Long = System::currentTimeMillis,) : ViewModel() {@@ -82,7 +125,7 @@ class TellyscopeViewModel(private val _done = MutableStateFlow<HistoryEntry?>(null)val done: StateFlow<HistoryEntry?> = _done.asStateFlow()- /** One-shot snackbar lines: the TV refused, went away mid-action, or a restore finished. */+ /** One-shot snackbar lines: the TV refused, went away mid-action, or a restore or copy finished. */private val _notice = MutableStateFlow<String?>(null)val notice: StateFlow<String?> = _notice.asStateFlow()@@ -90,6 +133,8 @@ class TellyscopeViewModel(private val lastSnapshot = mutableMapOf<String, Snapshot>()private var scanJob: Job? = null+ private var sideloadJob: Job? = null+ private var transferJob: Job? = nullprivate var liveJob: Job? = nullprivate var mediumJob: Job? = null@@ -217,6 +262,7 @@ class TellyscopeViewModel(// A TV that drops mid-read throws; the live flow ends and the offline card takes over.try {_state.update { it.copy(device = it.device.copy(apps = source.apps(id!!))) }+ loadFiles()while (true) {val net = source.network(id!!)_state.update { it.copy(device = it.device.copy(network = net)) }@@ -306,6 +352,174 @@ class TellyscopeViewModel(}}+ /** The user picked one or more files to install. Reads them, then asks the TV what it has. */+ fun pickedApp(uris: List<Uri>) {+ val id = _state.value.selectedId ?: return+ val storage = storage ?: return+ if (uris.isEmpty()) return+ setSideload(SideloadUi())+ sideloadJob = viewModelScope.launch {+ val ui = try {+ val app = storage.readApp(uris)+ SideloadUi(SideloadUi.Step.Ready, app, source.installed(id, app.info.packageName))+ } catch (e: CancellationException) {+ throw e+ } catch (_: NotAnApp) {+ SideloadUi(SideloadUi.Step.Failed, error = Copy.NOT_AN_APP)+ } catch (_: Exception) {+ SideloadUi(SideloadUi.Step.Failed, error = Copy.SIDELOAD_LOST)+ }+ setSideload(ui)+ }+ }++ fun allowDowngrade(allow: Boolean) = updateSideload { it.copy(allowDowngrade = allow) }++ fun install() {+ val id = _state.value.selectedId ?: return+ val ready = _state.value.device.sideload?.takeIf { it.step == SideloadUi.Step.Ready } ?: return+ val app = ready.app ?: return+ if (ready.kind == InstallKind.DOWNGRADE && !ready.allowDowngrade) return+ setSideload(ready.copy(step = SideloadUi.Step.Installing))+ sideloadJob = viewModelScope.launch {+ val r = try {+ source.install(id, app.files, app.info, ready.allowDowngrade) { p -> updateSideload { it.copy(progress = p) } }+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ return@launch setSideload(ready.copy(step = SideloadUi.Step.Failed, error = Copy.SIDELOAD_LOST))+ }+ when (r) {+ InstallResult.Done -> {+ setSideload(ready.copy(step = SideloadUi.Step.Installed))+ runCatching { source.apps(id) }.onSuccess { apps -> _state.update { it.copy(device = it.device.copy(apps = apps)) } }+ }+ is InstallResult.Refused -> setSideload(+ ready.copy(step = SideloadUi.Step.Failed, error = Copy.installRefused(r.reason, app.label), detail = r.detail),+ )+ }+ }+ }++ /** Cancel or Done on the install dialog. Not while installing: the dialog has no button then. */+ fun closeSideload() {+ if (_state.value.device.sideload?.step == SideloadUi.Step.Installing) return+ sideloadJob?.cancel()+ storage?.clearApp()+ setSideload(null)+ }++ /** "Open on TV" after a successful install. */+ fun openInstalled() {+ val pkg = _state.value.device.sideload?.app?.info?.packageName ?: return+ closeSideload()+ run(pkg, Action.Open)+ }++ fun folder(folder: TvFolder) {+ _state.update { it.copy(device = it.device.copy(files = FilesUi(folder))) }+ viewModelScope.launch { loadFiles() }+ }++ private suspend fun loadFiles() {+ val id = _state.value.selectedId ?: return+ val folder = _state.value.device.files.folder+ val ui = try {+ FilesUi(folder, source.files(id, folder))+ } catch (e: CancellationException) {+ throw e+ } catch (_: Exception) {+ FilesUi(folder, emptyList(), Copy.FILES_LOST)+ }+ _state.update { s -> if (s.device.files.folder == folder) s.copy(device = s.device.copy(files = ui)) else s }+ }++ /** Copies a phone file into the folder on show. Never overwrites: a taken name gets " (1)". */+ fun push(uri: Uri) {+ val id = _state.value.selectedId ?: return+ val storage = storage ?: return+ val folder = _state.value.device.files.folder+ transferJob = viewModelScope.launch {+ val file = try {+ storage.open(uri)+ } catch (_: Exception) {+ _notice.value = Copy.CANT_READ+ return@launch+ }+ setTransfer(TransferUi(file.name, toTv = true, folder = folder))+ try {+ val saved = file.source.use { src ->+ source.push(id, folder, file.name, file.size, src) { p -> updateTransfer { it.copy(progress = p) } }+ }+ // Close the dialog before the reload: a Cancel tapped now would report a sent file as cancelled.+ setTransfer(null)+ _notice.value = Copy.sent(file.name, saved, folder)+ loadFiles()+ } catch (e: CancellationException) {+ _notice.value = Copy.CANCELLED_SEND+ throw e+ } catch (_: Exception) {+ _notice.value = Copy.sendFailed(file.name)+ } finally {+ setTransfer(null)+ }+ }+ }++ /** The file whose "save as" picker is open. Kept here so it survives the activity being recreated behind the picker. */+ private var saving: TvFile? = null++ fun saving(file: TvFile) {+ saving = file+ }++ /** The picker's answer: copies the file there, or does nothing if the user backed out. */+ fun saveTo(uri: Uri?) {+ val file = saving ?: return+ saving = null+ if (uri != null) pull(file, uri)+ }++ /** A cancelled or failed copy removes the partial file. */+ private fun pull(file: TvFile, uri: Uri) {+ val id = _state.value.selectedId ?: return+ val storage = storage ?: return+ val folder = _state.value.device.files.folder+ setTransfer(TransferUi(file.name, toTv = false, folder = folder, progress = Progress(0, file.size)))+ transferJob = viewModelScope.launch {+ try {+ storage.create(uri).use { sink ->+ source.pull(id, folder, file, sink) { p -> updateTransfer { it.copy(progress = p) } }+ }+ _notice.value = Copy.saved(file.name)+ } catch (e: CancellationException) {+ storage.delete(uri)+ _notice.value = Copy.CANCELLED_SAVE+ throw e+ } catch (_: Exception) {+ storage.delete(uri)+ _notice.value = Copy.saveFailed(file.name)+ } finally {+ setTransfer(null)+ }+ }+ }++ /** Only the dialog's Cancel button calls this. */+ fun cancelTransfer() {+ transferJob?.cancel()+ }++ private fun setSideload(ui: SideloadUi?) = _state.update { it.copy(device = it.device.copy(sideload = ui)) }++ private fun updateSideload(f: (SideloadUi) -> SideloadUi) =+ _state.update { s -> s.device.sideload?.let { s.copy(device = s.device.copy(sideload = f(it))) } ?: s }++ private fun setTransfer(ui: TransferUi?) = _state.update { it.copy(device = it.device.copy(transfer = ui)) }++ private fun updateTransfer(f: (TransferUi) -> TransferUi) =+ _state.update { s -> s.device.transfer?.let { s.copy(device = s.device.copy(transfer = f(it))) } ?: s }+fun doneShown() {_done.value = null}diff --git a/app/src/main/java/app/tellyscope/ui/Transfers.kt b/app/src/main/java/app/tellyscope/ui/Transfers.ktnew file mode 100644index 0000000..bf6b71e--- /dev/null+++ b/app/src/main/java/app/tellyscope/ui/Transfers.kt@@ -0,0 +1,260 @@+// 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.Box+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.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Add+import androidx.compose.material.icons.filled.CheckCircle+import androidx.compose.material.icons.filled.Send+import androidx.compose.material.icons.filled.Warning+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.Button+import androidx.compose.material3.ButtonDefaults+import androidx.compose.material3.Checkbox+import androidx.compose.material3.DropdownMenu+import androidx.compose.material3.DropdownMenuItem+import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi+import androidx.compose.material3.FilledTonalButton+import androidx.compose.material3.Icon+import androidx.compose.material3.LinearWavyProgressIndicator+import androidx.compose.material3.LoadingIndicator+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.SegmentedButton+import androidx.compose.material3.SegmentedButtonDefaults+import androidx.compose.material3.SingleChoiceSegmentedButtonRow+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.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.window.DialogProperties+import app.tellyscope.adb.InstallKind+import app.tellyscope.adb.TvFile+import app.tellyscope.adb.TvFolder+import app.tellyscope.ui.theme.SmallNumber++/**+ * Both dialogs here close only through their own buttons: a tap outside or Back would otherwise+ * drop an install halfway through its questions, or look like it cancelled a copy.+ */+private val Sticky = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)++/** The two ways onto the TV, under the stats. */+@Composable+fun SendRow(actions: DeviceActions) {+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ FilledTonalButton(onClick = actions.pickApp, Modifier.weight(1f)) {+ Icon(Icons.Default.Add, null, Modifier.size(ButtonDefaults.IconSize))+ Spacer(Modifier.width(ButtonDefaults.IconSpacing))+ Text("Install an app")+ }+ // Where the file lands is the user's choice, every time, not whatever folder was last shown.+ var choosing by remember { mutableStateOf(false) }+ Box(Modifier.weight(1f)) {+ FilledTonalButton(onClick = { choosing = true }, Modifier.fillMaxWidth()) {+ @Suppress("DEPRECATION") // the AutoMirrored set isn't in icons-core+ Icon(Icons.Default.Send, null, Modifier.size(ButtonDefaults.IconSize))+ Spacer(Modifier.width(ButtonDefaults.IconSpacing))+ Text("Send a file")+ }+ DropdownMenu(choosing, onDismissRequest = { choosing = false }) {+ TvFolder.entries.forEach { f ->+ DropdownMenuItem(+ text = { Text("To ${Copy.folder(f)}") },+ onClick = { choosing = false; actions.pickFile(f) },+ )+ }+ }+ }+ }+}++/** Body of the Files section: the folder switch, then the folder's files, each one tap from the phone. */+@Composable+fun FilesBlock(files: FilesUi, now: Long, actions: DeviceActions) {+ SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) {+ TvFolder.entries.forEachIndexed { i, f ->+ SegmentedButton(+ selected = files.folder == f,+ onClick = { actions.folder(f) },+ shape = SegmentedButtonDefaults.itemShape(i, TvFolder.entries.size),+ ) { Text(Copy.folder(f)) }+ }+ }+ Spacer(Modifier.size(4.dp))+ val list = files.list+ when {+ list == null -> Row(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.Center) {+ @OptIn(ExperimentalMaterial3ExpressiveApi::class)+ LoadingIndicator(Modifier.size(32.dp))+ }+ files.error != null -> Muted(files.error)+ list.isEmpty() -> Muted("Nothing in ${Copy.folder(files.folder)} yet. Files you send land here.")+ else -> list.forEach { f -> FileRow(f, now) { actions.saveFile(f) } }+ }+ Muted("Tap a file to save a copy on your phone.")+}++@Composable+private fun FileRow(f: TvFile, now: Long, onSave: () -> Unit) {+ Row(+ Modifier.fillMaxWidth().clickable(onClick = onSave).padding(vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(Modifier.weight(1f)) {+ Text(f.name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)+ Text(+ "${Copy.bytes(f.size)} · ${Copy.ago(f.modifiedMillis, now)}",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ TextButton(onClick = onSave) { Text("Save") }+ }+}++@Composable+private fun Muted(text: String) {+ Text(text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)+}++@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+fun SideloadDialog(s: SideloadUi, actions: DeviceActions) {+ val app = s.app+ val kind = s.kind+ AlertDialog(+ onDismissRequest = {},+ properties = Sticky,+ icon = when (s.step) {+ SideloadUi.Step.Installed -> ({ Icon(Icons.Default.CheckCircle, null) })+ SideloadUi.Step.Failed -> ({ Icon(Icons.Default.Warning, null) })+ else -> null+ },+ title = {+ Text(+ when (s.step) {+ SideloadUi.Step.Reading -> "Reading the app"+ SideloadUi.Step.Failed -> app?.let { "Couldn't install ${it.label}" } ?: "Can't install that"+ SideloadUi.Step.Installed -> Copy.installed(kind ?: InstallKind.NEW, app?.label.orEmpty())+ else -> app?.label.orEmpty()+ },+ )+ },+ text = {+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {+ if (s.step == SideloadUi.Step.Reading) {+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) { LoadingIndicator() }+ }+ if (app != null && s.step != SideloadUi.Step.Failed) {+ Column {+ Text(app.info.packageName, style = SmallNumber, color = MaterialTheme.colorScheme.onSurfaceVariant)+ Text(+ listOfNotNull(+ "Version ${app.info.versionName ?: app.info.versionCode}",+ Copy.bytes(app.sizeBytes),+ if (app.files.size > 1) "${app.files.size} parts" else null,+ ).joinToString(" · "),+ style = SmallNumber,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ when (s.step) {+ SideloadUi.Step.Ready -> if (kind != null) {+ Text(Copy.installKind(kind, s.installed?.versionName, app?.info?.versionName), style = MaterialTheme.typography.bodyMedium)+ if (kind == InstallKind.DOWNGRADE) {+ Row(+ Modifier.fillMaxWidth().clickable { actions.allowDowngrade(!s.allowDowngrade) },+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Checkbox(s.allowDowngrade, onCheckedChange = null)+ Spacer(Modifier.width(12.dp))+ Text(Copy.ALLOW_DOWNGRADE, style = MaterialTheme.typography.bodyMedium)+ }+ }+ }+ SideloadUi.Step.Installing -> {+ val f = s.progress?.fraction+ // Past the last byte the TV is still unpacking: say so rather than sit at 100%.+ val sending = f != null && f < 1f+ if (sending) LinearWavyProgressIndicator(progress = { f }, Modifier.fillMaxWidth())+ else LinearWavyProgressIndicator(Modifier.fillMaxWidth())+ Text(+ if (sending) "Sending to the TV · ${(f * 100).toInt()}%" else "Installing on the TV…",+ style = MaterialTheme.typography.bodyMedium,+ )+ Muted(Copy.INSTALL_KEEP_OPEN)+ }+ SideloadUi.Step.Failed -> {+ Text(s.error.orEmpty(), style = MaterialTheme.typography.bodyMedium)+ s.detail?.takeIf { it.isNotBlank() }?.let {+ Text("The TV said: $it", style = SmallNumber, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 4, overflow = TextOverflow.Ellipsis)+ }+ }+ else -> Unit+ }+ }+ },+ confirmButton = {+ when (s.step) {+ SideloadUi.Step.Ready -> if (kind != null) Button(+ onClick = actions.install,+ enabled = kind != InstallKind.DOWNGRADE || s.allowDowngrade,+ ) { Text(Copy.installButton(kind)) }+ SideloadUi.Step.Installed -> Button(onClick = actions.openInstalled) { Text("Open on TV") }+ SideloadUi.Step.Failed -> Button(onClick = actions.closeSideload) { Text("OK") }+ else -> Unit+ }+ },+ dismissButton = {+ when (s.step) {+ SideloadUi.Step.Reading, SideloadUi.Step.Ready -> TextButton(onClick = actions.closeSideload) { Text("Cancel") }+ SideloadUi.Step.Installed -> TextButton(onClick = actions.closeSideload) { Text("Done") }+ else -> Unit+ }+ },+ )+}++/** A copy in either direction. Cancel is the only way out before it's done. */+@OptIn(ExperimentalMaterial3ExpressiveApi::class)+@Composable+fun TransferDialog(t: TransferUi, onCancel: () -> Unit) {+ AlertDialog(+ onDismissRequest = {},+ properties = Sticky,+ title = { Text(if (t.toTv) "Sending to ${Copy.folder(t.folder)}" else "Saving to your phone") },+ text = {+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Text(t.name, style = MaterialTheme.typography.bodyLarge, maxLines = 2, overflow = TextOverflow.MiddleEllipsis)+ val f = t.progress?.fraction+ if (f != null) LinearWavyProgressIndicator(progress = { f }, Modifier.fillMaxWidth())+ else LinearWavyProgressIndicator(Modifier.fillMaxWidth())+ Text(+ t.progress?.let { p -> p.total?.let { "${Copy.bytes(p.done)} of ${Copy.bytes(it)}" } ?: Copy.bytes(p.done) } ?: "Starting…",+ style = SmallNumber,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ },+ confirmButton = {},+ dismissButton = { TextButton(onClick = onCancel) { Text("Cancel") } },+ )+}diff --git a/app/src/test/java/app/tellyscope/ScreenshotTest.kt b/app/src/test/java/app/tellyscope/ScreenshotTest.ktindex 6efd382..fe4c6ee 100644--- a/app/src/test/java/app/tellyscope/ScreenshotTest.kt+++ b/app/src/test/java/app/tellyscope/ScreenshotTest.kt@@ -5,11 +5,21 @@ package app.tellyscopeimport android.graphics.Bitmapimport android.graphics.Canvasimport android.graphics.Paint+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Surfaceimport androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dpimport androidx.compose.ui.test.junit4.v2.createComposeRuleimport androidx.compose.ui.test.onNodeWithTextimport androidx.compose.ui.test.onRootimport androidx.compose.ui.test.performClick+import app.tellyscope.adb.ApkInfo+import app.tellyscope.adb.InstallRefusal+import app.tellyscope.adb.InstalledVersion+import app.tellyscope.adb.Progress+import app.tellyscope.adb.TvFolderimport app.tellyscope.data.Actionimport app.tellyscope.data.AppInfoimport app.tellyscope.data.AppNames@@ -17,24 +27,33 @@ import app.tellyscope.data.Deviceimport app.tellyscope.data.DeviceStateimport app.tellyscope.data.FakeDeviceSourceimport app.tellyscope.data.HistoryEntry+import app.tellyscope.data.PickedAppimport app.tellyscope.data.ScanHitimport app.tellyscope.data.ScanKindimport app.tellyscope.data.ScanProgressimport app.tellyscope.ui.DeviceActionsimport app.tellyscope.ui.DeviceScreen+import app.tellyscope.ui.Copyimport app.tellyscope.ui.DeviceUiimport app.tellyscope.ui.ForgetDialog+import app.tellyscope.ui.FilesBlock+import app.tellyscope.ui.FilesUiimport app.tellyscope.ui.RestoreDialogimport app.tellyscope.ui.PermissionScreenimport app.tellyscope.ui.RowStateimport app.tellyscope.ui.ScanScreenimport app.tellyscope.ui.ScanUi+import app.tellyscope.ui.SideloadUi+import app.tellyscope.ui.TransferUiimport app.tellyscope.ui.UiStateimport app.tellyscope.ui.theme.TellyscopeThemeimport com.github.takahirom.roborazzi.ExperimentalRoborazziApiimport com.github.takahirom.roborazzi.captureRoboImageimport com.github.takahirom.roborazzi.captureScreenRoboImageimport java.io.ByteArrayOutputStream+import java.io.File+import java.io.RandomAccessFile+import java.nio.file.Filesimport kotlin.random.Randomimport kotlinx.coroutines.runBlockingimport org.junit.Rule@@ -209,6 +228,53 @@ class ScreenshotTest {shot("10_apps_fallback_names") { DeviceScreen(appsState(apps), DeviceActions()) }}+ /** The Files section's body on its own: the section is collapsed on the full page. */+ @Test fun device_files() = shot("09_device_files") {+ val files = runBlocking { fake.files(xgimi.ip, TvFolder.DOWNLOAD) }+ Surface { Column(Modifier.padding(16.dp)) { FilesBlock(FilesUi(TvFolder.DOWNLOAD, files), now, DeviceActions()) } }+ }++ private val dir = Files.createTempDirectory("shots").toFile()+ private fun apk(name: String, bytes: Long) = File(dir, name).also { RandomAccessFile(it, "rw").use { f -> f.setLength(bytes) } }+ private val kodi = PickedApp(listOf(apk("kodi.apk", 74_000_000)), ApkInfo("org.xbmc.kodi", 2101, "21.1"), "Kodi")+ private val split = PickedApp(+ listOf(apk("base.apk", 31_000_000), apk("split_config.armeabi_v7a.apk", 9_400_000), apk("split_config.xxhdpi.apk", 1_100_000)),+ ApkInfo("com.example.player", 410, "4.1.0"),+ "Example Player",+ )++ private fun sideload(name: String, s: SideloadUi, dark: Boolean = false) =+ shot(name, dark, screen = true) { DeviceScreen(deviceState { copy(sideload = s) }, DeviceActions()) }++ @Test fun sideload_new() = sideload("10_sideload_new", SideloadUi(SideloadUi.Step.Ready, split, null))++ @Test fun sideload_update() =+ sideload("10_sideload_update", SideloadUi(SideloadUi.Step.Ready, kodi, InstalledVersion(2050, "20.5")), dark = true)++ @Test fun sideload_downgrade() =+ sideload("11_sideload_downgrade", SideloadUi(SideloadUi.Step.Ready, kodi, InstalledVersion(2200, "22.0")))++ @Test fun sideload_installing() = sideload(+ "12_sideload_installing",+ SideloadUi(SideloadUi.Step.Installing, kodi, null, progress = Progress(30_000_000, 74_000_000)),+ )++ @Test fun sideload_refused() = sideload(+ "13_sideload_refused",+ SideloadUi(+ SideloadUi.Step.Failed, kodi, InstalledVersion(2050, "20.5"),+ error = Copy.installRefused(InstallRefusal.SIGNATURE, "Kodi"),+ detail = "Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE: Package org.xbmc.kodi signatures do not match previously installed version; ignoring!]",+ ),+ )++ @Test fun sideload_installed() = sideload("14_sideload_installed", SideloadUi(SideloadUi.Step.Installed, kodi, null))++ @Test fun transfer() = shot("15_transfer", screen = true) {+ val t = TransferUi("holiday-2025.mp4", toTv = false, folder = TvFolder.DOWNLOAD, progress = Progress(301_000_000, 812_000_000))+ DeviceScreen(deviceState { copy(transfer = t) }, 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, {}, {}) }