From 01359f1348453a4f0c580ed9ee6dfd04221b9dfe Mon Sep 17 00:00:00 2001 From: lotherk Date: Thu, 29 Oct 2026 19:00:16 +0000 Subject: [PATCH] Jellyfin remotes and a pause button in the player --- AGENTS.md | 116 +++++-- app/build.gradle.kts | 3 + app/src/main/AndroidManifest.xml | 14 +- .../java/dev/lotherk/kidstube/data/Catalog.kt | 27 ++ .../java/dev/lotherk/kidstube/data/Keys.kt | 17 + .../java/dev/lotherk/kidstube/data/Library.kt | 17 +- .../dev/lotherk/kidstube/data/MediaItem.kt | 17 +- .../java/dev/lotherk/kidstube/data/Series.kt | 37 +- .../dev/lotherk/kidstube/media/ThumbCache.kt | 49 ++- .../dev/lotherk/kidstube/remote/Jellyfin.kt | 317 ++++++++++++++++++ .../lotherk/kidstube/remote/RemoteCache.kt | 64 ++++ .../lotherk/kidstube/remote/RemoteCatalog.kt | 230 +++++++++++++ .../lotherk/kidstube/remote/RemoteLibrary.kt | 21 ++ .../lotherk/kidstube/remote/RemoteMapping.kt | 52 +++ .../lotherk/kidstube/remote/RemoteStore.kt | 80 +++++ .../dev/lotherk/kidstube/remote/SecretBox.kt | 92 +++++ .../dev/lotherk/kidstube/stats/StatsDb.kt | 5 +- .../dev/lotherk/kidstube/ui/MainActivity.kt | 111 ++++-- .../dev/lotherk/kidstube/ui/PlayerActivity.kt | 51 ++- .../kidstube/ui/RemoteLibrariesActivity.kt | 264 +++++++++++++++ app/src/main/res/drawable/ic_pause.xml | 10 + app/src/main/res/drawable/ic_play.xml | 10 + app/src/main/res/layout/activity_player.xml | 13 + app/src/main/res/layout/activity_remote.xml | 67 ++++ app/src/main/res/values/strings.xml | 23 +- .../dev/lotherk/kidstube/data/CatalogTest.kt | 46 +++ .../kidstube/remote/JellyfinClientTest.kt | 234 +++++++++++++ .../lotherk/kidstube/remote/JellyfinTest.kt | 87 +++++ 28 files changed, 1983 insertions(+), 91 deletions(-) create mode 100644 app/src/main/java/dev/lotherk/kidstube/data/Catalog.kt create mode 100644 app/src/main/java/dev/lotherk/kidstube/data/Keys.kt create mode 100644 app/src/main/java/dev/lotherk/kidstube/remote/Jellyfin.kt create mode 100644 app/src/main/java/dev/lotherk/kidstube/remote/RemoteCache.kt create mode 100644 app/src/main/java/dev/lotherk/kidstube/remote/RemoteCatalog.kt create mode 100644 app/src/main/java/dev/lotherk/kidstube/remote/RemoteLibrary.kt create mode 100644 app/src/main/java/dev/lotherk/kidstube/remote/RemoteMapping.kt create mode 100644 app/src/main/java/dev/lotherk/kidstube/remote/RemoteStore.kt create mode 100644 app/src/main/java/dev/lotherk/kidstube/remote/SecretBox.kt create mode 100644 app/src/main/java/dev/lotherk/kidstube/ui/RemoteLibrariesActivity.kt create mode 100644 app/src/main/res/drawable/ic_pause.xml create mode 100644 app/src/main/res/drawable/ic_play.xml create mode 100644 app/src/main/res/layout/activity_remote.xml create mode 100644 app/src/test/java/dev/lotherk/kidstube/data/CatalogTest.kt create mode 100644 app/src/test/java/dev/lotherk/kidstube/remote/JellyfinClientTest.kt create mode 100644 app/src/test/java/dev/lotherk/kidstube/remote/JellyfinTest.kt diff --git a/AGENTS.md b/AGENTS.md index a39e78c..517650a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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//`, `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//`, and the export is `stats-.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 diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 4ea3b2c..97e3ee8 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -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") } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 51e9908..1eec319 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,19 +2,25 @@ + READ_MEDIA_VIDEO from API 33. --> + + + + android:theme="@style/Theme.KidsTube" + android:usesCleartextTraffic="true"> + + , remote: List): List { + val out = ArrayList(local.size + remote.size) + out.addAll(local) + out.addAll(remote) + return out.sortedWith( + compareBy { 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): Int { + var hash = items.size + for (item in items) hash = hash * 31 + item.key.hashCode() + return hash + } +} diff --git a/app/src/main/java/dev/lotherk/kidstube/data/Keys.kt b/app/src/main/java/dev/lotherk/kidstube/data/Keys.kt new file mode 100644 index 0000000..621f3ef --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/data/Keys.kt @@ -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() + } +} diff --git a/app/src/main/java/dev/lotherk/kidstube/data/Library.kt b/app/src/main/java/dev/lotherk/kidstube/data/Library.kt index 2796d29..5aa012c 100644 --- a/app/src/main/java/dev/lotherk/kidstube/data/Library.kt +++ b/app/src/main/java/dev/lotherk/kidstube/data/Library.kt @@ -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) { 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) } diff --git a/app/src/main/java/dev/lotherk/kidstube/data/MediaItem.kt b/app/src/main/java/dev/lotherk/kidstube/data/MediaItem.kt index a8695da..65d40b0 100644 --- a/app/src/main/java/dev/lotherk/kidstube/data/MediaItem.kt +++ b/app/src/main/java/dev/lotherk/kidstube/data/MediaItem.kt @@ -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 diff --git a/app/src/main/java/dev/lotherk/kidstube/data/Series.kt b/app/src/main/java/dev/lotherk/kidstube/data/Series.kt index 1446f8e..4c0154a 100644 --- a/app/src/main/java/dev/lotherk/kidstube/data/Series.kt +++ b/app/src/main/java/dev/lotherk/kidstube/data/Series.kt @@ -71,28 +71,33 @@ object Series { val used = hashSetOf(current.key) val out = ArrayList(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) } diff --git a/app/src/main/java/dev/lotherk/kidstube/media/ThumbCache.kt b/app/src/main/java/dev/lotherk/kidstube/media/ThumbCache.kt index ecced27..d115f31 100644 --- a/app/src/main/java/dev/lotherk/kidstube/media/ThumbCache.kt +++ b/app/src/main/java/dev/lotherk/kidstube/media/ThumbCache.kt @@ -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() + ) + 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. diff --git a/app/src/main/java/dev/lotherk/kidstube/remote/Jellyfin.kt b/app/src/main/java/dev/lotherk/kidstube/remote/Jellyfin.kt new file mode 100644 index 0000000..d07f900 --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/remote/Jellyfin.kt @@ -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 { + 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(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 { + val out = ArrayList() + 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" } + ) +} diff --git a/app/src/main/java/dev/lotherk/kidstube/remote/RemoteCache.kt b/app/src/main/java/dev/lotherk/kidstube/remote/RemoteCache.kt new file mode 100644 index 0000000..c7e5507 --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/remote/RemoteCache.kt @@ -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? { + 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(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) { + 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. + } + } +} diff --git a/app/src/main/java/dev/lotherk/kidstube/remote/RemoteCatalog.kt b/app/src/main/java/dev/lotherk/kidstube/remote/RemoteCatalog.kt new file mode 100644 index 0000000..c51b7ab --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/remote/RemoteCatalog.kt @@ -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>() + private val verifiedAt = HashMap() + private val listeners = ArrayList<(List) -> 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 = synchronized(lock) { + val out = ArrayList() + 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) -> 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) { + 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) + } + } +} diff --git a/app/src/main/java/dev/lotherk/kidstube/remote/RemoteLibrary.kt b/app/src/main/java/dev/lotherk/kidstube/remote/RemoteLibrary.kt new file mode 100644 index 0000000..888fbe2 --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/remote/RemoteLibrary.kt @@ -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" + } +} diff --git a/app/src/main/java/dev/lotherk/kidstube/remote/RemoteMapping.kt b/app/src/main/java/dev/lotherk/kidstube/remote/RemoteMapping.kt new file mode 100644 index 0000000..7321967 --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/remote/RemoteMapping.kt @@ -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 + ): List = 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) + } +} diff --git a/app/src/main/java/dev/lotherk/kidstube/remote/RemoteStore.kt b/app/src/main/java/dev/lotherk/kidstube/remote/RemoteStore.kt new file mode 100644 index 0000000..7473ea4 --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/remote/RemoteStore.kt @@ -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 { + 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) { + 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") + ) + } +} diff --git a/app/src/main/java/dev/lotherk/kidstube/remote/SecretBox.kt b/app/src/main/java/dev/lotherk/kidstube/remote/SecretBox.kt new file mode 100644 index 0000000..d380364 --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/remote/SecretBox.kt @@ -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() + } +} diff --git a/app/src/main/java/dev/lotherk/kidstube/stats/StatsDb.kt b/app/src/main/java/dev/lotherk/kidstube/stats/StatsDb.kt index c8907a0..32c4f12 100644 --- a/app/src/main/java/dev/lotherk/kidstube/stats/StatsDb.kt +++ b/app/src/main/java/dev/lotherk/kidstube/stats/StatsDb.kt @@ -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) ?: "" diff --git a/app/src/main/java/dev/lotherk/kidstube/ui/MainActivity.kt b/app/src/main/java/dev/lotherk/kidstube/ui/MainActivity.kt index 3007324..782c635 100644 --- a/app/src/main/java/dev/lotherk/kidstube/ui/MainActivity.kt +++ b/app/src/main/java/dev/lotherk/kidstube/ui/MainActivity.kt @@ -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 = emptyList() + private var localItems: List = emptyList() private var folders: List = 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 = 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) { + 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 { + 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) { 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) diff --git a/app/src/main/java/dev/lotherk/kidstube/ui/PlayerActivity.kt b/app/src/main/java/dev/lotherk/kidstube/ui/PlayerActivity.kt index 9136671..ec4aada 100644 --- a/app/src/main/java/dev/lotherk/kidstube/ui/PlayerActivity.kt +++ b/app/src/main/java/dev/lotherk/kidstube/ui/PlayerActivity.kt @@ -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() { diff --git a/app/src/main/java/dev/lotherk/kidstube/ui/RemoteLibrariesActivity.kt b/app/src/main/java/dev/lotherk/kidstube/ui/RemoteLibrariesActivity.kt new file mode 100644 index 0000000..eed52b3 --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/ui/RemoteLibrariesActivity.kt @@ -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 + ) { + 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() +} diff --git a/app/src/main/res/drawable/ic_pause.xml b/app/src/main/res/drawable/ic_pause.xml new file mode 100644 index 0000000..0211aad --- /dev/null +++ b/app/src/main/res/drawable/ic_pause.xml @@ -0,0 +1,10 @@ + + + + diff --git a/app/src/main/res/drawable/ic_play.xml b/app/src/main/res/drawable/ic_play.xml new file mode 100644 index 0000000..30ae04d --- /dev/null +++ b/app/src/main/res/drawable/ic_play.xml @@ -0,0 +1,10 @@ + + + + diff --git a/app/src/main/res/layout/activity_player.xml b/app/src/main/res/layout/activity_player.xml index 4f1feb2..c10236b 100644 --- a/app/src/main/res/layout/activity_player.xml +++ b/app/src/main/res/layout/activity_player.xml @@ -56,6 +56,19 @@ android:src="@drawable/ic_heart" app:tint="@android:color/white" /> + + + + + + + + + + + + + + + + + +