Files

204 lines
12 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# KidsTube
Android app that reproduces the **iOS** YouTube Kids interface over a **local
folder**: 3x3 tile grid, category pills, fullscreen player, four-tab bar. No
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
- 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`
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
next to top bar, pills and tab bar (they need ~340dp, the grid has ~216dp), so
the third row is reached by scrolling rather than by shrinking the tiles —
half-width tiles with wide gaps read as a zoomed-out page.
- When the choice is "Material default" vs "the iOS app's proportions", take iOS.
## Environment (this machine, verified)
- JDK 21 (`/usr/lib/jvm/java-21-openjdk-amd64`); no JDK 8 or 17.
- SDK in `/home/lotherk/android-sdk`. The distro's `/usr/lib/android-sdk` has no
`platforms/` or `build-tools/`, and its bundled `sdkmanager` dies on JDK 21
(`NoClassDefFoundError: javax/xml/bind/...`, JAXB removed in JDK 11).
- `gradle` is not on PATH; the standalone distribution is
`/home/lotherk/android-tools/gradle-8.13`. Wrapper pinned to 8.13,
`local.properties` points at the SDK.
- AGP 8.13.2, Kotlin 2.1.20, compileSdk 35, build-tools 35.0.0. AGP 8.13 needs
Gradle >= 8.13, Build-Tools >= 35.0.0, JDK >= 17.
## Build, test, run
export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
export ANDROID_HOME=/home/lotherk/android-sdk
./gradlew :app:assembleDebug # apk -> app/build/outputs/apk/debug/
./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
adb shell am start -n dev.lotherk.kidstube/.ui.MainActivity
adb exec-out screencap -p > /tmp/kt.png
Target device: Huawei AGS2-W09, LineageOS 18.1, API 30, arm64-v8a, 1200x1920 at
480 dpi — 640dp wide in landscape. API 21 cannot be exercised here (no emulator
image installed).
## Content
Library is `Movies/KidsTube`, scanned via MediaStore; a SAF tree picked behind
the parent gate takes precedence. Copying needs a scan:
adb push video.mp4 /sdcard/Movies/KidsTube/
adb shell am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file:///sdcard/Movies/KidsTube/video.mp4
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; 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; 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. 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. "Your stuff" is filtered
against the current catalogue, so a liked remote video disappears with its
server.
## Pitfalls
- Never size tiles from whichever list is visible: the search tab is shorter
(56dp bar) and shrank the tiles for every tab.
- `content delete --uri content://media/external/video/media/<id>` deletes the
media **file** as well, not just the row. Only use it for rows whose file is
already gone; a broad `WHERE name LIKE ...` pattern once took seven real videos
with it (recoverable only because the originals were still on the host).
- Filenames must be ASCII. Fullwidth `|`/`:` or emoji in the name make
`MEDIA_SCANNER_SCAN_FILE` succeed with nothing indexed, so the video stays
invisible; renaming to ASCII and broadcasting again indexes it.
- The tablet's USB link dies every minute or two. `adb tcpip 5555` +
`adb connect <ip>:5555` keeps the session alive (`adb -s <ip>:5555 …`).
- The search `TextWatcher` must not run on other tabs. `selectTab` clears the
field, that fires `afterTextChanged`, and an unguarded `applyFilter("")` refills
the result list with the whole library — which is why "Your stuff" showed every
video. Clear the field first, submit the tab's own list afterwards.
- `VideoView` swallows touches; the player needs the transparent `tap_catcher`
to bring the chrome back.
- Tint AppCompat widgets with `app:tint`, never `android:tint` — lint fails on
`UseAppTint`, and the vectors are white, so a missing tint hides the icon.
- The tablet's adbd crash-loops (`Could not install *smartsocket* listener`) and
the device then vanishes from `lsusb`. Re-plugging the cable brings it back; a
missing device is the hardware, not the app.
- `uiautomator dump` takes seconds here, longer than the 4s chrome timeout, so a
dump right after a tap shows stale state. Screenshot instead.
- The tablet randomly brings up the camera app. Force-stop `com.android.camera2`
and restart the activity if the focus looks wrong.
- 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
Initialised locally, no remote yet; Konrad's convention is `origin` = hiddenbox
when one is added. Short imperative commit subjects.