Jellyfin remotes and a pause button in the player

This commit is contained in:
lotherk committed 2026-10-29 19:00:16 +00:00
1 parent d75eccdc17
commit 01359f1348
28 files changed
+1983 -91

No files matched your search

+93 -23
View File
@@ -2,20 +2,34 @@
Android app that reproduces the **iOS** YouTube Kids interface over a **local
folder**: 3x3 tile grid, category pills, fullscreen player, four-tab bar. No
network, no account, no recommendations. It exists because the son accepts only
the iOS kids look, so this is a convincing shell around local files.
account, no recommendations. It exists because the son accepts only the iOS kids
look, so this is a convincing shell around local files.
Floor: Android 5.0 / API 21. App name: KidsTube.
A parent can additionally point the app at one or more **Jellyfin** libraries.
Their videos then appear as if they were files in the folder — same grid, same
pills, same series order, same stats.
**Primary orientation is landscape** — the child always watches in landscape, so
landscape is the layout that must not break. Portrait must still work.
## Non-negotiables
- No network: the APK carries no `INTERNET` permission and no HTTP client.
`unzip -p app/build/outputs/apk/debug/app-debug.apk AndroidManifest.xml | strings | grep -ci internet`
prints `0`, and
- Local playback is offline. The only network use is a Jellyfin library a parent
configured behind the multiplication gate; with no remote configured the app
fetches nothing. The APK therefore carries `INTERNET`:
`/home/lotherk/android-sdk/build-tools/35.0.0/aapt2 dump permissions app/build/outputs/apk/debug/app-debug.apk`
lists only the two storage permissions.
must show `INTERNET` plus the two storage permissions and nothing else of
ours (AndroidX adds its own `DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION`).
- An unreachable remote is **invisible**: no tiles, no toast, no dialog, no
spinner, no long timeout. One authenticated `/Users/{id}/Views` call with a
~2s leash is the check, all remotes in parallel. A failed check drops that
remote's items even when its manifest and artwork are cached — a child must
never see a video that cannot play. The silence is deliberate; only the
parent's add-server screen reports errors.
- A reachable remote may render its cached manifest before the full fetch, so the
grid fills in without waiting. `RemoteCatalog.pruneStale` guarantees a snapshot
from before the app slept is not painted again.
- `minSdk` stays `21`. Check every new AAR's `minSdk` before adding it.
- Grid is always **3 columns** and tiles take their full cell width. The title
lives *inside* the tile. Three rows of 16:9 tiles cannot fit a landscape screen
@@ -42,7 +56,7 @@ landscape is the layout that must not break. Portrait must still work.
export ANDROID_HOME=/home/lotherk/android-sdk
./gradlew :app:assembleDebug # apk -> app/build/outputs/apk/debug/
./gradlew :app:testDebugUnitTest # Series rules, no device needed
./gradlew :app:testDebugUnitTest # Series, catalog, Jellyfin client; no device
./gradlew :app:lintDebug # abortOnError = true
adb install -r app/build/outputs/apk/debug/app-debug.apk
adb shell pm grant dev.lotherk.kidstube android.permission.READ_EXTERNAL_STORAGE
@@ -64,36 +78,75 @@ the parent gate takes precedence. Copying needs a scan:
Mandatory: from API 29 scoped storage forbids directory listing (the app uid gets
`EACCES`), and a pushed file stays invisible until MediaStore indexes it.
Remote content is configured behind the parent gate → *Remote libraries*: server
address, Jellyfin username/password, connection test, then the server's library
list (multi-select; every selected library is its own remote, so several
libraries and several servers can run side by side). The client speaks
`POST /Users/AuthenticateByName`, `GET /Users/{id}/Views`,
`GET /Users/{id}/Items?ParentId=…&Recursive=true` and plays
`/Videos/{id}/stream?static=true` — direct play, so the container must be one
Android can decode (mp4/h264 is safe, mkv is not guaranteed). Artwork comes from
`/Items/{id}/Images/Backdrop/0` (16:9) or `Primary`, `maxWidth=640`.
## Code map
- `data/Library` — SAF tree else MediaStore; `MediaItem`; sorted by folder then
`Series.naturalOrder` (leading `001`, `002` … numeric, not lexical).
- `data/Library` — SAF tree else MediaStore; local `MediaItem`; sorted by folder
then `Series.naturalOrder` (leading `001`, `002` … numeric, not lexical).
- `data/Catalog` — merges local and verified remote items into that same sort
order; `fingerprint` stops the "All" mix from reshuffling on every poll.
- `data/Keys` — the sha1 identity of a video. Local: the content URI. Remote:
`jellyfin|server|itemId`, so a new access token does not change stats or likes.
- `data/Series` — ordering plus the player's suggestion rule, pure and unit
tested: the visible four are `[outsider, previous of the series, next of the
series, outsider]`, followed by a shuffled tail so the strip can be swiped
sideways. Slots 1 and 4 always come from another folder; the tail is only
appended when both of them are really filled, otherwise the promise would break
as a series entry slides into position four.
- `media/ThumbCache` — decode via `MediaMetadataRetriever`, take the brightest of
three offsets (openings often fade from black), write JPEGs to
`filesDir/thumbs`, `LruCache` in memory, 3 threads, tag-guarded callback.
sideways. Slots 1 and 4 always come from another folder; a missing previous or
next is filled with another outsider, and without an outsider for slot 4 the
strip ends short instead of sliding a series entry into position four.
- `remote/Jellyfin` — plain `HttpURLConnection` + `org.json`, short timeouts, no
Android classes, unit tested against a stub HTTP server (auth, views, paging,
401 vs unreachable).
- `remote/RemoteCatalog` — the only place that decides what a remote contributes.
Checks all remotes in parallel (one authenticated `Views` call, 1.2s connect /
2s read), drops a failed remote immediately, publishes the cached manifest of a
reachable one before the full fetch, and re-checks every 30s while the app is
in front. `pruneStale` stops a snapshot from before the app slept from being
painted again.
- `remote/RemoteStore` — configured remotes in `Library.prefs`. `SecretBox`
seals the password with an Android-keystore AES/GCM key (API 23+; older
devices only encode it) so a revoked token can be renewed silently.
- `remote/RemoteMapping` — Jellyfin item → `MediaItem`: a show is the folder
(pill), an episode is titled `003 - Name` so `Series.naturalOrder` just works,
a movie belongs to its library; runtime comes from `RunTimeTicks`.
- `remote/RemoteCache` — last manifest per remote under `filesDir/remote/`. Read
only after the server answered, never as a standalone source.
- `media/ThumbCache` — local: decode via `MediaMetadataRetriever`, brightest of
three offsets (openings often fade from black). Remote: download the artwork
URL with a 2s/5s leash, remember failures so a struggling server is not asked
again on every rebind. JPEGs in `filesDir/thumbs/<library-tag>/`, `LruCache`
in memory, 3 threads, tag-guarded callback.
- `ui/TileView` — one view draws the whole tile: rounded 16:9 bitmap, duration
pill top-right, two-line title over a bottom scrim, heart when liked.
- `ui/MainActivity` — pills, grid, tabs, parent gate. The "All" pill shows a
shuffled mix across folders; a folder pill keeps that series in numeric order. `ui/TileSpacing` centres a
tile in its cell. Tiles are sized from the **home grid** height, one value
shared by both lists.
- `ui/PlayerActivity` — VideoView, immersive, chrome auto-hides; four suggestions,
heart to like. When a video ends, `Series.nextToPlay` continues the same folder
with the next episode; if the series is finished it starts another folder at
its first episode.
shuffled mix across folders; a folder pill keeps that series in numeric order.
`ui/TileSpacing` centres a tile in its cell. Tiles are sized from the **home
grid** height, one value shared by both lists. Local items paint first, remote
ones follow as their server answers; a 30s poll keeps them honest.
- `ui/PlayerActivity` — VideoView, immersive, chrome auto-hides while playing and
stays up while paused. A centre play/pause button; four suggestions; heart to
like. Leaving the app pauses the picture. When a video ends,
`Series.nextToPlay` continues the same folder with the next episode; if the
series is finished it starts another folder at its first episode.
- `ui/RemoteLibrariesActivity` — the parent's add/remove screen. The only place
that reports a connection error.
- `stats/StatsDb` — SQLite: `sessions` (plays, watched ms, per day) and `likes`.
**One store per library**: the picked folder is the identity (`Library.id`), the
file is `stats-<12-hex>.db` (`StatsStore`), thumbnails live under
`filesDir/thumbs/<tag>/`, and the export is `stats-<tag>.json` with a `library`
field. Switching the folder therefore switches stats, likes and artwork as if it
were another library. The single `stats.db` of earlier builds is copied into the
first library that opens, newer folders start empty.
first library that opens, newer folders start empty. "Your stuff" is filtered
against the current catalogue, so a liked remote video disappears with its
server.
## Pitfalls
@@ -126,6 +179,23 @@ Mandatory: from API 29 scoped storage forbids directory listing (the app uid get
- Rotation is sensor driven; force a test orientation with
`adb shell settings put system accelerometer_rotation 0` then
`adb shell settings put system user_rotation 0|1`.
- Never call a Jellyfin endpoint from the main thread or from `Library.scan`.
Everything remote goes through `RemoteCatalog`, which owns the timeouts and the
"offline means invisible" rule. A `Toast` about a remote belongs only on the
add-server screen.
- Jellyfin tokens and passwords live in `Library.prefs`; the password is sealed
by `SecretBox` (AES/GCM, Android keystore on API 23+, plain base64 below).
Losing the key just means the parent has to add the server again.
- `org.json` is part of Android, so main code needs no JSON dependency; the JVM
unit tests add `org.json:json` or the mockable `android.jar` throws at the first
parse.
- `android:usesCleartextTraffic="true"` is required: most home Jellyfin servers
speak plain `http://` on the LAN and API 28+ blocks that by default.
- The grid must not reshuffle because a poll answered with the same list —
`Catalog.fingerprint` is what keeps the "All" mix still.
- A `MediaItem.uri` is a String on purpose (content/file URI or stream URL); do
not reintroduce `android.net.Uri` into the data classes, it is what lets the
Jellyfin mapping run under a plain JVM test.
## Repo
+3
View File
@@ -47,4 +47,7 @@ dependencies {
implementation("androidx.documentfile:documentfile:1.0.1")
testImplementation("junit:junit:4.13.2")
// Android ships org.json; the JVM test classpath needs a real implementation
// so the Jellyfin parser can be tested without a device.
testImplementation("org.json:json:20231013")
}
+11 -3
View File
@@ -2,19 +2,25 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Storage read only, both regimes: READ_EXTERNAL_STORAGE up to API 32,
READ_MEDIA_VIDEO from API 33. Never INTERNET - the app is offline by
construction, and the built APK is checked for that. -->
READ_MEDIA_VIDEO from API 33. -->
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<!-- The only network use is an optional Jellyfin server a parent adds on
the settings screen. With no remote configured the app is exactly as
offline as before. Local servers speak plain http on the LAN, hence
cleartext traffic. -->
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.KidsTube">
android:theme="@style/Theme.KidsTube"
android:usesCleartextTraffic="true">
<activity
android:name=".ui.MainActivity"
@@ -27,6 +33,8 @@
<activity android:name=".ui.StatsActivity" />
<activity android:name=".ui.RemoteLibrariesActivity" />
<activity
android:name=".ui.PlayerActivity"
android:configChanges="orientation|screenSize|keyboardHidden"
@@ -0,0 +1,27 @@
package dev.lotherk.kidstube.data
/**
* The one list the app shows: local folder plus every reachable remote, sorted
* exactly like the folder alone was.
*/
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(
compareBy<MediaItem> { it.folder.lowercase() }.then(Series.naturalOrder)
)
}
/**
* Cheap change detector. The grid must not reshuffle its "All" mix every
* time the remote poll answers with the same videos.
*/
fun fingerprint(items: List<MediaItem>): Int {
var hash = items.size
for (item in items) hash = hash * 31 + item.key.hashCode()
return hash
}
}
@@ -0,0 +1,17 @@
package dev.lotherk.kidstube.data
import java.security.MessageDigest
/**
* Stable identity for a video. Local files hash their content URI, remote
* videos hash "jellyfin|server|itemId" so the key survives a new access token.
*/
object Keys {
fun sha1(value: String): String {
val digest = MessageDigest.getInstance("SHA-1").digest(value.toByteArray())
val sb = StringBuilder(digest.size * 2)
for (b in digest) sb.append(String.format("%02x", b))
return sb.toString()
}
}
@@ -12,7 +12,6 @@ import android.util.Log
import androidx.core.content.ContextCompat
import androidx.documentfile.provider.DocumentFile
import java.io.File
import java.security.MessageDigest
/**
* Video sources, in order of precedence:
@@ -191,7 +190,14 @@ object Library {
private fun addFile(name: String, uri: Uri, folder: String, out: MutableList<MediaItem>) {
val ext = name.substringAfterLast('.', "").lowercase()
if (ext !in VIDEO_EXT) return
out.add(MediaItem(uri = uri, title = titleOf(name), folder = folder, key = sha1(uri.toString())))
out.add(
MediaItem(
uri = uri.toString(),
title = titleOf(name),
folder = folder,
key = Keys.sha1(uri.toString())
)
)
}
private val VIDEO_EXT = setOf("mp4", "m4v", "webm", "mkv", "3gp", "ts")
@@ -199,12 +205,5 @@ object Library {
private fun titleOf(fileName: String): String =
fileName.substringBeforeLast('.').replace('_', ' ').trim().ifEmpty { fileName }
private fun sha1(value: String): String {
val digest = MessageDigest.getInstance("SHA-1").digest(value.toByteArray())
val sb = StringBuilder(digest.size * 2)
for (b in digest) sb.append(String.format("%02x", b))
return sb.toString()
}
fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
}
@@ -1,11 +1,18 @@
package dev.lotherk.kidstube.data
import android.net.Uri
/** One video found under the chosen folder. */
/**
* One video, whether it lives in the picked folder or on a Jellyfin server.
*
* [uri] is a content/file URI for local videos and the direct stream URL for
* remote ones, so the player treats both the same way.
*/
data class MediaItem(
val uri: Uri,
val uri: String,
override val title: String,
override val folder: String,
override val key: String
override val key: String,
/** Remote artwork; local files decode their own frame instead. */
val thumbUrl: String? = null,
/** Runtime reported by the remote (0 = probe the file). */
val durationMs: Long = 0L
) : SeriesItem
@@ -71,28 +71,33 @@ object Series {
val used = hashSetOf(current.key)
val out = ArrayList<T>(size)
fun takeOutsider(): Boolean {
fun takeOutsider(): T? {
while (outsiders.hasNext()) {
val candidate = outsiders.next()
if (used.add(candidate.key)) {
out.add(candidate)
return true
}
if (candidate.key !in used) return candidate
}
return false
return null
}
val firstFilled = takeOutsider()
previous?.let { if (used.add(it.key) && out.size < size) out.add(it) }
next?.let { if (used.add(it.key) && out.size < size) out.add(it) }
val fourthFilled = takeOutsider()
fun add(candidate: T?): Boolean {
if (candidate == null || out.size >= size || !used.add(candidate.key)) return false
out.add(candidate)
return true
}
// The swiping tail is only appended when both end slots really carry a
// video from outside the series. Otherwise the promise would break the
// moment a series entry slides into position four.
if (firstFilled && fourthFilled && out.size < size) {
val rest = all.filter { it.key !in used }.shuffled()
for (candidate in rest) {
// Slots 1 and 4 are always from another folder. The first video of a
// series has no previous and the last one no next: that gap is filled
// with another outsider instead of shifting the strip up, so the fourth
// tile never turns into a continuation of the running series.
add(takeOutsider())
if (!add(previous)) add(takeOutsider())
if (!add(next)) add(takeOutsider())
if (!add(takeOutsider())) return out
// The swiping tail may continue the series; it starts behind the four
// fixed slots and only exists when slot four really is an outsider.
if (out.size < size) {
for (candidate in all.filter { it.key !in used }.shuffled()) {
if (out.size >= size) break
if (used.add(candidate.key)) out.add(candidate)
}
@@ -4,6 +4,7 @@ import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.util.Log
@@ -13,6 +14,8 @@ import dev.lotherk.kidstube.data.MediaItem
import dev.lotherk.kidstube.stats.StatsStore
import android.view.View
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.util.Locale
import java.util.concurrent.Executors
@@ -32,7 +35,18 @@ object ThumbCache {
override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount / 1024
}
/**
* Artwork that could not be downloaded. Without it every rebind of the same
* tile would start another HTTP request against a struggling server.
*/
private val failed = java.util.Collections.newSetFromMap(
java.util.concurrent.ConcurrentHashMap<String, Boolean>()
)
fun label(context: Context, item: MediaItem): String? {
// Remote libraries report the runtime with the item, so the pill is there
// before a single byte of video was touched.
if (item.durationMs > 0) return formatDuration(item.durationMs)
val ms = Library.prefs(context).getLong("dur_" + item.key, 0L)
return if (ms > 0) formatDuration(ms) else null
}
@@ -61,9 +75,11 @@ object ThumbCache {
}
apply(null, label(context, item))
if (item.thumbUrl != null && key in failed) return
val app = context.applicationContext
pool.execute {
val data = generateThumb(app, item)
if (data.bitmap == null && item.thumbUrl != null) failed.add(key)
main.post {
if (data.bitmap != null) memory.put(key, data.bitmap)
if (view.tag == key) apply(data.bitmap, data.label)
@@ -74,13 +90,23 @@ object ThumbCache {
private class ThumbData(val bitmap: Bitmap?, val label: String?)
private fun generateThumb(context: Context, item: MediaItem): ThumbData {
item.thumbUrl?.let { url ->
val bitmap = download(url)?.let { scaleToWidth(it, THUMB_WIDTH) }
if (bitmap != null) writeDisk(context, item, bitmap)
return ThumbData(bitmap, label(context, item))
}
// A remote item without artwork must not be probed over HTTP: the
// retriever would sit on the network for a frame it will not get.
if (item.uri.startsWith("http")) return ThumbData(null, label(context, item))
val retriever = MediaMetadataRetriever()
try {
val path = item.uri.path
if (item.uri.scheme == "file" && path != null) {
val parsed = Uri.parse(item.uri)
val path = parsed.path
if (parsed.scheme == "file" && path != null) {
retriever.setDataSource(path)
} else {
retriever.setDataSource(context, item.uri)
retriever.setDataSource(context, parsed)
}
val durationMs = retriever
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
@@ -103,6 +129,23 @@ object ThumbCache {
}
/** Jellyfin artwork, on the same short leash as the catalogue calls. */
private fun download(url: String): Bitmap? {
var conn: HttpURLConnection? = null
try {
conn = URL(url).openConnection() as HttpURLConnection
conn.connectTimeout = 2000
conn.readTimeout = 5000
conn.instanceFollowRedirects = true
if (conn.responseCode !in 200..299) return null
return conn.inputStream.use { BitmapFactory.decodeStream(it) }
} catch (t: Throwable) {
return null
} finally {
conn?.disconnect()
}
}
/**
* Videos often open on a fade from black, so the first second is a black
* frame. Sample several offsets and keep the brightest one.
@@ -0,0 +1,317 @@
package dev.lotherk.kidstube.remote
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
/**
* Thin Jellyfin client.
*
* Deliberately plain `HttpURLConnection` + `org.json`: no dependency, no
* background service, and short timeouts everywhere so an unreachable server can
* never make the overview wait. Everything here is free of Android classes, so
* the parsing and the request flow run under a plain JVM unit test.
*/
class JellyfinException(val kind: Kind, message: String, cause: Throwable? = null) :
Exception(message, cause) {
enum class Kind {
/** DNS, refused connection, timeout: the server is simply not there. */
UNREACHABLE,
/** The token was revoked or the user cannot see the library. */
UNAUTHORIZED,
/** The server answered, but not with what the API promises. */
BAD_RESPONSE
}
}
data class JfAuth(val token: String, val userId: String, val userName: String)
data class JfView(val id: String, val name: String, val collectionType: String?)
data class JfItem(
val id: String,
val name: String,
val type: String,
val seriesName: String?,
val season: Int?,
val episode: Int?,
val runTimeTicks: Long,
val primaryTag: String?,
val backdropTag: String?
)
object Jellyfin {
const val CLIENT = "KidsTube"
const val VERSION = "0.2"
private const val DEFAULT_DEVICE = "kidstube"
private const val PAGE = 200
private const val MAX_PAGES = 40
// --- URLs ---------------------------------------------------------------
/** "192.168.1.10:8096/" -> "http://192.168.1.10:8096"; null if unusable. */
fun normalizeServer(raw: String): String? {
val trimmed = raw.trim().trimEnd('/')
if (trimmed.isEmpty()) return null
val withScheme = if (
trimmed.startsWith("http://", ignoreCase = true) ||
trimmed.startsWith("https://", ignoreCase = true)
) {
trimmed
} else {
"http://$trimmed"
}
return try {
val uri = java.net.URI(withScheme)
if (uri.host.isNullOrEmpty()) null else withScheme
} catch (t: Throwable) {
null
}
}
fun streamUrl(server: String, token: String, itemId: String): String =
"$server/Videos/${enc(itemId)}/stream?static=true&api_key=${enc(token)}"
/**
* A 16:9 backdrop looks right in the grid; a poster would be cropped to its
* middle. Fall back to the primary image when there is no backdrop.
*/
fun imageUrl(
server: String,
token: String,
itemId: String,
backdropTag: String?,
primaryTag: String?
): String? {
val base = when {
backdropTag != null ->
"$server/Items/${enc(itemId)}/Images/Backdrop/0?maxWidth=640&quality=80&tag=${enc(backdropTag)}"
primaryTag != null ->
"$server/Items/${enc(itemId)}/Images/Primary?maxWidth=640&quality=80&tag=${enc(primaryTag)}"
else -> return null
}
return "$base&api_key=${enc(token)}"
}
/** Music, books, photos and live TV are not something this app can show. */
fun isVideoLibrary(collectionType: String?): Boolean = when (collectionType?.lowercase()) {
null, "", "movies", "tvshows", "homevideos", "musicvideos", "boxsets", "mixed" -> true
else -> false
}
// --- calls --------------------------------------------------------------
fun authenticate(
server: String,
username: String,
password: String,
deviceId: String = DEFAULT_DEVICE,
connectMs: Int = 3000,
readMs: Int = 5000
): JfAuth {
val body = JSONObject()
.put("Username", username)
.put("Pw", password)
.toString()
val text = request(
"POST", "$server/Users/AuthenticateByName", null, deviceId, body, connectMs, readMs
)
val root = JSONObject(text)
val token = root.optString("AccessToken")
val user = root.optJSONObject("User")
val userId = user?.optString("Id").orEmpty()
if (token.isEmpty() || userId.isEmpty()) {
throw JellyfinException(JellyfinException.Kind.BAD_RESPONSE, "no token in answer")
}
return JfAuth(
token = token,
userId = userId,
userName = user?.optString("Name").orEmpty().ifEmpty { username }
)
}
/**
* The libraries this user may see. Also the cheapest authenticated call, so
* it doubles as the reachability check of a configured remote.
*/
fun views(
server: String,
token: String,
userId: String,
deviceId: String = DEFAULT_DEVICE,
connectMs: Int = 1500,
readMs: Int = 2500
): List<JfView> {
val text = request(
"GET", "$server/Users/${enc(userId)}/Views", token, deviceId, null, connectMs, readMs
)
val items = JSONObject(text).optJSONArray("Items") ?: return emptyList()
val out = ArrayList<JfView>(items.length())
for (i in 0 until items.length()) {
val o = items.optJSONObject(i) ?: continue
val id = o.optString("Id")
if (id.isEmpty()) continue
out.add(
JfView(
id = id,
name = o.optString("Name").ifEmpty { "Library" },
collectionType = o.optString("CollectionType").takeIf { it.isNotEmpty() }
)
)
}
return out
}
/** Every playable item of one library, a page at a time. */
fun items(
server: String,
token: String,
userId: String,
libraryId: String,
deviceId: String = DEFAULT_DEVICE,
connectMs: Int = 2500,
readMs: Int = 6000
): List<JfItem> {
val out = ArrayList<JfItem>()
var start = 0
var pages = 0
while (pages++ < MAX_PAGES) {
val url = buildString {
append(server).append("/Users/").append(enc(userId)).append("/Items?")
append("ParentId=").append(enc(libraryId))
append("&Recursive=true")
append("&IncludeItemTypes=").append(enc("Movie,Episode,Video,MusicVideo"))
append("&Fields=")
append(enc("RunTimeTicks,SeriesName,IndexNumber,ParentIndexNumber,ImageTags,BackdropImageTags"))
append("&SortBy=").append(enc("SortName"))
append("&StartIndex=").append(start)
append("&Limit=").append(PAGE)
}
val text = request("GET", url, token, deviceId, null, connectMs, readMs)
val root = JSONObject(text)
val arr = root.optJSONArray("Items") ?: break
for (i in 0 until arr.length()) {
parseItem(arr.optJSONObject(i))?.let(out::add)
}
start += arr.length()
val total = root.optInt("TotalRecordCount", -1)
if (arr.length() < PAGE) break
if (total in 0..start) break
}
return out
}
// --- parsing ------------------------------------------------------------
private val PLAYABLE_TYPES = setOf("Movie", "Episode", "Video", "MusicVideo")
private fun parseItem(o: JSONObject?): JfItem? {
if (o == null) return null
val id = o.optString("Id")
if (id.isEmpty()) return null
val type = o.optString("Type")
// A library can contain folders and box sets; only real videos belong in
// the grid, and the type is what tells them apart.
if (type !in PLAYABLE_TYPES) return null
val tags = o.optJSONObject("ImageTags")
val backdrops = o.optJSONArray("BackdropImageTags")
return JfItem(
id = id,
name = o.optString("Name").ifEmpty { o.optString("SortName") },
type = type,
seriesName = o.optString("SeriesName").takeIf { it.isNotEmpty() },
season = o.optInt("ParentIndexNumber", 0).takeIf { it > 0 },
episode = o.optInt("IndexNumber", 0).takeIf { it > 0 },
runTimeTicks = o.optLong("RunTimeTicks", 0L),
primaryTag = tags?.optString("Primary")?.takeIf { it.isNotEmpty() },
backdropTag = backdrops?.optString(0)?.takeIf { it.isNotEmpty() }
)
}
// --- transport ----------------------------------------------------------
private fun request(
method: String,
url: String,
token: String?,
deviceId: String,
body: String?,
connectMs: Int,
readMs: Int
): String {
var conn: HttpURLConnection? = null
try {
conn = URL(url).openConnection() as HttpURLConnection
conn.requestMethod = method
conn.connectTimeout = connectMs
conn.readTimeout = readMs
conn.instanceFollowRedirects = true
conn.setRequestProperty("Accept", "application/json")
conn.setRequestProperty(
"X-Emby-Authorization",
"MediaBrowser Client=\"$CLIENT\", Device=\"Android\", " +
"DeviceId=\"$deviceId\", Version=\"$VERSION\""
)
if (token != null) conn.setRequestProperty("X-Emby-Token", token)
if (body != null) {
conn.doOutput = true
conn.setRequestProperty("Content-Type", "application/json")
conn.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }
}
val code = conn.responseCode
if (code == 401 || code == 403) {
throw JellyfinException(JellyfinException.Kind.UNAUTHORIZED, "HTTP $code")
}
if (code !in 200..299) {
throw JellyfinException(JellyfinException.Kind.BAD_RESPONSE, "HTTP $code")
}
return conn.inputStream.use { it.readBytes().toString(Charsets.UTF_8) }
} catch (e: JellyfinException) {
throw e
} catch (t: Throwable) {
throw JellyfinException(
JellyfinException.Kind.UNREACHABLE,
t.message ?: t.javaClass.simpleName,
t
)
} finally {
conn?.disconnect()
}
}
private fun enc(value: String): String = URLEncoder.encode(value, "UTF-8")
}
/** On-disk form of one item, so a verified remote can render before the fetch. */
fun JfItem.toJson(): JSONObject = JSONObject()
.put("id", id)
.put("name", name)
.put("type", type)
.put("series", seriesName ?: JSONObject.NULL)
.put("season", season ?: JSONObject.NULL)
.put("episode", episode ?: JSONObject.NULL)
.put("ticks", runTimeTicks)
.put("primary", primaryTag ?: JSONObject.NULL)
.put("backdrop", backdropTag ?: JSONObject.NULL)
fun jfItemFromJson(o: JSONObject?): JfItem? {
if (o == null) return null
val id = o.optString("id")
if (id.isEmpty()) return null
return JfItem(
id = id,
name = o.optString("name"),
type = o.optString("type"),
seriesName = o.optString("series").takeIf { it.isNotEmpty() && it != "null" },
season = o.optInt("season", 0).takeIf { it > 0 },
episode = o.optInt("episode", 0).takeIf { it > 0 },
runTimeTicks = o.optLong("ticks", 0L),
primaryTag = o.optString("primary").takeIf { it.isNotEmpty() && it != "null" },
backdropTag = o.optString("backdrop").takeIf { it.isNotEmpty() && it != "null" }
)
}
@@ -0,0 +1,64 @@
package dev.lotherk.kidstube.remote
import android.content.Context
import dev.lotherk.kidstube.data.MediaItem
import dev.lotherk.kidstube.stats.StatsStore
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/**
* Last known manifest of a remote library.
*
* It exists so a reachable server renders immediately instead of after a full
* fetch. It is never shown on its own: [RemoteCatalog] only publishes it after
* the server answered this session.
*/
object RemoteCache {
private fun file(context: Context, id: String): File =
File(File(context.filesDir, "remote"), StatsStore.libraryTag(id) + ".json")
fun read(context: Context, remote: RemoteLibrary): List<MediaItem>? {
val file = file(context, remote.id)
if (!file.isFile) return null
return try {
val arr = JSONObject(file.readText()).optJSONArray("items") ?: return null
val raw = ArrayList<JfItem>(arr.length())
for (i in 0 until arr.length()) {
jfItemFromJson(arr.optJSONObject(i))?.let(raw::add)
}
RemoteMapping.toMediaItems(remote.server, remote.token, remote.name, raw)
} catch (t: Throwable) {
null
}
}
fun write(context: Context, remote: RemoteLibrary, raw: List<JfItem>) {
try {
val dir = File(context.filesDir, "remote")
if (!dir.exists()) dir.mkdirs()
val root = JSONObject()
.put("v", 1)
.put("saved_at", System.currentTimeMillis())
.put("items", JSONArray().apply { for (item in raw) put(item.toJson()) })
val target = file(context, remote.id)
val tmp = File(target.absolutePath + ".tmp")
tmp.writeText(root.toString())
if (!tmp.renameTo(target)) {
target.writeText(root.toString())
tmp.delete()
}
} catch (t: Throwable) {
// A missing cache only costs one full fetch on the next start.
}
}
fun delete(context: Context, id: String) {
try {
file(context, id).delete()
} catch (t: Throwable) {
// Nothing to do.
}
}
}
@@ -0,0 +1,230 @@
package dev.lotherk.kidstube.remote
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import dev.lotherk.kidstube.data.MediaItem
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
/**
* Availability of the configured remotes, checked off the main thread.
*
* Rules, in the order they matter:
* - a remote that does not answer is dropped from the published list at once,
* even when its manifest and artwork are cached. Nothing of an offline
* library is ever shown, so a child can never tap a video that cannot play;
* - the check is a single small authenticated call with a ~2s leash, and all
* remotes are checked in parallel, so one dead server never delays the rest;
* - a reachable remote publishes its cached manifest before the full fetch, so
* the grid fills in without a spinner.
*/
object RemoteCatalog {
private const val PING_CONNECT_MS = 1200
private const val PING_READ_MS = 2000
private const val FETCH_CONNECT_MS = 2500
private const val FETCH_READ_MS = 6000
/** A snapshot older than this is not painted again before a fresh check. */
private const val STALE_MS = 60_000L
private val lock = Any()
private val published = LinkedHashMap<String, List<MediaItem>>()
private val verifiedAt = HashMap<String, Long>()
private val listeners = ArrayList<(List<MediaItem>) -> Unit>()
private val running = AtomicBoolean(false)
private val pool = Executors.newFixedThreadPool(4)
private val main = Handler(Looper.getMainLooper())
/** Everything currently verified. Never touches the network. */
fun items(): List<MediaItem> = synchronized(lock) {
val out = ArrayList<MediaItem>()
for (list in published.values) out.addAll(list)
out
}
/**
* Drops snapshots older than [STALE_MS]. Called before the first paint so a
* library that was verified before the app went to sleep is not shown again
* until it answered.
*/
fun pruneStale() {
val now = SystemClock.elapsedRealtime()
synchronized(lock) {
val dead = verifiedAt.filterValues { now - it > STALE_MS }.keys.toList()
for (id in dead) {
published.remove(id)
verifiedAt.remove(id)
}
}
}
fun refresh(context: Context, onUpdate: (List<MediaItem>) -> Unit) {
val app = context.applicationContext
synchronized(lock) {
listeners.clear()
listeners.add(onUpdate)
}
val remotes = RemoteStore.list(app)
val configured = remotes.mapTo(HashSet()) { it.id }
synchronized(lock) {
published.keys.retainAll(configured)
verifiedAt.keys.retainAll(configured)
}
pruneStale()
if (remotes.isEmpty()) {
notifyNow()
return
}
// A poll that is already running will answer this listener as well.
if (!running.compareAndSet(false, true)) {
notifyNow()
return
}
val remaining = AtomicInteger(remotes.size)
for (remote in remotes) {
pool.execute {
try {
refreshOne(app, remote)
} catch (t: Throwable) {
drop(remote.id)
} finally {
if (remaining.decrementAndGet() == 0) running.set(false)
notifyNow()
}
}
}
}
/** Forgets a remote that was just deleted. */
fun forget(context: Context, id: String) {
drop(id)
RemoteCache.delete(context, id)
notifyNow()
}
/** Drops the activity callback; the process keeps the verified items. */
fun detach() {
synchronized(lock) { listeners.clear() }
}
// --- one remote ---------------------------------------------------------
private fun refreshOne(context: Context, remote: RemoteLibrary) {
var current = remote
when (check(current)) {
null -> Unit
JellyfinException.Kind.UNAUTHORIZED -> {
// A dead token is the one failure worth a second chance; an
// unreachable server must not pay for an auth round trip.
if (!renewToken(context, current)) {
drop(current.id)
return
}
current = RemoteStore.list(context).firstOrNull { it.id == remote.id } ?: remote
if (check(current) != null) {
drop(current.id)
return
}
}
else -> {
drop(current.id)
return
}
}
// The server answered, so its last known manifest is trustworthy enough
// to render now; the fetch below replaces it.
if (!RemoteStore.contains(context, current.id)) {
drop(current.id)
return
}
if (synchronized(lock) { published[current.id] } == null) {
RemoteCache.read(context, current)?.let { publish(current.id, it) }
}
try {
val raw = Jellyfin.items(
current.server,
current.token,
current.userId,
current.libraryId,
connectMs = FETCH_CONNECT_MS,
readMs = FETCH_READ_MS
)
val items = RemoteMapping.toMediaItems(current.server, current.token, current.name, raw)
RemoteCache.write(context, current, raw)
publish(current.id, items)
} catch (e: JellyfinException) {
when (e.kind) {
JellyfinException.Kind.UNAUTHORIZED -> drop(current.id)
else -> if (synchronized(lock) { published[current.id] } == null) {
publish(current.id, emptyList())
}
}
}
}
/** Short authenticated call: server up and token still accepted. */
private fun check(remote: RemoteLibrary): JellyfinException.Kind? = try {
Jellyfin.views(
remote.server,
remote.token,
remote.userId,
connectMs = PING_CONNECT_MS,
readMs = PING_READ_MS
)
null
} catch (e: JellyfinException) {
e.kind
} catch (t: Throwable) {
JellyfinException.Kind.UNREACHABLE
}
private fun renewToken(context: Context, remote: RemoteLibrary): Boolean {
val password = SecretBox.open(context, remote.password) ?: return false
return try {
val auth = Jellyfin.authenticate(
remote.server,
remote.username,
password,
RemoteStore.deviceId(context),
connectMs = 2000,
readMs = 3000
)
RemoteStore.save(context, remote.copy(token = auth.token, userId = auth.userId))
true
} catch (t: Throwable) {
false
}
}
// --- publishing ---------------------------------------------------------
private fun publish(id: String, items: List<MediaItem>) {
synchronized(lock) {
published[id] = items
verifiedAt[id] = SystemClock.elapsedRealtime()
}
}
private fun drop(id: String) {
synchronized(lock) {
published.remove(id)
verifiedAt.remove(id)
}
}
private fun notifyNow() {
main.post {
val snapshot = items()
val copy = synchronized(lock) { ArrayList(listeners) }
for (listener in copy) listener(snapshot)
}
}
}
@@ -0,0 +1,21 @@
package dev.lotherk.kidstube.remote
/**
* One library on a Jellyfin server. A server can contribute several libraries;
* each is its own remote with its own identity.
*/
data class RemoteLibrary(
val id: String,
val server: String,
val name: String,
val libraryId: String,
val userId: String,
val username: String,
val token: String,
/** Sealed password, only used to re-authenticate when the token dies. */
val password: String
) {
companion object {
fun idFor(server: String, libraryId: String): String = "jellyfin|$server|$libraryId"
}
}
@@ -0,0 +1,52 @@
package dev.lotherk.kidstube.remote
import dev.lotherk.kidstube.data.Keys
import dev.lotherk.kidstube.data.MediaItem
import java.util.Locale
/**
* Turns Jellyfin items into the same [MediaItem] the local folder produces, so
* the grid, the pills, the suggestions and the stats cannot tell them apart.
*
* A show is a series (its name becomes the folder/pill), an episode is numbered
* like the local files ("003 - Title"), and a movie belongs to its library.
*/
object RemoteMapping {
fun toMediaItems(
server: String,
token: String,
libraryName: String,
raw: List<JfItem>
): List<MediaItem> = raw.mapNotNull { toMediaItem(server, token, libraryName, it) }
fun toMediaItem(
server: String,
token: String,
libraryName: String,
item: JfItem
): MediaItem? {
if (item.id.isEmpty() || item.name.isEmpty()) return null
val folder = item.seriesName?.takeIf { it.isNotBlank() } ?: libraryName
return MediaItem(
uri = Jellyfin.streamUrl(server, token, item.id),
title = displayTitle(item),
folder = folder,
key = Keys.sha1("jellyfin|$server|${item.id}"),
thumbUrl = Jellyfin.imageUrl(server, token, item.id, item.backdropTag, item.primaryTag),
durationMs = if (item.runTimeTicks > 0) item.runTimeTicks / 10_000 else 0L
)
}
/**
* "003 - Title" keeps [dev.lotherk.kidstube.data.Series.naturalOrder] working
* for episodes without a second ordering rule. From season 2 on the season is
* folded into the number (201, 202, ...) so it still sorts as one series.
*/
fun displayTitle(item: JfItem): String {
val episode = item.episode ?: return item.name
val season = item.season ?: 1
val number = if (season > 1) season * 100 + episode else episode
return String.format(Locale.US, "%03d - %s", number, item.name)
}
}
@@ -0,0 +1,80 @@
package dev.lotherk.kidstube.remote
import android.content.Context
import dev.lotherk.kidstube.data.Library
import org.json.JSONArray
import org.json.JSONObject
import java.util.UUID
/**
* The configured remotes, in the same preferences the folder picker uses.
* Nothing here is contacted: the list is a configuration, not a cache.
*/
object RemoteStore {
private const val KEY_LIST = "remote_libraries_v1"
private const val KEY_DEVICE = "remote_device_id"
fun list(context: Context): List<RemoteLibrary> {
val raw = Library.prefs(context).getString(KEY_LIST, null) ?: return emptyList()
return try {
val arr = JSONArray(raw)
(0 until arr.length()).mapNotNull { i -> fromJson(arr.optJSONObject(i)) }
} catch (t: Throwable) {
emptyList()
}
}
fun save(context: Context, remote: RemoteLibrary) {
write(context, list(context).filterNot { it.id == remote.id } + remote)
}
fun remove(context: Context, id: String) {
write(context, list(context).filterNot { it.id == id })
}
fun contains(context: Context, id: String): Boolean = list(context).any { it.id == id }
/** One id per install, so Jellyfin can tell this tablet apart. */
fun deviceId(context: Context): String {
val prefs = Library.prefs(context)
val existing = prefs.getString(KEY_DEVICE, null)
if (!existing.isNullOrEmpty()) return existing
val fresh = UUID.randomUUID().toString()
prefs.edit().putString(KEY_DEVICE, fresh).apply()
return fresh
}
private fun write(context: Context, remotes: List<RemoteLibrary>) {
val arr = JSONArray()
for (remote in remotes) arr.put(toJson(remote))
Library.prefs(context).edit().putString(KEY_LIST, arr.toString()).apply()
}
private fun toJson(r: RemoteLibrary): JSONObject = JSONObject()
.put("id", r.id)
.put("server", r.server)
.put("name", r.name)
.put("library", r.libraryId)
.put("user_id", r.userId)
.put("user", r.username)
.put("token", r.token)
.put("password", r.password)
private fun fromJson(o: JSONObject?): RemoteLibrary? {
if (o == null) return null
val server = o.optString("server")
val library = o.optString("library")
if (server.isEmpty() || library.isEmpty()) return null
return RemoteLibrary(
id = o.optString("id").ifEmpty { RemoteLibrary.idFor(server, library) },
server = server,
name = o.optString("name").ifEmpty { "Library" },
libraryId = library,
userId = o.optString("user_id"),
username = o.optString("user"),
token = o.optString("token"),
password = o.optString("password")
)
}
}
@@ -0,0 +1,92 @@
package dev.lotherk.kidstube.remote
import android.content.Context
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/**
* The stored Jellyfin password only exists so a revoked token can be renewed
* without asking the parent again. On API 23+ it is AES/GCM sealed with a key
* that never leaves the Android keystore; older devices have no such key, so the
* value is merely encoded there and the token does the work.
*/
object SecretBox {
private const val ALIAS = "kidstube.remote"
private const val PREFIX_PLAIN = "p:"
private const val PREFIX_AES = "v1:"
private const val IV_BYTES = 12
fun seal(context: Context, plain: String): String {
if (plain.isEmpty()) return ""
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return PREFIX_PLAIN + encode(plain)
return try {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, key())
val payload = cipher.iv + cipher.doFinal(plain.toByteArray(Charsets.UTF_8))
PREFIX_AES + Base64.encodeToString(payload, Base64.NO_WRAP)
} catch (t: Throwable) {
PREFIX_PLAIN + encode(plain)
}
}
fun open(context: Context, sealed: String?): String? {
if (sealed.isNullOrEmpty()) return null
return try {
when {
sealed.startsWith(PREFIX_PLAIN) ->
String(decode(sealed.removePrefix(PREFIX_PLAIN)), Charsets.UTF_8)
sealed.startsWith(PREFIX_AES) -> {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return null
val all = decode(sealed.removePrefix(PREFIX_AES))
if (all.size <= IV_BYTES) return null
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(
Cipher.DECRYPT_MODE,
key(),
GCMParameterSpec(128, all, 0, IV_BYTES)
)
String(
cipher.doFinal(all, IV_BYTES, all.size - IV_BYTES),
Charsets.UTF_8
)
}
else -> null
}
} catch (t: Throwable) {
null
}
}
private fun encode(plain: String): String =
Base64.encodeToString(plain.toByteArray(Charsets.UTF_8), Base64.NO_WRAP)
private fun decode(text: String): ByteArray = Base64.decode(text, Base64.NO_WRAP)
@Synchronized
@androidx.annotation.RequiresApi(Build.VERSION_CODES.M)
private fun key(): SecretKey {
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(store.getEntry(ALIAS, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
generator.init(
KeyGenParameterSpec.Builder(
ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build()
)
return generator.generateKey()
}
}
@@ -4,7 +4,6 @@ import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.net.Uri
import dev.lotherk.kidstube.data.MediaItem
import org.json.JSONArray
import org.json.JSONObject
@@ -215,7 +214,7 @@ class StatsDb(context: Context, val libraryId: String) :
while (c.moveToNext()) {
out.add(
MediaItem(
uri = Uri.parse(c.getString(1)),
uri = c.getString(1) ?: continue,
title = c.getString(2),
folder = c.getString(3),
key = c.getString(0)
@@ -242,7 +241,7 @@ class StatsDb(context: Context, val libraryId: String) :
if (uri.isEmpty()) continue
out.add(
MediaItem(
uri = Uri.parse(uri),
uri = uri,
title = c.getString(2) ?: "",
folder = c.getString(3) ?: "",
key = c.getString(0) ?: ""
@@ -3,6 +3,8 @@ package dev.lotherk.kidstube.ui
import android.content.Intent
import android.content.res.ColorStateList
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
@@ -15,8 +17,10 @@ import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import dev.lotherk.kidstube.R
import dev.lotherk.kidstube.data.Catalog
import dev.lotherk.kidstube.data.Library
import dev.lotherk.kidstube.data.MediaItem
import dev.lotherk.kidstube.remote.RemoteCatalog
import dev.lotherk.kidstube.stats.StatsDb
import dev.lotherk.kidstube.databinding.ActivityMainBinding
import java.util.concurrent.Executors
@@ -26,23 +30,40 @@ import kotlin.random.Random
class MainActivity : AppCompatActivity() {
companion object {
/** How often a running app re-checks its remotes, in ms. */
private const val POLL_MS = 30_000L
}
private lateinit var binding: ActivityMainBinding
private lateinit var gridAdapter: VideoAdapter
private lateinit var resultsAdapter: VideoAdapter
private val executor = Executors.newSingleThreadExecutor()
private val handler = Handler(Looper.getMainLooper())
private var statsDb: StatsDb? = null
private var statsLibrary: String? = null
private var all: List<MediaItem> = emptyList()
private var localItems: List<MediaItem> = emptyList()
private var folders: List<String> = emptyList()
private var selectedFolder: String? = null
private var scanning = false
private var activeTab = 0
private var currentTileWidth = 0
/** Sentinel, so the very first (possibly empty) publish is not skipped. */
private var lastFingerprint = Int.MIN_VALUE
/** "All" is a mix across folders, not one series after another. */
private var mixed: List<MediaItem> = emptyList()
/** Re-checks the remotes while the app is in front, without blocking. */
private val poll = object : Runnable {
override fun run() {
RemoteCatalog.refresh(this@MainActivity) { remote -> publish(remote) }
handler.postDelayed(this, POLL_MS)
}
}
private val openFolder =
registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
if (uri != null) {
@@ -150,33 +171,72 @@ class MainActivity : AppCompatActivity() {
override fun onResume() {
super.onResume()
if (!scanning) reload()
handler.removeCallbacks(poll)
handler.postDelayed(poll, POLL_MS)
}
override fun onPause() {
super.onPause()
handler.removeCallbacks(poll)
}
override fun onDestroy() {
handler.removeCallbacksAndMessages(null)
RemoteCatalog.detach()
executor.shutdown()
super.onDestroy()
}
/**
* Local files first, then the remotes as they answer. The local folder is
* read off the main thread; the remote refresh has its own pool and posts
* its snapshot when a server answers, so a slow server only delays its own
* tiles.
*/
private fun reload() {
if (scanning) return
val hasSource = Library.treeUri(this) != null || Library.hasReadPermission(this)
if (!hasSource) {
all = emptyList()
gridAdapter.submit(emptyList())
refreshEmptyState()
return
}
scanning = true
val hasSource = Library.treeUri(this) != null || Library.hasReadPermission(this)
executor.execute {
val items = Library.scan(this)
val local = if (hasSource) Library.scan(this) else emptyList()
runOnUiThread {
scanning = false
all = items
mixed = items.shuffled()
buildChips(items)
applyFolderFilter()
if (activeTab == 1) applyFilter(binding.searchInput.text?.toString().orEmpty())
if (activeTab == 2) resultsAdapter.submit(stats().likedItems(), stats().likedKeys())
refreshEmptyState()
localItems = local
// Anything verified before the app went to sleep must not be
// painted again until this session confirmed the server.
RemoteCatalog.pruneStale()
publish(RemoteCatalog.items())
}
RemoteCatalog.refresh(this) { remote -> publish(remote) }
}
}
/** Merges local and verified remote items and redraws only on real change. */
private fun publish(remote: List<MediaItem>) {
if (isFinishing || isDestroyed) return
val merged = Catalog.merge(localItems, remote)
val fingerprint = Catalog.fingerprint(merged)
if (fingerprint == lastFingerprint) return
lastFingerprint = fingerprint
all = merged
mixed = merged.shuffled()
buildChips(merged)
applyFolderFilter()
if (activeTab == 1) applyFilter(binding.searchInput.text?.toString().orEmpty())
if (activeTab == 2) resultsAdapter.submit(likedItems(), stats().likedKeys())
refreshEmptyState()
}
/**
* "Your stuff" only ever shows videos that are there right now: a liked
* remote video disappears with its server instead of dangling.
*/
private fun likedItems(): List<MediaItem> {
val byKey = Catalog.merge(localItems, RemoteCatalog.items()).associateBy { it.key }
return stats().likedItems().mapNotNull { byKey[it.key] }
}
/** "All" plus one pill per folder, as the reference shows. */
private fun buildChips(items: List<MediaItem>) {
folders = items.groupBy { it.folder }.keys.toList()
@@ -236,7 +296,7 @@ class MainActivity : AppCompatActivity() {
if (index != 1) binding.searchInput.setText("")
when (index) {
1 -> binding.searchInput.requestFocus()
2 -> resultsAdapter.submit(stats().likedItems(), stats().likedKeys())
2 -> resultsAdapter.submit(likedItems(), stats().likedKeys())
}
refreshEmptyState()
binding.grid.post { layoutTiles() }
@@ -295,15 +355,20 @@ class MainActivity : AppCompatActivity() {
private fun showFolderInfo() {
val name = Library.folderName(this) ?: getString(R.string.folder_label)
val message = "$name\n\n${getString(R.string.video_count, all.size)}"
val entries = arrayOf(
getString(R.string.change_folder),
getString(R.string.stats_open),
getString(R.string.remote_title)
)
AlertDialog.Builder(this)
.setTitle(R.string.folder_label)
.setMessage(message)
.setPositiveButton(R.string.change_folder) { d, _ ->
d.dismiss()
pickFolder()
}
.setNeutralButton(R.string.stats_open) { _, _ ->
startActivity(Intent(this, StatsActivity::class.java))
.setItems(entries) { _, which ->
when (which) {
0 -> pickFolder()
1 -> startActivity(Intent(this, StatsActivity::class.java))
2 -> startActivity(Intent(this, RemoteLibrariesActivity::class.java))
}
}
.setNegativeButton(R.string.ok, null)
.show()
@@ -312,7 +377,7 @@ class MainActivity : AppCompatActivity() {
private fun openPlayer(item: MediaItem) {
startActivity(
Intent(this, PlayerActivity::class.java)
.putExtra(PlayerActivity.EXTRA_URI, item.uri.toString())
.putExtra(PlayerActivity.EXTRA_URI, item.uri)
.putExtra(PlayerActivity.EXTRA_TITLE, item.title)
.putExtra(PlayerActivity.EXTRA_FOLDER, item.folder)
.putExtra(PlayerActivity.EXTRA_KEY, item.key)
@@ -15,9 +15,11 @@ import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import dev.lotherk.kidstube.R
import dev.lotherk.kidstube.data.Catalog
import dev.lotherk.kidstube.data.Library
import dev.lotherk.kidstube.data.MediaItem
import dev.lotherk.kidstube.data.Series
import dev.lotherk.kidstube.remote.RemoteCatalog
import dev.lotherk.kidstube.stats.StatsDb
import dev.lotherk.kidstube.databinding.ActivityPlayerBinding
import java.util.concurrent.Executors
@@ -68,7 +70,7 @@ class PlayerActivity : AppCompatActivity() {
stats = StatsDb(this, Library.id(this))
item = MediaItem(
uri = Uri.parse(rawUri),
uri = rawUri,
title = intent.getStringExtra(EXTRA_TITLE).orEmpty(),
folder = intent.getStringExtra(EXTRA_FOLDER).orEmpty(),
key = intent.getStringExtra(EXTRA_KEY) ?: rawUri
@@ -78,6 +80,7 @@ class PlayerActivity : AppCompatActivity() {
binding.title.text = intent.getStringExtra(EXTRA_TITLE).orEmpty()
binding.btnBack.setOnClickListener { finish() }
binding.btnLike.setOnClickListener { toggleLike() }
binding.btnPlay.setOnClickListener { togglePlay() }
binding.tapCatcher.setOnClickListener { setChrome(!chromeVisible) }
binding.chrome.setOnClickListener { setChrome(!chromeVisible) }
@@ -108,6 +111,8 @@ class PlayerActivity : AppCompatActivity() {
player.isLooping = false
binding.seek.max = if (player.duration > 0) player.duration else 1
binding.video.start()
resumedAt = SystemClock.elapsedRealtime()
updatePlayIcon()
handler.post(ticker)
setChrome(true)
}
@@ -142,10 +147,31 @@ class PlayerActivity : AppCompatActivity() {
updateLikeIcon(stats.isLiked(next.key))
binding.spinner.visibility = View.VISIBLE
setChrome(true)
binding.video.setVideoURI(next.uri)
binding.video.setVideoURI(Uri.parse(next.uri))
loadSuggestions(next)
}
/** The one control a child asks for: pause the picture, then continue it. */
private fun togglePlay() {
if (!prepared) return
if (binding.video.isPlaying) {
binding.video.pause()
commitWatch()
} else {
binding.video.start()
resumedAt = SystemClock.elapsedRealtime()
}
updatePlayIcon()
setChrome(true)
}
private fun updatePlayIcon() {
val playing = prepared && binding.video.isPlaying
binding.btnPlay.setImageResource(if (playing) R.drawable.ic_pause else R.drawable.ic_play)
binding.btnPlay.contentDescription =
getString(if (playing) R.string.pause else R.string.play)
}
/** The heart in the corner; "Your stuff" shows exactly these videos. */
private fun toggleLike() {
val current = item ?: return
@@ -164,7 +190,9 @@ class PlayerActivity : AppCompatActivity() {
private fun loadSuggestions(current: MediaItem) {
executor.execute {
val scan = Library.scan(this)
// Remote suggestions come from the verified snapshot, never from a
// network call: the strip must be there as fast as for local files.
val scan = Catalog.merge(Library.scan(this), RemoteCatalog.items())
val others = Series.suggestionsFor(scan, current, 24)
library = scan
pool = others
@@ -187,14 +215,23 @@ class PlayerActivity : AppCompatActivity() {
override fun onResume() {
super.onResume()
resumedAt = SystemClock.elapsedRealtime()
// Watch time only runs while the picture actually runs; a paused player
// must not collect minutes.
if (prepared && binding.video.isPlaying) resumedAt = SystemClock.elapsedRealtime()
if (segmentStart == 0L) segmentStart = System.currentTimeMillis()
updatePlayIcon()
// Coming back to a paused picture must show the button that restarts it.
if (prepared && !binding.video.isPlaying) setChrome(true)
}
override fun onPause() {
super.onPause()
// Leaving the app stops the picture (and the audio) instead of playing
// on behind the home screen; the play button brings it back.
if (prepared && binding.video.isPlaying) binding.video.pause()
commitWatch()
recordSegment()
updatePlayIcon()
}
/** Watches the clock only while this activity is actually visible. */
@@ -233,7 +270,11 @@ class PlayerActivity : AppCompatActivity() {
chromeVisible = visible
binding.chrome.visibility = if (visible) View.VISIBLE else View.INVISIBLE
handler.removeCallbacks(hideChrome)
if (visible) handler.postDelayed(hideChrome, 8000)
// A paused picture keeps its controls: otherwise the play button would
// vanish and the child could not restart the video.
if (visible && prepared && binding.video.isPlaying) {
handler.postDelayed(hideChrome, 8000)
}
}
private fun immersive() {
@@ -0,0 +1,264 @@
package dev.lotherk.kidstube.ui
import android.os.Bundle
import android.text.InputType
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import dev.lotherk.kidstube.R
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.RemoteLibrary
import dev.lotherk.kidstube.remote.RemoteStore
import dev.lotherk.kidstube.remote.SecretBox
import java.util.concurrent.Executors
import kotlin.math.roundToInt
/**
* Parent-only screen behind the multiplication gate: which Jellyfin servers this
* tablet reads from. Adding one runs exactly the flow the child never sees —
* address and credentials, connection test, then the server's library list.
*
* Errors are reported here, while the parent is looking. The child's overview
* stays silent about an unreachable server and simply does not show it.
*/
class RemoteLibrariesActivity : AppCompatActivity() {
private lateinit var binding: ActivityRemoteBinding
private val executor = Executors.newSingleThreadExecutor()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityRemoteBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnBack.setOnClickListener { finish() }
binding.btnAdd.setOnClickListener { addJellyfin() }
reloadList()
}
override fun onDestroy() {
executor.shutdown()
super.onDestroy()
}
// --- list ---------------------------------------------------------------
private fun reloadList() {
binding.list.removeAllViews()
val remotes = RemoteStore.list(this)
if (remotes.isEmpty()) {
binding.list.addView(note(getString(R.string.remote_empty)))
return
}
for (remote in remotes) binding.list.addView(row(remote))
}
private fun row(remote: RemoteLibrary): View {
val row = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
setPadding(0, dp(12), 0, dp(12))
}
val texts = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
texts.addView(
TextView(this).apply {
text = remote.name
setTextColor(ContextCompat.getColor(this@RemoteLibrariesActivity, R.color.kt_text))
textSize = 16f
}
)
texts.addView(
TextView(this).apply {
text = remote.server + " · " + remote.username
setTextColor(ContextCompat.getColor(this@RemoteLibrariesActivity, R.color.kt_text_sub))
textSize = 12f
maxLines = 1
ellipsize = TextUtils.TruncateAt.END
}
)
row.addView(texts, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f))
row.addView(
TextView(this).apply {
text = getString(R.string.remote_remove)
setTextColor(ContextCompat.getColor(this@RemoteLibrariesActivity, R.color.kt_text_sub))
textSize = 13f
setPadding(dp(12), dp(8), 0, dp(8))
setOnClickListener { confirmRemove(remote) }
}
)
return row
}
private fun note(text: String): TextView = TextView(this).apply {
this.text = text
setTextColor(ContextCompat.getColor(this@RemoteLibrariesActivity, R.color.kt_text_sub))
textSize = 14f
setPadding(0, dp(12), 0, dp(12))
}
private fun confirmRemove(remote: RemoteLibrary) {
AlertDialog.Builder(this)
.setTitle(remote.name)
.setMessage(R.string.remote_remove_body)
.setPositiveButton(R.string.remote_remove) { _, _ ->
RemoteStore.remove(this, remote.id)
RemoteCatalog.forget(this, remote.id)
reloadList()
}
.setNegativeButton(R.string.cancel, null)
.show()
}
// --- add flow -----------------------------------------------------------
private fun addJellyfin() {
val pad = dp(20)
val form = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setPadding(pad, dp(8), pad, 0)
}
val url = EditText(this).apply {
hint = getString(R.string.remote_url_hint)
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI
setSingleLine(true)
}
val user = EditText(this).apply {
hint = getString(R.string.remote_user)
inputType = InputType.TYPE_CLASS_TEXT
setSingleLine(true)
}
val pass = EditText(this).apply {
hint = getString(R.string.remote_password)
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
setSingleLine(true)
}
form.addView(url)
form.addView(user)
form.addView(pass)
val dialog = AlertDialog.Builder(this)
.setTitle(R.string.remote_add)
.setView(form)
.setPositiveButton(R.string.remote_connect, null)
.setNegativeButton(R.string.cancel, null)
.create()
dialog.setOnShowListener {
val connect = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
connect.setOnClickListener {
val server = Jellyfin.normalizeServer(url.text.toString())
val username = user.text.toString().trim()
val password = pass.text.toString()
if (server == null) {
url.error = getString(R.string.remote_bad_url)
return@setOnClickListener
}
if (username.isEmpty()) {
user.error = getString(R.string.remote_need_user)
return@setOnClickListener
}
connect.isEnabled = false
connect.text = getString(R.string.remote_connecting)
executor.execute {
try {
val auth = Jellyfin.authenticate(
server,
username,
password,
RemoteStore.deviceId(this)
)
val views = Jellyfin.views(server, auth.token, auth.userId)
.filter { Jellyfin.isVideoLibrary(it.collectionType) }
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
dialog.dismiss()
if (views.isEmpty()) {
toast(R.string.remote_no_libraries)
} else {
chooseLibraries(server, username, password, auth, views)
}
}
} catch (t: Throwable) {
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
connect.isEnabled = true
connect.text = getString(R.string.remote_connect)
toast(
if (t is JellyfinException &&
t.kind == JellyfinException.Kind.UNAUTHORIZED
) {
R.string.remote_bad_login
} else {
R.string.remote_failed
}
)
}
}
}
}
}
dialog.show()
}
private fun chooseLibraries(
server: String,
username: String,
password: String,
auth: JfAuth,
views: List<JfView>
) {
val labels = views.map { it.name }.toTypedArray()
val checked = BooleanArray(views.size) { true }
AlertDialog.Builder(this)
.setTitle(R.string.remote_pick_library)
.setMultiChoiceItems(labels, checked) { _, which, isChecked ->
checked[which] = isChecked
}
.setPositiveButton(R.string.ok) { _, _ ->
val sealed = SecretBox.seal(this, password)
var added = 0
for (index in views.indices) {
if (!checked[index]) continue
val view = views[index]
RemoteStore.save(
this,
RemoteLibrary(
id = RemoteLibrary.idFor(server, view.id),
server = server,
name = view.name,
libraryId = view.id,
userId = auth.userId,
username = username,
token = auth.token,
password = sealed
)
)
added++
}
if (added > 0) {
reloadList()
toast(R.string.remote_added)
}
}
.setNegativeButton(R.string.cancel, null)
.show()
}
private fun toast(res: Int) {
Toast.makeText(this, res, Toast.LENGTH_SHORT).show()
}
private fun dp(value: Int): Int = (value * resources.displayMetrics.density).roundToInt()
}
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M6,5h4v14h-4zM14,5h4v14h-4z" />
</vector>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M8,5v14l11,-7z" />
</vector>
@@ -56,6 +56,19 @@
android:src="@drawable/ic_heart"
app:tint="@android:color/white" />
<!-- Play/pause sits in the middle of the picture, where a child looks
for it. It hides with the rest of the chrome. -->
<ImageButton
android:id="@+id/btn_play"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_gravity="center"
android:background="@drawable/bg_scrim_circle"
android:contentDescription="@string/pause"
android:padding="18dp"
android:src="@drawable/ic_pause"
app:tint="@android:color/white" />
<LinearLayout
android:id="@+id/bottom_panel"
android:layout_width="match_parent"
@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/kt_bg"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingStart="4dp"
android:paddingEnd="16dp">
<ImageButton
android:id="@+id/btn_back"
android:layout_width="44dp"
android:layout_height="44dp"
android:background="?android:attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/back"
android:padding="10dp"
android:src="@drawable/ic_back"
app:tint="@color/kt_text" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:fontFamily="sans-serif-medium"
android:text="@string/remote_title"
android:textColor="@color/kt_text"
android:textSize="20sp" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:fillViewport="true">
<LinearLayout
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingStart="20dp"
android:paddingTop="8dp"
android:paddingEnd="20dp"
android:paddingBottom="16dp" />
</ScrollView>
<Button
android:id="@+id/btn_add"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="@drawable/bg_button"
android:text="@string/remote_add"
android:textAllCaps="false"
android:textColor="@android:color/white"
android:textSize="15sp" />
</LinearLayout>
+22 -1
View File
@@ -10,7 +10,7 @@
<string name="chip_all">All</string>
<string name="empty_title">No videos yet</string>
<string name="empty_body">Put the videos into the folder Movies/KidsTube, or pick another folder. The app only reads that folder and never goes online.</string>
<string name="empty_body">Put the videos into the folder Movies/KidsTube, or pick another folder. Parents can also add a Jellyfin library.</string>
<string name="pick_folder">Choose folder</string>
<string name="change_folder">Change folder</string>
<string name="folder_label">Folder</string>
@@ -36,4 +36,25 @@
<string name="likes_empty">Nothing liked yet. Tap the heart while a video plays.</string>
<string name="search_empty">Nothing found.</string>
<string name="error_play">This video cannot be played on this device</string>
<string name="pause">Pause</string>
<string name="play">Play</string>
<string name="remote_title">Remote libraries</string>
<string name="remote_add">Add Jellyfin server</string>
<string name="remote_url_hint">http://192.168.1.10:8096</string>
<string name="remote_user">Username</string>
<string name="remote_password">Password</string>
<string name="remote_connect">Connect</string>
<string name="remote_connecting">Connecting…</string>
<string name="remote_bad_url">Enter a server address</string>
<string name="remote_need_user">Enter a username</string>
<string name="remote_failed">Server not reachable</string>
<string name="remote_bad_login">Wrong username or password</string>
<string name="remote_no_libraries">No video libraries on this server</string>
<string name="remote_pick_library">Choose libraries</string>
<string name="remote_empty">No remote libraries yet. Add a Jellyfin server to play its videos here.</string>
<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>
</resources>
@@ -0,0 +1,46 @@
package dev.lotherk.kidstube.data
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
class CatalogTest {
private fun item(title: String, folder: String, key: String = title) =
MediaItem(uri = "file:///$key", title = title, folder = folder, key = key)
@Test
fun remoteItemsAreSortedLikeLocalFiles() {
val local = listOf(
item("001 - A", "Bluey"),
item("002 - B", "Bluey")
)
val remote = listOf(
item("010 - K", "Bluey"),
item("Cars", "Movies")
)
val merged = Catalog.merge(local, remote)
assertEquals(
listOf("001 - A", "002 - B", "010 - K", "Cars"),
merged.map { it.title }
)
}
@Test
fun numbersSortNumericallyNotLexically() {
val merged = Catalog.merge(
listOf(item("010 - Ten", "S")),
listOf(item("009 - Nine", "S"))
)
assertEquals(listOf("009 - Nine", "010 - Ten"), merged.map { it.title })
}
@Test
fun fingerprintOnlyMovesWhenTheSetMoves() {
val one = listOf(item("A", "S"), item("B", "S"))
val same = listOf(item("A", "S"), item("B", "S"))
val changed = listOf(item("A", "S"))
assertEquals(Catalog.fingerprint(one), Catalog.fingerprint(same))
assertNotEquals(Catalog.fingerprint(one), Catalog.fingerprint(changed))
}
}
@@ -0,0 +1,234 @@
package dev.lotherk.kidstube.remote
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Test
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.InetAddress
import java.net.ServerSocket
import kotlin.concurrent.thread
/**
* The request flow against a stand-in Jellyfin: the same JSON shapes, the same
* header names. Catches the mistakes a pure parser test cannot (wrong path,
* missing token header, ignored pagination).
*/
class JellyfinClientTest {
private lateinit var server: StubServer
private var base = ""
/** Two episodes plus filler, so the client really has to page. */
private val total = 201
@Before
fun startServer() {
server = StubServer { method, target, headers, body -> answer(method, target, headers, body) }
base = "http://127.0.0.1:" + server.port
}
@After
fun stopServer() {
server.close()
}
private fun answer(
method: String,
target: String,
headers: Map<String, String>,
body: String
): Pair<Int, String> {
val path = target.substringBefore('?')
val query = target.substringAfter('?', "")
return when (path) {
"/Users/AuthenticateByName" -> {
val auth = headers["x-emby-authorization"]
when {
auth == null || !auth.contains("MediaBrowser") -> 400 to "{}"
!body.contains("\"Username\":\"kid\"") -> 401 to "{}"
else -> 200 to
"""{"User":{"Id":"u1","Name":"kid"},"AccessToken":"tok-1"}"""
}
}
"/Users/u1/Views" ->
if (headers["x-emby-token"] != "tok-1") {
401 to "{}"
} else {
200 to """{"Items":[
{"Id":"lib-movies","Name":"Movies","CollectionType":"movies"},
{"Id":"lib-music","Name":"Music","CollectionType":"music"}
]}"""
}
"/Users/u1/Items" -> {
val start = Regex("StartIndex=(\\d+)").find(query)
?.groupValues?.get(1)?.toInt() ?: 0
val limit = Regex("Limit=(\\d+)").find(query)
?.groupValues?.get(1)?.toInt() ?: 200
val end = minOf(start + limit, total)
val page = (start until end).joinToString(",") { index -> jsonItem(index) }
200 to """{"Items":[$page],"TotalRecordCount":$total}"""
}
else -> 404 to "{}"
}
}
private fun jsonItem(index: Int): String = when (index) {
0 -> """{"Id":"e1","Name":"Pilot","Type":"Episode","SeriesName":"Bluey",
"ParentIndexNumber":1,"IndexNumber":1,"RunTimeTicks":600000000,
"ImageTags":{"Primary":"p1"},"BackdropImageTags":["b1"]}"""
1 -> """{"Id":"e2","Name":"Sleepytime","Type":"Episode","SeriesName":"Bluey",
"ParentIndexNumber":1,"IndexNumber":2,"RunTimeTicks":600000000}"""
2 -> """{"Id":"f2","Name":"Season 1","Type":"Folder"}"""
total - 1 -> """{"Id":"m1","Name":"Cars","Type":"Movie","RunTimeTicks":0}"""
else -> """{"Id":"f$index","Name":"Filler $index","Type":"Movie","RunTimeTicks":0}"""
}
@Test
fun authenticatesAndFindsTheVideoLibraries() {
val auth = Jellyfin.authenticate(base, "kid", "pw")
assertEquals("tok-1", auth.token)
assertEquals("u1", auth.userId)
val views = Jellyfin.views(base, auth.token, auth.userId)
assertEquals(2, views.size)
assertEquals(
listOf("lib-movies"),
views.filter { Jellyfin.isVideoLibrary(it.collectionType) }.map { it.id }
)
}
@Test
fun readsEveryPageOfALibrary() {
val items = Jellyfin.items(base, "tok-1", "u1", "lib-movies")
// The folder in the middle of the page is not a video and must not show.
assertEquals(total - 1, items.size)
assertEquals("e1", items.first().id)
assertEquals("m1", items.last().id)
assertEquals("Bluey", items[0].seriesName)
assertEquals(1, items[0].season)
assertEquals(1, items[0].episode)
assertEquals("b1", items[0].backdropTag)
assertEquals("p1", items[0].primaryTag)
}
@Test
fun aLibraryMergesIntoTheGridLikeLocalFiles() {
val raw = Jellyfin.items(base, "tok-1", "u1", "lib-movies")
val remote = RemoteMapping.toMediaItems(base, "tok-1", "Movies", raw)
val local = dev.lotherk.kidstube.data.MediaItem(
uri = "file:///local.mp4",
title = "001 - Local",
folder = "Bluey",
key = "local"
)
val merged = dev.lotherk.kidstube.data.Catalog.merge(listOf(local), remote)
assertEquals(201, merged.size)
assertEquals("Bluey", merged[0].folder)
assertEquals("001 - Local", merged[0].title)
assertEquals("001 - Pilot", merged[1].title)
assertEquals("Bluey", merged[2].folder)
assertEquals("002 - Sleepytime", merged[2].title)
assertEquals("Movies", merged[3].folder)
}
@Test
fun aRevokedTokenIsUnauthorizedNotUnreachable() {
try {
Jellyfin.views(base, "stale", "u1")
fail("expected a JellyfinException")
} catch (e: JellyfinException) {
assertEquals(JellyfinException.Kind.UNAUTHORIZED, e.kind)
}
}
@Test
fun aDeadServerFailsFast() {
val started = System.currentTimeMillis()
try {
Jellyfin.views("http://127.0.0.1:1", "tok", "u1", connectMs = 500, readMs = 500)
fail("expected a JellyfinException")
} catch (e: JellyfinException) {
assertEquals(JellyfinException.Kind.UNREACHABLE, e.kind)
}
assertTrue(System.currentTimeMillis() - started < 3000)
}
}
/**
* Just enough HTTP/1.1 to answer HttpURLConnection: one request per connection,
* `Connection: close` on the way out.
*/
private class StubServer(
private val handler: (String, String, Map<String, String>, String) -> Pair<Int, String>
) {
private val socket = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"))
val port: Int = socket.localPort
private val worker = thread(isDaemon = true, name = "stub-jellyfin") {
while (!socket.isClosed) {
try {
socket.accept().use { client ->
val reader = BufferedReader(InputStreamReader(client.getInputStream(), "UTF-8"))
val requestLine = reader.readLine() ?: return@use
val parts = requestLine.split(" ")
if (parts.size < 2) return@use
val headers = HashMap<String, String>()
while (true) {
val line = reader.readLine() ?: break
if (line.isEmpty()) break
val colon = line.indexOf(':')
if (colon > 0) {
headers[line.substring(0, colon).trim().lowercase()] =
line.substring(colon + 1).trim()
}
}
val length = headers["content-length"]?.toIntOrNull() ?: 0
val body = if (length > 0) {
val buffer = CharArray(length)
var read = 0
while (read < length) {
val n = reader.read(buffer, read, length - read)
if (n < 0) break
read += n
}
String(buffer, 0, read)
} else {
""
}
val (code, payload) = handler(parts[0], parts[1], headers, body)
val bytes = payload.toByteArray(Charsets.UTF_8)
val out = client.getOutputStream()
out.write(
("HTTP/1.1 $code OK\r\n" +
"Content-Type: application/json\r\n" +
"Content-Length: ${bytes.size}\r\n" +
"Connection: close\r\n\r\n").toByteArray(Charsets.UTF_8)
)
out.write(bytes)
out.flush()
}
} catch (t: Throwable) {
if (socket.isClosed) return@thread
}
}
}
fun close() {
try {
socket.close()
} catch (t: Throwable) {
// Already closed.
}
worker.join(1000)
}
}
@@ -0,0 +1,87 @@
package dev.lotherk.kidstube.remote
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/** Parsing and mapping rules, no network, no Android. */
class JellyfinTest {
@Test
fun normalizesServerAddresses() {
assertEquals("http://192.168.1.10:8096", Jellyfin.normalizeServer("192.168.1.10:8096"))
assertEquals("http://192.168.1.10:8096", Jellyfin.normalizeServer(" 192.168.1.10:8096/ "))
assertEquals("https://media.example.org", Jellyfin.normalizeServer("https://media.example.org/"))
assertEquals("https://media.example.org", Jellyfin.normalizeServer("https://media.example.org"))
assertNull(Jellyfin.normalizeServer(""))
assertNull(Jellyfin.normalizeServer(" "))
}
@Test
fun onlyVideoLibrariesAreOffered() {
assertTrue(Jellyfin.isVideoLibrary("movies"))
assertTrue(Jellyfin.isVideoLibrary("tvshows"))
assertTrue(Jellyfin.isVideoLibrary("homevideos"))
assertTrue(Jellyfin.isVideoLibrary(null))
assertFalse(Jellyfin.isVideoLibrary("music"))
assertFalse(Jellyfin.isVideoLibrary("books"))
assertFalse(Jellyfin.isVideoLibrary("livetv"))
}
@Test
fun episodesGetTheNumericPrefixTheLocalFilesUse() {
val item = JfItem("e1", "The Pilot", "Episode", "Bluey", 1, 3, 0, null, null)
assertEquals("003 - The Pilot", RemoteMapping.displayTitle(item))
val later = JfItem("e2", "Sleepytime", "Episode", "Bluey", 2, 4, 0, null, null)
assertEquals("204 - Sleepytime", RemoteMapping.displayTitle(later))
val movie = JfItem("m1", "Cars", "Movie", null, null, null, 0, null, null)
assertEquals("Cars", RemoteMapping.displayTitle(movie))
}
@Test
fun showBecomesTheFolderMovieUsesItsLibrary() {
val episode = JfItem("e1", "Pilot", "Episode", "Bluey", 1, 1, 600_000_000, "p", "b")
val mapped = RemoteMapping.toMediaItem("http://s", "tok", "Kids Movies", episode)!!
assertEquals("Bluey", mapped.folder)
assertEquals("001 - Pilot", mapped.title)
assertEquals(60_000L, mapped.durationMs)
assertTrue(mapped.uri.contains("/Videos/e1/stream"))
assertTrue(mapped.uri.contains("static=true"))
assertTrue(mapped.thumbUrl!!.contains("/Images/Backdrop/0"))
val movie = JfItem("m1", "Cars", "Movie", null, null, null, 0, "primary", null)
val movieMapped = RemoteMapping.toMediaItem("http://s", "tok", "Kids Movies", movie)!!
assertEquals("Kids Movies", movieMapped.folder)
assertEquals("Cars", movieMapped.title)
assertEquals(0L, movieMapped.durationMs)
assertTrue(movieMapped.thumbUrl!!.contains("/Images/Primary"))
}
@Test
fun keySurvivesANewTokenButNotANewServer() {
val item = JfItem("e1", "Pilot", "Episode", "Bluey", 1, 1, 0, null, null)
val first = RemoteMapping.toMediaItem("http://s", "token-a", "Kids", item)!!
val second = RemoteMapping.toMediaItem("http://s", "token-b", "Kids", item)!!
val otherServer = RemoteMapping.toMediaItem("http://other", "token-a", "Kids", item)!!
assertEquals(first.key, second.key)
assertTrue(first.key != otherServer.key)
assertTrue(first.uri != second.uri)
}
@Test
fun itemSurvivesTheDiskCache() {
val item = JfItem("e1", "Pilot", "Episode", "Bluey", 2, 7, 123, "p", "b")
val restored = jfItemFromJson(item.toJson())!!
assertEquals(item, restored)
}
@Test
fun missingArtworkIsNotAnImageUrl() {
val item = JfItem("m1", "Cars", "Movie", null, null, null, 0, null, null)
assertNull(RemoteMapping.toMediaItem("http://s", "t", "Kids", item)!!.thumbUrl)
}
}