From cef9e74d888e15d9b61f28307aa2ae38d170d9ba Mon Sep 17 00:00:00 2001 From: Pauljd Date: Mon, 2 Nov 2026 00:04:34 +0000 Subject: [PATCH] Add the shared scheduling engine, on Paradox only (0.39.0, Phase A in testing) Co-Authored-By: Claude Opus 5.5 (1M context) --- android/app/build.gradle.kts | 4 +- .../java/tv/orbit/classic/ChannelSchedule.kt | 99 ++++++++ .../java/tv/orbit/classic/ChannelScheduler.kt | 66 ++++++ .../main/java/tv/orbit/classic/EmbyClient.kt | 2 +- .../tv/orbit/classic/EmbyConnectionScreen.kt | 70 +++++- .../tv/orbit/classic/EmbyPlaybackDialog.kt | 2 + .../tv/orbit/classic/EmbyPlaybackProtocol.kt | 19 ++ .../java/tv/orbit/classic/EpisodeDiscovery.kt | 44 ++++ .../main/java/tv/orbit/classic/GuideGrid.kt | 12 +- .../java/tv/orbit/classic/SampleChannel.kt | 4 +- .../tv/orbit/classic/SampleChannelScreens.kt | 6 +- .../java/tv/orbit/classic/ScheduleStore.kt | 104 ++++++++ .../tv/orbit/classic/SecureMediaDataSource.kt | 2 +- .../tv/orbit/classic/ChannelScheduleTest.kt | 223 ++++++++++++++++++ 14 files changed, 643 insertions(+), 14 deletions(-) create mode 100644 android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt create mode 100644 android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt create mode 100644 android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt create mode 100644 android/app/src/test/java/tv/orbit/classic/ChannelScheduleTest.kt diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 38480027..0c424df9 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 = 39 - versionName = "0.38.0-orbit-one-art" + versionCode = 40 + versionName = "0.39.0-smart-paradox" } buildFeatures { compose = true } compileOptions { sourceCompatibility = JavaVersion.VERSION_17; targetCompatibility = JavaVersion.VERSION_17 } diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt b/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt new file mode 100644 index 00000000..0ac959c1 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt @@ -0,0 +1,99 @@ +package tv.orbit.classic + +/** What makes a channel itself. The engine below knows nothing about any particular channel. */ +internal data class ChannelProgramming(val number: Int, val name: String, val searches: List, val seriesCount: Int = 3) + +internal val SmartChannels = listOf(ChannelProgramming(152, "Paradox", ChannelPresets.first { it.number == 152 }.searches)) + +internal data class EpisodeMark(val season: Int, val episode: Int) : Comparable { + override fun compareTo(other: EpisodeMark) = compareValuesBy(this, other, { it.season }, { it.episode }) +} +internal data class PoolEpisode(val id: String, val sourceId: String, val mark: EpisodeMark, val title: String, val durationMs: Long) +internal data class PoolSeries(val id: String, val title: String, val episodes: List) + +/** Where a channel has got to: the last episode of each show, and whose turn was last. */ +internal data class ScheduleCursor(val lastSeriesId: String? = null, val marks: Map = emptyMap()) + +internal data class ScheduleEntry(val seriesId: String, val mark: EpisodeMark, val media: ScheduledMedia, val startMs: Long) { + val endMs get() = startMs + media.durationMs +} + +/** Committed programmes, and the cursor after the last of them. */ +internal data class ChannelPlan(val entries: List, val tail: ScheduleCursor) { + val endMs get() = entries.lastOrNull()?.endMs ?: Long.MIN_VALUE +} + +internal const val SCHEDULE_AHEAD_MS = 7 * 24 * 60 * 60_000L +internal const val SCHEDULE_TOP_UP_MS = 6 * 24 * 60 * 60_000L +internal const val SCHEDULE_KEEP_PAST_MS = 24 * 60 * 60_000L + +/** The next episode in season order, starting the show again once it has finished. */ +internal fun nextEpisode(series: PoolSeries, last: EpisodeMark?): PoolEpisode = + last?.let { mark -> series.episodes.firstOrNull { it.mark > mark } } ?: series.episodes.first() + +/** Shows take turns, one episode each, back to back from [fromMs] until [untilMs] is covered. */ +internal fun extendSchedule(pool: List, cursor: ScheduleCursor, fromMs: Long, untilMs: Long): ChannelPlan { + require(pool.isNotEmpty() && pool.all { it.episodes.isNotEmpty() }) + val marks = cursor.marks.toMutableMap() + val entries = mutableListOf() + var last = cursor.lastSeriesId + var start = fromMs + while (start < untilMs) { + val series = pool[(pool.indexOfFirst { it.id == last } + 1) % pool.size] + val episode = nextEpisode(series, marks[series.id]) + val media = ScheduledMedia(scheduledItem(series.title, episode), episode.sourceId, episode.durationMs) + entries += ScheduleEntry(series.id, episode.mark, media, start) + marks[series.id] = episode.mark + last = series.id + start += episode.durationMs + } + return ChannelPlan(entries, ScheduleCursor(last, marks)) +} + +internal fun scheduledItem(seriesTitle: String, episode: PoolEpisode) = SampleItem( + "$seriesTitle / S${episode.mark.season} E${episode.mark.episode} / ${episode.title}", + "Episode", episode.durationMs / 60_000, "", episode.id, episode.durationMs) + +/** What has actually gone out by [nowMs]. Saved apart from the schedule, so losing the schedule doesn't lose the place. */ +internal fun airedCursor(base: ScheduleCursor, entries: List, nowMs: Long): ScheduleCursor { + val marks = base.marks.toMutableMap() + var last = base.lastSeriesId + entries.takeWhile { it.startMs <= nowMs }.forEach { marks[it.seriesId] = it.mark; last = it.seriesId } + return ScheduleCursor(last, marks) +} + +/** + * Only ever appends. Programmes already committed stay as they are, apart from dropping old ones. + * With no usable plan it starts from now at the aired position. + */ +internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List?, nowMs: Long): ChannelPlan? { + val kept = existing?.let { plan -> plan.copy(entries = plan.entries.dropWhile { it.endMs < nowMs - SCHEDULE_KEEP_PAST_MS }) } + if (kept != null && kept.endMs >= nowMs + SCHEDULE_TOP_UP_MS) return kept + if (pool.isNullOrEmpty()) return kept + val from = if (kept != null && kept.endMs > nowMs) kept.endMs else nowMs + val added = extendSchedule(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS) + return ChannelPlan(kept?.entries.orEmpty() + added.entries, added.tail) +} + +/** + * A channel that reads committed programmes, and falls back to its existing loop outside them. + * The plan is swapped inside one object, so a top-up never looks like a new channel and never interrupts playback. + */ +internal class ScheduledChannel(val loop: SampleChannel, plan: ChannelPlan) : SampleChannel(loop.lineup, loop.name, loop.number) { + @Volatile var plan: ChannelPlan = plan + override fun at(timeMs: Long): SampleBroadcast { + val entries = plan.entries + var low = 0 + var high = entries.lastIndex + while (low <= high) { + val middle = (low + high) ushr 1 + val entry = entries[middle] + when { + timeMs < entry.startMs -> high = middle - 1 + timeMs >= entry.endMs -> low = middle + 1 + else -> return SampleBroadcast(entry.media, entry.startMs) + } + } + return loop.at(timeMs) + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt new file mode 100644 index 00000000..3d4c5e99 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -0,0 +1,66 @@ +package tv.orbit.classic + +import android.util.Log + +internal const val POOL_REFRESH_MS = 7 * 24 * 60 * 60_000L + +/** Only counts and times, so it's safe to log. Never titles, addresses or the account. */ +internal class SchedulerReport(val programmes: Int, val episodes: Int, val shows: List, val requests: Int, + val fetchMs: Long, val planMs: Long, val bytes: Long, val fromCache: Boolean, val endMs: Long) { + fun logLine(number: Int) = "channel=$number programmes=$programmes episodes=$episodes shows=${shows.size} requests=$requests fetchMs=$fetchMs planMs=$planMs bytes=$bytes cache=$fromCache" +} + +internal class ChannelScheduler(private val store: ScheduleStore, private val clock: () -> Long = System::currentTimeMillis) { + /** Disk only and quick, so the guide and player agree from the first frame after a restart. */ + fun load(userId: String, loop: SampleChannel): ScheduledChannel? { + if (store.loadProgress(userId, loop.number)?.enabled != true) return null + val plan = store.loadPlan(userId, loop.number)?.takeIf { it.entries.isNotEmpty() } ?: return null + return ScheduledChannel(loop, plan) + } + + fun enabled(userId: String, number: Int) = store.loadProgress(userId, number)?.enabled == true + + /** Going back to the loop keeps the schedule and the place, so turning it on again carries on. */ + fun setEnabled(userId: String, number: Int, enabled: Boolean) { + val progress = store.loadProgress(userId, number) + store.saveProgress(userId, number, ScheduleStore.SavedProgress(enabled, progress?.aired ?: ScheduleCursor())) + } + + /** + * Brings a channel's plan up to seven days ahead, reading the provider only if the cached pool is missing or old. + * A failed refresh keeps what's there, so a provider outage can't disturb what's committed. + */ + fun topUp(session: EmbySampleSession, userId: String, programming: ChannelProgramming, checkActive: () -> Unit = {}): SchedulerReport { + val number = programming.number + val now = clock() + val cached = store.loadPool(userId, number) + var pool = cached + var requests = 0 + var fetchMs = 0L + if (cached == null || now - cached.fetchedAtMs >= POOL_REFRESH_MS) { + val started = android.os.SystemClock.elapsedRealtime() + try { + val read = session.readChannelPool(programming, checkActive) + requests = read.requests + fetchMs = android.os.SystemClock.elapsedRealtime() - started + if (read.series.isNotEmpty()) { + pool = ScheduleStore.SavedPool(read.series, now) + store.savePool(userId, number, pool) + } + } catch (failure: EmbyCheckException) { if (cached == null) throw failure } + } + val started = android.os.SystemClock.elapsedRealtime() + val existing = store.loadPlan(userId, number) + val progress = store.loadProgress(userId, number) + val base = progress?.aired ?: ScheduleCursor() + val plan = topUpPlan(existing, base, pool?.series, now) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.") + if (plan !== existing) store.savePlan(userId, number, plan) + 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 + val report = SchedulerReport(plan.entries.size, pool?.series.orEmpty().sumOf { it.episodes.size }, pool?.series.orEmpty().map { it.title }, + requests, fetchMs, planMs, store.sizes(number).values.sum(), requests == 0, plan.endMs) + Log.i("OrbitSchedule", report.logLine(number)) + return report + } +} 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 0a56e94d..dfea6981 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt @@ -41,7 +41,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.38.0\"") + connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.39.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 9d135367..a3237298 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt @@ -91,6 +91,10 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea var watchingChannel by remember { mutableStateOf(false) } var guideCategory by remember { mutableStateOf(ChannelCategory.All) } val liveHandoff = remember { LiveHandoff() } + val scheduleStore = remember { ScheduleStore(java.io.File(appContext.noBackupFilesDir, "schedule")) } + val scheduler = remember { ChannelScheduler(scheduleStore) } + var scheduledChannels by remember { mutableStateOf>(emptyMap()) } + fun onAir(loop: SampleChannel) = scheduledChannels[loop.number]?.takeIf { it.loop === loop } ?: loop var channelClockOffset by remember { mutableLongStateOf(0) } var busyLabel by remember { mutableStateOf("Connecting…") } val sessionSlot = remember { EmbySessionSlot() } @@ -111,7 +115,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea seriesMatches = saved.matches.takeIf { it.isNotEmpty() }; approvedSeries = saved.approved episodeSamples = saved.episodes; channel = saved.orbitOne; toonamiChannel = saved.toonami; extraChannels = saved.extra darkMovies = saved.darkMovies; approvedDark = saved.approvedDark; afterDarkChannel = saved.afterDark - val available = availableSampleChannels(channel, afterDarkChannel, toonamiChannel, *extraChannels.toTypedArray()) + val available = availableSampleChannels(channel, afterDarkChannel, toonamiChannel, *extraChannels.map(::onAir).toTypedArray()) selectedNumber = available.firstOrNull { it.number == saved.selectedNumber }?.number ?: available.firstOrNull()?.number ?: 101 onChannelAvailable(available.isNotEmpty()) } @@ -120,6 +124,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea savedStore.invalidate() if (forget) { pendingSaved = null + scheduleStore.clear() try { savedStore.clear() } catch (_: Exception) { message = "The saved connection could not be removed. Clear Orbit TV app data in Android Settings before leaving this device." } try { catalogue.clear() } @@ -128,7 +133,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea seriesMatches = null; episodeSamples = null; reviewingSeries = false; approvedSeries = emptySet() darkMovies = emptyList(); approvedDark = emptySet(); reviewingDark = false; afterDarkChannel = null metadataCoverage = null; reviewingCoverage = false; reviewingCatalogue = false; catalogueSummary = null; catalogueRun = null; reviewingHealth = false; libraryHealth = null; lastNumber = null - playback = null; session = null; sample = null; channel = null; toonamiChannel = null; extraChannels = emptyList(); selectedNumber = 101; watchingChannel = false + playback = null; session = null; sample = null; channel = null; toonamiChannel = null; extraChannels = emptyList(); scheduledChannels = emptyMap(); selectedNumber = 101; watchingChannel = false onChannelAvailable(false) sessionSlot.clear()?.let { active -> EmbyCleanup.run { active.close() } } } @@ -166,6 +171,10 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea if (!sessionSlot.attach(active, slotTicket)) { active.detach(); throw CancellationException() } active } + // Read before the channels appear, so the guide never shows the loop for a moment first. + scheduledChannels = withContext(Dispatchers.IO) { + saved.extra.mapNotNull { loop -> scheduler.load(saved.identity.userId, loop)?.also { resumed.rememberScheduledItems(it.plan.entries.map { entry -> entry.media.item }) } }.associateBy { it.number } + } session = resumed; sample = resumed.sample; applyChoices(saved) saveTicket = savedStore.ticket() message = "Saved connection restored." @@ -203,6 +212,28 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea } } LaunchedEffect(Unit) { while (true) { now = System.currentTimeMillis(); delay(1000) } } + // Keeps smart channels topped up in the background. A failure changes nothing on air. + LaunchedEffect(session, extraChannels) { + val active = session ?: return@LaunchedEffect + while (true) { + for (programming in SmartChannels) { + val loop = extraChannels.firstOrNull { it.number == programming.number } ?: continue + try { + withContext(Dispatchers.IO) { + if (scheduler.enabled(active.accountId, programming.number)) { + scheduler.topUp(active, active.accountId, programming) + val fresh = scheduleStore.loadPlan(active.accountId, programming.number) + val onAirNow = scheduledChannels[programming.number]?.takeIf { it.loop === loop } + if (fresh != null && onAirNow != null) onAirNow.plan = fresh + else scheduler.load(active.accountId, loop)?.let { scheduledChannels = scheduledChannels + (programming.number to it) } + } + } + } catch (cancelled: CancellationException) { throw cancelled } + catch (_: Exception) { /* Tried again next hour. */ } + } + delay(60 * 60_000L) + } + } LaunchedEffect(visible) { if (!visible) { clearPassword(); username = ""; keyboard?.hide() @@ -220,7 +251,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea val ready = !busy && !restoring && now >= nextAttemptAt && username.isNotBlank() && password.text.isNotEmpty() playback?.let { plan -> session?.let { active -> EmbyPlaybackDialog(active, plan, onClose = { playback = null }) } } val liveSession = session - val availableChannels = availableSampleChannels(channel, afterDarkChannel, toonamiChannel, *extraChannels.toTypedArray()) + val availableChannels = availableSampleChannels(channel, afterDarkChannel, toonamiChannel, *extraChannels.map(::onAir).toTypedArray()) val liveChannel = availableChannels.firstOrNull { it.number == selectedNumber } if ((mainGuide || mainHome) && liveSession != null && liveChannel != null) { if (watchingChannel) ScheduledChannelPlayer(liveSession, liveChannel, channelClockOffset, @@ -389,6 +420,34 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea finally { busy = false } } } + fun setSmartSchedule(programming: ChannelProgramming, turnOn: Boolean) { + val active = session ?: return + val loop = extraChannels.firstOrNull { it.number == programming.number } ?: return + if (busy) return + busy = true; busyLabel = "Reading ${programming.name}'s whole series and planning seven days…"; message = null + job = scope.launch { + try { + if (turnOn) { + val report = withContext(Dispatchers.IO) { + val context = coroutineContext + scheduler.setEnabled(active.accountId, programming.number, true) + scheduler.topUp(active, active.accountId, programming) { context.ensureActive() }.also { + scheduler.load(active.accountId, loop)?.let { on -> scheduledChannels = scheduledChannels + (programming.number to on) } + } + } + message = "${programming.name} is scheduled: ${report.programmes} programmes from ${report.episodes} episodes of ${report.shows.joinToString()}. " + + "${report.requests} requests, ${report.fetchMs / 1000} s to read, ${report.planMs} ms to plan, ${report.bytes / 1024} KB stored." + } else { + withContext(Dispatchers.IO) { scheduler.setEnabled(active.accountId, programming.number, false) } + scheduledChannels = scheduledChannels - programming.number + message = "${programming.name} is back on its loop. Its schedule and place are kept." + } + } catch (cancelled: CancellationException) { throw cancelled } + catch (failure: EmbyCheckException) { withContext(Dispatchers.IO) { scheduler.setEnabled(active.accountId, programming.number, false) }; message = failure.message } + catch (_: Exception) { withContext(Dispatchers.IO) { scheduler.setEnabled(active.accountId, programming.number, false) }; message = "${programming.name} could not be scheduled, so it stays on its loop." } + finally { busy = false } + } + } fun checkMoreSeries() { val active = session ?: return if (busy) return @@ -575,6 +634,11 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea OrbitButton("${preset.number} ${preset.name} — ${if (built) "rebuild" else "build"}", Modifier.fillMaxWidth(), enabled = !busy && session != null, onClick = { buildPreset(preset) }) } + SmartChannels.forEach { programming -> + val on = scheduledChannels.containsKey(programming.number) + OrbitButton("${programming.number} ${programming.name} — smart schedule ${if (on) "on (press for loop)" else "off (press to start)"}", Modifier.fillMaxWidth(), + enabled = !busy && session != null && extraChannels.any { it.number == programming.number }, onClick = { setSmartSchedule(programming, !on) }) + } OrbitButton("Check metadata coverage", Modifier.fillMaxWidth(), enabled = !busy && session != null, onClick = { message = null; reviewingCoverage = true }) OrbitButton("Library import test", Modifier.fillMaxWidth(), diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackDialog.kt b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackDialog.kt index 7e1d0d0f..17462c8d 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackDialog.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackDialog.kt @@ -48,6 +48,7 @@ internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPl var lastInteraction by remember { mutableLongStateOf(SystemClock.elapsedRealtime()) } fun showInfo() { infoVisible = true; lastInteraction = SystemClock.elapsedRealtime() } var handedBack by remember { mutableStateOf(false) } + val openedAt = remember { SystemClock.elapsedRealtime() } var numberEntry by remember { mutableStateOf(null) } var numberProblem by remember { mutableStateOf(null) } var okHeld by remember { mutableStateOf(false) } @@ -127,6 +128,7 @@ internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPl val target = scheduled.programme.offsetAt(scheduled.nowMs()) if (kotlin.math.abs(player.currentPosition - target) > 2_000) player.seekTo(target) } + if (!ready) android.util.Log.i("OrbitSchedule", "channel=${scheduled?.channel?.number} tuneReadyMs=${SystemClock.elapsedRealtime() - openedAt} handedOver=${runningPlayer != null}") ready = true } } diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt index 59ea5038..715465ba 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt @@ -49,6 +49,7 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v @Volatile private var darkLineup: Map = emptyMap() @Volatile private var active: EmbyPlaybackPlan? = null @Volatile private var lastPositionMs = 0L + val accountId get() = userId fun rememberedIdentity() = RememberedIdentity(userId, currentToken(), (transport as? HttpsEmbyTransport)?.deviceId ?: "fixture-device") fun matchesAccount(identity: RememberedIdentity) = userId == identity.userId @@ -183,6 +184,24 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v return PresetBuild(SampleChannel(media, preset.name, preset.number), groups.map { it.series.title }, missing) } + internal class PoolRead(val series: List, val requests: Int) + /** The first shows in the channel's list that have episodes to schedule. */ + fun readChannelPool(programming: ChannelProgramming, checkActive: () -> Unit = {}): PoolRead { + var requests = 0 + val pool = mutableListOf() + for (search in programming.searches) { + if (pool.size == programming.seriesCount) break + checkActive() + requests++ + val match = bestSeriesMatch(search, searchSeries(transport, userId, ::currentToken, search).candidates) ?: continue + if (pool.any { it.id == match.id }) continue + val whole = readWholeSeries(transport, userId, ::currentToken, match, checkActive, onRequest = { requests++ }) + if (whole.episodes.isNotEmpty()) pool += whole + } + return PoolRead(pool, requests) + } + fun rememberScheduledItems(items: List) { channelEpisodes = channelEpisodes + items.associateBy { it.id } } + fun checkMetadataCoverage(checkActive: () -> Unit = {}): List = auditMetadataCoverage(transport, userId, ::currentToken, checkActive) fun importCatalogue(sink: CatalogueSink, maxPages: Int = CATALOGUE_PAGES_PER_RUN, pause: () -> Unit = {}, checkActive: () -> Unit = {}, onPage: () -> Unit = {}, diff --git a/android/app/src/main/java/tv/orbit/classic/EpisodeDiscovery.kt b/android/app/src/main/java/tv/orbit/classic/EpisodeDiscovery.kt index f72f43f4..76b3ebe7 100644 --- a/android/app/src/main/java/tv/orbit/classic/EpisodeDiscovery.kt +++ b/android/app/src/main/java/tv/orbit/classic/EpisodeDiscovery.kt @@ -43,3 +43,47 @@ internal fun episodeMediaLabel(item: org.json.JSONObject): String { .joinToString(" / ").takeIf { it.isNotEmpty() } return listOfNotNull(resolution, container, codecs).joinToString(" • ") } + +internal const val WHOLE_SERIES_PAGE = 100 +internal const val WHOLE_SERIES_MAX_EPISODES = 5_000 +internal const val WHOLE_SERIES_TIMEOUT_MS = 60_000 + +/** A whole series, read in bounded pages one at a time: regular numbered episodes with a playable source, once each, in order. */ +internal fun readWholeSeries(transport: EmbyTransport, userId: String, token: () -> String, series: SeriesCandidate, + checkActive: () -> Unit = {}, onRequest: () -> Unit = {}): PoolSeries { + require(EmbyClient.validId(userId) && EmbyClient.validId(series.id)) + val episodes = mutableListOf() + var start = 0 + while (start < WHOLE_SERIES_MAX_EPISODES) { + checkActive() + onRequest() + val request = EmbyRequest("GET", "/Shows/${series.id}/Episodes?UserId=$userId&StartIndex=$start&Limit=$WHOLE_SERIES_PAGE&Fields=MediaSources&EnableImages=false&EnableUserData=false", + token = token(), readTimeoutMs = WHOLE_SERIES_TIMEOUT_MS) + // One more try on a slow answer. Anything further fails the read, and the app tries again later. + val reply = try { transport.execute(request) } catch (failure: EmbyCheckException) { + if (!failure.retryable) throw failure + onRequest() + transport.execute(request) + } + EmbyClient.expectSuccess(reply.status, false) + val body = EmbyClient.parse(reply.body) + val rows = body.optJSONArray("Items") ?: throw EmbyCheckException("The provider did not return the episode list.") + (0 until rows.length()).forEach { index -> rows.optJSONObject(index)?.let(::poolEpisode)?.let { episodes += it } } + start += rows.length() + if (rows.length() == 0 || start >= body.optInt("TotalRecordCount", 0)) break + } + return PoolSeries(series.id, series.title, episodes.sortedBy { it.mark }.distinctBy { it.mark }) +} + +private fun poolEpisode(item: org.json.JSONObject): PoolEpisode? { + val id = item.optString("Id") + val season = item.optInt("ParentIndexNumber", -1) + val number = item.optInt("IndexNumber", -1) + if (item.optString("Type") != "Episode" || !EmbyClient.validId(id) || season < 1 || number < 1) return null + val sources = item.optJSONArray("MediaSources") ?: return null + val source = (0 until minOf(sources.length(), 20)).mapNotNull { sources.optJSONObject(it) } + .firstOrNull { supportedDirectContainer(it.optString("Container")) != null && EmbyClient.validId(it.optString("Id")) } ?: return null + val ticks = source.optLong("RunTimeTicks", 0).takeIf { it > 0 } ?: item.optLong("RunTimeTicks", 0) + val duration = (ticks / 10_000).takeIf { it in 1_000..SampleChannel.MAX_DURATION_MS } ?: return null + return PoolEpisode(id, source.getString("Id"), EpisodeMark(season, number), EmbyClient.clean(item.optString("Name"), 160).ifBlank { "Untitled episode" }, duration) +} diff --git a/android/app/src/main/java/tv/orbit/classic/GuideGrid.kt b/android/app/src/main/java/tv/orbit/classic/GuideGrid.kt index 0b9e1245..1bc0ea51 100644 --- a/android/app/src/main/java/tv/orbit/classic/GuideGrid.kt +++ b/android/app/src/main/java/tv/orbit/classic/GuideGrid.kt @@ -24,7 +24,7 @@ import kotlinx.coroutines.delay internal const val GUIDE_SLOT_MS = 30 * 60_000L internal const val GUIDE_SLOTS = 4 -private const val GUIDE_MAX_SLOTS_AHEAD = 48 +private const val GUIDE_MAX_SLOTS_AHEAD = 7 * 48 internal data class GuideCell(val show: SampleBroadcast, val startFraction: Float, val widthFraction: Float) @@ -51,6 +51,12 @@ internal fun guideTitleParts(title: String): Pair { return parts[0] to parts.drop(1).joinToString(" • ").ifBlank { null } } +/** A day name once the guide has moved past today, so a week ahead stays readable. */ +internal fun guideDayPrefix(timeMs: Long, nowMs: Long): String { + val day = java.text.SimpleDateFormat("yyyyDDD", java.util.Locale.UK) + return if (day.format(java.util.Date(timeMs)) == day.format(java.util.Date(nowMs))) "" else java.text.SimpleDateFormat("EEE d MMM ", java.util.Locale.UK).format(java.util.Date(timeMs)) +} + /** The first row to draw, moving only as far as it takes to keep the chosen row on screen. */ internal fun guideFirstRow(row: Int, first: Int, visible: Int, count: Int): Int { val last = (count - visible).coerceAtLeast(0) @@ -110,7 +116,7 @@ internal fun GuideGrid(channels: List, selectedNumber: Int, modif val (focusedName, focusedDetail) = guideTitleParts(focused.media.item.title) Text(focusedName, color = Color.White, fontSize = 17.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis) if (focusedDetail != null) Text(focusedDetail, color = Color.White, fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis) - Text("${clock(focused.startMs)} to ${clock(focused.endMs)} • ${channel.number} ${ChannelBrands.displayName(channel)}", color = Muted, fontSize = 12.sp, maxLines = 1) + Text("${guideDayPrefix(focused.startMs, now)}${clock(focused.startMs)} to ${clock(focused.endMs)} • ${channel.number} ${ChannelBrands.displayName(channel)}", color = Muted, fontSize = 12.sp, maxLines = 1) } Column(verticalArrangement = Arrangement.Top) { OrbitButton("Test transition", Modifier.focusRequester(toolsFocus).onPreviewKeyEvent { event -> @@ -119,7 +125,7 @@ internal fun GuideGrid(channels: List, selectedNumber: Int, modif } } Row(Modifier.fillMaxWidth().height(20.dp).background(Panel), verticalAlignment = Alignment.CenterVertically) { - Text(title, Modifier.width(130.dp).padding(start = 8.dp), color = Color.White, fontSize = 12.sp, fontWeight = FontWeight.SemiBold) + Text(guideDayPrefix(windowStart, now).trim().ifEmpty { title }, Modifier.width(130.dp).padding(start = 8.dp), color = Color.White, fontSize = 12.sp, fontWeight = FontWeight.SemiBold) Row(Modifier.weight(1f)) { repeat(GUIDE_SLOTS) { Text(clock(windowStart + it * GUIDE_SLOT_MS), Modifier.weight(1f).padding(start = 4.dp), color = Color.White, fontSize = 12.sp, fontWeight = FontWeight.SemiBold) } } diff --git a/android/app/src/main/java/tv/orbit/classic/SampleChannel.kt b/android/app/src/main/java/tv/orbit/classic/SampleChannel.kt index d1a0a88a..4cc41dd3 100644 --- a/android/app/src/main/java/tv/orbit/classic/SampleChannel.kt +++ b/android/app/src/main/java/tv/orbit/classic/SampleChannel.kt @@ -7,7 +7,7 @@ internal data class SampleBroadcast(val media: ScheduledMedia, val startMs: Long } /** A repeating UTC timeline: it advances even when no screen or player exists. */ -internal class SampleChannel(entries: List, val name: String = "Orbit One", val number: Int = 101) { +internal open class SampleChannel(entries: List, val name: String = "Orbit One", val number: Int = 101) { val lineup = entries.toList() companion object { const val MAX_DURATION_MS = 7 * 24 * 60 * 60 * 1000L } init { @@ -16,7 +16,7 @@ internal class SampleChannel(entries: List, val name: String = " require(lineup.all { EmbyClient.validId(it.item.id) && EmbyClient.validId(it.sourceId) && it.durationMs in 1_000..MAX_DURATION_MS }) } val cycleMs = lineup.sumOf { it.durationMs } - fun at(timeMs: Long): SampleBroadcast { + open fun at(timeMs: Long): SampleBroadcast { require(timeMs in -8_000_000_000_000_000L..8_000_000_000_000_000L) val position = Math.floorMod(timeMs, cycleMs) var cursor = 0L diff --git a/android/app/src/main/java/tv/orbit/classic/SampleChannelScreens.kt b/android/app/src/main/java/tv/orbit/classic/SampleChannelScreens.kt index f66ff916..4b090882 100644 --- a/android/app/src/main/java/tv/orbit/classic/SampleChannelScreens.kt +++ b/android/app/src/main/java/tv/orbit/classic/SampleChannelScreens.kt @@ -115,17 +115,19 @@ internal fun ScheduledChannelPlayer(session: EmbySampleSession, channel: SampleC if (handed != null && prepared === handed.plan && preparedSlot == current.startMs) return@LaunchedEffect prepared = null; preparedSlot = null; problem = null try { + val tuneStarted = android.os.SystemClock.elapsedRealtime() val plan = prepareMutex.withLock { withContext(Dispatchers.IO) { session.prepareForTuning(current.media.item, current.media.sourceId) { Thread.sleep(2_000) } } } + android.util.Log.i("OrbitSchedule", "channel=${channel.number} tunePrepareMs=${android.os.SystemClock.elapsedRealtime() - tuneStarted}") if (!scheduledRuntimeMatches(plan.durationMs, current.media.durationMs)) throw EmbyCheckException("This programme's runtime changed. Return and rebuild the sample channel.") preparedSlot = current.startMs; prepared = plan } catch (cancelled: CancellationException) { throw cancelled } - catch (failure: EmbyCheckException) { problem = failure.message } - catch (_: Exception) { problem = "This scheduled programme could not be opened. Return to the guide and try again." } + catch (failure: EmbyCheckException) { problem = if (channel is ScheduledChannel) "This programme isn't available right now. Orbit moves on at ${clock(current.endMs)}." else failure.message } + catch (_: Exception) { problem = if (channel is ScheduledChannel) "This programme isn't available right now. Orbit moves on at ${clock(current.endMs)}." else "This scheduled programme could not be opened. Return to the guide and try again." } } // Suppress the preceding plan immediately at a boundary while the effect schedules its replacement. val plan = prepared?.takeIf { it.item.id == current.media.item.id && preparedSlot == current.startMs && problem == null } diff --git a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt new file mode 100644 index 00000000..09575c07 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt @@ -0,0 +1,104 @@ +package tv.orbit.classic + +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.io.FileOutputStream + +/** + * Three small files per channel in app-private storage, away from the library database: the episode cache, + * the committed schedule and the aired progress. Each can be lost without affecting the others. Holds no login. + */ +internal class ScheduleStore(private val directory: File) { + companion object { const val SCHEMA = 1 } + internal class SavedProgress(val enabled: Boolean, val aired: ScheduleCursor) + internal class SavedPool(val series: List, val fetchedAtMs: Long) + + private fun file(kind: String, number: Int) = File(directory, "$kind-$number.json") + + /** Replaces in one step, keeping the last good copy. An interrupted write can't damage either. */ + private fun write(target: File, root: JSONObject) { + directory.mkdirs() + val temporary = File(directory, "${target.name}.tmp") + FileOutputStream(temporary).use { output -> output.write(root.toString().toByteArray(Charsets.UTF_8)); output.fd.sync() } + if (target.exists()) target.copyTo(File(directory, "${target.name}.prev"), overwrite = true) + if (!temporary.renameTo(target)) throw java.io.IOException("Schedule file could not be replaced.") + } + + /** Falls back to the last good copy. Anything unreadable or from another account counts as absent. */ + private fun read(target: File, userId: String, number: Int, parse: (JSONObject) -> T): T? { + for (candidate in listOf(target, File(directory, "${target.name}.prev"))) { + try { + if (!candidate.exists()) continue + val root = JSONObject(candidate.readText(Charsets.UTF_8)) + require(root.getInt("schema") == SCHEMA && root.getString("user") == userId && root.getInt("channel") == number) + return parse(root) + } catch (_: Exception) { /* Damaged: try the last good copy. */ } + } + return null + } + + private fun root(userId: String, number: Int) = JSONObject().put("schema", SCHEMA).put("user", userId).put("channel", number) + + private fun encodeCursor(cursor: ScheduleCursor) = JSONObject().put("last", cursor.lastSeriesId ?: JSONObject.NULL) + .put("marks", JSONObject().also { marks -> cursor.marks.forEach { (id, mark) -> marks.put(id, JSONArray().put(mark.season).put(mark.episode)) } }) + private fun decodeCursor(o: JSONObject): ScheduleCursor { + val marks = o.getJSONObject("marks") + return ScheduleCursor(if (o.isNull("last")) null else validId(o.getString("last")), + marks.keys().asSequence().associate { id -> validId(id) to marks.getJSONArray(id).let { EpisodeMark(it.getInt(0), it.getInt(1)) } }) + } + private fun validId(id: String) = id.also { require(EmbyClient.validId(it)) } + private fun validDuration(ms: Long) = ms.also { require(it in 1_000..SampleChannel.MAX_DURATION_MS) } + + fun savePlan(userId: String, number: Int, plan: ChannelPlan) { + val entries = JSONArray() + plan.entries.forEach { e -> entries.put(JSONObject().put("s", e.seriesId).put("n", JSONArray().put(e.mark.season).put(e.mark.episode)) + .put("i", e.media.item.id).put("c", e.media.sourceId).put("t", e.media.item.title).put("d", e.media.durationMs).put("a", e.startMs)) } + write(file("schedule", number), root(userId, number).put("tail", encodeCursor(plan.tail)).put("entries", entries)) + } + fun loadPlan(userId: String, number: Int): ChannelPlan? = read(file("schedule", number), userId, number) { root -> + val rows = root.getJSONArray("entries") + val entries = (0 until rows.length()).map { index -> + val o = rows.getJSONObject(index) + val duration = validDuration(o.getLong("d")) + val mark = o.getJSONArray("n").let { EpisodeMark(it.getInt(0), it.getInt(1)) } + val item = SampleItem(o.getString("t"), "Episode", duration / 60_000, "", validId(o.getString("i")), duration) + ScheduleEntry(validId(o.getString("s")), mark, ScheduledMedia(item, validId(o.getString("c")), duration), o.getLong("a")) + } + require(entries.zipWithNext().all { (first, second) -> first.endMs <= second.startMs }) + ChannelPlan(entries, decodeCursor(root.getJSONObject("tail"))) + } + + fun saveProgress(userId: String, number: Int, progress: SavedProgress) = + write(file("progress", number), root(userId, number).put("enabled", progress.enabled).put("aired", encodeCursor(progress.aired))) + fun loadProgress(userId: String, number: Int): SavedProgress? = read(file("progress", number), userId, number) { root -> + SavedProgress(root.getBoolean("enabled"), decodeCursor(root.getJSONObject("aired"))) + } + + fun savePool(userId: String, number: Int, pool: SavedPool) { + val series = JSONArray() + pool.series.forEach { show -> + val episodes = JSONArray() + show.episodes.forEach { e -> episodes.put(JSONArray().put(e.id).put(e.sourceId).put(e.mark.season).put(e.mark.episode).put(e.title).put(e.durationMs)) } + series.put(JSONObject().put("id", show.id).put("title", show.title).put("episodes", episodes)) + } + write(file("episodes", number), root(userId, number).put("fetched", pool.fetchedAtMs).put("series", series)) + } + fun loadPool(userId: String, number: Int): SavedPool? = read(file("episodes", number), userId, number) { root -> + val rows = root.getJSONArray("series") + SavedPool((0 until rows.length()).map { index -> + val show = rows.getJSONObject(index) + val episodes = show.getJSONArray("episodes") + PoolSeries(validId(show.getString("id")), show.getString("title"), (0 until episodes.length()).map { row -> + val e = episodes.getJSONArray(row) + PoolEpisode(validId(e.getString(0)), validId(e.getString(1)), EpisodeMark(e.getInt(2), e.getInt(3)), e.getString(4), validDuration(e.getLong(5))) + }.also { require(it.isNotEmpty()) }) + }, root.getLong("fetched")) + } + + /** Bytes held for a channel, for the measurements. */ + fun sizes(number: Int) = listOf("episodes", "schedule", "progress").associateWith { file(it, number).length() } + + /** On forgetting the account. Rollback never needs this: the channel simply goes back to its loop. */ + fun clear() { directory.listFiles()?.forEach { it.delete() } } +} 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 31664b53..ce33ca85 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.38.0") + next.setRequestProperty("User-Agent", "OrbitTV/0.39.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/test/java/tv/orbit/classic/ChannelScheduleTest.kt b/android/app/src/test/java/tv/orbit/classic/ChannelScheduleTest.kt new file mode 100644 index 00000000..7f2e70c8 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/ChannelScheduleTest.kt @@ -0,0 +1,223 @@ +package tv.orbit.classic + +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class ChannelScheduleTest { + @get:Rule val folder = TemporaryFolder() + private val minute = 60_000L + private val day = 24 * 60 * minute + private val now = 1_800_000_000_000L + private val user = "fixture-user" + private fun show(id: String, seasons: Int, perSeason: Int, minutes: Long = 45) = PoolSeries(id, "Show $id", (1..seasons).flatMap { season -> + (1..perSeason).map { number -> PoolEpisode("$id-$season-$number", "src-$id-$season-$number", EpisodeMark(season, number), "E$number", minutes * minute) } + }) + private val pool = listOf(show("a", 2, 3), show("b", 1, 2), show("c", 3, 10, 22)) + private val loop = SampleChannel(listOf(media("x"), media("y")), "Paradox", 152) + private fun media(id: String) = ScheduledMedia(SampleItem(id, "Episode", 1, "", id, minute), "s-$id", minute) + private fun store() = ScheduleStore(folder.newFolder()) + + @Test fun showsTakeTurnsOneEpisodeEach() { + val entries = extendSchedule(pool, ScheduleCursor(), now, now + 8 * 60 * minute).entries + assertEquals(listOf("a", "b", "c", "a", "b", "c"), entries.take(6).map { it.seriesId }) + } + + @Test fun episodesRunInOrderAcrossSeasonsThenStartAgain() { + val only = listOf(show("a", 2, 2)) + val entries = extendSchedule(only, ScheduleCursor(), now, now + 6 * 45 * minute).entries + assertEquals(listOf(EpisodeMark(1, 1), EpisodeMark(1, 2), EpisodeMark(2, 1), EpisodeMark(2, 2), EpisodeMark(1, 1), EpisodeMark(1, 2)), entries.map { it.mark }) + } + + @Test fun programmesRunBackToBackWithExactTimes() { + val entries = extendSchedule(pool, ScheduleCursor(), now, now + day).entries + assertEquals(now, entries.first().startMs) + assertTrue(entries.zipWithNext().all { (first, second) -> first.endMs == second.startMs }) + } + + @Test fun aSevenDayPlanCoversTheWeek() { + val plan = topUpPlan(null, ScheduleCursor(), pool, now)!! + assertTrue(plan.endMs >= now + SCHEDULE_AHEAD_MS) + } + + @Test fun extendingNeverChangesWhatIsCommitted() { + val first = topUpPlan(null, ScheduleCursor(), pool, now)!! + val later = now + 2 * day + val second = topUpPlan(first, ScheduleCursor(), pool, later)!! + val stillThere = first.entries.filter { it.endMs >= later - SCHEDULE_KEEP_PAST_MS } + assertEquals(stillThere, second.entries.take(stillThere.size)) + assertTrue(second.endMs >= later + SCHEDULE_AHEAD_MS) + assertTrue(second.entries.zipWithNext().all { (a, b) -> a.endMs == b.startMs }) + } + + @Test fun extendingCarriesOnFromTheTailNotTheStart() { + val first = topUpPlan(null, ScheduleCursor(), pool, now)!! + val second = topUpPlan(first, ScheduleCursor(), pool, now + 2 * day)!! + val added = second.entries[second.entries.indexOf(first.entries.last()) + 1] + val expected = extendSchedule(pool, first.tail, first.endMs, first.endMs + 1).entries.single() + assertEquals(expected, added) + } + + @Test fun aFreshPlanNeedsNoWorkWithinTheTopUpWindow() { + val first = topUpPlan(null, ScheduleCursor(), pool, now)!! + assertEquals(first.entries, topUpPlan(first, ScheduleCursor(), null, now + 60 * minute)!!.entries) + } + + @Test fun aProviderOutageKeepsThePlanButAddsNothing() { + val first = topUpPlan(null, ScheduleCursor(), pool, now)!! + val later = now + 3 * day + assertEquals(first.entries.last(), topUpPlan(first, ScheduleCursor(), null, later)!!.entries.last()) + assertNull(topUpPlan(null, ScheduleCursor(), null, now)) + } + + @Test fun guideAndPlayerAgreeAndJoinPartWayThrough() { + val plan = topUpPlan(null, ScheduleCursor(), pool, now)!! + val channel = ScheduledChannel(loop, plan) + val entry = plan.entries[5] + val joined = channel.at(entry.startMs + 18 * minute) + assertEquals(entry.media, joined.media) + assertEquals(18 * minute, joined.offsetAt(entry.startMs + 18 * minute)) + val cells = guideCells(channel, entry.startMs, entry.startMs + 2 * 60 * minute) + assertEquals(entry.media, cells.first().show.media) + } + + @Test fun outsideThePlanTheLoopCarriesOn() { + val plan = topUpPlan(null, ScheduleCursor(), pool, now)!! + val channel = ScheduledChannel(loop, plan) + assertEquals(loop.at(plan.endMs + day), channel.at(plan.endMs + day)) + assertEquals(loop.at(now - day), channel.at(now - day)) + } + + @Test fun aTopUpKeepsTheSameChannelObject() { + val channel = ScheduledChannel(loop, topUpPlan(null, ScheduleCursor(), pool, now)!!) + val probe = now + 3 * day + val before = channel.at(probe) + channel.plan = topUpPlan(channel.plan, ScheduleCursor(), pool, now + 2 * day)!! + assertEquals(before, channel.at(probe)) + } + + @Test fun airedPositionOnlyCountsWhatHasStarted() { + val plan = extendSchedule(pool, ScheduleCursor(), now, now + day) + val aired = airedCursor(ScheduleCursor(), plan.entries, plan.entries[3].startMs) + assertEquals("a", aired.lastSeriesId) + assertEquals(EpisodeMark(1, 2), aired.marks["a"]) + assertEquals(EpisodeMark(1, 1), aired.marks["b"]) + } + + @Test fun aRestartReadsBackTheSameSchedule() { + val store = store() + val plan = topUpPlan(null, ScheduleCursor(), pool, now)!! + store.savePlan(user, 152, plan) + assertEquals(plan, store.loadPlan(user, 152)) + } + + @Test fun losingTheScheduleCarriesOnFromTheAiredPlace() { + val store = store() + val plan = topUpPlan(null, ScheduleCursor(), pool, now)!! + val aired = airedCursor(ScheduleCursor(), plan.entries, plan.entries[6].startMs) + store.saveProgress(user, 152, ScheduleStore.SavedProgress(true, aired)) + val rebuilt = topUpPlan(store.loadPlan(user, 152), store.loadProgress(user, 152)!!.aired, pool, plan.entries[6].startMs + minute)!! + assertEquals(extendSchedule(pool, aired, 0, 1).entries.single().media, rebuilt.entries.first().media) + } + + @Test fun aDamagedScheduleFallsBackToItsLastGoodCopy() { + val dir = folder.newFolder() + val store = ScheduleStore(dir) + val plan = topUpPlan(null, ScheduleCursor(), pool, now)!! + store.savePlan(user, 152, plan) + store.savePlan(user, 152, plan) + java.io.File(dir, "schedule-152.json").writeText("{ not json") + assertEquals(plan, store.loadPlan(user, 152)) + } + + @Test fun aScheduleDamagedEverywhereIsAbsentAndProgressSurvives() { + val dir = folder.newFolder() + val store = ScheduleStore(dir) + store.savePlan(user, 152, topUpPlan(null, ScheduleCursor(), pool, now)!!) + store.saveProgress(user, 152, ScheduleStore.SavedProgress(true, ScheduleCursor("a", mapOf("a" to EpisodeMark(2, 1))))) + dir.listFiles()!!.filter { it.name.startsWith("schedule") }.forEach { it.writeText("") } + assertNull(store.loadPlan(user, 152)) + assertEquals(EpisodeMark(2, 1), store.loadProgress(user, 152)!!.aired.marks["a"]) + } + + @Test fun anotherAccountOrChannelOrFormatIsIgnored() { + val dir = folder.newFolder() + val store = ScheduleStore(dir) + store.savePlan(user, 152, topUpPlan(null, ScheduleCursor(), pool, now)!!) + assertNull(store.loadPlan("other-user", 152)) + assertNull(store.loadPlan(user, 140)) + val file = java.io.File(dir, "schedule-152.json") + file.writeText(JSONObject(file.readText()).put("schema", 999).toString()) + assertNull(store.loadPlan(user, 152)) + } + + @Test fun overlappingEntriesAreRejected() { + val dir = folder.newFolder() + val store = ScheduleStore(dir) + store.savePlan(user, 152, topUpPlan(null, ScheduleCursor(), pool, now)!!) + val file = java.io.File(dir, "schedule-152.json") + val root = JSONObject(file.readText()) + root.getJSONArray("entries").getJSONObject(1).put("a", now) + file.writeText(root.toString()) + assertNull(store.loadPlan(user, 152)) + } + + @Test fun theEpisodeCacheRoundTrips() { + val store = store() + store.savePool(user, 152, ScheduleStore.SavedPool(pool, now)) + val read = store.loadPool(user, 152)!! + assertEquals(pool, read.series); assertEquals(now, read.fetchedAtMs) + } + + @Test fun loopChoiceKeepsTheSavedPlace() { + val store = store() + val scheduler = ChannelScheduler(store) { now } + store.saveProgress(user, 152, ScheduleStore.SavedProgress(true, ScheduleCursor("a", mapOf("a" to EpisodeMark(1, 2))))) + scheduler.setEnabled(user, 152, false) + assertFalse(scheduler.enabled(user, 152)) + assertEquals(EpisodeMark(1, 2), store.loadProgress(user, 152)!!.aired.marks["a"]) + store.savePlan(user, 152, topUpPlan(null, ScheduleCursor(), pool, now)!!) + assertNull(scheduler.load(user, loop)) + scheduler.setEnabled(user, 152, true) + assertNotNull(scheduler.load(user, loop)) + } + + private fun episode(id: String, season: Int, number: Int, container: String = "mkv", sourceId: String = "src-$id") = JSONObject().put("Id", id).put("Type", "Episode") + .put("Name", "Episode").put("ParentIndexNumber", season).put("IndexNumber", number).put("RunTimeTicks", 13_200_000_000L) + .put("MediaSources", JSONArray().put(JSONObject().put("Id", sourceId).put("Container", container).put("RunTimeTicks", 13_300_000_000L))) + private val series = SeriesCandidate("fixture-series", "Fixture", 1996, "") + + @Test fun aWholeSeriesIsReadInBoundedPages() { + val requests = mutableListOf() + val all = (1..250).map { episode("e$it", 1, it) } + val transport = EmbyTransport { request -> + requests += request + val start = Regex("StartIndex=(\\d+)").find(request.path)!!.groupValues[1].toInt() + val rows = JSONArray(); all.drop(start).take(WHOLE_SERIES_PAGE).forEach { rows.put(it) } + EmbyReply(200, JSONObject().put("Items", rows).put("TotalRecordCount", all.size).toString()) + } + val result = readWholeSeries(transport, user, { "fixture-token" }, series) + assertEquals(250, result.episodes.size) + assertEquals(3, requests.size) + assertTrue(requests.all { it.path.contains("Limit=$WHOLE_SERIES_PAGE") && !it.path.contains("fixture-token") }) + } + + @Test fun onlyRegularPlayableEpisodesAreKeptInOrderOnce() { + val rows = JSONArray().put(episode("late", 2, 1)).put(episode("special", 0, 1)).put(episode("early", 1, 1)) + .put(episode("copy", 1, 1)).put(episode("bad", 1, 2, container = "iso")) + .put(JSONObject().put("Id", "nosource").put("Type", "Episode").put("ParentIndexNumber", 1).put("IndexNumber", 3).put("RunTimeTicks", 13_200_000_000L)) + val transport = EmbyTransport { EmbyReply(200, JSONObject().put("Items", rows).put("TotalRecordCount", rows.length()).toString()) } + val result = readWholeSeries(transport, user, { "t" }, series) + assertEquals(listOf("early", "late"), result.episodes.map { it.id }) + assertEquals(1_330_000L, result.episodes.first().durationMs) + assertEquals("src-early", result.episodes.first().sourceId) + } + + @Test fun guideDayLabelOnlyAppearsAwayFromToday() { + assertEquals("", guideDayPrefix(now, now)) + assertTrue(guideDayPrefix(now + 3 * day, now).isNotEmpty()) + } +}