diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index d3ad7b3f..1dc78721 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 = 41 - versionName = "0.40.0-smart-terra-after-dark" + versionCode = 42 + versionName = "0.41.0-smart-vortex" } 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 index 7da1456e..c518025c 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt @@ -3,15 +3,26 @@ 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, /** Set for a film channel: how long before a film may air again, as long as the pool allows it. */ - val filmRestMs: Long? = null) + val filmRestMs: Long? = null, + /** A show that finishes waits until every show has finished, so nothing repeats while others have new episodes. */ + val finishTogether: Boolean = false, + /** Only the exact title counts, for channels whose short names could match something unrelated. */ + val exactTitles: Boolean = false) { + /** Changes when the list does, so the episode cache is read again. What's already committed stays. */ + val signature get() = "${searches.joinToString("|")}#$seriesCount" +} internal val SmartChannels = listOf( ChannelProgramming(102, "After Dark", listOf("The Thing", "The Evil Dead", "Re-Animator", "Hellraiser", "Videodrome", "An American Werewolf in London", "Halloween", "Day of the Dead", "They Live", "Escape from New York", "The Fog", "Near Dark", "The Lost Boys", "Fright Night", "Society", "Tremors", "Basket Case", "Phantasm", "Repo Man", "Donnie Darko", "The Wicker Man", "Suspiria", "Eraserhead", "Blue Velvet", "From Dusk Till Dawn", "Scream", "Poltergeist", "The Howling", "Creepshow", "Prince of Darkness"), seriesCount = 40, filmRestMs = 48 * 60 * 60_000L), - ChannelProgramming(140, "Terra", listOf("Blue Planet", "Planet Earth", "Frozen Planet", "Life on Earth", "Our Planet", "Dynasties", - "Seven Worlds One Planet", "A Perfect Planet", "Hostile Planet", "The Living Planet"), seriesCount = 8), + ChannelProgramming(103, "Vortex", listOf("Dragon Ball Z", "Batman Beyond", "Superman: The Animated Series", "Naruto", "Gundam Wing", "Yu Yu Hakusho", "Samurai Jack"), + seriesCount = 6, finishTogether = true), + ChannelProgramming(140, "Terra", listOf("The Blue Planet", "Blue Planet II", "Planet Earth", "Planet Earth II", "Planet Earth III", "Frozen Planet", "Frozen Planet II", + "Life on Earth", "The Living Planet", "The Trials of Life", "Our Planet", "Our Planet II", "Dynasties", "Dynasties II", "Seven Worlds, One Planet", "A Perfect Planet", + "Hostile Planet", "Africa", "Wild China", "South Pacific", "Great Barrier Reef", "The Hunt", "The Life of Mammals", "The Life of Birds", "Nature's Great Events", "Green Planet", "Prehistoric Planet"), + seriesCount = 20, finishTogether = true, exactTitles = true), ChannelProgramming(152, "Paradox", ChannelPresets.first { it.number == 152 }.searches)) internal data class EpisodeMark(val season: Int, val episode: Int) : Comparable { @@ -42,6 +53,12 @@ internal const val SCHEDULE_KEEP_PAST_MS = 24 * 60 * 60_000L internal fun nextEpisode(series: PoolSeries, last: EpisodeMark?): PoolEpisode = last?.let { mark -> series.episodes.firstOrNull { it.mark > mark } } ?: series.episodes.first() +/** The next show after [last] in the rota that [eligible] allows. */ +internal fun nextInTurn(pool: List, last: String?, eligible: (PoolSeries) -> Boolean): PoolSeries { + val after = pool.indexOfFirst { it.id == last } + 1 + return (0 until pool.size).map { pool[(after + it) % pool.size] }.first(eligible) +} + /** * A film past its rest, chosen by a generator seeded from the start time so a plan can be explained and reproduced. * If the pool is too small for the rest period, the film that has waited longest. @@ -71,7 +88,7 @@ internal fun extendFilmSchedule(pool: List, cursor: ScheduleCursor, } /** 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, filmRestMs: Long? = null): ChannelPlan { +internal fun extendSchedule(pool: List, cursor: ScheduleCursor, fromMs: Long, untilMs: Long, filmRestMs: Long? = null, finishTogether: Boolean = false): ChannelPlan { require(pool.isNotEmpty() && pool.all { it.episodes.isNotEmpty() }) if (filmRestMs != null) return extendFilmSchedule(pool, cursor, fromMs, untilMs, filmRestMs) val marks = cursor.marks.toMutableMap() @@ -79,7 +96,8 @@ internal fun extendSchedule(pool: List, cursor: ScheduleCursor, from var last = cursor.lastSeriesId var start = fromMs while (start < untilMs) { - val series = pool[(pool.indexOfFirst { it.id == last } + 1) % pool.size] + if (finishTogether && pool.all { marks[it.id] == it.episodes.last().mark }) marks.clear() + val series = nextInTurn(pool, last) { !finishTogether || marks[it.id] != it.episodes.last().mark } 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) @@ -110,12 +128,12 @@ internal fun airedCursor(base: ScheduleCursor, entries: List, now * 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, filmRestMs: Long? = null): ChannelPlan? { +internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List?, nowMs: Long, filmRestMs: Long? = null, finishTogether: Boolean = false): 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, filmRestMs) + val added = extendSchedule(pool, existing?.tail ?: aired, from, nowMs + SCHEDULE_AHEAD_MS, filmRestMs, finishTogether) return ChannelPlan(kept?.entries.orEmpty() + added.entries, added.tail) } diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt index 07a5d372..d8668b2b 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -37,14 +37,14 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl var pool = cached var requests = 0 var fetchMs = 0L - if (cached == null || now - cached.fetchedAtMs >= POOL_REFRESH_MS) { + if (cached == null || now - cached.fetchedAtMs >= POOL_REFRESH_MS || cached.signature != programming.signature) { val started = android.os.SystemClock.elapsedRealtime() try { val read = session.readChannelPool(programming, loop, checkActive) requests = read.requests fetchMs = android.os.SystemClock.elapsedRealtime() - started if (read.series.isNotEmpty()) { - pool = ScheduleStore.SavedPool(read.series, now) + pool = ScheduleStore.SavedPool(read.series, now, programming.signature) store.savePool(userId, number, pool) } } catch (failure: EmbyCheckException) { if (cached == null) throw failure } @@ -53,7 +53,7 @@ internal class ChannelScheduler(private val store: ScheduleStore, private val cl 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, programming.filmRestMs) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.") + val plan = topUpPlan(existing, base, pool?.series, now, programming.filmRestMs, programming.finishTogether) ?: 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 }) 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 58f9e1af..0cfda2ca 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.40.0\"") + connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.41.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 c4a4234d..751528b6 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt @@ -116,7 +116,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?.let(::onAir), toonamiChannel, *extraChannels.map(::onAir).toTypedArray()) + val available = availableSampleChannels(channel, afterDarkChannel?.let(::onAir), toonamiChannel?.let(::onAir), *extraChannels.map(::onAir).toTypedArray()) selectedNumber = available.firstOrNull { it.number == saved.selectedNumber }?.number ?: available.firstOrNull()?.number ?: 101 onChannelAvailable(available.isNotEmpty()) } @@ -174,7 +174,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea } // Read before the channels appear, so the guide never shows the loop for a moment first. scheduledChannels = withContext(Dispatchers.IO) { - (saved.extra + listOfNotNull(saved.afterDark)).mapNotNull { loop -> scheduler.load(saved.identity.userId, loop)?.also { resumed.rememberScheduledItems(it.plan.entries.map { entry -> entry.media.item }) } }.associateBy { it.number } + (saved.extra + listOfNotNull(saved.afterDark, saved.toonami)).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() @@ -213,9 +213,9 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea } } LaunchedEffect(Unit) { while (true) { now = System.currentTimeMillis(); delay(1000) } } - fun smartLoop(programming: ChannelProgramming) = (extraChannels + listOfNotNull(afterDarkChannel)).firstOrNull { it.number == programming.number } + fun smartLoop(programming: ChannelProgramming) = (extraChannels + listOfNotNull(afterDarkChannel, toonamiChannel)).firstOrNull { it.number == programming.number } // Keeps smart channels topped up in the background. A failure changes nothing on air. - LaunchedEffect(session, extraChannels, afterDarkChannel) { + LaunchedEffect(session, extraChannels, afterDarkChannel, toonamiChannel) { val active = session ?: return@LaunchedEffect while (true) { for (programming in SmartChannels) { @@ -253,7 +253,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?.let(::onAir), toonamiChannel, *extraChannels.map(::onAir).toTypedArray()) + val availableChannels = availableSampleChannels(channel, afterDarkChannel?.let(::onAir), toonamiChannel?.let(::onAir), *extraChannels.map(::onAir).toTypedArray()) val liveChannel = availableChannels.firstOrNull { it.number == selectedNumber } if ((mainGuide || mainHome) && liveSession != null && liveChannel != null) { if (watchingChannel) ScheduledChannelPlayer(liveSession, liveChannel, channelClockOffset, 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 5ac770f6..337eabeb 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt @@ -205,7 +205,8 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v if (pool.size == programming.seriesCount) break checkActive() requests++ - val match = bestSeriesMatch(search, searchSeries(transport, userId, ::currentToken, search).candidates) ?: continue + val candidates = searchSeries(transport, userId, ::currentToken, search).candidates + val match = bestSeriesMatch(search, if (programming.exactTitles) candidates.filter { seriesKey(it.title) == seriesKey(search) } else 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 diff --git a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt index 8227149a..7b8c63af 100644 --- a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt @@ -12,7 +12,7 @@ import java.io.FileOutputStream 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) + internal class SavedPool(val series: List, val fetchedAtMs: Long, val signature: String = "") private fun file(kind: String, number: Int) = File(directory, "$kind-$number.json") @@ -85,7 +85,7 @@ internal class ScheduleStore(private val directory: File) { 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)) + write(file("episodes", number), root(userId, number).put("fetched", pool.fetchedAtMs).put("signature", pool.signature).put("series", series)) } fun loadPool(userId: String, number: Int): SavedPool? = read(file("episodes", number), userId, number) { root -> val rows = root.getJSONArray("series") @@ -96,7 +96,7 @@ internal class ScheduleStore(private val directory: File) { 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")) + }, root.getLong("fetched"), root.optString("signature")) } /** Bytes held for a channel, for the measurements. */ 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 76536205..6fa1e3bb 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.40.0") + next.setRequestProperty("User-Agent", "OrbitTV/0.41.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 index 34ad8bc7..b484df3a 100644 --- a/android/app/src/test/java/tv/orbit/classic/ChannelScheduleTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/ChannelScheduleTest.kt @@ -296,4 +296,50 @@ class ChannelScheduleTest { assertEquals(now, guideDayJump(now + 60 * minute, now, false)) assertTrue(guideDayJump(now + 7 * day, now, true) < now + 7 * day) } + + @Test fun aVeryLongSeriesStaysInOrderWithNoRepeats() { + val long = listOf(show("dbz", 9, 33, 24), show("bb", 3, 17, 22), show("nar", 9, 25, 24)) + val entries = extendSchedule(long, ScheduleCursor(), now, now + 7 * day, finishTogether = true).entries.filter { it.seriesId == "dbz" } + assertTrue(entries.size > 100) + assertEquals(entries.map { it.mark }.sorted(), entries.map { it.mark }) + assertEquals(entries.size, entries.map { it.mark }.distinct().size) + } + + @Test fun aFinishedShowWaitsForTheOthers() { + val short = show("s", 1, 2) + val long = show("l", 1, 6) + val entries = extendSchedule(listOf(short, long), ScheduleCursor(), now, now + 8 * 45 * minute, finishTogether = true).entries + assertEquals(listOf("s", "l", "s", "l", "l", "l", "l", "l"), entries.map { it.seriesId }) + assertEquals(EpisodeMark(1, 6), entries.last().mark) + } + + @Test fun onceEveryShowHasFinishedTheyAllStartAgain() { + val pool = listOf(show("s", 1, 1), show("l", 1, 2)) + val entries = extendSchedule(pool, ScheduleCursor(), now, now + 5 * 45 * minute, finishTogether = true).entries + assertEquals(listOf("s" to 1, "l" to 1, "l" to 2, "s" to 1, "l" to 1), entries.map { it.seriesId to it.mark.episode }) + } + + @Test fun finishingTogetherSurvivesAnExtension() { + val pool = listOf(show("s", 1, 2), show("l", 1, 300)) + val first = topUpPlan(null, ScheduleCursor(), pool, now, finishTogether = true)!! + val later = topUpPlan(first, ScheduleCursor(), pool, now + 2 * day, finishTogether = true)!! + assertEquals(2, later.entries.count { it.seriesId == "s" } + first.entries.count { it.seriesId == "s" && it.endMs < now + day }) + } + + @Test fun takingTurnsSkipsOnlyWhatItMust() { + val pool = listOf(show("a", 1, 1), show("b", 1, 1), show("c", 1, 1)) + assertEquals("c", nextInTurn(pool, "a") { it.id != "b" }.id) + assertEquals("a", nextInTurn(pool, null) { true }.id) + } + + @Test fun theEpisodeCacheKeepsItsSignature() { + val store = store() + store.savePool(user, 140, ScheduleStore.SavedPool(pool, now, "sig")) + assertEquals("sig", store.loadPool(user, 140)!!.signature) + val dir = folder.newFolder(); val old = ScheduleStore(dir) + old.savePool(user, 140, ScheduleStore.SavedPool(pool, now, "sig")) + val file = java.io.File(dir, "episodes-140.json") + file.writeText(JSONObject(file.readText()).apply { remove("signature") }.toString()) + assertEquals("", old.loadPool(user, 140)!!.signature) + } }