Add the shared scheduling engine, on Paradox only (0.39.0, Phase A in testing)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -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<String>, 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<EpisodeMark> {
|
||||
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<PoolEpisode>)
|
||||
|
||||
/** 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<String, EpisodeMark> = 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<ScheduleEntry>, 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<PoolSeries>, cursor: ScheduleCursor, fromMs: Long, untilMs: Long): ChannelPlan {
|
||||
require(pool.isNotEmpty() && pool.all { it.episodes.isNotEmpty() })
|
||||
val marks = cursor.marks.toMutableMap()
|
||||
val entries = mutableListOf<ScheduleEntry>()
|
||||
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<ScheduleEntry>, 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<PoolSeries>?, 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)
|
||||
}
|
||||
}
|
||||
@@ -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<String>, 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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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<Map<Int, ScheduledChannel>>(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(),
|
||||
|
||||
@@ -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<ChannelEntry?>(null) }
|
||||
var numberProblem by remember { mutableStateOf<String?>(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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,6 +49,7 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
|
||||
@Volatile private var darkLineup: Map<String, SampleItem> = 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<PoolSeries>, 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<PoolSeries>()
|
||||
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<SampleItem>) { channelEpisodes = channelEpisodes + items.associateBy { it.id } }
|
||||
|
||||
fun checkMetadataCoverage(checkActive: () -> Unit = {}): List<MetadataCoverage> =
|
||||
auditMetadataCoverage(transport, userId, ::currentToken, checkActive)
|
||||
fun importCatalogue(sink: CatalogueSink, maxPages: Int = CATALOGUE_PAGES_PER_RUN, pause: () -> Unit = {}, checkActive: () -> Unit = {}, onPage: () -> Unit = {},
|
||||
|
||||
@@ -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<PoolEpisode>()
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -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<String, String?> {
|
||||
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<SampleChannel>, 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<SampleChannel>, 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) }
|
||||
}
|
||||
|
||||
@@ -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<ScheduledMedia>, val name: String = "Orbit One", val number: Int = 101) {
|
||||
internal open class SampleChannel(entries: List<ScheduledMedia>, 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<ScheduledMedia>, 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
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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<PoolSeries>, 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 <T> 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() } }
|
||||
}
|
||||
@@ -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()) {
|
||||
|
||||
Reference in New Issue
Block a user