Follow a series, from the phone: reminders whenever any channel plans one of its episodes in the next day

The phone's programme sheet offers Follow this series for an episode (never a
film). The TV checks every ten minutes, and straight after a follow, adding a
reminder per planned episode as if set in the guide. Per profile; the planner
is never asked for more of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 19:44:48 +00:00
co-authored by Claude Opus 5.5
parent 103a8a9961
commit eb45d5ca45
6 changed files with 118 additions and 4 deletions
@@ -201,7 +201,9 @@ function pickSheet(n) {
<div class="room" style="margin-top:12px"><span class="dot"></span>Watching on: <b>${esc(state.now?.room || 'this TV')}</b></div>
<div class="row" style="gap:8px"><button class="btn gold" data-tune="${c.number}">Watch on this TV</button><button class="btn" data-queue="${c.number}">Queue next</button></div>
<div class="small" style="margin-top:10px">Queue next switches to ${c.number} ${esc(c.name)} when the programme on the TV ends. Next on it at ${hm(c.next.startMs)}: ${esc(c.next.title)}</div>
<button class="btn${c.next.reminded ? '' : ' gold'}" style="margin-top:10px" data-remind="${c.number}:${c.next.startMs}:${c.next.reminded ? 0 : 1}">${c.next.reminded ? 'Reminder set · take it off' : 'Remind me about ' + esc(c.next.title)}</button>`;
<button class="btn${c.next.reminded ? '' : ' gold'}" style="margin-top:10px" data-remind="${c.number}:${c.next.startMs}:${c.next.reminded ? 0 : 1}">${c.next.reminded ? 'Reminder set · take it off' : 'Remind me about ' + esc(c.next.title)}</button>`
+ (c.next.series ? `<button class="btn" style="margin-top:8px" data-follow="${c.number}:${c.next.startMs}:${c.next.following ? 0 : 1}">${c.next.following ? 'Following this series · stop' : 'Follow this series'}</button>
<div class="small" style="margin-top:6px">Following sets a reminder whenever any channel plans one of its episodes in the next day.</div>` : '');
}
// The Drive-In (phase 2): the coming bills, tickets, and out to the lot while one is showing.
function driveIn() {
@@ -857,6 +859,7 @@ document.addEventListener('click', e => {
if (d.filter) { state.filter = d.filter; render(); }
if (d.pick) openSheet(pickSheet(+d.pick));
if (d.tune) send('/api/tune', {number: +d.tune}, () => { closeSheet(); toast('Watching on the TV'); setTimeout(() => load('guide'), 700); });
if (d.follow) { const [number, startMs, on] = d.follow.split(':').map(Number); send('/api/follow', {number, startMs, on: !!on}, () => { closeSheet(); setTimeout(() => load('guide'), 400); toast(on ? 'Following: the TV will remind you of its episodes' : 'Stopped following'); }); return; }
if (d.remind) { const [number, startMs, on] = d.remind.split(':').map(Number); send('/api/remind', {number, startMs, on: !!on}, () => { closeSheet(); setTimeout(() => load('guide'), 400); toast(on ? 'The TV will remind you before it starts' : 'Reminder taken off'); }); return; }
if (d.queue) send('/api/queue', {number: +d.queue}, j => { state.now = {...state.now, queue: j.queue}; closeSheet(); toast('Queued: switches when this one ends'); });
if (d.cupick) { const [n, st] = d.cupick.split(':').map(Number); openSheet(cuSheet(n, st)); return; }
@@ -500,6 +500,17 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
val active = session ?: return
scope.launch(Dispatchers.IO) { runCatching { scheduleStore.saveReminders(active.accountId, changed) } }
}
// Follow a series (9 November 2026): every ten minutes, and straight after a follow, each followed series' planned
// episodes in the next day get a reminder, like one set in the guide.
LaunchedEffect(session, FollowSeries.version) {
if (session == null) return@LaunchedEffect
while (true) {
val followed = FollowSeries.followed(appContext, Profiles.current?.id)
val added = followedReminders(followed, scheduledChannels.values.toList(), liveReminders(reminders, System.currentTimeMillis()), System.currentTimeMillis())
if (added.isNotEmpty()) saveReminders(liveReminders(reminders, System.currentTimeMillis()) + added)
delay(10 * 60_000L)
}
}
// What's On's reminders, checked wherever the viewer is, as the Drive-In's are.
LaunchedEffect(reminders) {
while (reminders.isNotEmpty()) {
@@ -0,0 +1,45 @@
package tv.orbit.classic
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import org.json.JSONObject
/**
* Follow a series (9 November 2026, from the recommendations Paul approved): pick a show once, and whenever any channel
* plans one of its episodes in the next day, a reminder is set for it, as if you'd set it yourself in the guide. Per
* profile. The planner is never asked to schedule more of it: this only notices what's already planned.
*/
internal object FollowSeries {
private fun prefs(context: Context) = context.getSharedPreferences("orbit_settings", Context.MODE_PRIVATE)
private fun key(profile: String?) = "followed_" + (profile ?: "all").filter { it.isLetterOrDigit() }.take(40)
/** Followed series for [profile], by series id, with their names. */
fun followed(context: Context, profile: String?): Map<String, String> = runCatching {
JSONObject(prefs(context).getString(key(profile), "{}")!!).let { o -> o.keys().asSequence().filter(EmbyClient::validId).associateWith { o.getString(it) } }
}.getOrDefault(emptyMap())
fun set(context: Context, profile: String?, seriesId: String, name: String, on: Boolean) {
if (!EmbyClient.validId(seriesId)) return
val now = followed(context, profile).let { if (on) it + (seriesId to name.take(120)) else it - seriesId }.entries.take(MAX).associate { it.key to it.value }
prefs(context).edit().putString(key(profile), JSONObject(now).toString()).apply()
}
const val MAX = 50
/** Goes up whenever someone follows or stops following, so the TV looks for episodes straight away. */
var version by androidx.compose.runtime.mutableIntStateOf(0)
fun changed() { version++ }
/** A programme's series name from its guide title ("Show / S1 E2 / Title" gives "Show"). */
fun seriesName(title: String) = title.substringBefore(" / ").trim().ifBlank { title }
const val HORIZON_MS = 24 * 60 * 60_000L
}
/**
* The reminders to add for followed series: each planned episode starting within [FollowSeries.HORIZON_MS] that has no
* reminder yet. One per airing; a repeat of the same episode on another channel or time is its own airing.
*/
internal fun followedReminders(followed: Map<String, String>, channels: Collection<ScheduledChannel>, existing: List<ProgrammeReminder>, nowMs: Long): List<ProgrammeReminder> {
if (followed.isEmpty()) return emptyList()
val have = existing.map { it.channel to it.startMs }.toSet()
return channels.flatMap { c ->
c.plan.entries.filter { e -> e.seriesId in followed && e.startMs > nowMs && e.startMs - nowMs <= FollowSeries.HORIZON_MS && (c.number to e.startMs) !in have }
.map { e -> ProgrammeReminder(c.number, e.startMs, guideTitle(c.number, SampleBroadcast(e.media, e.startMs)).first) }
}.sortedBy { it.startMs }
}
@@ -141,10 +141,16 @@ internal object OrbitCompanion {
}
/** Every channel's now and next. */
fun guide(screen: CompanionScreen, nowMs: Long): JSONObject = JSONObject().put("selected", screen.selected()).put("serverMs", nowMs).put("channels",
fun guide(screen: CompanionScreen, nowMs: Long): JSONObject {
val followed = PhoneLink.context()?.let { FollowSeries.followed(it, Profiles.current?.id) }.orEmpty()
return JSONObject().put("selected", screen.selected()).put("serverMs", nowMs).put("channels",
JSONArray(screen.channels().map { c -> val on = c.at(nowMs)
channelJson(c).put("category", ChannelBrands.forNumber(c.number)?.category?.label ?: JSONObject.NULL).put("now", programme(on)).put("next", programme(c.at(on.endMs)).let { next ->
next.put("reminded", screen.reminders().any { it.channel == c.number && it.startMs == next.getLong("startMs") }) }) }))
// Follow a series (9 November 2026): only for an episode of a series, never a film.
val series = (c as? ScheduledChannel)?.seriesIdAt(next.getLong("startMs"))?.takeIf { s -> c.at(next.getLong("startMs")).media.item.type == "Episode" && EmbyClient.validId(s) }
next.put("reminded", screen.reminders().any { it.channel == c.number && it.startMs == next.getLong("startMs") })
.put("series", series != null).put("following", series != null && series in followed) }) }))
}
fun catchUp(screen: CompanionScreen, nowMs: Long): JSONArray = JSONArray(catchUpShelves(screen.channels(), nowMs).map { shelf ->
JSONObject().put("title", shelf.title).put("entries", JSONArray(shelf.entries.map { e ->
@@ -152,6 +158,15 @@ internal object OrbitCompanion {
})
/** A reminder from the phone, for a programme still to come on a channel this TV shows; false when there's no such programme. */
/** Follow (or stop following) the series of a coming programme, for whoever's watching. */
fun follow(context: android.content.Context, screen: CompanionScreen, number: Int, startMs: Long, on: Boolean, nowMs: Long): Boolean {
val c = screen.channels().firstOrNull { it.number == number } as? ScheduledChannel ?: return false
val show = runCatching { c.at(startMs) }.getOrNull()?.takeIf { it.startMs == startMs && it.startMs > nowMs && it.media.item.type == "Episode" } ?: return false
val series = c.seriesIdAt(startMs)?.takeIf(EmbyClient::validId) ?: return false
FollowSeries.set(context, Profiles.current?.id, series, FollowSeries.seriesName(guideTitle(number, show).first), on); FollowSeries.changed()
return true
}
fun remind(screen: CompanionScreen, number: Int, startMs: Long, on: Boolean, nowMs: Long): Boolean {
val c = screen.channels().firstOrNull { it.number == number } ?: return false
val show = runCatching { c.at(startMs) }.getOrNull()?.takeIf { it.startMs == startMs && it.startMs > nowMs } ?: return false
@@ -500,7 +500,7 @@ internal object PhoneLink {
}
private val companionRoutes = setOf("GET /api/now", "GET /api/guide", "GET /api/catchup", "GET /api/rooms", "GET /api/looks", "POST /api/key", "POST /api/volume",
"POST /api/channel", "POST /api/tune", "POST /api/remind", "GET /api/times", "POST /api/section", "POST /api/catchup/watch",
"POST /api/channel", "POST /api/tune", "POST /api/remind", "POST /api/follow", "GET /api/times", "POST /api/section", "POST /api/catchup/watch",
"GET /api/queue", "POST /api/queue", "POST /api/queue/remove", "GET /api/drivein", "POST /api/drivein/ticket", "POST /api/drivein/watch",
"GET /api/director", "POST /api/director/place", "POST /api/director/drop", "POST /api/director/idea", "GET /api/profiles", "POST /api/profile",
"POST /api/profile/add", "POST /api/profile/rename", "POST /api/profile/remove")
@@ -544,6 +544,12 @@ internal object PhoneLink {
if (!done) return json(out, 404, JSONObject().put("error", "That programme isn't coming up on this TV."))
json(out, 200, JSONObject().put("ok", true))
}
"POST /api/follow" -> {
val o = body(); var done = false; val ctx = appContext ?: return json(out, 503, JSONObject().put("error", "Orbit isn't ready."))
onScreen { done = OrbitCompanion.follow(ctx, s, o.optInt("number"), o.optLong("startMs"), o.optBoolean("on", true), now) }
if (!done) return json(out, 404, JSONObject().put("error", "That isn't an episode coming up on this TV."))
json(out, 200, JSONObject().put("ok", true))
}
"POST /api/section" -> {
val section = OrbitCompanion.sections[body().optString("section")] ?: return json(out, 400, JSONObject().put("error", "Unknown place"))
onScreen { OrbitCompanion.open(section) }; json(out, 200, JSONObject().put("ok", true))
@@ -0,0 +1,34 @@
package tv.orbit.classic
import org.junit.Assert.*
import org.junit.Test
/** Follow a series (9 November 2026): reminders for followed series' planned episodes in the next day. */
class FollowSeriesTest {
private val minute = 60_000L
private val now = 1_794_300_000_000L
private fun media(id: String) = ScheduledMedia(SampleItem("Show / S1 E$id / Pilot", "Episode", 30, "", "ep$id", 30 * minute), "src$id", 30 * minute)
private fun channel(number: Int, vararg entries: Pair<String, Long>): ScheduledChannel {
val list = entries.mapIndexed { i, (series, start) -> ScheduleEntry(series, EpisodeMark(1, i + 1), media("$number$i"), start) }
return ScheduledChannel(SampleChannel(listOf(media("${number}x"), media("${number}y")), "Test", number), ChannelPlan(list, ScheduleCursor()))
}
@Test fun remindsForFollowedEpisodesInTheNextDay() {
val c1 = channel(304, "showA" to now + 60 * minute, "showB" to now + 90 * minute, "showA" to now + 26 * 60 * minute)
val c2 = channel(305, "showA" to now + 5 * 60 * minute)
val got = followedReminders(mapOf("showA" to "Show A"), listOf(c1, c2), emptyList(), now)
assertEquals(listOf(304 to now + 60 * minute, 305 to now + 5 * 60 * minute), got.map { it.channel to it.startMs })
}
@Test fun neverTwiceAndNeverPast() {
val c = channel(304, "showA" to now - 10 * minute, "showA" to now + 60 * minute)
val existing = listOf(ProgrammeReminder(304, now + 60 * minute, "Show"))
assertTrue(followedReminders(mapOf("showA" to "Show A"), listOf(c), existing, now).isEmpty())
assertTrue(followedReminders(emptyMap(), listOf(c), emptyList(), now).isEmpty())
}
@Test fun seriesNameFromTheGuideTitle() {
assertEquals("Gavin & Stacey", FollowSeries.seriesName("Gavin & Stacey / S2 E7 / The Baby"))
assertEquals("Train to Busan", FollowSeries.seriesName("Train to Busan"))
}
}