Catch Up v2: Continue watching, picture cards, search and channel filters, options while catching up

Where you leave a programme, live or catching up, is noted for whoever's watching and offered
first in Catch Up once it has aired; held OK takes it off. Cards show the programme's picture.
Search and a chip per channel filter the page. Catching up, a held OK opens subtitles, sound,
Start again, Go to a channel and Back to live. 0.108.94.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-07 15:31:16 +00:00
co-authored by Claude Opus 5.5
parent 2ef38b7f70
commit af2c78de73
8 changed files with 311 additions and 54 deletions
+2 -2
View File
@@ -9,8 +9,8 @@ android {
applicationId = "tv.orbit.classic"
minSdk = 26
targetSdk = 36
versionCode = 253
versionName = "0.108.93-zlib-subtitles"
versionCode = 254
versionName = "0.108.94-catch-up-v2"
}
buildFeatures { compose = true }
// The finished build for the TVs (Paul, 6 November 2026: the test build stuttered on the box). Not debuggable, so
@@ -10,6 +10,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
@@ -129,86 +130,208 @@ internal fun CatchUpCard(entry: CatchUpEntry, nowMs: Long, onWatch: () -> Unit,
OrbitButton("Watch from the start", Modifier.focusRequester(watchFocus), onClick = onWatch)
OrbitButton("Back", onClick = onDismiss)
}
Text("While watching: ◄► skip 30 s OK pause ▲▼ back to live Back leave Catch Up", color = Muted, fontSize = 11.sp)
Text("While watching: ◄► skip 30 s OK pause Hold OK subtitles and options ▲▼ back to live", color = Muted, fontSize = 11.sp)
}
}
}
/** The Catch Up tab on the top bar: the last two days in rows, newest first. */
/** A row on the Catch Up page: Continue watching first, then the shelves. */
private class CatchUpRow(val title: String, val entries: List<CatchUpEntry>, val carryOn: List<ContinueEntry>? = null)
/** What the page's filters leave: one channel, and words in the title. */
internal fun catchUpMatches(entry: CatchUpEntry, channel: Int?, query: String): Boolean =
(channel == null || entry.channel.number == channel) && (query.isBlank() || entry.show.media.item.title.contains(query.trim(), ignoreCase = true))
/**
* The Catch Up tab on the top bar (v2, Paul, 7 November 2026: design/catch-up/v2): Continue watching first, then the last two
* days in rows, newest first, as picture cards. Above them, Search and a chip for each channel with something to catch up on.
* Held OK on a Continue watching card asks to take it off the row.
*/
@Composable
internal fun CatchUpScreen(channels: List<SampleChannel>, modifier: Modifier = Modifier, onOpen: (CatchUpEntry) -> Unit) {
internal fun CatchUpScreen(channels: List<SampleChannel>, session: EmbySampleSession?, modifier: Modifier = Modifier, onOpen: (CatchUpEntry) -> Unit,
onResume: (ContinueEntry) -> Unit = {}) {
var now by remember { mutableLongStateOf(System.currentTimeMillis()) }
LaunchedEffect(Unit) { while (true) { delay(30_000); if (!FullScreen.active) now = System.currentTimeMillis() } }
val shelves = remember(channels, now / 60_000) { catchUpShelves(channels, now) }
var channelFilter by remember { mutableStateOf<Int?>(null) }
var query by remember { mutableStateOf("") }
var searching by remember { mutableStateOf(false) }
var removing by remember { mutableStateOf<ContinueEntry?>(null) }
val allShelves = remember(channels, now / 60_000) { catchUpShelves(channels, now) }
val carryOn = remember(channels, now / 60_000, ContinueWatching.marks) { continueEntries(channels, ContinueWatching.marks, now) }
// The chips: a channel only when it has something here, in channel order.
val chipChannels = remember(allShelves) { allShelves.flatMap { it.entries }.map { it.channel }.distinctBy { it.number }.sortedBy { it.number } }
val rows = remember(allShelves, carryOn, channelFilter, query) {
val kept = carryOn.filter { catchUpMatches(it.entry, channelFilter, query) }
listOfNotNull(kept.takeIf { it.isNotEmpty() }?.let { CatchUpRow("CONTINUE WATCHING", it.map { c -> c.entry }, it) }) +
allShelves.map { CatchUpRow(it.title, it.entries.filter { e -> catchUpMatches(e, channelFilter, query) }) }.filter { it.entries.isNotEmpty() }
}
// Row -1 is the filter bar; its items are Search, All, then each channel.
var row by remember { mutableIntStateOf(0) }
val columns = remember { mutableStateMapOf<Int, Int>() }
var chip by remember { mutableIntStateOf(1) }
var okHeld by remember { mutableStateOf(false) }
val columns = remember { mutableStateMapOf<String, Int>() }
val focus = remember { FocusRequester() }
var focused by remember { mutableStateOf(false) }
val nav = LocalNavFocus.current
LaunchedEffect(Unit) { runCatching { focus.requestFocus() } }
Column(modifier.fillMaxWidth().background(Navy).padding(horizontal = 14.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("CATCH UP", color = CatchUpGreen, fontFamily = Anton, fontSize = 26.sp)
Text("Anything shown on Orbit in the last two days, from the start", color = Muted, fontSize = 14.sp)
if (shelves.isEmpty()) {
Text("Nothing to catch up on yet. Programmes appear here once they've aired.", color = Ink, fontSize = 16.sp,
modifier = Modifier.focusRequester(focus).focusProperties { if (nav != null) up = nav }.focusable())
return@Column
}
val r = row.coerceIn(shelves.indices)
Column(Modifier.weight(1f).fillMaxWidth().focusRequester(focus).focusProperties { if (nav != null) up = nav }.onFocusChanged { focused = it.isFocused }.focusable().onPreviewKeyEvent { event ->
LaunchedEffect(searching, removing) { if (!searching && removing == null) runCatching { focus.requestFocus() } }
val chipCount = 2 + chipChannels.size
Column(modifier.fillMaxWidth().background(Navy).padding(horizontal = 14.dp, vertical = 8.dp).focusRequester(focus).focusProperties { if (nav != null) up = nav }
.onFocusChanged { focused = it.isFocused }.focusable().onPreviewKeyEvent { event ->
val native = event.nativeKeyEvent
val r = row.coerceIn(-1, rows.lastIndex)
val isOk = native.keyCode == KeyEvent.KEYCODE_DPAD_CENTER || native.keyCode == KeyEvent.KEYCODE_ENTER
if (native.action == KeyEvent.ACTION_UP) {
if (!isOk) return@onPreviewKeyEvent false
if (okHeld) { okHeld = false; return@onPreviewKeyEvent true }
if (r == -1) when (val c = chip.coerceIn(0, chipCount - 1)) {
0 -> searching = true
1 -> { channelFilter = null; query = "" }
else -> channelFilter = chipChannels[c - 2].number.takeIf { it != channelFilter }
} else if (rows.isNotEmpty()) {
val shelf = rows[r]; val col = (columns[shelf.title] ?: 0).coerceIn(shelf.entries.indices)
shelf.carryOn?.let { onResume(it[col]) } ?: onOpen(shelf.entries[col])
}
return@onPreviewKeyEvent true
}
if (native.action != KeyEvent.ACTION_DOWN) return@onPreviewKeyEvent false
val col = (columns[r] ?: 0).coerceIn(shelves[r].entries.indices)
if (isOk) {
// Held on a Continue watching card: ask to take it off.
if (native.repeatCount > 0 && !okHeld && r >= 0 && rows.getOrNull(r)?.carryOn != null) {
okHeld = true
val shelf = rows[r]; removing = shelf.carryOn!![(columns[shelf.title] ?: 0).coerceIn(shelf.entries.indices)]
}
return@onPreviewKeyEvent true
}
when (native.keyCode) {
// At the top row, up leaves for the top bar.
KeyEvent.KEYCODE_DPAD_UP -> if (r > 0) { row = r - 1; true } else false
KeyEvent.KEYCODE_DPAD_DOWN -> { if (r < shelves.lastIndex) row = r + 1; true }
KeyEvent.KEYCODE_DPAD_LEFT -> { columns[r] = (col - 1).coerceAtLeast(0); true }
KeyEvent.KEYCODE_DPAD_RIGHT -> { columns[r] = (col + 1).coerceAtMost(shelves[r].entries.lastIndex); true }
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER -> { if (native.repeatCount == 0) onOpen(shelves[r].entries[col]); true }
// At the filter bar, up leaves for the top bar.
KeyEvent.KEYCODE_DPAD_UP -> if (r > -1) { row = r - 1; true } else false
KeyEvent.KEYCODE_DPAD_DOWN -> { if (r < rows.lastIndex) row = r + 1; true }
KeyEvent.KEYCODE_DPAD_LEFT -> { if (r == -1) chip = (chip - 1).coerceAtLeast(0) else rows.getOrNull(r)?.let { columns[it.title] = ((columns[it.title] ?: 0) - 1).coerceAtLeast(0) }; true }
KeyEvent.KEYCODE_DPAD_RIGHT -> { if (r == -1) chip = (chip + 1).coerceAtMost(chipCount - 1) else rows.getOrNull(r)?.let { columns[it.title] = ((columns[it.title] ?: 0) + 1).coerceAtMost(it.entries.lastIndex) }; true }
else -> false
}
}, verticalArrangement = Arrangement.spacedBy(6.dp)) {
// Three rows at a time, moving with the cursor.
val first = (r - 1).coerceIn(0, (shelves.size - 3).coerceAtLeast(0))
shelves.subList(first, minOf(first + 3, shelves.size)).forEachIndexed { offset, shelf ->
}, verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(verticalAlignment = Alignment.Bottom) {
Text("CATCH UP", color = CatchUpGreen, fontFamily = Anton, fontSize = 26.sp)
Spacer(Modifier.width(16.dp))
Text("Everything on Orbit in the last two days, from the start", color = Muted, fontSize = 14.sp, modifier = Modifier.padding(bottom = 4.dp))
}
// The filter bar.
val r = row.coerceIn(-1, rows.lastIndex)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
@Composable fun Chip(label: String, index: Int, chosen: Boolean) {
val on = focused && r == -1 && chip == index
Text(label, Modifier.background(if (chosen) Yellow else Panel, RoundedCornerShape(16.dp)).border(if (on) 3.dp else 0.dp, if (on) Ink else Color.Transparent, RoundedCornerShape(16.dp))
.padding(horizontal = 14.dp, vertical = 5.dp), color = if (chosen) OnAccent else Ink, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1)
}
Chip(if (query.isBlank()) "⌕ Search" else "⌕ “${query.trim()}”", 0, query.isNotBlank())
Chip("All", 1, channelFilter == null && query.isBlank())
// The chips around the cursor, so a long list still fits.
val start = (chip - 2 - 3).coerceIn(0, (chipChannels.size - 7).coerceAtLeast(0))
chipChannels.subList(start, minOf(start + 7, chipChannels.size)).forEachIndexed { k, ch -> Chip(ChannelBrands.displayName(ch), start + k + 2, channelFilter == ch.number) }
if (start + 7 < chipChannels.size) Text("›", color = Muted, fontSize = 16.sp)
}
if (rows.isEmpty()) {
Text(if (channelFilter != null || query.isNotBlank()) "Nothing here matches. Choose All to see everything." else "Nothing to catch up on yet. Programmes appear here once they've aired.",
color = Ink, fontSize = 16.sp)
} else Column(Modifier.weight(1f).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
// Two rows at a time, moving with the cursor.
val first = r.coerceAtLeast(0).coerceIn(0, (rows.size - 2).coerceAtLeast(0))
rows.subList(first, minOf(first + 2, rows.size)).forEachIndexed { offset, shelf ->
val index = first + offset
val col = (columns[index] ?: 0).coerceIn(shelf.entries.indices)
Text(shelf.title, color = if (index == r) Yellow else Muted, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
val start = (col - 2).coerceIn(0, (shelf.entries.size - 5).coerceAtLeast(0))
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
shelf.entries.subList(start, minOf(start + 5, shelf.entries.size)).forEachIndexed { k, entry ->
CatchUpTile(entry, now, focused && index == r && start + k == col, Modifier.weight(1f))
val col = (columns[shelf.title] ?: 0).coerceIn(shelf.entries.indices)
Text(shelf.title, color = if (index == r) Yellow else Muted, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.sp)
val start = (col - 1).coerceIn(0, (shelf.entries.size - 4).coerceAtLeast(0))
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
shelf.entries.subList(start, minOf(start + 4, shelf.entries.size)).forEachIndexed { k, entry ->
CatchUpTile(entry, now, focused && index == r && start + k == col, session, shelf.carryOn?.get(start + k), Modifier.weight(1f))
}
repeat(5 - minOf(5, shelf.entries.size - start)) { Spacer(Modifier.weight(1f)) }
repeat(4 - minOf(4, shelf.entries.size - start)) { Spacer(Modifier.weight(1f)) }
}
}
}
Text("▲▼ Rows ◄► Move OK Catch Up Back Home", color = Muted, fontSize = 11.sp)
Text(if (rows.getOrNull(r)?.carryOn != null) "OK Carry on watching Hold OK Remove ▲▼ Rows ◄► Move Back Home"
else if (r == -1) "OK Choose ◄► Move ▼ Programmes Back Home" else "OK Catch Up ▲▼ Rows ◄► Move Back Home", color = Muted, fontSize = 11.sp)
}
if (searching) CatchUpSearch(query, onDone = { query = it; searching = false; row = if (it.isBlank()) -1 else 0 }, onCancel = { searching = false })
removing?.let { c ->
Dialog(onDismissRequest = { removing = null }, properties = DialogProperties(usePlatformDefaultWidth = false)) {
val corner = RoundedCornerShape(12.dp)
val removeFocus = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { removeFocus.requestFocus() } }
Column(Modifier.width(520.dp).background(themed(Color(0xFF0A1E42)) { Deep }, corner).border(2.dp, Yellow, corner).padding(24.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("REMOVE FROM CONTINUE WATCHING?", color = Ink, fontFamily = Anton, fontSize = 22.sp)
Text(c.entry.show.media.item.title, color = Muted, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text("It stays in Catch Up until ${guideDayPrefix(c.entry.untilMs, now).trim().ifEmpty { "today" }} ${clock(c.entry.untilMs)}, from the start.", color = Muted, fontSize = 14.sp)
Spacer(Modifier.height(6.dp))
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
OrbitButton("Remove", Modifier.focusRequester(removeFocus)) { ContinueWatching.remove(c.entry.channel.number, c.entry.show.startMs); removing = null }
OrbitButton("Keep it") { removing = null }
}
}
}
}
}
/** Search Catch Up by title, typed with the remote's keyboard. */
@Composable
private fun CatchUpSearch(current: String, onDone: (String) -> Unit, onCancel: () -> Unit) {
var text by remember { mutableStateOf(current) }
Dialog(onDismissRequest = onCancel, properties = DialogProperties(usePlatformDefaultWidth = false)) {
val corner = RoundedCornerShape(12.dp)
val field = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { field.requestFocus() } }
Column(Modifier.width(560.dp).background(themed(Color(0xFF0A1E42)) { Deep }, corner).border(2.dp, Yellow, corner).padding(24.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("SEARCH CATCH UP", color = CatchUpGreen, fontFamily = Anton, fontSize = 20.sp)
OrbitField(text, { text = it.take(60) }, "A programme's name", Modifier.fillMaxWidth().focusRequester(field))
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
OrbitButton("Search") { onDone(text) }
if (current.isNotBlank()) OrbitButton("Clear") { onDone("") }
OrbitButton("Back", onClick = onCancel)
}
}
}
}
@Composable
private fun CatchUpTile(entry: CatchUpEntry, nowMs: Long, on: Boolean, modifier: Modifier) {
val corner = RoundedCornerShape(6.dp)
private fun CatchUpTile(entry: CatchUpEntry, nowMs: Long, on: Boolean, session: EmbySampleSession?, carryOn: ContinueEntry?, modifier: Modifier) {
val corner = RoundedCornerShape(8.dp)
// Focused as on What's On: navy inside a gold ring, so the words stay crisp rather than washed out in gold.
val ink = Ink
Column(modifier.height(92.dp).background(if (on) Navy else Panel, corner).border(if (on) 3.dp else 0.dp, if (on) Yellow else Color.Transparent, corner).padding(horizontal = 10.dp, vertical = 7.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(modifier.background(if (on) Navy else Panel, corner).border(if (on) 3.dp else 0.dp, if (on) Yellow else Color.Transparent, corner)) {
Box(Modifier.fillMaxWidth().height(96.dp).clip(RoundedCornerShape(topStart = 8.dp, topEnd = 8.dp)).background(Deep)) {
val seriesId = remember(entry.channel, entry.show.startMs) { (entry.channel as? ScheduledChannel)?.seriesIdAt(entry.show.startMs) }
if (session != null) QueuedArtwork(session, entry.show.media.item.id, seriesId, Modifier.matchParentSize())
val mark = ChannelBrands.forNumber(entry.channel.number)
if (mark != null) Image(cachedPainter(mark.logo), mark.displayName, Modifier.logoPlate().width(60.dp).height(18.dp))
else Text(ChannelBrands.displayName(entry.channel), color = ink, fontSize = 11.sp, maxLines = 1)
Spacer(Modifier.weight(1f))
CatchUpMark()
Box(Modifier.padding(6.dp).background(Navy.copy(alpha = .8f), RoundedCornerShape(4.dp)).padding(horizontal = 5.dp, vertical = 3.dp)) {
if (mark != null) Image(cachedPainter(mark.logo), mark.displayName, Modifier.width(56.dp).height(16.dp))
else Text(ChannelBrands.displayName(entry.channel), color = ink, fontSize = 11.sp, maxLines = 1)
}
if (carryOn != null) {
Text(leftLabel(carryOn.leftMs), Modifier.align(Alignment.BottomEnd).padding(6.dp).background(Navy.copy(alpha = .85f), RoundedCornerShape(10.dp)).padding(horizontal = 8.dp, vertical = 2.dp),
color = Ink, fontSize = 11.sp, fontWeight = FontWeight.SemiBold)
Box(Modifier.align(Alignment.BottomStart).fillMaxWidth().height(4.dp).background(Color.Black.copy(alpha = .5f))) {
Box(Modifier.fillMaxWidth(carryOn.fraction).fillMaxHeight().background(CatchUpGreen))
}
} else Box(Modifier.align(Alignment.TopEnd).padding(6.dp)) { CatchUpMark() }
}
Column(Modifier.padding(horizontal = 10.dp, vertical = 6.dp), verticalArrangement = Arrangement.spacedBy(1.dp)) {
val (name, detail) = guideTitleParts(entry.show.media.item.title)
Text(name, color = ink, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(detail ?: "${entry.show.media.durationMs / 60_000} min", color = Muted, fontSize = 11.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text("${guideDayPrefix(entry.show.startMs, nowMs).trim().ifEmpty { "Ended" }.let { if (it == "Ended") "Ended ${clock(entry.show.endMs)}" else "$it ${clock(entry.show.startMs)}" }}",
color = if (on) Yellow else Muted, fontSize = 11.sp, maxLines = 1)
}
val (name, detail) = guideTitleParts(entry.show.media.item.title)
Text(name, color = ink, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(detail ?: "${entry.show.media.durationMs / 60_000} min", color = Muted, fontSize = 11.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text("${guideDayPrefix(entry.show.startMs, nowMs).trim().ifEmpty { "Ended" }.let { if (it == "Ended") "Ended ${clock(entry.show.endMs)}" else "$it ${clock(entry.show.startMs)}" }}",
color = if (on) Yellow else Muted, fontSize = 11.sp, maxLines = 1)
}
}
/** "17 min left", "1 h 12 min left". */
internal fun leftLabel(leftMs: Long): String {
val minutes = (leftMs / 60_000).coerceAtLeast(1)
return if (minutes < 60) "$minutes min left" else "${minutes / 60} h${if (minutes % 60 > 0) " ${minutes % 60} min" else ""} left"
}
/** The badge in the corner while catching up. */
@Composable
internal fun CatchUpBadge(modifier: Modifier = Modifier) {
@@ -0,0 +1,75 @@
package tv.orbit.classic
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/**
* Continue watching (Paul, 7 November 2026): where you left a programme part-way, from Catch Up or live, so Catch Up can
* carry it on from there while it's still in Catch Up. One list per profile, on this box only. It only reads the plans.
*/
internal class ContinueMark(val number: Int, val startMs: Long, val itemId: String, val positionMs: Long, val durationMs: Long, val atMs: Long) {
fun toJson(): JSONObject = JSONObject().put("n", number).put("s", startMs).put("i", itemId).put("p", positionMs).put("d", durationMs).put("a", atMs)
companion object {
fun fromJson(o: JSONObject) = ContinueMark(o.getInt("n"), o.getLong("s"), o.getString("i").also { require(EmbyClient.validId(it)) },
o.getLong("p").coerceAtLeast(0), o.getLong("d").coerceAtLeast(1), o.getLong("a"))
}
}
/** Under this far in, it hasn't really been started. */
internal const val CONTINUE_MIN_MS = 3 * 60_000L
/** Within this of the end, it counts as watched. */
internal const val CONTINUE_END_MS = 5 * 60_000L
private const val CONTINUE_MAX = 20
/**
* [marks] after noting [positionMs] into [show] on [number]: a programme watched to its last few minutes leaves the list,
* one barely begun doesn't join it (a mark already there stays), anything else is kept as the latest place.
*/
internal fun notedMarks(marks: List<ContinueMark>, number: Int, show: SampleBroadcast, positionMs: Long, nowMs: Long): List<ContinueMark> {
val same = { m: ContinueMark -> m.number == number && m.startMs == show.startMs }
val duration = show.media.durationMs
return when {
positionMs >= duration - CONTINUE_END_MS -> marks.filterNot(same)
positionMs < CONTINUE_MIN_MS -> marks
else -> (marks.filterNot(same) + ContinueMark(number, show.startMs, show.media.item.id, positionMs, duration, nowMs)).sortedByDescending { it.atMs }.take(CONTINUE_MAX)
}
}
/** A Continue watching card: the programme as Catch Up holds it, and where you were. */
internal class ContinueEntry(val entry: CatchUpEntry, val positionMs: Long) {
val leftMs get() = (entry.show.media.durationMs - positionMs).coerceAtLeast(0)
val fraction get() = (positionMs.toFloat() / entry.show.media.durationMs).coerceIn(0f, 1f)
}
/**
* The marks that can be carried on now: the programme has finished airing, is still in Catch Up, and its channel's plan still
* holds it. Newest first.
*/
internal fun continueEntries(channels: List<SampleChannel>, marks: List<ContinueMark>, nowMs: Long): List<ContinueEntry> =
marks.sortedByDescending { it.atMs }.mapNotNull { m ->
val channel = channels.firstOrNull { it.number == m.number } as? ScheduledChannel ?: return@mapNotNull null
val e = channel.plan.entries.firstOrNull { it.startMs == m.startMs && it.media.item.id == m.itemId } ?: return@mapNotNull null
val show = SampleBroadcast(e.media, e.startMs, e.presentation)
if (!catchUpAvailable(channel, show, nowMs)) null else ContinueEntry(catchUpEntry(channel, show), m.positionMs)
}
internal object ContinueWatching {
var marks by mutableStateOf<List<ContinueMark>>(emptyList())
private set
private var file: File? = null
fun load(scheduleDir: File, profile: String?) {
file = File(scheduleDir, "continue-${(profile ?: "all").filter { it.isLetterOrDigit() }.take(40)}.json")
marks = runCatching { JSONArray(file!!.readText()).let { a -> (0 until minOf(a.length(), CONTINUE_MAX)).mapNotNull { runCatching { ContinueMark.fromJson(a.getJSONObject(it)) }.getOrNull() } } }.getOrDefault(emptyList())
}
fun note(number: Int, show: SampleBroadcast, positionMs: Long, nowMs: Long) {
val next = notedMarks(marks, number, show, positionMs, nowMs)
if (next != marks) { marks = next; save() }
}
fun remove(number: Int, startMs: Long) { marks = marks.filterNot { it.number == number && it.startMs == startMs }; save() }
private fun save() { runCatching { file?.writeText(JSONArray(marks.map { it.toJson() }).toString()) } }
}
@@ -62,9 +62,9 @@ internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUI
}
/** The sign-in headers for this kind of server. */
internal fun authHeaders(token: String?): Map<String, String> = when (kind) {
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.93\"") +
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.94\"") +
(token?.let { mapOf("X-Emby-Token" to it) } ?: emptyMap())
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.93\"" +
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.94\"" +
(token?.let { ", Token=\"$it\"" } ?: ""))
}
/** One picture from the provider, or nothing. Same fixed origin and no redirects, and failures are never shown or logged. */
@@ -366,6 +366,20 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
delay(5 * 60_000L)
}
}
// Continue watching (Paul, 7 November 2026): every half minute of watching notes where you are in the programme, live or
// catching up, for whoever's watching; Catch Up offers it back once it has aired.
LaunchedEffect(workspace, Profiles.current?.id) { withContext(Dispatchers.IO) { ContinueWatching.load(workspace.scheduleDir, Profiles.current?.id) } }
LaunchedEffect(session) {
while (true) {
delay(30_000)
if (!watchingChannel || selectedNumber == DRIVE_IN_NUMBER) continue
val channel = scheduledChannels[selectedNumber] ?: continue
val now = System.currentTimeMillis(); val at = now + channelClockOffset
val show = runCatching { channel.at(at) }.getOrNull() ?: continue
if (show.endMs - show.startMs < 10 * 60_000L) continue
runCatching { withContext(Dispatchers.IO) { ContinueWatching.note(channel.number, show, at - show.startMs, now) } }
}
}
// A channel of your own whose first plan was cut short, picked up again (set by the round below, run once setSmartSchedule exists).
var resumeNumber by remember { mutableStateOf<Int?>(null) }
// Keeps smart channels topped up in the background. A failure changes nothing on air.
@@ -747,7 +761,8 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
val picture = @Composable { GuidePicture(liveSession, liveChannel, live = !watchingChannel, handoff = liveHandoff, onUnplayable = ::rememberUnplayable) }
when {
mainHome -> HomeScreen(availableChannels, modifier, onCategory = { guideCategory = it; onGuide() })
mainCatchUp -> CatchUpScreen(availableChannels, modifier, onOpen = { catchUpOpen = it })
mainCatchUp -> CatchUpScreen(availableChannels, liveSession, modifier, onOpen = { catchUpOpen = it },
onResume = { c -> if (c.entry.show.startMs >= System.currentTimeMillis() - CATCH_UP_MS) tune(c.entry.channel.number, c.entry.show.startMs + c.positionMs - System.currentTimeMillis()) })
mainWhatsOn -> WhatsOnScreen(liveSession, scheduledChannels.filterKeys { !lockedOut(it) && !profileHides(it) }.mapValues { it.value.plan },
driveInPlan.takeIf { Profiles.current?.let { it.kind != ProfileKind.Kids || it.driveIn } ?: true }, modifier, reminders,
onWatch = { tune(it, 0) }, onDriveIn = onDriveIn, onBack = onHome,
@@ -368,7 +368,18 @@ internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPl
// Number keys and a held OK open the box. A short OK still shows the programme bar.
if (scheduled != null && event.action == KeyEvent.ACTION_DOWN) {
if (isOk && event.repeatCount > 0 && numberEntry == null && !okHeld) {
okHeld = true; numberProblem = null; numberEntry = ChannelEntry.from(scheduled.channel.number)
okHeld = true; numberProblem = null
// Catching up, a held OK opens its options: ◄► skip there, so subtitles and sound live here (Paul,
// 7 November 2026), with starting again, a channel by number and back to live.
val catching = currentScheduled
if (catching?.catchingUp() == true) {
val rows = trackRows().filter { it.section != "Sleep timer" } + listOf(
TrackRow("Catch Up", "Start again", false) { shift(-player.currentPosition); player.seekTo(0); showInfo() },
TrackRow("Catch Up", "Go to a channel…", false) { numberEntry = ChannelEntry.from(catching.channel.number) },
TrackRow("Catch Up", "Back to live", false) { live(); player.seekTo(catching.programme.offsetAt(System.currentTimeMillis())); showInfo() })
trackCursor = rows.indexOfFirst { it.selected }.coerceAtLeast(0)
trackMenu = rows
} else numberEntry = ChannelEntry.from(scheduled.channel.number)
return@setOnKeyListener true
}
if (typedDigit != null && numberEntry == null) { numberProblem = null; numberEntry = ChannelEntry.from(scheduled.channel.number) }
@@ -39,7 +39,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.108.93")
next.setRequestProperty("User-Agent", "OrbitTV/0.108.94")
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()) {
@@ -138,4 +138,37 @@ class CatchUpTest {
SleepTimer.set(SleepChoice.AfterThis, now, null)
assertEquals(SleepChoice.Off, SleepTimer.choice)
}
// Continue watching (Paul, 7 November 2026): where you left a programme, offered once it has aired, gone when watched.
@Test fun continueWatchingKeepsWhereYouLeftOff() {
val c = channel()
val e = c.plan.entries.last { it.endMs <= now - hour }
val show = SampleBroadcast(e.media, e.startMs, e.presentation)
var marks = notedMarks(emptyList(), c.number, show, 2 * minute, now)
assertTrue("barely begun doesn't count", marks.isEmpty())
marks = notedMarks(marks, c.number, show, 20 * minute, now)
assertEquals(1, marks.size)
val carry = continueEntries(listOf(c), marks, now).single()
assertEquals(20 * minute, carry.positionMs); assertEquals(e.startMs, carry.entry.show.startMs)
assertEquals("25 min left", leftLabel(carry.leftMs))
// Watched to the last few minutes: off the row.
assertTrue(notedMarks(marks, c.number, show, e.media.durationMs - 2 * minute, now).isEmpty())
// Still airing, or gone from Catch Up: not offered.
val live = c.plan.entries.first { it.startMs <= now && it.endMs > now }
val liveMarks = notedMarks(emptyList(), c.number, SampleBroadcast(live.media, live.startMs, live.presentation), 10 * minute, now)
assertTrue(continueEntries(listOf(c), liveMarks, now).isEmpty())
assertTrue(continueEntries(listOf(c), marks, e.startMs + CATCH_UP_MS + minute).isEmpty())
assertEquals("1 h 12 min left", leftLabel(72 * minute))
}
@Test fun catchUpFiltersByChannelAndTitle() {
val c = channel()
val e = c.plan.entries.last { it.endMs <= now }
val entry = catchUpEntry(c, SampleBroadcast(e.media, e.startMs, e.presentation))
val title = e.media.item.title
assertTrue(catchUpMatches(entry, null, ""))
assertTrue(catchUpMatches(entry, 106, title.take(6).lowercase()))
assertFalse(catchUpMatches(entry, 107, ""))
assertFalse(catchUpMatches(entry, null, "Twin Peaks"))
}
}