Follow a series, refined (Paul): per-profile reminders, optional per series, one per run, next airing anywhere

Each profile follows its own series and only that profile is reminded. Reminders
can be turned off per series while the next episode is still shown. A run of
episodes back to back on one channel (a marathon) gives one reminder. The phone's
guide lists Following, each with its next episode on any channel, however far
ahead it's planned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 20:02:22 +00:00
co-authored by Claude Opus 5.5
parent 6a54ef49c0
commit 104ebbaf9d
8 changed files with 106 additions and 34 deletions
@@ -190,7 +190,14 @@ function guide() {
const chips = `<div class="chips">${cats.map(k => `<button class="${k === f ? 'on' : ''}" data-filter="${esc(k)}">${k === 'all' ? 'All' : esc(k)}</button>`).join('')}</div>`;
if (f === 'Drive-In') return head('Guide') + chips + driveIn();
const times = `<a href="/times" class="card small" style="display:block;margin-bottom:10px;text-decoration:none;border:2px solid var(--accent)"><b style="color:var(--ink)">Orbit TV Times</b> · the week's listings, picks and films ›</a>`;
return head('Guide') + times + chips +
// Following (Paul, 9 November 2026): each series you follow, with its next episode wherever it's planned.
const days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
const when = ms => { const d = new Date(ms), t = new Date(); return (d.toDateString() === t.toDateString() ? 'Today' : days[d.getDay()]) + ' ' + hm(ms); };
const follows = (g.following || []).length ? `<div class="card" style="margin-bottom:10px"><b>Following</b>${g.following.map(f => `<div class="row" style="justify-content:space-between;align-items:center;margin-top:8px;gap:8px">
<div class="grow"><div class="what">${esc(f.name)}</div><div class="small">${f.next ? 'Next: ' + when(f.next.startMs) + ' on ' + f.next.number + ' ' + esc(f.next.channel) : 'Nothing planned yet'}</div></div>
<button class="btn${f.remind ? ' gold' : ''}" data-fremind="${esc(f.id)}:${f.remind ? 0 : 1}">${f.remind ? 'Reminders on' : 'Reminders off'}</button>
<button class="btn" data-unfollow="${esc(f.id)}">Stop</button></div>`).join('')}</div>` : '';
return head('Guide') + times + follows + chips +
(list.map(c => `<button class="ch ${c.number === g.selected ? 'on' : ''}" data-pick="${c.number}"><div class="num"><b>${c.number}</b><small>${esc(c.name)}</small></div>
<div class="grow"><div class="what">${esc(c.now.title)}</div><div class="then">${hm(c.now.startMs)}–${hm(c.now.endMs)} · then ${esc(c.next.title)}</div></div>
${c.number === g.selected && state.now?.watching ? '<span class="pill mint">ON TV</span>' : '<span class="pill">LIVE</span>'}</button>`).join('') || '<div class="empty">No channels here.</div>');
@@ -203,7 +210,7 @@ function pickSheet(n) {
<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>`
+ (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>` : '');
<div class="small" style="margin-top:6px">Following shows its next episode on any channel under Following, and reminds you (you can turn that off): one reminder per run, never one per episode.</div>` : '');
}
// The Drive-In (phase 2): the coming bills, tickets, and out to the lot while one is showing.
function driveIn() {
@@ -859,6 +866,8 @@ 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.fremind) { const [seriesId, on] = d.fremind.split(':'); send('/api/follow', {seriesId, remind: on === '1'}, () => { setTimeout(() => load('guide'), 300); toast(on === '1' ? 'Reminders on: one per run of episodes' : 'Reminders off: still shows the next episode'); }); return; }
if (d.unfollow) { send('/api/follow', {seriesId: d.unfollow, on: false}, () => { setTimeout(() => load('guide'), 300); toast('Stopped following'); }); return; }
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'); });
@@ -505,9 +505,10 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
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)
// Everyone's follows, each reminding only its own profile.
val now = System.currentTimeMillis(); val live = liveReminders(reminders, now)
val added = Profiles.all.flatMap { p -> followedReminders(FollowSeries.followed(appContext, p.id), scheduledChannels.values.toList(), live, now, p.id) }
if (added.isNotEmpty()) saveReminders(live + added)
delay(10 * 60_000L)
}
}
@@ -2,44 +2,71 @@ package tv.orbit.classic
import android.content.Context
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
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.
* Follow a series (Paul, 9 November 2026): pick a show once, and Orbit keeps track of when any channel next has one of
* its episodes, even days ahead or on a channel you don't watch. Each profile follows its own. Reminders are optional
* per series: on, the TV reminds that profile before an episode starts, one reminder per run, so a marathon gives one, not
* ten. The planner is never asked to schedule more of it: this only notices what's already planned.
*/
internal object FollowSeries {
class Followed(val name: String, val remind: Boolean)
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) } }
/** Followed series for [profile], by series id. */
fun followed(context: Context, profile: String?): Map<String, Followed> = runCatching {
JSONObject(prefs(context).getString(key(profile), "{}")!!).let { o -> o.keys().asSequence().filter(EmbyClient::validId).associateWith { id ->
// The first version kept just the name; reminders were always on then.
o.optJSONObject(id)?.let { Followed(it.optString("n").take(120), it.optBoolean("r", true)) } ?: Followed(o.optString(id).take(120), true)
} }
}.getOrDefault(emptyMap())
fun set(context: Context, profile: String?, seriesId: String, name: String, on: Boolean) {
private fun save(context: Context, profile: String?, all: Map<String, Followed>) = prefs(context).edit()
.putString(key(profile), JSONObject().also { o -> all.entries.take(MAX).forEach { (id, f) -> o.put(id, JSONObject().put("n", f.name).put("r", f.remind)) } }.toString()).apply()
fun follow(context: Context, profile: String?, seriesId: String, name: String, remind: Boolean = true) {
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()
save(context, profile, followed(context, profile) + (seriesId to Followed(name.take(120), remind))); changed()
}
fun unfollow(context: Context, profile: String?, seriesId: String) { save(context, profile, followed(context, profile) - seriesId); changed() }
fun setRemind(context: Context, profile: String?, seriesId: String, remind: Boolean) {
val f = followed(context, profile)[seriesId] ?: return
save(context, profile, followed(context, profile) + (seriesId to Followed(f.name, remind))); changed()
}
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)
const val HORIZON_MS = 24 * 60 * 60_000L
/** Episodes closer together than this on one channel are one run (a marathon): one reminder, for the first. */
const val RUN_GAP_MS = 15 * 60_000L
/** Goes up whenever someone follows or changes a follow, so the TV looks for episodes straight away. */
var version by 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
}
/** A followed series' next planned episode, wherever it is: the soonest start on any channel, at any distance ahead. */
internal class NextAiring(val seriesId: String, val channel: ScheduledChannel, val entry: ScheduleEntry)
internal fun nextAirings(followed: Collection<String>, channels: Collection<ScheduledChannel>, nowMs: Long): Map<String, NextAiring> =
channels.flatMap { c -> c.plan.entries.filter { it.seriesId in followed && it.startMs > nowMs }.map { NextAiring(it.seriesId, c, it) } }
.groupBy { it.seriesId }.mapValues { (_, all) -> all.minBy { it.entry.startMs } }
/**
* 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.
* The reminders to add for [profile]'s followed series with reminders on: the first episode of each run planned to start
* within [FollowSeries.HORIZON_MS], when there's no reminder for it yet. A run is episodes back to back on one channel.
*/
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()
internal fun followedReminders(followed: Map<String, FollowSeries.Followed>, channels: Collection<ScheduledChannel>, existing: List<ProgrammeReminder>,
nowMs: Long, profile: String? = null): List<ProgrammeReminder> {
val reminding = followed.filterValues { it.remind }.keys
if (reminding.isEmpty()) return emptyList()
val have = existing.filter { it.profile == null || it.profile == profile }.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) }
val entries = c.plan.entries
entries.withIndex().filter { (i, e) ->
val previous = entries.getOrNull(i - 1)
val continuesRun = previous != null && previous.seriesId == e.seriesId && e.startMs - previous.endMs < FollowSeries.RUN_GAP_MS
e.seriesId in reminding && !continuesRun && 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, profile = profile) }
}.sortedBy { it.startMs }
}
@@ -143,7 +143,12 @@ internal object OrbitCompanion {
/** Every channel's now and next. */
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",
// What you follow, each with its next episode anywhere in the plans (Paul: "even if it isn't visible in the guide").
val next = nextAirings(followed.keys, screen.channels().filterIsInstance<ScheduledChannel>(), nowMs)
val following = JSONArray(followed.entries.sortedBy { it.value.name }.map { (id, f) -> JSONObject().put("id", id).put("name", f.name).put("remind", f.remind)
.put("next", next[id]?.let { a -> JSONObject().put("number", a.channel.number).put("channel", ChannelBrands.displayName(a.channel)).put("startMs", a.entry.startMs)
.put("title", guideTitle(a.channel.number, SampleBroadcast(a.entry.media, a.entry.startMs)).first) } ?: JSONObject.NULL) })
return JSONObject().put("selected", screen.selected()).put("serverMs", nowMs).put("following", following).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 ->
// Follow a series (9 November 2026): only for an episode of a series, never a film.
@@ -163,7 +168,8 @@ internal object OrbitCompanion {
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()
if (on) FollowSeries.follow(context, Profiles.current?.id, series, FollowSeries.seriesName(guideTitle(number, show).first))
else FollowSeries.unfollow(context, Profiles.current?.id, series)
return true
}
@@ -546,7 +546,10 @@ internal object PhoneLink {
}
"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) }
val series = o.optString("seriesId").takeIf { it.isNotBlank() && EmbyClient.validId(it) }
// From the Following list: reminders on or off, or stop following. From a programme: follow its series.
if (series != null) { done = true; if (o.has("remind")) FollowSeries.setRemind(ctx, Profiles.current?.id, series, o.optBoolean("remind")) else if (!o.optBoolean("on", true)) FollowSeries.unfollow(ctx, Profiles.current?.id, series) }
else 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))
}
@@ -229,11 +229,11 @@ internal class ScheduleStore(private val directory: File) {
/** Programme reminders set from What's On: channel, start, title and how far their reminders have got. */
fun saveReminders(userId: String, reminders: List<ProgrammeReminder>) =
write(file("reminders", 0), root(userId, 0).put("reminders", JSONArray().also { saved ->
reminders.forEach { saved.put(JSONObject().put("c", it.channel).put("a", it.startMs).put("t", it.title).put("s", it.stage)) }
reminders.forEach { saved.put(JSONObject().put("c", it.channel).put("a", it.startMs).put("t", it.title).put("s", it.stage).apply { it.profile?.let { p -> put("p", p) } }) }
}))
fun loadReminders(userId: String): List<ProgrammeReminder> = read(file("reminders", 0), userId, 0) { root ->
val saved = root.getJSONArray("reminders")
(0 until saved.length()).map { saved.getJSONObject(it) }.map { ProgrammeReminder(it.getInt("c"), it.getLong("a"), it.getString("t").take(120), it.getInt("s")) }
(0 until saved.length()).map { saved.getJSONObject(it) }.map { ProgrammeReminder(it.getInt("c"), it.getLong("a"), it.getString("t").take(120), it.getInt("s"), it.optString("p").takeIf { p -> p.isNotBlank() }?.take(40)) }
}.orEmpty()
/** Your accepted and rejected suggestions. Kept apart from the schedule, so a rebuild or a damaged plan never loses them. */
@@ -36,10 +36,13 @@ internal val BarlowCondensed = FontFamily(Font(R.font.barlow_condensed_medium))
private val Corner = RoundedCornerShape(6.dp)
/** A reminder set from What's On, shown 5 minutes before and at the start, as the Drive-In's are. Stage 0 set, 1 warned, 2 started. */
internal data class ProgrammeReminder(val channel: Int, val startMs: Long, val title: String, val stage: Int = 0)
internal data class ProgrammeReminder(val channel: Int, val startMs: Long, val title: String, val stage: Int = 0,
/** Whose reminder it is (9 November 2026: a followed series' episodes remind only the profile that follows it); null is everyone's. */
val profile: String? = null)
internal fun programmeReminderDue(reminders: List<ProgrammeReminder>, nowMs: Long): ProgrammeReminder? = reminders.firstOrNull { r ->
(nowMs >= r.startMs && nowMs < r.startMs + REMINDER_LATE_MS && r.stage < 2) || (nowMs >= r.startMs - REMINDER_BEFORE_MS && nowMs < r.startMs && r.stage < 1)
internal fun programmeReminderDue(reminders: List<ProgrammeReminder>, nowMs: Long, profile: String? = Profiles.current?.id): ProgrammeReminder? = reminders.firstOrNull { r ->
(r.profile == null || r.profile == profile) &&
((nowMs >= r.startMs && nowMs < r.startMs + REMINDER_LATE_MS && r.stage < 2) || (nowMs >= r.startMs - REMINDER_BEFORE_MS && nowMs < r.startMs && r.stage < 1))
}?.let { it.copy(stage = if (nowMs >= it.startMs) 2 else 1) }
/** Old reminders drop off, so the file stays small. */
@@ -16,14 +16,14 @@ class FollowSeriesTest {
@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)
val got = followedReminders(mapOf("showA" to FollowSeries.Followed("Show A", true)), 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(mapOf("showA" to FollowSeries.Followed("Show A", true)), listOf(c), existing, now).isEmpty())
assertTrue(followedReminders(emptyMap(), listOf(c), emptyList(), now).isEmpty())
}
@@ -31,4 +31,27 @@ class FollowSeriesTest {
assertEquals("Gavin & Stacey", FollowSeries.seriesName("Gavin & Stacey / S2 E7 / The Baby"))
assertEquals("Train to Busan", FollowSeries.seriesName("Train to Busan"))
}
@Test fun aMarathonGivesOneReminder() {
val start = now + 60 * minute
val c = channel(302, *(0 until 10).map { "buffy" to start + it * 30 * minute }.toTypedArray(), "buffy" to start + 10 * 30 * minute + 3 * 60 * minute)
val got = followedReminders(mapOf("buffy" to FollowSeries.Followed("Buffy", true)), listOf(c), emptyList(), now, "grown")
assertEquals(listOf(start, start + 10 * 30 * minute + 3 * 60 * minute), got.map { it.startMs }) // the marathon, then a later run
assertTrue(got.all { it.profile == "grown" })
}
@Test fun remindersAreOptionalButTheNextAiringIsAlwaysKnown() {
val c = channel(302, "buffy" to now + 3 * 24 * 60 * minute) // days ahead, beyond reminders' reach
val followed = mapOf("buffy" to FollowSeries.Followed("Buffy", false))
assertTrue(followedReminders(followed, listOf(c), emptyList(), now, "grown").isEmpty())
assertEquals(302, nextAirings(followed.keys, listOf(c), now)["buffy"]!!.channel.number)
}
@Test fun eachProfileSeesOnlyItsOwnFollowedReminders() {
val mine = ProgrammeReminder(302, now + 1_000, "Buffy", profile = "grown")
assertEquals(mine.copy(stage = 1), programmeReminderDue(listOf(mine), now + 1_000 - REMINDER_BEFORE_MS + 1, "grown"))
assertNull(programmeReminderDue(listOf(mine), now + 1_000 - REMINDER_BEFORE_MS + 1, "phveypj"))
val everyone = ProgrammeReminder(302, now + 1_000, "Buffy")
assertNotNull(programmeReminderDue(listOf(everyone), now + 1_000 - REMINDER_BEFORE_MS + 1, "phveypj"))
}
}