RemoteDownloader, player layout, remote layout, strings

This commit is contained in:
lotherk committed 2026-11-17 22:14:42 +00:00
1 parent 01359f1348
commit eeff29f102
7 files changed
+236 -13

No files matched your search

@@ -7,10 +7,19 @@ package dev.lotherk.kidstube.data
object Catalog {
fun merge(local: List<MediaItem>, remote: List<MediaItem>): List<MediaItem> {
val out = ArrayList<MediaItem>(local.size + remote.size)
out.addAll(local)
out.addAll(remote)
return out.sortedWith(
val byKey = LinkedHashMap<String, MediaItem>()
for (m in local) byKey[m.key] = m
for (m in remote) {
if (byKey.containsKey(m.key)) {
val existing = byKey[m.key]
if (existing != null && existing.key.startsWith("jellyfin|") && !m.key.startsWith("jellyfin|")) {
byKey[m.key] = m
}
continue
}
byKey[m.key] = m
}
return byKey.values.sortedWith(
compareBy<MediaItem> { it.folder.lowercase() }.then(Series.naturalOrder)
)
}
@@ -0,0 +1,96 @@
package dev.lotherk.kidstube.remote
import android.content.Context
import android.content.Intent
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.util.Log
import dev.lotherk.kidstube.data.MediaItem
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL
object RemoteDownloader {
fun download(context: Context, item: MediaItem): Boolean {
if (!item.key.startsWith("jellyfin|")) return false
val parts = item.key.split("|")
if (parts.size < 3) return false
val server = parts[1]
val itemId = parts[2]
val token = getToken(context, server) ?: return false
val stream = "${server.trimEnd('/')}/Videos/$itemId/stream?static=true&api_key=${Uri.encode(token)}"
val folder = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES),
"KidsTube/" + item.folder.replace("\\", "/")
)
folder.mkdirs()
val base = sanitize(item.title.ifBlank { itemId })
var outFile = File(folder, base + ".mp4")
var idx = 1
while (outFile.exists()) {
outFile = File(folder, base + " ($idx).mp4")
idx++
if (idx > 50) break
}
return try {
val url = URL(stream)
val conn = url.openConnection() as HttpURLConnection
conn.connectTimeout = 5000
conn.readTimeout = 60000
conn.instanceFollowRedirects = true
conn.inputStream.use { input ->
FileOutputStream(outFile).use { output ->
val buf = ByteArray(8192)
var read: Int
while (input.read(buf).also { read = it } != -1) {
output.write(buf, 0, read)
}
}
}
MediaScannerConnection.scanFile(
context,
arrayOf(outFile.absolutePath),
arrayOf("video/mp4")
) { _, _ -> }
try {
context.sendBroadcast(
Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE).setData(
Uri.fromFile(outFile)
)
)
} catch (_: Throwable) {
}
Log.d("kidstube", "downloaded " + outFile.absolutePath)
true
} catch (t: Throwable) {
Log.w("kidstube", "download failed", t)
try {
outFile.delete()
} catch (_: Throwable) {
}
false
}
}
private fun getToken(context: Context, server: String): String? {
val list = RemoteStore.list(context)
for (r in list) {
if (r.server == server) {
val pw = SecretBox.open(context, r.password)
if (pw != null) {
val res = Jellyfin.authenticate(r.server, r.username, pw, RemoteStore.deviceId(context))
return res.token
}
}
}
return null
}
private fun sanitize(name: String): String {
return name.replace("[\\\\/:*?\"<>|]".toRegex(), "_").take(120)
}
}
@@ -39,6 +39,7 @@ class PlayerActivity : AppCompatActivity() {
private var chromeVisible = true
private val executor = Executors.newSingleThreadExecutor()
private val downloadExecutor = Executors.newSingleThreadExecutor()
private lateinit var suggestions: SuggestionAdapter
private var pool: List<MediaItem> = emptyList()
private var library: List<MediaItem> = emptyList()
@@ -48,6 +49,7 @@ class PlayerActivity : AppCompatActivity() {
private var resumedAt = 0L
private var watchedMs = 0L
private var prepared = false
private var downloading = false
private val hideChrome = Runnable { setChrome(false) }
private val ticker = object : Runnable {
@@ -81,8 +83,10 @@ class PlayerActivity : AppCompatActivity() {
binding.btnBack.setOnClickListener { finish() }
binding.btnLike.setOnClickListener { toggleLike() }
binding.btnPlay.setOnClickListener { togglePlay() }
binding.btnDownload.setOnClickListener { startDownload() }
binding.tapCatcher.setOnClickListener { setChrome(!chromeVisible) }
binding.chrome.setOnClickListener { setChrome(!chromeVisible) }
updateDownloadButton(item ?: MediaItem(uri = rawUri, title = intent.getStringExtra(EXTRA_TITLE).orEmpty(), folder = intent.getStringExtra(EXTRA_FOLDER).orEmpty(), key = intent.getStringExtra(EXTRA_KEY) ?: rawUri))
binding.seek.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(bar: SeekBar?, progress: Int, fromUser: Boolean) {
@@ -145,6 +149,7 @@ class PlayerActivity : AppCompatActivity() {
item = next
binding.title.text = next.title
updateLikeIcon(stats.isLiked(next.key))
updateDownloadButton(next)
binding.spinner.visibility = View.VISIBLE
setChrome(true)
binding.video.setVideoURI(Uri.parse(next.uri))
@@ -188,6 +193,50 @@ class PlayerActivity : AppCompatActivity() {
)
}
private fun isRemote(item: MediaItem): Boolean = item.key.startsWith("jellyfin|")
private fun updateDownloadButton(m: MediaItem) {
if (!isRemote(m)) {
binding.btnDownload.visibility = View.GONE
return
}
if (downloading) {
binding.btnDownload.isEnabled = false
binding.btnDownload.visibility = View.VISIBLE
return
}
if (hasLocalFor(m)) {
binding.btnDownload.visibility = View.GONE
return
}
binding.btnDownload.isEnabled = true
binding.btnDownload.visibility = View.VISIBLE
}
private fun hasLocalFor(remote: MediaItem): Boolean {
val local = Catalog.merge(Library.scan(this), emptyList())
return local.any { it.key == remote.key && !it.key.startsWith("jellyfin|") }
}
private fun startDownload() {
val m = item ?: return
if (!isRemote(m) || downloading || hasLocalFor(m)) return
downloading = true
updateDownloadButton(m)
downloadExecutor.execute {
val ok = dev.lotherk.kidstube.remote.RemoteDownloader.download(this@PlayerActivity, m)
runOnUiThread {
downloading = false
if (ok) {
Toast.makeText(this@PlayerActivity, R.string.download_done, Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this@PlayerActivity, R.string.download_failed, Toast.LENGTH_SHORT).show()
}
updateDownloadButton(m)
}
}
}
private fun loadSuggestions(current: MediaItem) {
executor.execute {
// Remote suggestions come from the verified snapshot, never from a
@@ -220,6 +269,8 @@ class PlayerActivity : AppCompatActivity() {
if (prepared && binding.video.isPlaying) resumedAt = SystemClock.elapsedRealtime()
if (segmentStart == 0L) segmentStart = System.currentTimeMillis()
updatePlayIcon()
val cur = item
if (cur != null) updateDownloadButton(cur)
// Coming back to a paused picture must show the button that restarts it.
if (prepared && !binding.video.isPlaying) setChrome(true)
}
@@ -14,12 +14,15 @@ import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import dev.lotherk.kidstube.R
import dev.lotherk.kidstube.data.Catalog
import dev.lotherk.kidstube.data.Library
import dev.lotherk.kidstube.databinding.ActivityRemoteBinding
import dev.lotherk.kidstube.remote.Jellyfin
import dev.lotherk.kidstube.remote.JellyfinException
import dev.lotherk.kidstube.remote.JfAuth
import dev.lotherk.kidstube.remote.JfView
import dev.lotherk.kidstube.remote.RemoteCatalog
import dev.lotherk.kidstube.remote.RemoteDownloader
import dev.lotherk.kidstube.remote.RemoteLibrary
import dev.lotherk.kidstube.remote.RemoteStore
import dev.lotherk.kidstube.remote.SecretBox
@@ -45,6 +48,7 @@ class RemoteLibrariesActivity : AppCompatActivity() {
setContentView(binding.root)
binding.btnBack.setOnClickListener { finish() }
binding.btnAdd.setOnClickListener { addJellyfin() }
binding.btnDownloadAll.setOnClickListener { downloadAllMissing() }
reloadList()
}
@@ -256,9 +260,36 @@ class RemoteLibrariesActivity : AppCompatActivity() {
.show()
}
private fun downloadAllMissing() {
val remotes = RemoteStore.list(this)
if (remotes.isEmpty()) {
toast(R.string.remote_empty)
return
}
binding.btnDownloadAll.isEnabled = false
executor.execute {
val local = Catalog.merge(Library.scan(this@RemoteLibrariesActivity), emptyList())
val localKeys = local.filter { !it.key.startsWith("jellyfin|") }.map { it.key }.toHashSet()
val all = RemoteCatalog.items()
val missing = all.filter { it.key.startsWith("jellyfin|") && !localKeys.contains(it.key) }
var done = 0
for (m in missing) {
if (RemoteDownloader.download(this@RemoteLibrariesActivity, m)) done++
}
runOnUiThread {
binding.btnDownloadAll.isEnabled = true
toast(getString(R.string.remote_download_done, done, missing.size))
}
}
}
private fun toast(res: Int) {
Toast.makeText(this, res, Toast.LENGTH_SHORT).show()
}
private fun toast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
private fun dp(value: Int): Int = (value * resources.displayMetrics.density).roundToInt()
}
+27 -9
View File
@@ -44,17 +44,35 @@
android:src="@drawable/ic_back"
app:tint="@android:color/white" />
<ImageButton
android:id="@+id/btn_like"
android:layout_width="44dp"
android:layout_height="44dp"
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|end"
android:layout_margin="12dp"
android:background="@drawable/bg_scrim_circle"
android:contentDescription="@string/stats_open"
android:padding="10dp"
android:src="@drawable/ic_heart"
app:tint="@android:color/white" />
android:orientation="horizontal">
<ImageButton
android:id="@+id/btn_download"
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_marginEnd="8dp"
android:background="@drawable/bg_scrim_circle"
android:contentDescription="@string/download"
android:padding="10dp"
android:src="@drawable/ic_search"
android:visibility="gone"
app:tint="@android:color/white" />
<ImageButton
android:id="@+id/btn_like"
android:layout_width="44dp"
android:layout_height="44dp"
android:background="@drawable/bg_scrim_circle"
android:contentDescription="@string/stats_open"
android:padding="10dp"
android:src="@drawable/ic_heart"
app:tint="@android:color/white" />
</LinearLayout>
<!-- Play/pause sits in the middle of the picture, where a child looks
for it. It hides with the rest of the chrome. -->
@@ -52,6 +52,19 @@
android:paddingBottom="16dp" />
</ScrollView>
<Button
android:id="@+id/btn_download_all"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="8dp"
android:background="@drawable/bg_button"
android:text="@string/remote_download_all"
android:textAllCaps="false"
android:textColor="@android:color/white"
android:textSize="15sp" />
<Button
android:id="@+id/btn_add"
android:layout_width="match_parent"
+5
View File
@@ -57,4 +57,9 @@
<string name="remote_remove">Remove</string>
<string name="remote_remove_body">This tablet will stop showing this library.</string>
<string name="remote_added">Library added</string>
<string name="remote_download_all">Download all missing</string>
<string name="remote_download_done">Downloaded %1$d of %2$d</string>
<string name="download">Download</string>
<string name="download_done">Downloaded</string>
<string name="download_failed">Download failed</string>
</resources>