diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 1188a81c..a8e3b889 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -9,8 +9,8 @@ android { applicationId = "tv.orbit.classic" minSdk = 26 targetSdk = 36 - versionCode = 149 - versionName = "0.100.1-ui-fixes" + versionCode = 150 + versionName = "0.101.0-new-arrivals" } buildFeatures { compose = true } compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } diff --git a/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt b/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt index e3e32a89..9f45f9a6 100644 --- a/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt @@ -55,6 +55,28 @@ internal class CatalogueStore private constructor(context: Context) : CatalogueS db.setTransactionSuccessful() } finally { db.endTransaction() } } + /** Stage C: films and series with a premiere date from [fromDate] (yyyy-MM-dd) to [toDate], newest first. Read only. */ + @Synchronized fun releasedBetween(fromDate: String, toDate: String, limit: Int = 600): List = + readableDatabase.rawQuery("SELECT id, type, title, year, premiere, provider_ids FROM items WHERE substr(premiere, 1, 10) >= ? AND substr(premiere, 1, 10) <= ? ORDER BY premiere DESC LIMIT $limit", + arrayOf(fromDate, toDate)).use { c -> + generateSequence { if (c.moveToNext()) c else null }.map { row -> + val ids = runCatching { JSONObject(row.getString(5)).let { o -> o.keys().asSequence().associateWith { k -> o.optString(k) } } }.getOrDefault(emptyMap()) + val year = if (row.isNull(3)) null else row.getInt(3) + Arrival(row.getString(0), row.getString(1), row.getString(2), year, row.getString(4).take(10), workKey(ids, row.getString(2), year), 0) + }.toList() + } + /** Stage C: the work each of these library ids is, for telling which works a channel already holds. */ + @Synchronized fun worksOf(ids: Collection): Map = ids.chunked(400).flatMap { chunk -> + readableDatabase.rawQuery("SELECT id, title, year, provider_ids FROM items WHERE id IN (${chunk.joinToString(",") { "?" }})", chunk.toTypedArray()).use { c -> + generateSequence { if (c.moveToNext()) c else null }.map { row -> + val ids2 = runCatching { JSONObject(row.getString(3)).let { o -> o.keys().asSequence().associateWith { k -> o.optString(k) } } }.getOrDefault(emptyMap()) + row.getString(0) to workKey(ids2, row.getString(1), if (row.isNull(2)) null else row.getInt(2)) + }.toList() + } + }.toMap() + /** Whether the whole library has been read once: only after that is anything read new. */ + @Synchronized fun complete(): Boolean = summary().finished + @Synchronized fun summary(): CatalogueSummary { val db = readableDatabase fun count(where: String) = db.rawQuery("SELECT COUNT(*) FROM items WHERE $where", null).use { it.moveToFirst(); it.getLong(0) } diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt index 35586239..017cae46 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -47,6 +47,29 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl } /** Books the Drive-In's evenings from the film pools already on the box, so it asks the provider for nothing. */ + /** + * Stage C, report only: once a day after 12:00, reads only the titles the library gained since its last position and + * keeps them as new arrivals. Nothing here touches a plan, a pool or a channel. Until the whole library has been read + * once, what's read is the baseline, not news. + */ + fun refreshArrivals(session: EmbySampleSession, userId: String, catalogue: CatalogueStore) { + val now = clock() + val (kept, last) = store.loadArrivals(userId) + if (!arrivalsRefreshDue(last, now)) return + val baseline = catalogue.complete() + val found = mutableListOf() + val sink = object : CatalogueSink { + override fun position(userId: String) = catalogue.position(userId) + override fun write(userId: String, records: List, nextStart: Long, total: Long?, finished: Boolean) { + catalogue.write(userId, records, nextStart, total, finished); found += records + } + } + val run = session.importCatalogue(sink, ARRIVALS_REFRESH_PAGES) + val arrivals = if (baseline) found.map { arrivalOf(it, now) } else emptyList() + store.saveArrivals(userId, mergeArrivals(kept, arrivals, now), now) + Log.i("OrbitSchedule", "arrivals pages=${run.pages} read=${found.size} new=${arrivals.size} baseline=$baseline") + } + fun topUpDriveIn(userId: String): ChannelPlan? { val now = clock() val existing = store.loadPlan(userId, DRIVE_IN_NUMBER) @@ -111,6 +134,11 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl if (read.carried > 0) Log.w("OrbitSchedule", "channel=$number poolRefreshPartial carried=${read.carried}") pool = ScheduleStore.SavedPool(read.series, fetched, signature) store.savePool(userId, number, pool) + // Stage C, report only: episodes a show here didn't have at the previous read. Never touches the plan. + if (cached != null) runCatching { + val found = newEpisodes(number, cached.series, read.series, now) + if (found.isNotEmpty()) { store.saveNewEpisodes(userId, mergeNewEpisodes(store.loadNewEpisodes(userId), found, now)); Log.i("OrbitSchedule", "channel=$number newEpisodes=${found.size}") } + } } } catch (failure: EmbyCheckException) { Log.w("OrbitSchedule", "channel=$number poolReadFailed status=${failure.httpStatus} retryable=${failure.retryable} keptCache=${cached != null}") @@ -132,6 +160,12 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl avoid = { show, startMs, endMs -> others(show, startMs, endMs) }, shuffle = programming.shuffleEpisodes, mixed = programming::mixes, weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, stories = programming.storyGrouping) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.") if (plan !== existing) store.savePlan(userId, number, plan) + // Stage C, report only: every work any plan books, so "not yet shown on Orbit" has evidence. + if (plan !== existing) runCatching { + val known = store.loadBooked(userId) + val all = known + plan.entries.map { it.seriesId } + if (all.size != known.size) store.saveBooked(userId, all.toList().takeLast(BOOKED_MAX).toSet()) + } store.saveProgress(userId, number, ScheduleStore.SavedProgress(progress?.enabled ?: true, airedCursor(base, plan.entries, now))) session.rememberScheduledItems(plan.entries.map { it.media.item }) val planMs = android.os.SystemClock.elapsedRealtime() - started diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt b/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt index a54444ff..408716fe 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt @@ -66,7 +66,7 @@ internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUI connection.connectTimeout = 10_000 connection.readTimeout = request.readTimeoutMs ?: if (request.path == "/Sessions/Logout") 5_000 else 15_000 connection.setRequestProperty("Accept", "application/json") - connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.100.1\"") + connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.101.0\"") request.token?.let { connection.setRequestProperty("X-Emby-Token", it) } if (request.method == "POST") { val bytes = request.body.orEmpty().toByteArray(Charsets.UTF_8) diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt index ae0b1571..e619a414 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt @@ -268,6 +268,10 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea try { driveInPlan = withContext(Dispatchers.IO) { scheduler.topUpDriveIn(active.accountId) } } catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { /* Tried again next hour. */ } + // Stage C's light daily library refresh, in the background. A failure changes nothing and is tried next hour. + try { withContext(Dispatchers.IO) { scheduler.refreshArrivals(active, active.accountId, catalogue) } } + catch (cancelled: CancellationException) { throw cancelled } + catch (failure: Exception) { android.util.Log.w("OrbitSchedule", "arrivals failed=${failure.javaClass.simpleName}") } delay(60 * 60_000L) } } @@ -483,8 +487,18 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea return } if (session != null) { + /** Stage C's report, read on demand from the box's own records and the catalogue. Read only. */ + fun loadArrivalsReport(): ArrivalsReport? { + val active = session ?: return null + val (arrivals, _) = scheduleStore.loadArrivals(active.accountId) + val today = java.time.LocalDate.now() + val released = catalogue.releasedBetween(today.minusDays(NEWLY_RELEASED_DAYS).toString(), today.toString()) + val poolIds = SmartChannels.flatMap { p -> scheduleStore.loadPool(active.accountId, p.number)?.series.orEmpty().map { it.id } }.toSet() + val works = catalogue.worksOf(poolIds).entries.associate { (id, work) -> work to id } + return arrivalsReport(arrivals, released, scheduleStore.loadNewEpisodes(active.accountId), works, scheduleStore.loadBooked(active.accountId), System.currentTimeMillis()) + } SettingsScreen(settingsSection, { settingsSection = it }, modifier, busy, message, HttpsEmbyTransport.SERVER, sample?.total, - isOn = { scheduledChannels.containsKey(it) }, onSwitch = { programming, on -> setSmartSchedule(programming, on) }, onSuggestions = { openSuggestions(it) }, + arrivals = { detail, first -> NewArrivalsDetail(::loadArrivalsReport, first, detail) }, isOn = { scheduledChannels.containsKey(it) }, onSwitch = { programming, on -> setSmartSchedule(programming, on) }, onSuggestions = { openSuggestions(it) }, onSignOut = { job?.cancel(); closeSession(forget = true) }, windingDown = windingDown, onWindDown = { on -> val tots = scheduledChannels[TOTS_NUMBER] val active = session diff --git a/android/app/src/main/java/tv/orbit/classic/NewArrivals.kt b/android/app/src/main/java/tv/orbit/classic/NewArrivals.kt new file mode 100644 index 00000000..ad07f5f2 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/NewArrivals.kt @@ -0,0 +1,139 @@ +package tv.orbit.classic + +import androidx.compose.foundation.background +import androidx.compose.foundation.focusable +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId + +/** + * Living Network Stage C (approved by Paul on 4 November 2026): spotting what's new. Report only: these labels book + * nothing, change no channel and promote nothing. They're the evidence Stage D's suggestions and What's On's "new + * episodes" rule will use later, and even then only booked programmes are shown. + */ +internal const val NEW_TO_LIBRARY_DAYS = 14L +internal const val NEWLY_RELEASED_DAYS = 60L +internal const val ARRIVALS_KEPT_DAYS = 90L +internal const val ARRIVALS_MAX = 2_000 +internal const val NEW_EPISODES_MAX = 500 +internal const val BOOKED_MAX = 20_000 +/** Pages of the library a daily refresh may read: a thousand new titles, far more than a day brings. */ +internal const val ARRIVALS_REFRESH_PAGES = 5 +/** The daily refresh runs once a day, after this local hour (What's On's edition turns over at 12:00 too). */ +internal const val ARRIVALS_REFRESH_HOUR = 12 + +/** A film or series the library gained, first seen by Orbit's daily refresh at [firstSeenMs]. */ +internal data class Arrival(val id: String, val type: String, val title: String, val year: Int?, val premiere: String, val work: String, val firstSeenMs: Long) + +/** An episode a show already on a channel didn't have at the previous read of that channel's pool. */ +internal data class NewEpisode(val channel: Int, val show: String, val mark: EpisodeMark, val seenMs: Long) + +/** One work, whichever copy of it: its TMDB, TVDB or IMDb id, else its title and year. */ +internal fun workKey(providerIds: Map, title: String, year: Int?): String { + val ids = providerIds.mapKeys { it.key.lowercase(java.util.Locale.ROOT) } + return ids["tmdb"]?.let { "tmdb:$it" } ?: ids["tvdb"]?.let { "tvdb:$it" } ?: ids["imdb"]?.let { "imdb:$it" } ?: "title:${seriesKey(title)}:${year ?: ""}" +} + +internal fun arrivalOf(record: CatalogueRecord, nowMs: Long) = + Arrival(record.id, record.type, record.title, record.year, record.premiere.take(10), workKey(record.providerIds, record.title, record.year), nowMs) + +/** New arrivals added to what's kept: one per work, the first sighting kept, pruned by age and size. */ +internal fun mergeArrivals(kept: List, found: List, nowMs: Long): List { + val oldest = nowMs - ARRIVALS_KEPT_DAYS * 24 * 60 * 60_000L + return (kept + found).filter { it.firstSeenMs >= oldest }.distinctBy { it.work }.sortedByDescending { it.firstSeenMs }.take(ARRIVALS_MAX) +} + +/** + * Episodes in [current] that [previous] didn't have, matched by show and season and episode, never by file: a pool that + * switches to another copy of the same episodes has nothing new (American Dad! on 4 November looked like 399 new files). + */ +internal fun newEpisodes(channel: Int, previous: List, current: List, nowMs: Long): List { + val before = previous.filter { !it.isFilm }.associate { seriesKey(it.title) to it.episodes.mapTo(HashSet()) { e -> e.mark } } + return current.filter { !it.isFilm }.flatMap { show -> + // A show new to the pool is a new arrival on the channel, not a run of new episodes. + val known = before[seriesKey(show.title)] ?: return@flatMap emptyList() + show.episodes.filter { it.mark !in known }.map { NewEpisode(channel, show.title, it.mark, nowMs) } + } +} + +internal fun mergeNewEpisodes(kept: List, found: List, nowMs: Long): List { + val oldest = nowMs - ARRIVALS_KEPT_DAYS * 24 * 60 * 60_000L + return (kept + found).filter { it.seenMs >= oldest }.distinctBy { Triple(it.channel, seriesKey(it.show), it.mark) }.sortedByDescending { it.seenMs }.take(NEW_EPISODES_MAX) +} + +/** Whether today's refresh is due: once a day, after [ARRIVALS_REFRESH_HOUR]. */ +internal fun arrivalsRefreshDue(lastRefreshMs: Long?, nowMs: Long, zone: ZoneId = ZoneId.systemDefault()): Boolean { + val now = Instant.ofEpochMilli(nowMs).atZone(zone) + if (now.hour < ARRIVALS_REFRESH_HOUR) return false + return lastRefreshMs == null || Instant.ofEpochMilli(lastRefreshMs).atZone(zone).toLocalDate().isBefore(now.toLocalDate()) +} + +/** A line of the report: what it is, its labels, and the evidence for each. */ +internal data class ArrivalLine(val title: String, val type: String, val labels: List, val evidence: String) + +internal class ArrivalsReport(val newToLibrary: List, val newlyReleased: List, val newEpisodes: List, val notYetOnOrbit: List) + +private fun date(ms: Long, zone: ZoneId) = Instant.ofEpochMilli(ms).atZone(zone).toLocalDate() + +/** + * The four lists, each line with its evidence. [released] is the library's titles with a premiere date in the last + * [NEWLY_RELEASED_DAYS] days (read from the catalogue); [inPools] the works any channel's pool holds, by work key; + * [booked] every work any plan has booked since Stage C began, by series id. + */ +internal fun arrivalsReport(arrivals: List, released: List, episodes: List, inPools: Map, booked: Set, + nowMs: Long, zone: ZoneId = ZoneId.systemDefault()): ArrivalsReport { + val today = date(nowMs, zone) + fun isNew(a: Arrival) = !date(a.firstSeenMs, zone).isBefore(today.minusDays(NEW_TO_LIBRARY_DAYS)) + fun releasedRecently(a: Arrival) = a.premiere.takeIf { it.length == 10 }?.let { runCatching { LocalDate.parse(it) }.getOrNull() } + ?.let { !it.isAfter(today) && !it.isBefore(today.minusDays(NEWLY_RELEASED_DAYS)) } == true + fun labels(a: Arrival) = listOfNotNull("New to the library".takeIf { isNew(a) }, "Newly released".takeIf { releasedRecently(a) }, + "Not yet shown on Orbit".takeIf { inPools[a.work]?.let { id -> id !in booked } == true }) + fun line(a: Arrival, evidence: String) = ArrivalLine(a.title + (a.year?.let { " ($it)" } ?: ""), a.type, labels(a), evidence) + val newToLibrary = arrivals.filter(::isNew).map { line(it, "First seen ${date(it.firstSeenMs, zone)}" + if (it.premiere.isNotEmpty()) ", premiered ${it.premiere}" else "") } + val newlyReleased = released.filter(::releasedRecently).distinctBy { it.work }.sortedByDescending { it.premiere } + .map { line(it, "Premiered ${it.premiere}") } + val newEps = episodes.groupBy { it.channel to seriesKey(it.show) }.values.map { eps -> + val first = eps.first() + ArrivalLine(first.show, "Series", listOf("New episodes"), "${eps.size} new on channel ${first.channel}: " + + eps.sortedBy { it.mark }.take(4).joinToString { "S${it.mark.season} E${it.mark.episode}" } + (if (eps.size > 4) " and ${eps.size - 4} more" else "") + ", found ${date(first.seenMs, zone)}") + } + val fresh = (arrivals + released).distinctBy { it.work } + val notYet = fresh.filter { inPools[it.work]?.let { id -> id !in booked } == true }.map { line(it, "On a channel's list, not booked anywhere yet") } + return ArrivalsReport(newToLibrary, newlyReleased, newEps, notYet) +} + +/** Settings › New arrivals: the four lists, read only. Nothing here books or changes anything. */ +@androidx.compose.runtime.Composable +internal fun NewArrivalsDetail(load: () -> ArrivalsReport?, first: androidx.compose.ui.focus.FocusRequester, modifier: androidx.compose.ui.Modifier) { + val report by androidx.compose.runtime.produceState(null) { value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { runCatching(load).getOrNull() } } + val rows = report?.let { r -> + listOf("NEW TO THE LIBRARY" to r.newToLibrary, "NEWLY RELEASED" to r.newlyReleased, "NEW EPISODES ON A CHANNEL" to r.newEpisodes, "NOT YET SHOWN ON ORBIT" to r.notYetOnOrbit) + }.orEmpty() + androidx.compose.foundation.lazy.LazyColumn(modifier, verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(4.dp)) { + item { + androidx.tv.material3.Text(if (report == null) "Reading the library's records…" else "Found by the daily library check after 12:00. A report only: nothing here is booked or changed.", + androidx.compose.ui.Modifier.focusRequester(first).focusable(), color = Muted, fontSize = 12.sp) + } + rows.forEach { (heading, lines) -> + item { androidx.tv.material3.Text("$heading (${lines.size})", androidx.compose.ui.Modifier.padding(top = 8.dp), color = Yellow, fontFamily = Anton, fontSize = 15.sp) } + if (lines.isEmpty()) item { androidx.tv.material3.Text("Nothing yet.", color = Muted, fontSize = 12.sp) } + items(lines.take(60).size) { index -> + val line = lines[index] + var focused by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(false) } + androidx.compose.foundation.layout.Column(androidx.compose.ui.Modifier.fillMaxWidth().onFocusChanged { focused = it.isFocused }.focusable() + .background(if (focused) Blue else Panel, androidx.compose.foundation.shape.RoundedCornerShape(4.dp)).padding(horizontal = 10.dp, vertical = 5.dp)) { + androidx.tv.material3.Text("${line.title} · ${line.type}", color = androidx.compose.ui.graphics.Color.White, fontSize = 13.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, maxLines = 1) + androidx.tv.material3.Text((line.labels.joinToString(" · ") + " — " + line.evidence), color = Muted, fontSize = 11.sp, maxLines = 2) + } + } + } + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt index 882e9e95..f827382a 100644 --- a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt @@ -162,6 +162,30 @@ internal class ScheduleStore(private val directory: File) { saved.keys().asSequence().associate { it.toLong() to saved.getInt(it) } }.orEmpty() + /** Stage C's records: new arrivals, new episodes, every work ever booked, and when the library was last refreshed. Report only. */ + fun saveArrivals(userId: String, arrivals: List, lastRefreshMs: Long?) = + write(file("arrivals", 0), root(userId, 0).put("refreshed", lastRefreshMs ?: JSONObject.NULL).put("arrivals", JSONArray().also { saved -> + arrivals.forEach { saved.put(JSONObject().put("i", it.id).put("k", it.type).put("t", it.title).put("y", it.year ?: JSONObject.NULL).put("p", it.premiere).put("w", it.work).put("f", it.firstSeenMs)) } + })) + fun loadArrivals(userId: String): Pair, Long?> = read(file("arrivals", 0), userId, 0) { root -> + val saved = root.getJSONArray("arrivals") + (0 until saved.length()).map { saved.getJSONObject(it) }.map { + Arrival(validId(it.getString("i")), it.getString("k"), it.getString("t").take(160), if (it.isNull("y")) null else it.getInt("y"), it.getString("p").take(10), it.getString("w").take(120), it.getLong("f")) + } to (if (root.isNull("refreshed")) null else root.getLong("refreshed")) + } ?: (emptyList() to null) + fun saveNewEpisodes(userId: String, episodes: List) = + write(file("newepisodes", 0), root(userId, 0).put("episodes", JSONArray().also { saved -> + episodes.forEach { saved.put(JSONObject().put("c", it.channel).put("t", it.show).put("n", JSONArray().put(it.mark.season).put(it.mark.episode)).put("f", it.seenMs)) } + })) + fun loadNewEpisodes(userId: String): List = read(file("newepisodes", 0), userId, 0) { root -> + val saved = root.getJSONArray("episodes") + (0 until saved.length()).map { saved.getJSONObject(it) }.map { NewEpisode(it.getInt("c"), it.getString("t").take(160), it.getJSONArray("n").let { n -> EpisodeMark(n.getInt(0), n.getInt(1)) }, it.getLong("f")) } + }.orEmpty() + fun saveBooked(userId: String, ids: Set) = write(file("booked", 0), root(userId, 0).put("ids", JSONArray(ids.toList()))) + fun loadBooked(userId: String): Set = read(file("booked", 0), userId, 0) { root -> + val ids = root.getJSONArray("ids"); (0 until ids.length()).map { validId(ids.getString(it)) }.toSet() + }.orEmpty() + /** Programme reminders set from What's On: channel, start, title and how far their reminders have got. */ fun saveReminders(userId: String, reminders: List) = write(file("reminders", 0), root(userId, 0).put("reminders", JSONArray().also { saved -> diff --git a/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt b/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt index 5c5e9447..a6620648 100644 --- a/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt +++ b/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt @@ -33,7 +33,7 @@ internal class SecureMediaDataSource(private val session: EmbySampleSession) : B next.instanceFollowRedirects = false next.connectTimeout = 10_000 next.readTimeout = 20_000 - next.setRequestProperty("User-Agent", "OrbitTV/0.100.1") + next.setRequestProperty("User-Agent", "OrbitTV/0.101.0") next.setRequestProperty("Accept-Encoding", "identity") session.mediaHeaders(address).forEach { (key, value) -> next.setRequestProperty(key, value) } if (dataSpec.position != 0L || dataSpec.length != C.LENGTH_UNSET.toLong()) { diff --git a/android/app/src/main/java/tv/orbit/classic/Settings.kt b/android/app/src/main/java/tv/orbit/classic/Settings.kt index 6957117a..11dee7c5 100644 --- a/android/app/src/main/java/tv/orbit/classic/Settings.kt +++ b/android/app/src/main/java/tv/orbit/classic/Settings.kt @@ -76,6 +76,7 @@ internal class OrbitSettings(context: Context) { internal enum class SettingsSection(val label: String, val icon: Int) { Channels("Channels", R.drawable.orbit_icon_all), Viewing("Watching", R.drawable.orbit_icon_entertainment), + Arrivals("New arrivals", R.drawable.orbit_icon_movies), Account("Emby account", R.drawable.orbit_icon_profile), } @@ -225,6 +226,7 @@ private fun AccountDetail(server: String, titles: Long?, onSignOut: () -> Unit, /** Everything behind the gear: a rail of sections on the left, and the chosen one beside it. */ @Composable internal fun SettingsScreen(section: SettingsSection, onSection: (SettingsSection) -> Unit, modifier: Modifier, busy: Boolean, message: String?, server: String, titles: Long?, + arrivals: @Composable (Modifier, FocusRequester) -> Unit, isOn: (Int) -> Boolean, onSwitch: (ChannelProgramming, Boolean) -> Unit, onSuggestions: (ChannelProgramming) -> Unit, onSignOut: () -> Unit, windingDown: Boolean, onWindDown: (Boolean) -> Unit) { val firstFocus = remember { FocusRequester() } @@ -247,6 +249,7 @@ internal fun SettingsScreen(section: SettingsSection, onSection: (SettingsSectio when (section) { SettingsSection.Channels -> ChannelsDetail(busy, message, isOn, onSwitch, onSuggestions, firstSwitch, channelList, detail) SettingsSection.Viewing -> ViewingDetail(isOn(TOTS_NUMBER), windingDown, onWindDown, firstSwitch, detail) + SettingsSection.Arrivals -> arrivals(detail, firstSwitch) SettingsSection.Account -> AccountDetail(server, titles, onSignOut, firstSwitch, detail) } } diff --git a/android/app/src/test/java/tv/orbit/classic/NewArrivalsTest.kt b/android/app/src/test/java/tv/orbit/classic/NewArrivalsTest.kt new file mode 100644 index 00000000..256960a3 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/NewArrivalsTest.kt @@ -0,0 +1,71 @@ +package tv.orbit.classic + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.LocalDate +import java.time.ZoneId + +/** Stage C: what's new, each label with its evidence, and nothing booked or changed. */ +class NewArrivalsTest { + private val zone = ZoneId.of("Europe/London") + private fun at(date: String, hour: Int = 13) = LocalDate.parse(date).atTime(hour, 0).atZone(zone).toInstant().toEpochMilli() + private fun show(id: String, title: String, vararg marks: Pair, prefix: String = id) = + PoolSeries(id, title, marks.map { (s, e) -> PoolEpisode("$prefix-$s-$e", "src", EpisodeMark(s, e), "E$e", 25 * 60_000L) }) + + @Test fun oneWorkWhicheverCopy() { + assertEquals("tmdb:312359", workKey(mapOf("Tmdb" to "312359", "Tvdb" to "473154"), "Dragon Ball Super: Beerus", 2026)) + assertEquals(workKey(mapOf("Tmdb" to "312359"), "Beerus", 2026), workKey(mapOf("tmdb" to "312359", "Imdb" to "tt1"), "Dragon Ball Super: Beerus", 2026)) + assertEquals("tvdb:9", workKey(mapOf("Tvdb" to "9"), "X", null)) + assertEquals(workKey(emptyMap(), "Blue Planet III", 2026), workKey(emptyMap(), "Blue Planet III", 2026)) + } + + @Test fun newEpisodesAreMatchedBySeasonAndEpisodeNeverByFile() { + val before = listOf(show("1", "American Dad!", 1 to 1, 1 to 2, prefix = "copyA"), show("2", "QI", 1 to 1)) + // American Dad! switched to another copy of the same two episodes: nothing new. QI gained an episode. A new show isn't "new episodes". + val after = listOf(show("1", "American Dad!", 1 to 1, 1 to 2, prefix = "copyB"), show("2", "QI", 1 to 1, 1 to 2), show("3", "Brand New Show", 1 to 1)) + val found = newEpisodes(102, before, after, at("2026-11-05")) + assertEquals(listOf("QI" to EpisodeMark(1, 2)), found.map { it.show to it.mark }) + assertEquals(1, mergeNewEpisodes(found, found, at("2026-11-05")).size) + } + + @Test fun arrivalsKeepTheFirstSightingAndArePruned() { + val a = Arrival("1", "Series", "Blue Planet III", 2026, "2026-10-31", "tmdb:1", at("2026-11-05")) + val copy = a.copy(id = "2", firstSeenMs = at("2026-11-06")) + val merged = mergeArrivals(listOf(a), listOf(copy), at("2026-11-06")) + assertEquals(listOf("1"), merged.map { it.id }) + assertTrue(mergeArrivals(merged, emptyList(), at("2027-03-01")).isEmpty()) + } + + @Test fun theRefreshRunsOnceADayAfterNoon() { + assertFalse(arrivalsRefreshDue(null, at("2026-11-05", 11), zone)) + assertTrue(arrivalsRefreshDue(null, at("2026-11-05", 12), zone)) + assertFalse(arrivalsRefreshDue(at("2026-11-05", 12), at("2026-11-05", 20), zone)) + assertTrue(arrivalsRefreshDue(at("2026-11-05", 12), at("2026-11-06", 13), zone)) + } + + @Test fun eachLabelCarriesItsEvidence() { + val now = at("2026-11-06") + val blue = Arrival("10", "Series", "Blue Planet III", 2026, "2026-10-31", "tmdb:10", at("2026-11-05")) + val oldFilm = Arrival("11", "Movie", "Jaws", 1975, "1975-06-20", "tmdb:11", at("2026-11-05")) + val beerus = Arrival("12", "Series", "Dragon Ball Super: Beerus", 2026, "2026-10-10", "tmdb:12", 0) + val upcoming = Arrival("13", "Movie", "Not Out Yet", 2026, "2026-12-01", "tmdb:13", 0) + val report = arrivalsReport(listOf(blue, oldFilm), listOf(blue, beerus, upcoming), listOf(NewEpisode(102, "QI", EpisodeMark(1, 2), now)), + inPools = mapOf("tmdb:12" to "8016753", "tmdb:11" to "11"), booked = setOf("11"), nowMs = now, zone = zone) + // An old film added recently is new to the library but not newly released. + assertEquals(listOf("Blue Planet III (2026)", "Jaws (1975)"), report.newToLibrary.map { it.title }) + assertEquals(listOf("New to the library"), report.newToLibrary.first { it.title.startsWith("Jaws") }.labels) + // Newly released excludes a premiere in the future. + assertEquals(listOf("Blue Planet III (2026)", "Dragon Ball Super: Beerus (2026)"), report.newlyReleased.map { it.title }) + assertTrue(report.newlyReleased.first().evidence.contains("2026-10-31")) + // On a channel's list and never booked: Beerus. Jaws is booked, Blue Planet III isn't on a channel. + assertEquals(listOf("Dragon Ball Super: Beerus (2026)"), report.notYetOnOrbit.map { it.title }) + assertTrue(report.newEpisodes.single().evidence.contains("S1 E2")) + } + + @Test fun nothingInStageCTouchesScheduling() { + // Stage C has no booking path: its only outputs are reports. The four-week fingerprints are checked by the replays. + assertTrue(SmartChannels.none { it.dayParts.any { part -> part.titles.any { title -> title.contains("arrival", ignoreCase = true) } } }) + } +} diff --git a/docs/VERIFICATION-0.101.0.md b/docs/VERIFICATION-0.101.0.md new file mode 100644 index 00000000..17908a18 --- /dev/null +++ b/docs/VERIFICATION-0.101.0.md @@ -0,0 +1,42 @@ +# Orbit TV 0.101.0: Living Network Stage C, spotting what's new (report only) + +Paul approved building C1 on 4 November 2026 at 18:14. Installing it needs its own approval. Stage C labels what's new and books nothing: every channel's booking fingerprint is identical to 0.100.1. Later, Stage D will suggest slots, and eventually book them itself within each channel's rules, as Paul wants. + +## What's in it + +- **A light daily library refresh (`ChannelScheduler.refreshArrivals`).** + - Once a day, after 12:00, in the background while Orbit is open, at the end of the hourly top-up round. + - It reads only the titles the library gained since the catalogue's last position, at most 5 pages (1,000 titles). + - It uses the existing read-only catalogue import, and adds new rows to the catalogue. + - Until the whole library has been read once, what it reads is the baseline, not news. + - A failure changes nothing and is tried again the next hour. The log shows counts only. +- **Arrivals (`arrivals-0.json`):** each new film or series, with its first-seen time and its work identity (TMDB, TVDB or IMDb id, else title and year). Kept one per work, pruned after 90 days and capped at 2,000. +- **New episodes (`newepisodes-0.json`):** at each pool read, episodes a show already on that channel didn't have before. + - They're matched by season and episode, never by file, so a pool switching copies (American Dad!'s 399 files) finds nothing. + - A show new to a pool isn't counted as new episodes. +- **Booked works (`booked-0.json`):** the series id of everything any plan books, added at each top-up. It's only read for the report. +- **Settings › New arrivals:** a read-only page with four lists. Each line shows its labels and evidence: + - **New to the library:** first seen in the last 14 days. + - **Newly released:** premiered in the last 60 days, not in the future, read from the catalogue. + - **New episodes on a channel.** + - **Not yet shown on Orbit:** on a channel's list, never booked since Stage C began. +- **Unchanged:** bookings, pools, channel lists, cursors, What's On and presentation. +- **Version:** 0.101.0 (versionCode 150). + +## Checks before install + +- **467 unit tests pass** (2 skipped: hand-run replays that need input files), including the network audit on the box's files. Lint has no errors. +- **Six new tests in NewArrivalsTest:** + - one work whichever copy; + - new episodes by season and episode, not by file, and not for a new show; + - arrivals keep their first sighting and are pruned; + - the refresh runs once a day after noon; + - each label carries its evidence, including that an old film added recently is new to the library but not newly released, and that a future premiere isn't newly released; + - nothing in Stage C feeds scheduling. +- **Booking fingerprints:** the four-week replay of all 30 channels on 0.101.0 is identical to 0.100.1 on every channel. + +## Known limits + +- **First run:** arrivals start from the first refresh after install. Titles the library gained since 1 November (the last catalogue import) are recorded then, with that day as first seen. +- **Removed titles:** the refresh reads from a position in the library's date-added order. If titles are removed from the library, a new one can occasionally be missed until a full re-read. +- **Not yet shown on Orbit:** this is counted from install onwards. Older bookings aren't known, and only works new to the library or newly released are listed.