diff --git a/AGENTS.md b/AGENTS.md index d1bc814..096b5fd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,106 +1,106 @@ # KidsTube -Android app that reproduces the **iOS** YouTube Kids interface — thumbnail -shelves, fullscreen player, bottom bar — while playing video from a **local -folder only**. No network, no account, no recommendations. It exists because the -son accepts the iOS kids UI and rejects the Android one, so this is a convincing -shell around local files. Floor: Android 5.0 / API 21. App name: 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 +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. +Floor: Android 5.0 / API 21. App name: KidsTube. -State 2026-10-28: builds, installs and plays on the target tablet; shelves, -search, player and the parent gate were verified on the device. +**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 must carry no `INTERNET` permission and no HTTP client: +- 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` - must print `0`, and + prints `0`, and `/home/lotherk/android-sdk/build-tools/35.0.0/aapt2 dump permissions app/build/outputs/apk/debug/app-debug.apk` - must list only the two storage permissions. -- `minSdk` stays 21. Check any new AAR's `minSdk` before adding it — much of - current androidx sits at 23+. + lists only the two storage permissions. +- `minSdk` stays `21`. Check every new AAR's `minSdk` before adding it. +- Grid is always **3 columns**, and exactly **3 rows must fit** the landscape + screen without scrolling. The title lives *inside* the tile — a caption row + below it costs the height those three rows need. - 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 installed. -- SDK lives in `/home/lotherk/android-sdk` (user-local). The distro's - `/usr/lib/android-sdk` has no `platforms/` or `build-tools/`, and its bundled - `sdkmanager`/`apkanalyzer` die on JDK 21 with `NoClassDefFoundError: - javax/xml/bind/annotation/XmlSchema` (JAXB removed in JDK 11) — do not use it. +- 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`. The wrapper is pinned to 8.13 and + `/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 requires +- 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, install, run +## 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:lintDebug # must stay green; abortOnError = true + ./gradlew :app:testDebugUnitTest # Series rules, no device needed + ./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 - adb logcat -d | grep -E 'kidstube|AndroidRuntime' -Target device: Huawei AGS2-W09, LineageOS 18.1 (`18.1-20220523-UNOFFICIAL-prague`), -Android 11 / API 30, arm64-v8a, 1200x1920 at 480 dpi = 400dp wide. API 21 cannot -be exercised here — that needs an emulator image and none is installed. +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 -The library is `Movies/KidsTube` (`/storage/emulated/0/Movies/KidsTube`), scanned -through MediaStore; a SAF tree picked from the Profile screen takes precedence. -Copy files with +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 -The broadcast is not optional: a pushed file stays invisible until MediaStore -indexes it, and from API 29 scoped storage forbids directory listing (the app uid -gets `EACCES`), so there is no fallback route. +Mandatory: from API 29 scoped storage forbids directory listing (the app uid gets +`EACCES`), and a pushed file stays invisible until MediaStore indexes it. -## Layout and conventions +## Code map -- `data/` — `Library` (SAF tree, else MediaStore; folder grouping; `MediaItem` - carries a sha1 `key`), `MediaItem`. -- `media/ThumbCache` — decode via `MediaMetadataRetriever`, write JPEGs to - `filesDir/thumbs`, `LruCache` in memory, 3-thread pool, tag-guarded binds. -- `ui/` — `MainActivity` (shelves, search grid, parent gate), `SectionAdapter` - (vertical shelves, each a horizontal RecyclerView), `VideoAdapter` (modes HERO / - CAROUSEL / GRID), `PlayerActivity` (VideoView, immersive, auto-hiding chrome), - `ThumbView`. -- `ThumbView` owns the two numbers the look depends on — 16:9 and 12dp corner - radius — plus the duration pill. Never re-implement them per layout. -- Kotlin + Views + AppCompat, single `:app` module, viewBinding, no Compose. - Every dimension in dp/sp, designed against 400dp width. +- `data/Library` — SAF tree else MediaStore; `MediaItem`; sorted by folder then + `Series.naturalOrder` (leading `001`, `002` … numeric, not lexical). +- `data/Series` — ordering plus the player's suggestion rule, pure and unit + tested: slots are `[random, previous of the series, next of the series, random]`. +- `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. +- `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. `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, and a finished video rolls into a random one. +- `stats/StatsDb` — SQLite: `sessions` (plays, watched ms, per day) and `likes`. + Mirrored to `getExternalFilesDir()/stats.json` for another process to pull. ## Pitfalls -- `reload()` must treat "no SAF tree, storage permission granted" as a valid - source. Gating on the tree alone silently shows an empty home screen. -- `VideoView` swallows touches, so its `OnClickListener` never fires; the player - uses a transparent `tap_catcher` view above it to bring the chrome back. -- Tint AppCompat widgets with `app:tint`, never `android:tint` — lint fails the - build on `UseAppTint`, and the vector drawables are white by default, so a - missing tint makes an icon invisible rather than obviously wrong. -- The system "Viewing full screen" confirmation appears on first launch and holds - focus — dismiss it before trusting any UI dump. +- Never size tiles from whichever list is visible: the search tab is shorter + (56dp bar) and shrank the tiles for every tab. +- `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. -- adbd on the device crash-loops (`Could not install *smartsocket* listener`); a - dropped `adb` connection is the device, not the app. Reconnect and check - `sys.boot_completed`. -- The tablet randomly brings up the camera app between commands. Force-stop - `com.android.camera2` and restart the activity if the focus looks wrong. -- File paths: `/storage/emulated/0` is the real mount; `/sdcard` works for `ls` - but not for `df`. +- 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`. ## Repo -Initialised locally (one commit), no remote yet; Konrad's convention is `origin` -= hiddenbox when one is added. Short imperative commit subjects, no -conventional-commit prefixes. +Initialised locally, no remote yet; Konrad's convention is `origin` = hiddenbox +when one is added. Short imperative commit subjects. diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 21da632..4ea3b2c 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -45,4 +45,6 @@ dependencies { implementation("androidx.appcompat:appcompat:1.7.0") implementation("androidx.recyclerview:recyclerview:1.3.2") implementation("androidx.documentfile:documentfile:1.0.1") + + testImplementation("junit:junit:4.13.2") } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index bf841e1..51e9908 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -18,14 +18,15 @@ + android:exported="true"> + + = Comparator { a, b -> + val na = LEADING_NUMBER.find(a.title)?.groupValues?.get(1)?.toLongOrNull() + val nb = LEADING_NUMBER.find(b.title)?.groupValues?.get(1)?.toLongOrNull() + when { + na != null && nb != null -> if (na != nb) na.compareTo(nb) else a.title.compareTo(b.title) + na != null -> -1 + nb != null -> 1 + else -> a.title.compareTo(b.title, ignoreCase = true) + } + } + + /** The current video's neighbours inside its own folder. */ + fun neighbours(all: List, current: T): Pair { + val series = all.filter { it.folder == current.folder }.sortedWith(naturalOrder) + val index = series.indexOfFirst { it.key == current.key } + if (index < 0) return null to null + val previous = if (index > 0) series[index - 1] else null + val next = if (index < series.size - 1) series[index + 1] else null + return previous to next + } + + fun suggestionsFor(all: List, current: T, size: Int = 4): List { + val (previous, next) = neighbours(all, current) + val used = hashSetOf(current.key) + previous?.let { used.add(it.key) } + next?.let { used.add(it.key) } + + val rest = all.filter { it.key !in used }.shuffled().iterator() + val out = ArrayList(size) + + fun takeRandom() { + while (rest.hasNext() && out.size < size) { + val candidate = rest.next() + if (out.none { it.key == candidate.key }) { + out.add(candidate) + return + } + } + } + + takeRandom() + previous?.let { if (out.size < size) out.add(it) } + next?.let { if (out.size < size) out.add(it) } + takeRandom() + while (out.size < size && rest.hasNext()) { + val candidate = rest.next() + if (out.none { it.key == candidate.key }) out.add(candidate) + } + return out + } +} diff --git a/app/src/main/java/dev/lotherk/kidstube/data/SeriesItem.kt b/app/src/main/java/dev/lotherk/kidstube/data/SeriesItem.kt new file mode 100644 index 0000000..4b77825 --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/data/SeriesItem.kt @@ -0,0 +1,8 @@ +package dev.lotherk.kidstube.data + +/** The parts of a video that ordering and suggestion rules need. */ +interface SeriesItem { + val key: String + val title: String + val folder: String +} 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 ceecb57..0ea326b 100644 --- a/app/src/main/java/dev/lotherk/kidstube/media/ThumbCache.kt +++ b/app/src/main/java/dev/lotherk/kidstube/media/ThumbCache.kt @@ -6,10 +6,11 @@ import android.graphics.BitmapFactory import android.media.MediaMetadataRetriever import android.os.Handler import android.os.Looper +import android.util.Log import android.util.LruCache import dev.lotherk.kidstube.data.Library import dev.lotherk.kidstube.data.MediaItem -import dev.lotherk.kidstube.ui.ThumbView +import android.view.View import java.io.File import java.util.Locale import java.util.concurrent.Executors @@ -35,29 +36,36 @@ object ThumbCache { return if (ms > 0) formatDuration(ms) else null } - fun load(context: Context, item: MediaItem, view: ThumbView) { + fun memory(key: String): Bitmap? = memory.get(key) + + fun load( + context: Context, + item: MediaItem, + view: View, + apply: (Bitmap?, String?) -> Unit + ) { val key = item.key view.tag = key memory.get(key)?.let { - view.setThumb(it, label(context, item)) + apply(it, label(context, item)) return } val fromDisk = readDisk(context, item) if (fromDisk != null) { memory.put(key, fromDisk) - view.setThumb(fromDisk, label(context, item)) + apply(fromDisk, label(context, item)) return } - view.setThumb(null, label(context, item)) + apply(null, label(context, item)) val app = context.applicationContext pool.execute { val data = generateThumb(app, item) main.post { if (data.bitmap != null) memory.put(key, data.bitmap) - if (view.tag == key) view.setThumb(data.bitmap, data.label) + if (view.tag == key) apply(data.bitmap, data.label) } } } @@ -76,17 +84,14 @@ object ThumbCache { val durationMs = retriever .extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION) ?.toLongOrNull() ?: 0L - val frame = retriever.getFrameAtTime( - if (durationMs > 3000) 1_000_000L else 0L, - MediaMetadataRetriever.OPTION_CLOSEST_SYNC - ) - val scaled = frame?.let { scaleToWidth(it, THUMB_WIDTH) } + val scaled = pickFrame(retriever, durationMs)?.let { scaleToWidth(it, THUMB_WIDTH) } if (scaled != null) writeDisk(context, item, scaled) if (durationMs > 0) { Library.prefs(context).edit().putLong("dur_" + item.key, durationMs).apply() } return ThumbData(scaled, if (durationMs > 0) formatDuration(durationMs) else null) } catch (t: Throwable) { + Log.w("kidstube", "thumb failed: " + item.title + ": " + t) return ThumbData(null, null) } finally { try { @@ -96,6 +101,57 @@ object ThumbCache { } } + + /** + * Videos often open on a fade from black, so the first second is a black + * frame. Sample several offsets and keep the brightest one. + */ + private fun pickFrame(retriever: MediaMetadataRetriever, durationMs: Long): Bitmap? { + val offsets = if (durationMs > 5000) { + longArrayOf(durationMs / 10, durationMs / 4, durationMs / 2) + } else { + longArrayOf(0L) + } + var best: Bitmap? = null + var bestScore = -1.0 + for (offset in offsets) { + val frame = try { + retriever.getFrameAtTime(offset * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC) + } catch (t: Throwable) { + null + } ?: continue + val score = brightness(frame) + if (score > bestScore) { + best?.recycle() + best = frame + bestScore = score + } else { + frame.recycle() + } + if (bestScore > 40.0) break + } + return best + } + + private fun brightness(bitmap: Bitmap): Double { + var sum = 0.0 + var count = 0 + val stepX = (bitmap.width / 16).coerceAtLeast(1) + val stepY = (bitmap.height / 16).coerceAtLeast(1) + var y = 0 + while (y < bitmap.height) { + var x = 0 + while (x < bitmap.width) { + val c = bitmap.getPixel(x, y) + sum += ((c shr 16 and 0xFF) + (c shr 8 and 0xFF) + (c and 0xFF)) / 3.0 + count++ + x += stepX + } + y += stepY + } + return if (count == 0) 0.0 else sum / count + } + private fun scaleToWidth(source: Bitmap, width: Int): Bitmap { if (source.width <= width) return source val height = (source.height.toFloat() * width / source.width).toInt().coerceAtLeast(1) @@ -103,7 +159,7 @@ object ThumbCache { } private fun fileFor(context: Context, item: MediaItem): File = - File(File(context.filesDir, "thumbs"), item.key + ".jpg") + File(File(context.filesDir, "thumbs"), item.key + "_v2.jpg") private fun readDisk(context: Context, item: MediaItem): Bitmap? { val file = fileFor(context, item) diff --git a/app/src/main/java/dev/lotherk/kidstube/stats/StatsDb.kt b/app/src/main/java/dev/lotherk/kidstube/stats/StatsDb.kt new file mode 100644 index 0000000..caf9f1f --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/stats/StatsDb.kt @@ -0,0 +1,272 @@ +package dev.lotherk.kidstube.stats + +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 +import java.io.File +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +/** + * Local watch history. One row per playback session, no network, no account. + * + * Everything the parent view shows is a query over this table, and the same data + * is mirrored to a JSON file under the app's external files dir so another + * process can read it with `adb pull`. + */ +class StatsDb(context: Context) : + SQLiteOpenHelper(context.applicationContext, NAME, null, VERSION) { + + private val appContext: Context = context.applicationContext + + companion object { + private const val NAME = "stats.db" + private const val VERSION = 3 + private const val MIN_SESSION_MS = 1500L + } + + override fun onCreate(db: SQLiteDatabase) { + db.execSQL( + """ + CREATE TABLE sessions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + video_key TEXT NOT NULL, + uri TEXT NOT NULL, + title TEXT NOT NULL, + folder TEXT NOT NULL, + started_at INTEGER NOT NULL, + watched_ms INTEGER NOT NULL, + completed INTEGER NOT NULL + ) + """.trimIndent() + ) + db.execSQL("CREATE INDEX idx_sessions_started ON sessions(started_at)") + db.execSQL( + """ + CREATE TABLE likes ( + video_key TEXT PRIMARY KEY, + uri TEXT NOT NULL, + title TEXT NOT NULL, + folder TEXT NOT NULL, + liked_at INTEGER NOT NULL + ) + """.trimIndent() + ) + } + + override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { + if (oldVersion < 2) { + db.execSQL("ALTER TABLE sessions ADD COLUMN uri TEXT NOT NULL DEFAULT ''") + } + if (oldVersion < 3) { + db.execSQL( + """ + CREATE TABLE IF NOT EXISTS likes ( + video_key TEXT PRIMARY KEY, + uri TEXT NOT NULL, + title TEXT NOT NULL, + folder TEXT NOT NULL, + liked_at INTEGER NOT NULL + ) + """.trimIndent() + ) + } + } + + fun record(item: MediaItem, startedAt: Long, watchedMs: Long, completed: Boolean) { + if (watchedMs < MIN_SESSION_MS) return + val values = ContentValues().apply { + put("video_key", item.key) + put("uri", item.uri.toString()) + put("title", item.title) + put("folder", item.folder) + put("started_at", startedAt) + put("watched_ms", watchedMs) + put("completed", if (completed) 1 else 0) + } + writableDatabase.insert("sessions", null, values) + exportJson() + } + + class VideoStat(val title: String, val plays: Int, val watchedMs: Long) + + fun totals(): LongArray { + var plays = 0 + var watched = 0L + readableDatabase.rawQuery( + "SELECT COUNT(*), COALESCE(SUM(watched_ms),0) FROM sessions", null + ).use { c -> + if (c.moveToFirst()) { + plays = c.getInt(0) + watched = c.getLong(1) + } + } + var videos = 0 + readableDatabase.rawQuery( + "SELECT COUNT(DISTINCT video_key) FROM sessions", null + ).use { c -> if (c.moveToFirst()) videos = c.getInt(0) } + return longArrayOf(plays.toLong(), watched, videos.toLong()) + } + + fun topVideos(limit: Int = 15): List { + val out = ArrayList() + readableDatabase.rawQuery( + """ + SELECT title, COUNT(*) AS plays, SUM(watched_ms) AS ms + FROM sessions GROUP BY video_key ORDER BY ms DESC LIMIT ? + """.trimIndent(), + arrayOf(limit.toString()) + ).use { c -> + while (c.moveToNext()) { + out.add(VideoStat(c.getString(0), c.getInt(1), c.getLong(2))) + } + } + return out + } + + /** Plays and watch time per day, newest first. */ + fun perDay(days: Int = 14): List> { + val out = ArrayList>() + val format = SimpleDateFormat("yyyy-MM-dd", Locale.US) + readableDatabase.rawQuery( + """ + SELECT strftime('%Y-%m-%d', started_at/1000, 'unixepoch', 'localtime') AS day, + COUNT(*), SUM(watched_ms) + FROM sessions GROUP BY day ORDER BY day DESC LIMIT ? + """.trimIndent(), + arrayOf(days.toString()) + ).use { c -> + while (c.moveToNext()) { + out.add(Triple(c.getString(0) ?: format.format(Date()), c.getInt(1), c.getLong(2))) + } + } + return out + } + + // --- likes: the only thing "Your stuff" shows ------------------------- + + fun isLiked(key: String): Boolean { + readableDatabase.rawQuery( + "SELECT 1 FROM likes WHERE video_key = ? LIMIT 1", arrayOf(key) + ).use { c -> return c.moveToFirst() } + } + + /** Returns the new state. */ + fun toggleLike(item: MediaItem): Boolean { + return if (isLiked(item.key)) { + writableDatabase.delete("likes", "video_key = ?", arrayOf(item.key)) + false + } else { + val values = ContentValues().apply { + put("video_key", item.key) + put("uri", item.uri.toString()) + put("title", item.title) + put("folder", item.folder) + put("liked_at", System.currentTimeMillis()) + } + writableDatabase.insertWithOnConflict( + "likes", null, values, SQLiteDatabase.CONFLICT_REPLACE + ) + true + } + } + + fun likedKeys(): Set { + val out = HashSet() + readableDatabase.rawQuery("SELECT video_key FROM likes", null).use { c -> + while (c.moveToNext()) out.add(c.getString(0)) + } + return out + } + + fun likedItems(): List { + val out = ArrayList() + readableDatabase.rawQuery( + "SELECT video_key, uri, title, folder FROM likes ORDER BY liked_at DESC", null + ).use { c -> + while (c.moveToNext()) { + out.add( + MediaItem( + uri = Uri.parse(c.getString(1)), + title = c.getString(2), + folder = c.getString(3), + key = c.getString(0) + ) + ) + } + } + return out + } + + /** Videos watched before, most recent first. */ + fun watchedItems(limit: Int = 60): List { + val out = ArrayList() + readableDatabase.rawQuery( + """ + SELECT video_key, uri, title, folder, MAX(started_at) AS last + FROM sessions WHERE uri != '' + GROUP BY video_key ORDER BY last DESC LIMIT ? + """.trimIndent(), + arrayOf(limit.toString()) + ).use { c -> + while (c.moveToNext()) { + val uri = c.getString(1) ?: continue + if (uri.isEmpty()) continue + out.add( + MediaItem( + uri = Uri.parse(uri), + title = c.getString(2) ?: "", + folder = c.getString(3) ?: "", + key = c.getString(0) ?: "" + ) + ) + } + } + return out + } + + /** Mirrors the history to a file another process can pull. */ + fun exportJson() { + try { + val dir = appContext.getExternalFilesDir(null) ?: appContext.filesDir + val totals = totals() + val root = JSONObject().apply { + put("updated_at", System.currentTimeMillis()) + put("plays", totals[0]) + put("watched_ms", totals[1]) + put("videos", totals[2]) + put("top", JSONArray().apply { + for (v in topVideos(50)) { + put( + JSONObject() + .put("title", v.title) + .put("plays", v.plays) + .put("watched_ms", v.watchedMs) + ) + } + }) + put("days", JSONArray().apply { + for ((day, plays, ms) in perDay(60)) { + put(JSONObject().put("day", day).put("plays", plays).put("watched_ms", ms)) + } + }) + } + File(dir, "stats.json").writeText(root.toString(2)) + } catch (t: Throwable) { + // Export is a convenience; the SQLite rows stay authoritative. + } + } + + fun formatMs(ms: Long): String { + val totalMinutes = ms / 60000 + val hours = totalMinutes / 60 + val minutes = totalMinutes % 60 + return if (hours > 0) "${hours}h ${minutes}m" else "${minutes}m" + } +} diff --git a/app/src/main/java/dev/lotherk/kidstube/ui/ChipAdapter.kt b/app/src/main/java/dev/lotherk/kidstube/ui/ChipAdapter.kt new file mode 100644 index 0000000..bf09f4b --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/ui/ChipAdapter.kt @@ -0,0 +1,56 @@ +package dev.lotherk.kidstube.ui + +import android.view.LayoutInflater +import android.view.ViewGroup +import android.widget.TextView +import androidx.core.content.ContextCompat +import androidx.recyclerview.widget.RecyclerView +import dev.lotherk.kidstube.R +import dev.lotherk.kidstube.databinding.ItemChipBinding + +/** + * Category pills: "All" plus one per folder. Single selection, white capsule for + * the active one and a dark capsule for the rest, as in the iPad app. + */ +class ChipAdapter( + private val labels: List, + private val onSelect: (Int) -> Unit +) : RecyclerView.Adapter() { + + private var selected = 0 + + fun select(index: Int) { + if (index == selected) return + val previous = selected + selected = index + notifyItemChanged(previous) + notifyItemChanged(selected) + } + + class Holder(val binding: ItemChipBinding) : RecyclerView.ViewHolder(binding.root) { + val label: TextView = binding.root + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { + val binding = ItemChipBinding.inflate(LayoutInflater.from(parent.context), parent, false) + return Holder(binding) + } + + override fun onBindViewHolder(holder: Holder, position: Int) { + val context = holder.itemView.context + holder.label.text = labels[position] + val isSelected = position == selected + holder.label.setBackgroundResource( + if (isSelected) R.drawable.bg_chip_active else R.drawable.bg_chip + ) + holder.label.setTextColor( + ContextCompat.getColor( + context, + if (isSelected) R.color.kt_chip_text_active else R.color.kt_text + ) + ) + holder.itemView.setOnClickListener { onSelect(position) } + } + + override fun getItemCount(): Int = labels.size +} 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 f2b71e2..c5a3f48 100644 --- a/app/src/main/java/dev/lotherk/kidstube/ui/MainActivity.kt +++ b/app/src/main/java/dev/lotherk/kidstube/ui/MainActivity.kt @@ -17,20 +17,27 @@ import androidx.recyclerview.widget.LinearLayoutManager import dev.lotherk.kidstube.R import dev.lotherk.kidstube.data.Library import dev.lotherk.kidstube.data.MediaItem +import dev.lotherk.kidstube.stats.StatsDb import dev.lotherk.kidstube.databinding.ActivityMainBinding import java.util.concurrent.Executors +import kotlin.math.min +import kotlin.math.roundToInt import kotlin.random.Random class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding - private val sectionAdapter = SectionAdapter { openPlayer(it) } - private val executor = Executors.newSingleThreadExecutor() - + private lateinit var gridAdapter: VideoAdapter private lateinit var resultsAdapter: VideoAdapter + private val executor = Executors.newSingleThreadExecutor() + private lateinit var stats: StatsDb + private var all: List = emptyList() + private var folders: List = emptyList() + private var selectedFolder: String? = null private var scanning = false private var activeTab = 0 + private var currentTileWidth = 0 private val openFolder = registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri -> @@ -47,19 +54,25 @@ class MainActivity : AppCompatActivity() { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) + stats = StatsDb(this) - binding.rows.layoutManager = LinearLayoutManager(this) - binding.rows.adapter = sectionAdapter + binding.grid.layoutManager = GridLayoutManager(this, columns()) + gridAdapter = VideoAdapter { openPlayer(it) } + binding.grid.adapter = gridAdapter - resultsAdapter = VideoAdapter(VideoAdapter.Mode.GRID) { openPlayer(it) } - binding.results.layoutManager = GridLayoutManager(this, 2) + binding.results.layoutManager = GridLayoutManager(this, columns()) + resultsAdapter = VideoAdapter { openPlayer(it) } binding.results.adapter = resultsAdapter + binding.chips.layoutManager = + LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) + binding.btnPick.setOnClickListener { pickFolder() } - binding.btnTopSearch.setOnClickListener { selectTab(1) } - binding.avatar.setOnClickListener { parentGate() } + binding.btnShield.setOnClickListener { parentGate() } + binding.btnGear.setOnClickListener { pickFolder() } binding.tabHome.setOnClickListener { selectTab(0) } binding.tabSearch.setOnClickListener { selectTab(1) } + binding.tabStuff.setOnClickListener { selectTab(2) } binding.tabProfile.setOnClickListener { parentGate() } binding.btnSearchClose.setOnClickListener { selectTab(0) } @@ -69,10 +82,46 @@ class MainActivity : AppCompatActivity() { override fun afterTextChanged(s: Editable?) = applyFilter(s?.toString().orEmpty()) }) + binding.grid.post { layoutTiles() } + selectTab(0) start() } + /** Always three across, so the overview reads as three rows of three. */ + private fun columns(): Int = 3 + + /** + * Tiles are sized from the available height so exactly three rows fit; the + * leftover width becomes the gaps (see [TileSpacing]). + */ + private fun layoutTiles() { + // Always measure the home grid: the other tabs have a shorter content + // area (search bar) and must not shrink the tiles for everybody. + val source = binding.grid + val width = source.width + val height = source.height + if (width <= 0 || height <= 0) return + val density = resources.displayMetrics.density + val rowGap = (8 * density).roundToInt() + val cell = width / columns() + // Every row carries a bottom gap, including the last, and the list has + // its own padding — both must come off before dividing by three, or the + // third row ends up under the tab bar. + val usable = height - source.paddingTop - source.paddingBottom - 3 * rowGap + val byHeight = ((usable / 3.0) * 16.0 / 9.0).toInt() + val tile = min(cell, byHeight).coerceAtLeast((120 * density).roundToInt()) + if (tile <= 0 || tile == currentTileWidth) return + currentTileWidth = tile + + for (list in listOf(binding.grid, binding.results)) { + while (list.itemDecorationCount > 0) list.removeItemDecorationAt(0) + list.addItemDecoration(TileSpacing(columns(), tile, rowGap)) + } + gridAdapter.tileWidth = tile + resultsAdapter.tileWidth = tile + } + /** Default folder needs a read permission once; a picked SAF tree does not. */ private fun start() { if (Library.treeUri(this) == null && !Library.hasReadPermission(this)) { @@ -92,7 +141,7 @@ class MainActivity : AppCompatActivity() { val hasSource = Library.treeUri(this) != null || Library.hasReadPermission(this) if (!hasSource) { all = emptyList() - sectionAdapter.submit(emptyList()) + gridAdapter.submit(emptyList()) refreshEmptyState() return } @@ -102,26 +151,39 @@ class MainActivity : AppCompatActivity() { runOnUiThread { scanning = false all = items - buildSections(items) - applyFilter(binding.searchInput.text?.toString().orEmpty()) + buildChips(items) + applyFolderFilter() + if (activeTab == 1) applyFilter(binding.searchInput.text?.toString().orEmpty()) + if (activeTab == 2) resultsAdapter.submit(stats.likedItems(), stats.likedKeys()) refreshEmptyState() } } } - private fun buildSections(items: List) { - if (items.isEmpty()) { - sectionAdapter.submit(emptyList()) - return + /** "All" plus one pill per folder, as the reference shows. */ + private fun buildChips(items: List) { + folders = items.groupBy { it.folder }.keys.toList() + if (selectedFolder != null && selectedFolder !in folders) selectedFolder = null + + val labels = ArrayList(folders.size + 1) + labels.add(getString(R.string.chip_all)) + labels.addAll(folders) + + val adapter = ChipAdapter(labels) { index -> + selectedFolder = if (index == 0) null else folders.getOrNull(index - 1) + binding.chips.adapter?.let { (it as ChipAdapter).select(index) } + applyFolderFilter() } - val sections = ArrayList() - sections.add(SectionAdapter.Section(getString(R.string.shelf_recent), items.take(8), true)) - for ((folder, list) in items.groupBy { it.folder }) { - if (list.size < 2 || sections.size >= 5) continue - sections.add(SectionAdapter.Section(folder, list.take(20), false)) - } - sections.add(SectionAdapter.Section(getString(R.string.shelf_all), items.take(30), false)) - sectionAdapter.submit(sections) + binding.chips.adapter = adapter + val active = selectedFolder?.let { folders.indexOf(it) + 1 } ?: 0 + if (active > 0) adapter.select(active) + } + + private fun applyFolderFilter() { + val folder = selectedFolder + val list = if (folder == null) all else all.filter { it.folder == folder } + gridAdapter.submit(list, stats.likedKeys()) + refreshEmptyState() } private fun applyFilter(query: String) { @@ -129,35 +191,53 @@ class MainActivity : AppCompatActivity() { val list = if (q.isEmpty()) all else all.filter { it.title.lowercase().contains(q) || it.folder.lowercase().contains(q) } - resultsAdapter.submit(list) + resultsAdapter.submit(list, stats.likedKeys()) } private fun selectTab(index: Int) { activeTab = index - val active = ContextCompat.getColor(this, R.color.kt_red) + val active = ContextCompat.getColor(this, R.color.kt_text) val idle = ContextCompat.getColor(this, R.color.kt_tab_idle) binding.tabHomeIcon.imageTintList = ColorStateList.valueOf(if (index == 0) active else idle) binding.tabHomeLabel.setTextColor(if (index == 0) active else idle) binding.tabSearchIcon.imageTintList = ColorStateList.valueOf(if (index == 1) active else idle) binding.tabSearchLabel.setTextColor(if (index == 1) active else idle) + binding.tabStuffIcon.imageTintList = ColorStateList.valueOf(if (index == 2) active else idle) + binding.tabStuffLabel.setTextColor(if (index == 2) active else idle) binding.tabProfileIcon.imageTintList = ColorStateList.valueOf(idle) + binding.tabProfileLabel.setTextColor(idle) binding.searchBar.visibility = if (index == 1) View.VISIBLE else View.GONE - binding.results.visibility = if (index == 1) View.VISIBLE else View.GONE - binding.rows.visibility = if (index == 0) View.VISIBLE else View.GONE + binding.results.visibility = if (index in 1..2) View.VISIBLE else View.GONE + binding.grid.visibility = if (index == 0) View.VISIBLE else View.GONE + binding.chips.visibility = if (index == 0) View.VISIBLE else View.GONE - if (index == 1) { - binding.searchInput.requestFocus() - } else { - binding.searchInput.setText("") + when (index) { + 1 -> binding.searchInput.requestFocus() + 2 -> resultsAdapter.submit(stats.likedItems(), stats.likedKeys()) + else -> binding.searchInput.setText("") } + if (index != 1) binding.searchInput.setText("") refreshEmptyState() + binding.grid.post { layoutTiles() } } private fun refreshEmptyState() { - val show = all.isEmpty() && activeTab == 0 - binding.empty.visibility = if (show) View.VISIBLE else View.GONE + val homeEmpty = all.isEmpty() && activeTab == 0 + binding.empty.visibility = if (homeEmpty) View.VISIBLE else View.GONE + + // Search and "Your stuff" must say something when their list is empty, + // otherwise the tab looks broken (grid hidden, nothing drawn). + val listEmpty = when (activeTab) { + 1 -> resultsAdapter.itemCount == 0 + 2 -> resultsAdapter.itemCount == 0 + else -> false + } + binding.resultsEmpty.text = + getString(if (activeTab == 2) R.string.likes_empty else R.string.search_empty) + binding.resultsEmpty.visibility = + if (listEmpty && resultsAdapter.itemCount == 0) View.VISIBLE else View.GONE } private fun pickFolder() { @@ -203,6 +283,9 @@ class MainActivity : AppCompatActivity() { d.dismiss() pickFolder() } + .setNeutralButton(R.string.stats_open) { _, _ -> + startActivity(Intent(this, StatsActivity::class.java)) + } .setNegativeButton(R.string.ok, null) .show() } @@ -212,6 +295,8 @@ class MainActivity : AppCompatActivity() { Intent(this, PlayerActivity::class.java) .putExtra(PlayerActivity.EXTRA_URI, item.uri.toString()) .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 4187de6..470c932 100644 --- a/app/src/main/java/dev/lotherk/kidstube/ui/PlayerActivity.kt +++ b/app/src/main/java/dev/lotherk/kidstube/ui/PlayerActivity.kt @@ -5,6 +5,7 @@ import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper +import android.os.SystemClock import android.view.View import android.view.WindowInsets import android.view.WindowInsetsController @@ -12,8 +13,14 @@ import android.view.WindowManager import android.widget.SeekBar import android.widget.Toast import androidx.appcompat.app.AppCompatActivity +import androidx.recyclerview.widget.LinearLayoutManager import dev.lotherk.kidstube.R +import dev.lotherk.kidstube.data.Library +import dev.lotherk.kidstube.data.MediaItem +import dev.lotherk.kidstube.data.Series +import dev.lotherk.kidstube.stats.StatsDb import dev.lotherk.kidstube.databinding.ActivityPlayerBinding +import java.util.concurrent.Executors /** Fullscreen local playback. No pre-roll, no controls until a tap. */ class PlayerActivity : AppCompatActivity() { @@ -21,12 +28,24 @@ class PlayerActivity : AppCompatActivity() { companion object { const val EXTRA_URI = "uri" const val EXTRA_TITLE = "title" + const val EXTRA_FOLDER = "folder" + const val EXTRA_KEY = "key" } private lateinit var binding: ActivityPlayerBinding private val handler = Handler(Looper.getMainLooper()) private var chromeVisible = true + private val executor = Executors.newSingleThreadExecutor() + private lateinit var suggestions: SuggestionAdapter + private var pool: List = emptyList() + private lateinit var stats: StatsDb + private var item: MediaItem? = null + private var segmentStart = 0L + private var resumedAt = 0L + private var watchedMs = 0L + private var prepared = false + private val hideChrome = Runnable { setChrome(false) } private val ticker = object : Runnable { override fun run() { @@ -46,9 +65,18 @@ class PlayerActivity : AppCompatActivity() { return } + stats = StatsDb(this) + item = MediaItem( + uri = Uri.parse(rawUri), + title = intent.getStringExtra(EXTRA_TITLE).orEmpty(), + folder = intent.getStringExtra(EXTRA_FOLDER).orEmpty(), + key = intent.getStringExtra(EXTRA_KEY) ?: rawUri + ) + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) binding.title.text = intent.getStringExtra(EXTRA_TITLE).orEmpty() binding.btnBack.setOnClickListener { finish() } + binding.btnLike.setOnClickListener { toggleLike() } binding.tapCatcher.setOnClickListener { setChrome(!chromeVisible) } binding.chrome.setOnClickListener { setChrome(!chromeVisible) } @@ -67,20 +95,120 @@ class PlayerActivity : AppCompatActivity() { } }) - binding.video.setVideoURI(Uri.parse(rawUri)) + suggestions = SuggestionAdapter { play(it) } + binding.suggestions.layoutManager = + LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) + binding.suggestions.adapter = suggestions + binding.video.setOnPreparedListener { player -> binding.spinner.visibility = View.GONE - player.isLooping = true + prepared = true + segmentStart = System.currentTimeMillis() + player.isLooping = false binding.seek.max = if (player.duration > 0) player.duration else 1 binding.video.start() handler.post(ticker) setChrome(true) } + // A finished video rolls into another one, like the iOS app. + binding.video.setOnCompletionListener { + commitWatch() + recordSegment() + val next = pool.firstOrNull { it.uri != item?.uri } + if (next != null) play(next) else finish() + } + binding.video.setOnErrorListener { _, _, _ -> binding.spinner.visibility = View.GONE Toast.makeText(this, R.string.error_play, Toast.LENGTH_LONG).show() true } + + play(item ?: return) + } + + /** Switches the running video and offers four others while chrome is up. */ + private fun play(next: MediaItem) { + if (item != null && prepared) recordSegment() + prepared = false + item = next + binding.title.text = next.title + updateLikeIcon(stats.isLiked(next.key)) + binding.spinner.visibility = View.VISIBLE + setChrome(true) + binding.video.setVideoURI(next.uri) + loadSuggestions(next) + } + + /** The heart in the corner; "Your stuff" shows exactly these videos. */ + private fun toggleLike() { + val current = item ?: return + val liked = stats.toggleLike(current) + updateLikeIcon(liked) + } + + private fun updateLikeIcon(liked: Boolean) { + binding.btnLike.imageTintList = android.content.res.ColorStateList.valueOf( + androidx.core.content.ContextCompat.getColor( + this, + if (liked) dev.lotherk.kidstube.R.color.kt_red else android.R.color.white + ) + ) + } + + private fun loadSuggestions(current: MediaItem) { + executor.execute { + val scan = Library.scan(this) + val others = Series.suggestionsFor(scan, current, 4) + pool = others + runOnUiThread { + suggestions.submit(others) + binding.suggestions.visibility = if (others.isEmpty()) View.GONE else View.VISIBLE + } + } + } + + override fun onConfigurationChanged(newConfig: android.content.res.Configuration) { + super.onConfigurationChanged(newConfig) + // The activity survives rotation, so the tile widths have to be rebuilt + // by hand or the strip keeps the old (wrong) size. + val current = item ?: return + suggestions = SuggestionAdapter { play(it) } + binding.suggestions.adapter = suggestions + loadSuggestions(current) + } + + override fun onResume() { + super.onResume() + resumedAt = SystemClock.elapsedRealtime() + if (segmentStart == 0L) segmentStart = System.currentTimeMillis() + } + + override fun onPause() { + super.onPause() + commitWatch() + recordSegment() + } + + /** Watches the clock only while this activity is actually visible. */ + private fun commitWatch() { + if (resumedAt > 0L) { + watchedMs += SystemClock.elapsedRealtime() - resumedAt + resumedAt = 0L + } + } + + /** One row per visible segment, so a resumed app counts as a new play. */ + private fun recordSegment() { + val current = item ?: return + if (prepared && watchedMs >= 1500L) { + val duration = binding.video.duration + val position = binding.video.currentPosition + val completed = duration > 0 && position >= duration - 3000 + stats.record(current, segmentStart, watchedMs, completed) + } + watchedMs = 0L + segmentStart = 0L } override fun onWindowFocusChanged(hasFocus: Boolean) { diff --git a/app/src/main/java/dev/lotherk/kidstube/ui/SectionAdapter.kt b/app/src/main/java/dev/lotherk/kidstube/ui/SectionAdapter.kt deleted file mode 100644 index 960c8cd..0000000 --- a/app/src/main/java/dev/lotherk/kidstube/ui/SectionAdapter.kt +++ /dev/null @@ -1,71 +0,0 @@ -package dev.lotherk.kidstube.ui - -import android.view.LayoutInflater -import android.view.ViewGroup -import androidx.recyclerview.widget.LinearLayoutManager -import androidx.recyclerview.widget.LinearSnapHelper -import androidx.recyclerview.widget.RecyclerView -import dev.lotherk.kidstube.data.MediaItem -import dev.lotherk.kidstube.databinding.ItemSectionBinding - -/** Vertical list of shelves; each shelf is its own horizontal RecyclerView. */ -class SectionAdapter( - private val onTap: (MediaItem) -> Unit -) : RecyclerView.Adapter() { - - class Section(val title: String, val items: List, val hero: Boolean) - - private val sections = ArrayList
() - - fun submit(list: List
) { - sections.clear() - sections.addAll(list) - notifyDataSetChanged() - } - - class Holder(val binding: ItemSectionBinding) : RecyclerView.ViewHolder(binding.root) { - var snap: LinearSnapHelper? = null - } - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { - val binding = ItemSectionBinding.inflate( - LayoutInflater.from(parent.context), parent, false - ) - return Holder(binding) - } - - override fun onBindViewHolder(holder: Holder, position: Int) { - val section = sections[position] - val binding = holder.binding - binding.sectionTitle.text = section.title - - val row = binding.row - val context = row.context - if (row.layoutManager == null) { - row.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) - } - val adapter = VideoAdapter( - if (section.hero) VideoAdapter.Mode.HERO else VideoAdapter.Mode.CAROUSEL, - onTap - ) - row.adapter = adapter - adapter.submit(section.items) - - // The wide top shelf snaps page by page like the iOS carousel; the - // smaller shelves scroll freely. - if (section.hero && holder.snap == null) { - holder.snap = LinearSnapHelper().apply { attachToRecyclerView(row) } - } else if (!section.hero && holder.snap != null) { - holder.snap?.attachToRecyclerView(null) - holder.snap = null - } - } - - override fun onViewRecycled(holder: Holder) { - holder.snap?.attachToRecyclerView(null) - holder.snap = null - super.onViewRecycled(holder) - } - - override fun getItemCount(): Int = sections.size -} diff --git a/app/src/main/java/dev/lotherk/kidstube/ui/StatsActivity.kt b/app/src/main/java/dev/lotherk/kidstube/ui/StatsActivity.kt new file mode 100644 index 0000000..5c79a65 --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/ui/StatsActivity.kt @@ -0,0 +1,67 @@ +package dev.lotherk.kidstube.ui + +import android.os.Bundle +import android.widget.LinearLayout +import android.widget.TextView +import androidx.appcompat.app.AppCompatActivity +import androidx.core.content.ContextCompat +import dev.lotherk.kidstube.R +import dev.lotherk.kidstube.databinding.ActivityStatsBinding +import dev.lotherk.kidstube.stats.StatsDb +import java.io.File + +/** Parent-facing view over the local watch history. */ +class StatsActivity : AppCompatActivity() { + + private lateinit var binding: ActivityStatsBinding + private lateinit var stats: StatsDb + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityStatsBinding.inflate(layoutInflater) + setContentView(binding.root) + stats = StatsDb(this) + + val totals = stats.totals() + binding.statPlays.text = totals[0].toString() + binding.statTime.text = stats.formatMs(totals[1]) + binding.statVideos.text = totals[2].toString() + + val dim = ContextCompat.getColor(this, R.color.kt_text_sub) + val bright = ContextCompat.getColor(this, R.color.kt_text) + + for (video in stats.topVideos()) { + val row = TextView(this).apply { + text = "${video.plays}x ${stats.formatMs(video.watchedMs)} ${video.title}" + setTextColor(bright) + textSize = 13f + maxLines = 2 + setPadding(0, 12, 0, 12) + } + binding.topList.addView(row) + } + if (binding.topList.childCount == 0) { + binding.topList.addView(note(getString(R.string.stats_empty))) + } + + for ((day, plays, ms) in stats.perDay()) { + val row = TextView(this).apply { + text = "$day ${plays}x ${stats.formatMs(ms)}" + setTextColor(dim) + textSize = 13f + setPadding(0, 8, 0, 8) + } + binding.dayList.addView(row) + } + + val dir: File = getExternalFilesDir(null) ?: filesDir + binding.statsPath.text = getString(R.string.stats_export, File(dir, "stats.json").absolutePath) + } + + private fun note(text: String): TextView = TextView(this).apply { + this.text = text + setTextColor(ContextCompat.getColor(this@StatsActivity, R.color.kt_text_sub)) + textSize = 13f + setPadding(0, 8, 0, 8) + } +} diff --git a/app/src/main/java/dev/lotherk/kidstube/ui/SuggestionAdapter.kt b/app/src/main/java/dev/lotherk/kidstube/ui/SuggestionAdapter.kt new file mode 100644 index 0000000..714c919 --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/ui/SuggestionAdapter.kt @@ -0,0 +1,58 @@ +package dev.lotherk.kidstube.ui + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import androidx.recyclerview.widget.RecyclerView +import dev.lotherk.kidstube.R +import dev.lotherk.kidstube.data.MediaItem +import dev.lotherk.kidstube.media.ThumbCache +import kotlin.math.roundToInt + +/** The four "more videos" tiles shown while the player chrome is visible. */ +class SuggestionAdapter( + private val onTap: (MediaItem) -> Unit +) : RecyclerView.Adapter() { + + private val items = ArrayList() + + fun submit(list: List) { + items.clear() + items.addAll(list) + notifyDataSetChanged() + } + + class Holder(view: View) : RecyclerView.ViewHolder(view) { + val thumb: ThumbView = view.findViewById(R.id.thumb) + val title: TextView = view.findViewById(R.id.title) + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { + val view = LayoutInflater.from(parent.context) + .inflate(R.layout.item_suggestion, parent, false) + // Four tiles side by side, never a 2x2 block: the strip must stay low. + val density = parent.resources.displayMetrics.density + val margins = (32 * density).roundToInt() + 3 * (8 * density).roundToInt() + val params = view.layoutParams as RecyclerView.LayoutParams + params.width = ((parent.resources.displayMetrics.widthPixels - margins) / 4) + .coerceAtLeast((72 * density).roundToInt()) + params.marginEnd = (8 * density).roundToInt() + view.layoutParams = params + return Holder(view) + } + + override fun onBindViewHolder(holder: Holder, position: Int) { + val item = items[position] + holder.title.text = item.title + ThumbCache.load(holder.itemView.context, item, holder.thumb) { bitmap, label -> + holder.thumb.setThumb(bitmap, label) + } + holder.itemView.setOnClickListener { + val current = holder.bindingAdapterPosition + if (current != RecyclerView.NO_POSITION && current < items.size) onTap(items[current]) + } + } + + override fun getItemCount(): Int = items.size +} diff --git a/app/src/main/java/dev/lotherk/kidstube/ui/TileSpacing.kt b/app/src/main/java/dev/lotherk/kidstube/ui/TileSpacing.kt new file mode 100644 index 0000000..2057f71 --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/ui/TileSpacing.kt @@ -0,0 +1,32 @@ +package dev.lotherk.kidstube.ui + +import android.graphics.Rect +import android.view.View +import androidx.recyclerview.widget.RecyclerView + +/** + * Centers every tile inside its grid cell and adds the row gap. + * + * GridLayoutManager gives each child its cell's width, but the tiles are sized + * from the available height so three rows fit — they end up narrower than the + * cell and must be pulled to the middle. + */ +class TileSpacing( + private val spans: Int, + private val tileWidth: Int, + private val rowGap: Int +) : RecyclerView.ItemDecoration() { + + override fun getItemOffsets( + outRect: Rect, + view: View, + parent: RecyclerView, + state: RecyclerView.State + ) { + val cell = parent.width / spans + val side = ((cell - tileWidth) / 2).coerceAtLeast(0) + outRect.left = side + outRect.right = side + outRect.bottom = rowGap + } +} diff --git a/app/src/main/java/dev/lotherk/kidstube/ui/TileView.kt b/app/src/main/java/dev/lotherk/kidstube/ui/TileView.kt new file mode 100644 index 0000000..ad21f49 --- /dev/null +++ b/app/src/main/java/dev/lotherk/kidstube/ui/TileView.kt @@ -0,0 +1,194 @@ +package dev.lotherk.kidstube.ui + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.LinearGradient +import android.graphics.Matrix +import android.graphics.Paint +import android.graphics.Path +import android.graphics.Shader +import android.graphics.Typeface +import android.os.Build +import android.text.Layout +import android.text.StaticLayout +import android.text.TextPaint +import android.text.TextUtils +import android.util.AttributeSet +import android.view.View +import androidx.core.content.ContextCompat +import dev.lotherk.kidstube.R +import kotlin.math.max +import kotlin.math.roundToInt + +/** + * One 16:9 tile with everything inside it: rounded corners, duration pill and a + * two-line title over a bottom scrim. Keeping the label inside the bitmap is + * what lets three rows fit on a landscape screen. + */ +class TileView @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, + defStyle: Int = 0 +) : View(context, attrs, defStyle) { + + private val density = resources.displayMetrics.density + private val radiusPx = 12f * density + private val pillMargin = 6f * density + private val pillPadH = 5f * density + private val pillPadV = 2f * density + private val textPad = 8f * density + private val scrimHeight = 34f * density + + private val bitmapPaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG) + private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = ContextCompat.getColor(context, R.color.kt_placeholder) + } + private val pillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = ContextCompat.getColor(context, R.color.kt_pill) + } + private val pillTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.WHITE + textSize = 10f * density + typeface = Typeface.DEFAULT_BOLD + } + private val titlePaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { + color = Color.WHITE + textSize = 12f * density + typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD) + } + private val heartPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { + color = ContextCompat.getColor(context, R.color.kt_red) + } + + private val clip = Path() + private val scaleMatrix = Matrix() + + private var thumb: Bitmap? = null + private var duration: String? = null + private var title: CharSequence? = null + private var liked = false + + private val scrimPaint = Paint() + private var scrimFor = 0 + + private var layout: StaticLayout? = null + private var layoutFor: String? = null + private var layoutWidth = 0 + + fun bind(bitmap: Bitmap?, label: String?, text: CharSequence?, isLiked: Boolean) { + thumb = bitmap + duration = label + title = text + liked = isLiked + layout = null + contentDescription = text + invalidate() + } + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val width = MeasureSpec.getSize(widthMeasureSpec) + val height = if (width > 0) (width * 9f / 16f).roundToInt() else 0 + setMeasuredDimension(width, height) + } + + override fun onDraw(canvas: Canvas) { + val w = width.toFloat() + val h = height.toFloat() + if (w <= 0f || h <= 0f) return + + clip.reset() + clip.addRoundRect(0f, 0f, w, h, radiusPx, radiusPx, Path.Direction.CW) + canvas.save() + canvas.clipPath(clip) + + val bmp = thumb + if (bmp == null || bmp.isRecycled) { + canvas.drawRect(0f, 0f, w, h, fillPaint) + } else { + val scale = max(w / bmp.width, h / bmp.height) + scaleMatrix.reset() + scaleMatrix.setScale(scale, scale) + scaleMatrix.postTranslate((w - bmp.width * scale) / 2f, (h - bmp.height * scale) / 2f) + canvas.drawBitmap(bmp, scaleMatrix, bitmapPaint) + } + + val text = layoutFor(w, title) + if (text != null) { + val heightKey = height + if (scrimFor != heightKey) { + scrimPaint.shader = LinearGradient( + 0f, h - scrimHeight, 0f, h, + intArrayOf(0x00000000, 0xB3000000.toInt()), + null, Shader.TileMode.CLAMP + ) + scrimFor = heightKey + } + canvas.drawRect(0f, h - scrimHeight, w, h, scrimPaint) + canvas.save() + canvas.translate(textPad, h - text.height.toFloat() - textPad * 0.5f) + text.draw(canvas) + canvas.restore() + } + canvas.restore() + + duration?.let { drawPill(canvas, it, w) } + if (liked) drawHeart(canvas, w) + } + + private fun layoutFor(width: Float, text: CharSequence?): StaticLayout? { + if (text.isNullOrEmpty()) return null + val available = (width - 2 * textPad).roundToInt() + if (available <= 0) return null + if (layout != null && layoutFor == text.toString() && layoutWidth == available) { + return layout + } + val ellipsized = TextUtils.ellipsize(text, titlePaint, available.toFloat(), TextUtils.TruncateAt.END) + ?: text + val built = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + StaticLayout.Builder.obtain(ellipsized, 0, ellipsized.length, titlePaint, available) + .setMaxLines(2) + .setEllipsize(TextUtils.TruncateAt.END) + .setAlignment(Layout.Alignment.ALIGN_NORMAL) + .build() + } else { + @Suppress("DEPRECATION") + StaticLayout( + ellipsized, titlePaint, available, Layout.Alignment.ALIGN_NORMAL, + 1f, 0f, false + ) + } + layout = built + layoutFor = text.toString() + layoutWidth = available + return built + } + + private fun drawPill(canvas: Canvas, label: String, w: Float) { + val textWidth = pillTextPaint.measureText(label) + val pillH = pillTextPaint.textSize + 2 * pillPadV + val pillW = textWidth + 2 * pillPadH + val left = w - pillMargin - pillW + val top = pillMargin + val r = pillH / 2f + canvas.drawRoundRect(left, top, left + pillW, top + pillH, r, r, pillPaint) + val baseline = top + pillH / 2f - (pillTextPaint.descent() + pillTextPaint.ascent()) / 2f + canvas.drawText(label, left + pillPadH, baseline, pillTextPaint) + } + + /** Small filled heart in the top-left corner marks a liked video. */ + private val heartPath = Path() + + private fun drawHeart(canvas: Canvas, w: Float) { + if (heartPath.isEmpty) { + val cx = pillMargin + 7f * density + val cy = pillMargin + 7f * density + val r = 6f * density + heartPath.moveTo(cx, cy + r) + heartPath.cubicTo(cx - r * 1.6f, cy - r * 0.2f, cx - r * 0.6f, cy - r * 1.4f, cx, cy - r * 0.5f) + heartPath.cubicTo(cx + r * 0.6f, cy - r * 1.4f, cx + r * 1.6f, cy - r * 0.2f, cx, cy + r) + } + canvas.drawPath(heartPath, heartPaint) + } +} diff --git a/app/src/main/java/dev/lotherk/kidstube/ui/VideoAdapter.kt b/app/src/main/java/dev/lotherk/kidstube/ui/VideoAdapter.kt index 85c71b4..94b2512 100644 --- a/app/src/main/java/dev/lotherk/kidstube/ui/VideoAdapter.kt +++ b/app/src/main/java/dev/lotherk/kidstube/ui/VideoAdapter.kt @@ -3,61 +3,62 @@ package dev.lotherk.kidstube.ui import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import dev.lotherk.kidstube.R import dev.lotherk.kidstube.data.MediaItem import dev.lotherk.kidstube.media.ThumbCache -import kotlin.math.roundToInt /** - * One tile row. HERO is the wide top shelf, CAROUSEL the smaller ones, GRID the - * two-column search result list. + * The video grid. Tile size comes from the activity: it is derived from the + * available height so exactly three rows fit on the landscape screen. The title + * lives inside the tile, there is no text row underneath. */ class VideoAdapter( - private val mode: Mode, private val onTap: (MediaItem) -> Unit ) : RecyclerView.Adapter() { - enum class Mode { HERO, CAROUSEL, GRID } - private val items = ArrayList() + private var likedKeys: Set = emptySet() - fun submit(list: List) { + var tileWidth: Int = 0 + set(value) { + if (field == value) return + field = value + notifyDataSetChanged() + } + + fun submit(list: List, liked: Set = likedKeys) { items.clear() items.addAll(list) + likedKeys = liked notifyDataSetChanged() } class Holder(view: View) : RecyclerView.ViewHolder(view) { - val thumb: ThumbView = view.findViewById(R.id.thumb) - val title: TextView = view.findViewById(R.id.title) - val meta: TextView = view.findViewById(R.id.meta) + val tile: TileView = view.findViewById(R.id.tile) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { - val layout = if (mode == Mode.HERO) R.layout.item_hero else R.layout.item_video - val view = LayoutInflater.from(parent.context).inflate(layout, parent, false) - val density = parent.resources.displayMetrics.density + val view = LayoutInflater.from(parent.context) + .inflate(R.layout.item_card, parent, false) val params = view.layoutParams as RecyclerView.LayoutParams - when (mode) { - Mode.HERO -> - params.width = parent.resources.displayMetrics.widthPixels - - (56 * density).roundToInt() - Mode.CAROUSEL -> params.width = (210 * density).roundToInt() - Mode.GRID -> params.width = ViewGroup.LayoutParams.MATCH_PARENT - } - params.marginEnd = (12 * density).roundToInt() - params.bottomMargin = if (mode == Mode.GRID) (16 * density).roundToInt() else 0 + params.width = if (tileWidth > 0) tileWidth else ViewGroup.LayoutParams.MATCH_PARENT view.layoutParams = params return Holder(view) } override fun onBindViewHolder(holder: Holder, position: Int) { val item = items[position] - holder.title.text = item.title - holder.meta.text = item.folder - ThumbCache.load(holder.itemView.context, item, holder.thumb) + val liked = item.key in likedKeys + holder.tile.bind( + ThumbCache.memory(item.key), + ThumbCache.label(holder.itemView.context, item), + item.title, + liked + ) + ThumbCache.load(holder.itemView.context, item, holder.tile) { bitmap, label -> + holder.tile.bind(bitmap, label, item.title, item.key in likedKeys) + } holder.itemView.setOnClickListener { val current = holder.bindingAdapterPosition if (current != RecyclerView.NO_POSITION && current < items.size) onTap(items[current]) diff --git a/app/src/main/res/drawable/bg_chip.xml b/app/src/main/res/drawable/bg_chip.xml new file mode 100644 index 0000000..cc53b4b --- /dev/null +++ b/app/src/main/res/drawable/bg_chip.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/app/src/main/res/drawable/bg_chip_active.xml b/app/src/main/res/drawable/bg_chip_active.xml new file mode 100644 index 0000000..c8be571 --- /dev/null +++ b/app/src/main/res/drawable/bg_chip_active.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_gear.xml b/app/src/main/res/drawable/ic_gear.xml new file mode 100644 index 0000000..abd4e83 --- /dev/null +++ b/app/src/main/res/drawable/ic_gear.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_heart.xml b/app/src/main/res/drawable/ic_heart.xml new file mode 100644 index 0000000..a8ba29f --- /dev/null +++ b/app/src/main/res/drawable/ic_heart.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_kids_logo.xml b/app/src/main/res/drawable/ic_kids_logo.xml new file mode 100644 index 0000000..807e13d --- /dev/null +++ b/app/src/main/res/drawable/ic_kids_logo.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_shield.xml b/app/src/main/res/drawable/ic_shield.xml new file mode 100644 index 0000000..dd5aad4 --- /dev/null +++ b/app/src/main/res/drawable/ic_shield.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_star.xml b/app/src/main/res/drawable/ic_star.xml new file mode 100644 index 0000000..3c3df63 --- /dev/null +++ b/app/src/main/res/drawable/ic_star.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 1f8ac55..a8ac528 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -10,7 +10,7 @@ android:layout_height="match_parent" android:orientation="vertical"> - + - + + + - - + + + + + + + + - - - - - @@ -156,16 +176,16 @@ android:layout_height="24dp" android:contentDescription="@string/tab_home" android:src="@drawable/ic_home" - app:tint="@color/kt_red" /> + app:tint="@color/kt_text" /> + android:textColor="@color/kt_text" + android:textSize="10sp" /> + android:textSize="10sp" /> + + + + + + + + android:textSize="10sp" /> - + + android:visibility="gone"> diff --git a/app/src/main/res/layout/activity_player.xml b/app/src/main/res/layout/activity_player.xml index 5d72ea8..4f1feb2 100644 --- a/app/src/main/res/layout/activity_player.xml +++ b/app/src/main/res/layout/activity_player.xml @@ -44,6 +44,18 @@ android:src="@drawable/ic_back" app:tint="@android:color/white" /> + + + + + diff --git a/app/src/main/res/layout/activity_stats.xml b/app/src/main/res/layout/activity_stats.xml new file mode 100644 index 0000000..59b9864 --- /dev/null +++ b/app/src/main/res/layout/activity_stats.xml @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/item_card.xml b/app/src/main/res/layout/item_card.xml new file mode 100644 index 0000000..9fe4f20 --- /dev/null +++ b/app/src/main/res/layout/item_card.xml @@ -0,0 +1,5 @@ + + diff --git a/app/src/main/res/layout/item_chip.xml b/app/src/main/res/layout/item_chip.xml new file mode 100644 index 0000000..23230c4 --- /dev/null +++ b/app/src/main/res/layout/item_chip.xml @@ -0,0 +1,5 @@ + + diff --git a/app/src/main/res/layout/item_hero.xml b/app/src/main/res/layout/item_hero.xml deleted file mode 100644 index a7780c3..0000000 --- a/app/src/main/res/layout/item_hero.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - diff --git a/app/src/main/res/layout/item_section.xml b/app/src/main/res/layout/item_section.xml deleted file mode 100644 index 2ce4676..0000000 --- a/app/src/main/res/layout/item_section.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - diff --git a/app/src/main/res/layout/item_video.xml b/app/src/main/res/layout/item_suggestion.xml similarity index 63% rename from app/src/main/res/layout/item_video.xml rename to app/src/main/res/layout/item_suggestion.xml index 3252eb0..4bf42c6 100644 --- a/app/src/main/res/layout/item_video.xml +++ b/app/src/main/res/layout/item_suggestion.xml @@ -13,17 +13,9 @@ android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" - android:layout_marginTop="8dp" + android:layout_marginTop="6dp" android:ellipsize="end" - android:maxLines="2" + android:maxLines="1" android:textColor="@color/kt_text" - android:textSize="14sp" /> - - + android:textSize="11sp" /> diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml index c7db567..398c166 100644 --- a/app/src/main/res/values/colors.xml +++ b/app/src/main/res/values/colors.xml @@ -1,13 +1,16 @@ - - #FFFFFFFF + + #FF0F0F0F #FFFF0000 - #FF212121 - #FF606060 - #FF9E9E9E - #FFE6E6E6 - #FFE8E8E8 + #FFFFFFFF + #FFAAAAAA + #FF8A8A8A + #FF272727 + #FF1F1F1F #B3000000 #66000000 + #FF272727 + #FFFFFFFF + #FF000000 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 45d497e..4b2730e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,12 +1,13 @@ KidsTube - Kids - Tube + Kids Home Search Profile + Your stuff + All No videos yet Put the videos into the folder Movies/KidsTube, or pick another folder. The app only reads that folder and never goes online. @@ -23,5 +24,16 @@ OK Cancel Back + Statistics + plays + watch time + videos + Most watched + Per day + Nothing watched yet + Also written to %1$s + Statistics + Nothing liked yet. Tap the heart while a video plays. + Nothing found. This video cannot be played on this device diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml index e64ac45..b22d71e 100644 --- a/app/src/main/res/values/themes.xml +++ b/app/src/main/res/values/themes.xml @@ -1,11 +1,12 @@ - + + + diff --git a/app/src/test/java/dev/lotherk/kidstube/data/SeriesTest.kt b/app/src/test/java/dev/lotherk/kidstube/data/SeriesTest.kt new file mode 100644 index 0000000..57e6760 --- /dev/null +++ b/app/src/test/java/dev/lotherk/kidstube/data/SeriesTest.kt @@ -0,0 +1,110 @@ +package dev.lotherk.kidstube.data + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class SeriesTest { + + /** Deliberately not MediaItem: no Android classes in a JVM unit test. */ + private data class TestItem( + override val key: String, + override val title: String, + override val folder: String + ) : SeriesItem + + private fun item(folder: String, title: String) = TestItem("$folder/$title", title, folder) + + private fun series(folder: String, count: Int) = + (1..count).map { item(folder, String.format("%03d - Folge %d", it, it)) } + + @Test + fun naturalOrder_sortsByNumericPrefix() { + val shuffled = listOf( + item("A", "010 - zehn"), + item("A", "002 - zwei"), + item("A", "001 - eins") + ) + val sorted = shuffled.sortedWith(Series.naturalOrder).map { it.title } + assertEquals(listOf("001 - eins", "002 - zwei", "010 - zehn"), sorted) + } + + @Test + fun naturalOrder_putsNumberedBeforePlainTitles() { + val sorted = listOf(item("A", "Zebra"), item("A", "007 - Bond")) + .sortedWith(Series.naturalOrder).map { it.title } + assertEquals(listOf("007 - Bond", "Zebra"), sorted) + } + + @Test + fun neighbours_middleOfSeries() { + val all = series("Sandmann", 10) + val (previous, next) = Series.neighbours(all, all[4]) + assertEquals("004 - Folge 4", previous?.title) + assertEquals("006 - Folge 6", next?.title) + } + + @Test + fun neighbours_firstAndLastHaveOneSide() { + val all = series("Sandmann", 5) + val (firstPrev, firstNext) = Series.neighbours(all, all.first()) + assertNull(firstPrev) + assertEquals("002 - Folge 2", firstNext?.title) + + val (lastPrev, lastNext) = Series.neighbours(all, all.last()) + assertEquals("004 - Folge 4", lastPrev?.title) + assertNull(lastNext) + } + + @Test + fun suggestions_middleOfSeries_keepsFixedSlotOrder() { + val all = series("Sandmann", 10) + val current = all[4] + val out = Series.suggestionsFor(all, current) + assertEquals(4, out.size) + // slot 1 random, slot 2 previous, slot 3 next, slot 4 random + assertTrue(out[0].key != current.key) + assertEquals("004 - Folge 4", out[1].title) + assertEquals("006 - Folge 6", out[2].title) + assertTrue(out[3].key != current.key) + assertEquals(4, out.map { it.key }.distinct().size) + } + + @Test + fun suggestions_firstOfSeries_hasNoPrevious() { + val all = series("Sandmann", 6) + val out = Series.suggestionsFor(all, all.first()) + assertEquals(4, out.size) + assertEquals("002 - Folge 2", out[1].title) // next moves up one slot + assertEquals(4, out.map { it.key }.distinct().size) + } + + @Test + fun suggestions_prefersNeighboursOverOtherFolders() { + val sandmann = series("Sandmann", 4) + val other = (1..6).map { item("Tiere", String.format("%03d - Tier %d", it, it)) } + val all = (sandmann + other).shuffled() + val current = sandmann[1] + val out = Series.suggestionsFor(all, current) + assertEquals("001 - Folge 1", out[1].title) + assertEquals("003 - Folge 3", out[2].title) + } + + @Test + fun suggestions_handlesShortLibrary() { + val all = series("Sandmann", 2) + val out = Series.suggestionsFor(all, all[0]) + assertEquals(1, out.size) + assertEquals("002 - Folge 2", out[0].title) + } + + @Test + fun suggestions_neverRepeatsTheCurrentVideo() { + val all = series("Sandmann", 3) + repeat(20) { + val out = Series.suggestionsFor(all, all[1]) + assertTrue(out.none { it.key == all[1].key }) + } + } +}