Create: the Director takes the lead, plus Off, Undo and new arrivals

A big collection comes back in the Director's order, so the 200 a channel carries are its picks:
the series with the most to watch and films from right across it. Picking a collection goes
straight to the Director's plan, with every title by part of the day, to star, move or take off.
Your channels get an Off switch and an Undo after removing; titles new to a channel's collection
are offered in the Director's Chair. The tabs and action bar step aside while typing, so they no
longer sit over the search. 0.108.90.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-07 13:51:14 +00:00
co-authored by Claude Opus 5.5
parent 2ce22fe2e9
commit c04029533c
11 changed files with 194 additions and 32 deletions
+2 -2
View File
@@ -9,8 +9,8 @@ android {
applicationId = "tv.orbit.classic"
minSdk = 26
targetSdk = 36
versionCode = 249
versionName = "0.108.89-remove-mixed"
versionCode = 250
versionName = "0.108.90-director-plan"
}
buildFeatures { compose = true }
// The finished build for the TVs (Paul, 6 November 2026: the test build stuttered on the box). Not debuggable, so
@@ -79,6 +79,9 @@ main.kpad .ch{margin-bottom:10px;padding:13px 16px}
main.kpad .ch .then{white-space:normal}
/* Above Create's action bar, never over its button. */
body:has(main.kpad) .toast{bottom:calc(250px + env(safe-area-inset-bottom))}
/* While typing, the keyboard pushes fixed bars up over the search results (Paul, 7 November 2026): hide them until it's down. */
body.typing .kbar,body.typing nav{display:none}
.toast button{margin-left:10px;font-weight:800;text-decoration:underline;color:inherit}
.toast{position:fixed;left:50%;bottom:90px;transform:translateX(-50%);background:var(--accent);color:var(--on-accent);padding:9px 16px;border-radius:999px;font-weight:700;font-size:13px;z-index:9;display:none;max-width:90vw;text-align:center}
.empty{color:var(--muted);text-align:center;padding:30px 10px}
</style></head><body>
@@ -94,7 +97,10 @@ const api = async (path, body) => {
if (r.headers.get('content-type')?.includes('text/html')) { location.reload(); throw new Error('Join again'); }
const j = await r.json().catch(() => ({})); if (!r.ok) throw new Error(j.error || 'Something went wrong'); return j;
};
const toast = t => { const e = $('#toast'); e.textContent = t; e.style.display = 'block'; clearTimeout(toast.t); toast.t = setTimeout(() => e.style.display = 'none', 2200); };
const toast = (t, undo) => { const e = $('#toast'); e.textContent = t; if (undo) { const b = document.createElement('button'); b.textContent = 'Undo'; b.dataset.undo = undo; e.appendChild(b); }
e.style.display = 'block'; clearTimeout(toast.t); toast.t = setTimeout(() => e.style.display = 'none', undo ? 8000 : 2200); };
addEventListener('focusin', e => { if (e.target.matches('input[type=text],input:not([type]),input[type=search]')) document.body.classList.add('typing'); });
addEventListener('focusout', () => setTimeout(() => { if (!document.activeElement?.matches?.('input')) document.body.classList.remove('typing'); }, 50));
const buzz = () => navigator.vibrate?.(12);
const hm = ms => new Date(ms).toLocaleTimeString('en-GB', {hour:'2-digit', minute:'2-digit', hourCycle:'h23'});
let skew = 0; const now = () => Date.now() + skew;
@@ -254,7 +260,9 @@ function more() {
h += `<div style="display:flex;justify-content:space-between;align-items:baseline"><div class="label">Your channels</div></div>
<div style="display:flex;gap:10px;overflow-x:auto;padding-bottom:4px;scrollbar-width:none">${(yours?.channels || []).map(c => `<div style="flex:0 0 140px;position:relative"><button data-edit="${c.number}" style="width:100%;height:100%;text-align:left;background:var(--surface);border-radius:16px;padding:14px">
<div style="color:var(--accent);font-weight:800;font-size:18px">${c.number}</div><div style="font-weight:700;margin-top:6px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(c.name)}</div>
<div class="small">${esc((c.styleTitle || '').replace(' by the Director', ''))} · ${c.on ? 'on' : 'off'}</div><div class="small" style="color:var(--accent);font-weight:700;margin-top:8px">Edit</div></button>
<div class="small">${esc((c.styleTitle || '').replace(' by the Director', ''))}</div><div class="small" style="color:var(--accent);font-weight:700;margin-top:8px;padding-bottom:30px">Edit</div></button>
<button data-kpower="${c.number}:${c.on ? 0 : 1}" aria-label="Turn ${esc(c.name)} ${c.on ? 'off' : 'on'}" style="position:absolute;left:14px;bottom:12px;display:flex;align-items:center;gap:6px;font-size:12px;font-weight:700;color:${c.on ? 'var(--mint)' : 'var(--muted)'}">
<span style="width:30px;height:18px;border-radius:9px;background:${c.on ? 'var(--mint)' : 'var(--deep)'};position:relative;display:inline-block"><span style="position:absolute;top:2px;${c.on ? 'right:2px' : 'left:2px'};width:14px;height:14px;border-radius:7px;background:${c.on ? 'var(--deep)' : 'var(--muted)'}"></span></span>${c.on ? 'On' : 'Off'}</button>
<button data-kremove="${c.number}" aria-label="Remove ${esc(c.name)}" style="position:absolute;top:6px;right:6px;width:32px;height:32px;border-radius:16px;display:flex;align-items:center;justify-content:center;color:var(--muted);font-size:18px">×</button></div>`).join('')}
${!yours || yours.next ? `<button data-create="1" aria-label="Create a channel" style="flex:0 0 ${yours?.channels?.length ? '64px' : '100%'};border:2px dashed var(--accent);border-radius:16px;color:var(--accent);font-size:${yours?.channels?.length ? '28px' : '16px'};font-weight:700;padding:14px">${yours?.channels?.length ? '+' : '+ Create a channel'}</button>` : ''}</div>`;
const line = (label, value, attr, first) => `<button ${attr} style="display:flex;width:100%;align-items:center;padding:15px 16px;${first ? '' : 'border-top:1px solid var(--raised);'}text-align:left"><span style="flex:1;font-weight:600">${label}</span><span class="small" style="margin-right:8px">${value}</span>${fold(false).replace('M6 9l6 6 6-6', 'M9 6l6 6-6 6')}</button>`;
@@ -271,7 +279,7 @@ function more() {
const STYLES = [['Shaped','Shaped by the Director',"Daytime, evening and late, like Orbit's own channels, with your core shows more often"],['Standard','Standard TV',"Shows take turns all day, episodes in order"],['Shuffled','Shuffled','Episodes in a mixed order, every one before any repeats'],
['Blocks','Blocks','A timetable: each show at its own times, every day'],['Marathon','Marathon','One show at a time, several episodes back to back']];
const HOURS = [[null,'All day'],[{from:18,to:0},'Evenings, 18:00 to midnight'],[{from:6,to:12},'Mornings, 06:00 to noon'],[{from:9,to:17},'Daytime, 09:00 to 17:00']];
const STEPS = ['Shows','Shape','When','Review'];
const STEPS = ['Shows','Plan','When','Review'];
const VIEWS = {shows: 0, collection: 0, shape: 1, when: 2, review: 3};
const SLOTS = [['Daytime','06:00 to 17:00'],['Evening','17:00 to 22:00'],['Late','22:00 to 06:00']];
const WEEK_HOURS = {Daytime: 77, Evening: 35, Late: 56};
@@ -350,15 +358,17 @@ function create() {
<div class="small">Collection · ${(k.total || 0).toLocaleString()} titles</div>
<div class="small" style="color:${k.complete ? 'var(--mint)' : 'var(--accent)'};font-weight:700">${k.complete ? 'Read in full from your library' : 'Still being read: more will appear'}</div>
<div class="small">${(k.found || 0).toLocaleString()} in your library copy</div></div>
<button class="btn gold" data-kaddall="1" style="width:auto;flex:none">Add ${items.length === (k.items || []).length ? 'all' : items.length}</button></div>
</div>
<button class="ch" data-krefine="1" style="margin-top:10px"><div class="grow"><b>Refine</b> <span class="small">${[rf.type === 'Series' ? 'Shows' : rf.type === 'Movie' ? 'Films' : '', rf.band].filter(Boolean).join(' · ')}</span></div>${fold(k.refineOpen)}</button>
${k.refineOpen ? `<div class="card" style="border-radius:14px"><div class="label" style="margin-top:0">Type</div><div class="chips">${chip('type', '', 'Both')}${chip('type', 'Series', 'Shows')}${chip('type', 'Movie', 'Films')}</div>
<div class="label">Age</div><div class="chips" style="flex-wrap:wrap">${chip('band', '', 'Any')}${chip('band', 'Kids', 'Kids')}${chip('band', 'Family', 'Family')}${chip('band', 'Teen', 'Teen')}${chip('band', 'Adult', 'Grown-up')}${chip('band', 'Unknown', 'Unrated')}</div></div>` : ''}
${note}${items.slice(0, k.shown || 60).map(x => rowTitle(x, d.shows.some(y => y.id === x.id))).join('')}
${items.length > (k.shown || 60) ? `<button class="btn" data-kmore="1" style="margin:6px 0 10px">Show ${Math.min(60, items.length - (k.shown || 60))} more of ${items.length}</button>` : ''}` +
cBar('Done with this collection', 'data-kcoldone="1"', null, null, `${chosenHere} from here · ${chosenNote()}`);
cBar(chosenHere ? 'Next: the Director\'s plan' : `Let the Director plan it`, chosenHere ? 'data-knext="shape"' : 'data-kaddall="1"', chosenHere ? 'Add more' : null, 'data-kcoldone="1"',
chosenHere ? `${chosenHere} from here · ${chosenNote()}` : `The Director picks the best ${Math.min(CHANNEL_MAX, items.length)}${rf.type || rf.band ? ' of these' : ''} and lays out the day. Or tick your own below.`);
}
if (c.view === 'shape') return cTop('Shape the day') + shapeView() + note + cBar('Next: when it’s on', 'data-knext="when"', null, null, d.style === 'Shaped' ? '★ comes round more often' : '');
if (c.view === 'shape') return cTop('The Director’s plan') + note + shapeView() + cBar('Next: when it’s on', 'data-knext="when"', '+ Add', 'data-kaddmore="1"',
`${chosenNote()}${d.style === 'Shaped' ? ' · ★ comes round more often' : ''}`);
if (c.view === 'when') {
return cTop('When it’s on') + `<div class="label" style="margin-top:0">Hours</div>` +
HOURS.map(([h, l], i) => `<button class="ch ${sameHours(h, d.hours) ? 'on' : ''}" data-chours="${i}"><div class="grow"><div class="what">${l}</div></div></button>`).join('') + seasonPicker() + note +
@@ -368,19 +378,21 @@ function create() {
return '';
}
const dropBtn = x => `<button data-kdrop="${esc(x.id)}" aria-label="Take ${esc(x.title)} off" style="width:30px;height:30px;flex:none;border-radius:15px;color:var(--muted);font-size:18px">×</button>`;
function shapeView() {
const c = state.create, d = c.draft, sh = c.shape;
if (d.style !== 'Shaped') return `<div class="card small">${esc(STYLES.find(s => s[0] === d.style)[1])}: ${esc(STYLES.find(s => s[0] === d.style)[2])}. Change the style on Review.</div>`;
if (d.style !== 'Shaped') return `<div class="card small">${esc(STYLES.find(s => s[0] === d.style)[1])}: ${esc(STYLES.find(s => s[0] === d.style)[2])}. Change the style on Review.</div>` +
d.shows.map(x => `<div class="ch" style="cursor:default"><div class="grow"><div class="what">${esc(x.title)}</div><div class="then">${x.type === 'Movie' ? 'Film' : 'Series'}${x.year ? ' · ' + x.year : ''}</div></div>${dropBtn(x)}</div>`).join('');
if (!sh) return '<div class="empty">The Director is laying out the day…</div>';
let h = '';
if (sh.suggestedCore?.length && !d.core.length && !c.coreSet) h += `<div class="card small">The Director would star ${sh.suggestedCore.map(id => esc(d.shows.find(x => x.id === id)?.title || '')).join(', ')} to come round more often.
<div style="display:flex;gap:8px;margin-top:8px"><button class="btn gold" data-cstarok="1">Star them</button><button class="btn" data-cstarno="1">No thanks</button></div></div>`;
if (!Object.keys(d.slots).length) return h + `<div class="card small">Your picks are all one kind, so they play all day rather than being split into daytime, evening and late.</div>` +
d.shows.map(x => `<div class="ch" style="cursor:default"><button data-ccore="${esc(x.id)}" style="font-size:20px;color:${d.core.includes(x.id) ? 'var(--accent)' : 'var(--muted)'}">${d.core.includes(x.id) ? '★' : '☆'}</button><div class="grow what">${esc(x.title)}</div></div>`).join('');
h += `<div class="card small" style="background:var(--deep)">The Director balanced this for you. Open a part of the day to star a show or move it.${sh.notes?.length ? ' ' + esc(sh.notes.slice(0, 2).join(' ')) : ''}</div>`;
d.shows.map(x => `<div class="ch" style="cursor:default"><button data-ccore="${esc(x.id)}" style="font-size:20px;color:${d.core.includes(x.id) ? 'var(--accent)' : 'var(--muted)'}">${d.core.includes(x.id) ? '★' : '☆'}</button><div class="grow what">${esc(x.title)}</div>${dropBtn(x)}</div>`).join('');
h += `<div class="card small" style="background:var(--deep)">The Director laid out the day. Star a show to see it more, move it to another part of the day, or × to take it off.${sh.notes?.length ? ' ' + esc(sh.notes.slice(0, 2).join(' ')) : ''}</div>`;
const hoursOf = id => (sh.runHours || {})[id] || 0;
for (const [slot, span] of SLOTS) {
const mine = d.shows.filter(x => (d.slots[x.id] || 'Evening') === slot), open = c.open?.[slot];
const mine = d.shows.filter(x => (d.slots[x.id] || 'Evening') === slot), open = c.open?.[slot] ?? true;
const hrs = Math.round(mine.reduce((a, x) => a + hoursOf(x.id), 0)), need = WEEK_HOURS[slot], frac = Math.min(1, hrs / (need * 3));
h += `<div class="rm" style="padding:12px 14px"><button data-kfold="${slot}" style="width:100%;text-align:left;display:block">
<div style="display:flex;align-items:center;gap:8px"><b style="font-size:16px">${slot}</b><span class="small">${span}</span><span style="margin-left:auto">${fold(open)}</span></div>
@@ -389,7 +401,7 @@ function shapeView() {
${open ? (mine.length ? mine.map(x => `<div style="display:flex;align-items:center;gap:8px;margin-top:10px">
<button data-ccore="${esc(x.id)}" aria-label="Core" style="font-size:20px;color:${d.core.includes(x.id) ? 'var(--accent)' : 'var(--muted)'}">${d.core.includes(x.id) ? '★' : '☆'}</button>
<div class="grow"><div style="font-weight:700">${esc(x.title)}</div></div>
<select data-kmove="${esc(x.id)}" style="padding:6px;border-radius:14px;background:var(--raised);color:var(--ink);border:0">${SLOTS.map(([s]) => `<option ${s === slot ? 'selected' : ''}>${s}</option>`).join('')}</select></div>`).join('')
<select data-kmove="${esc(x.id)}" style="padding:6px;border-radius:14px;background:var(--raised);color:var(--ink);border:0">${SLOTS.map(([s]) => `<option ${s === slot ? 'selected' : ''}>${s}</option>`).join('')}</select>${dropBtn(x)}</div>`).join('')
: '<div class="small" style="margin-top:8px">Nothing here: these hours share the daytime and evening shows.</div>') : ''}</div>`;
}
return h;
@@ -487,7 +499,7 @@ function startCreate(draft) {
}
// Name the Director suggests: the collection's own name, or the description in a few words.
const suggestName = text => text.replace(/\s+/g, ' ').trim().split(' ').slice(0, 3).map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ').slice(0, 40);
function goTo(view) { const c = state.create; c.view = view; c.note = '';
function goTo(view) { const c = state.create; c.view = view; c.note = view === 'shape' ? (c.capNote || '') : ''; if (view === 'shape') c.capNote = '';
if (view === 'review' && !state.brands) api('/api/brands').then(r => { state.brands = r.packs; if (state.create?.view === 'review') render(); }).catch(() => { state.brands = []; });
render(); scrollTo(0, 0);
if (view === 'shape' || (view === 'review' && !c.shape) || view === 'when') shapeShows(); if (view === 'review') checkClashes(); }
@@ -510,11 +522,11 @@ async function quickBuild() {
try {
const col = (state.collections || []).find(k => k.name.toLowerCase() === d.description.toLowerCase());
let picks;
if (col) { const r = await api('/api/browse?collection=' + encodeURIComponent(col.name)); picks = r.items.slice(0, CHANNEL_MAX); c.suggestedName = col.name;
if (r.items.length > CHANNEL_MAX) c.capNote = `${col.name} has ${titles(r.found)}. A channel carries up to ${CHANNEL_MAX}, so the Director took the first ${CHANNEL_MAX}. Untick any, or build it yourself to choose.`; }
if (col) { const r = await api('/api/browse?collection=' + encodeURIComponent(col.name)); picks = r.items.slice(0, CHANNEL_MAX); c.suggestedName = col.name; d.collection = col.name;
if (r.items.length > CHANNEL_MAX) c.capNote = `${col.name} has ${titles(r.found)}. A channel carries up to ${CHANNEL_MAX}, so the Director chose its best ${CHANNEL_MAX}: the series with the most to watch, and films from right across it.`; }
else { picks = await api('/api/suggest?d=' + encodeURIComponent(d.description) + '&chosen=&skipped='); c.suggestedName = suggestName(d.description); }
if (!picks.length) { c.note = 'Nothing in your library fits that yet. Try other words, a collection or a network, or build it yourself.'; c.busy = false; render(); return; }
d.shows = picks; c.quick = true; c.results = null; c.busy = false; goTo('shows'); if (c.capNote) { c.note = c.capNote; c.capNote = ''; render(); }
d.shows = picks; c.quick = true; c.results = null; c.busy = false; goTo('shape');
} catch (e) { c.note = e.message; c.busy = false; render(); }
}
function chosenSheet() {
@@ -583,7 +595,7 @@ async function makeChannel(ending) {
c.busy = true; render();
try { const r = await api('/api/channels', {number: d.number, name: d.name, description: d.description, style: d.style, hours: d.hours, shows: d.shows.map(x => ({id: x.id, title: x.title, year: x.year ?? null, type: x.type})),
slots: d.style === 'Shaped' ? d.slots : undefined, core: d.style === 'Shaped' ? d.core : undefined, season: d.season || null,
brand: d.brand !== undefined ? d.brand : undefined});
brand: d.brand !== undefined ? d.brand : undefined, collection: d.collection || undefined});
c.done = {number: r.number, name: d.name, message: r.message, edit: !!d.number}; c.busy = false; render(); load('more');
// Create & watch next: queued for after the programme on now, never interrupting it (Paul, 7 November 2026).
if (ending === 'next') { await watchNew('next'); }
@@ -602,6 +614,10 @@ function director() {
<div class="small">${esc(i.format)} · ${esc(i.evening)}</div><div style="margin:8px 0">${i.films.map(f => `<div style="font-weight:600">${esc(f)}</div>`).join('')}</div>
${i.reasons.length ? `<div class="small">${esc(i.reasons[0])}</div>` : ''}
${i.decision === 'approved' ? '' : `<div class="row" style="gap:8px;margin-top:10px"><button class="btn gold" data-idea="${esc(i.signature)}:approved">Approve</button><button class="btn" data-idea="${esc(i.signature)}:deferred">Defer</button><button class="btn" data-idea="${esc(i.signature)}:dismissed">Dismiss</button></div>`}</div>`).join('');
if (state.arrivals?.length) h += '<div class="label">New in your collections</div>' + state.arrivals.map(a => `<div class="rm"><h3 style="display:block">${titles(a.titles.length)} new for ${esc(a.channel)}</h3>
<div class="small">Arrived in ${esc(a.collection)} since you made it${!a.room ? ` · it's full at ${CHANNEL_MAX}, so take some off to make room` : a.room < a.titles.length ? ` · room for ${a.room} more` : ''}</div>
<div style="margin:8px 0">${a.titles.slice(0, 6).map(t => `<div style="font-weight:600">${esc(t.title)}${t.year ? ` <span class="small">${t.year}</span>` : ''}</div>`).join('')}${a.titles.length > 6 ? `<div class="small">and ${a.titles.length - 6} more</div>` : ''}</div>
<div class="row" style="gap:8px"><button class="btn gold" data-arrive="${a.number}:1">Add to ${esc(a.channel)}</button><button class="btn" data-arrive="${a.number}:0">Not now</button></div></div>`).join('');
h += '<div class="label">Titles for your channels</div>';
h += r.choices.length ? r.choices.map(c => `<div class="rm"><h3 style="display:block">${esc(c.title)}</h3><div class="small">${c.type === 'Movie' ? 'Film' : 'Series'}${c.year ? ' · ' + c.year : ''}${c.line ? ' · ' + esc(c.line) : ''}</div>
<div class="chips" style="flex-wrap:wrap;margin:10px 0 0">${c.options.map((o, k) => `<button class="${k === 0 ? 'on' : ''}" data-place="${esc(c.id)}:${o.number}">${k === 0 ? 'Place on ' : ''}${o.number} ${esc(o.name)}</button>`).join('')}
@@ -646,7 +662,7 @@ async function load(what) {
if (what === 'more') { const [l, c, p] = await Promise.all([api('/api/looks'), api('/api/channels').catch(() => null), api('/api/profiles').catch(() => null)]);
state.looks = l.looks; state.channels = c; state.profiles = p; look(state.now?.look);
if (p?.current?.kind !== 'Kids') api('/api/director').then(r => { state.directorCount = r.ready ? r.ideas.filter(i => i.decision !== 'approved').length + r.choices.length : 0; if (tab === 'more' && !state.create && !state.chair) render(); }).catch(() => {}); }
if (what === 'director') state.director = await api('/api/director');
if (what === 'director') { const [r, a] = await Promise.all([api('/api/director'), api('/api/arrivals').catch(() => ({arrivals: []}))]); state.director = r; state.arrivals = a.arrivals; }
offline = false;
} catch (e) { if (!offline) toast(e.message === 'Failed to fetch' ? "Orbit isn't open on the TV" : e.message); offline = true; }
// Making a channel isn't redrawn by the background refresh, so typing is never lost.
@@ -710,9 +726,10 @@ document.addEventListener('click', e => {
if (d.kaddall) { const c = state.create, rf = c.col.refine;
const items = c.col.items.filter(x => (!rf.type || x.type === rf.type) && (!rf.band || x.band === rf.band));
const fresh = items.filter(x => !c.draft.shows.some(y => y.id === x.id)), room = Math.max(0, CHANNEL_MAX - c.draft.shows.length);
fresh.slice(0, room).forEach(x => c.draft.shows.push(x));
c.note = fresh.length > room ? `A channel carries up to ${CHANNEL_MAX} titles, so ${room ? `the first ${room} of these ${fresh.length.toLocaleString()} were added` : 'none more could be added'}. Refine to Shows, Films or an age to choose a different ${CHANNEL_MAX}.` : '';
toast(`Added ${Math.min(room, fresh.length)}`); render(); return; }
fresh.slice(0, room).forEach(x => c.draft.shows.push(x)); c.draft.collection = c.col.name;
// Straight to the Director's plan, which says what it chose.
c.capNote = fresh.length > room ? `${c.col.name} has ${titles(fresh.length)}${rf.type || rf.band ? ' that fit' : ''}. A channel carries up to ${CHANNEL_MAX}, so the Director chose its best ${room}: the series with the most to watch, and films from right across it.` : '';
goTo('shape'); return; }
if (d.krefine) { state.create.col.refineOpen = !state.create.col.refineOpen; render(); return; }
if (d.kref) { const cut = d.kref.indexOf(':'), k = d.kref.slice(0, cut), v = d.kref.slice(cut + 1); state.create.col.refine[k] = v; render(); return; }
if (d.kmore) { state.create.col.shown = (state.create.col.shown || 60) + 60; render(); return; }
@@ -728,13 +745,21 @@ document.addEventListener('click', e => {
if (d.kmake) { makeChannel(d.kmake); return; }
if (d.kbrand !== undefined) { const c = state.create; c.draft.name = ($('#kname')?.value || c.draft.name || '').trim(); c.draft.brand = d.kbrand; render(); return; }
if (d.create) { startCreate({name: '', description: '', style: 'Shaped', hours: null, shows: [], skipped: []}); return; }
if (d.kaddmore) { const c = state.create; c.quick = false; c.view = 'shows'; c.note = ''; render(); scrollTo(0, 0); return; }
if (d.kdrop) { const dr = state.create.draft; dr.shows = dr.shows.filter(x => x.id !== d.kdrop); dr.core = dr.core.filter(i => i !== d.kdrop); delete dr.slots[d.kdrop]; render(); return; }
if (d.kpower) { const [n, on] = d.kpower.split(':');
api('/api/channels/power', {number: +n, on: on === '1'}).then(r => { toast(r.message); load('more'); }).catch(e => toast(e.message)); return; }
if (d.undo) { const n = +d.undo; $('#toast').style.display = 'none';
api('/api/channels/restore', {number: n}).then(r => { toast(r.message); load('more'); }).catch(e => toast(e.message)); return; }
if (d.arrive) { const [n, add] = d.arrive.split(':'), a = state.arrivals?.find(x => x.number === +n); if (!a) return;
api('/api/arrivals', {number: +n, ids: a.titles.map(t => t.id), add: add === '1'}).then(r => { toast(r.message); state.arrivals = state.arrivals.filter(x => x !== a); render(); }).catch(e => toast(e.message)); return; }
// Remove a channel of your own (Paul, 7 November 2026: "a little x to remove ones"), always asked first.
if (d.kremove) { const ch = state.channels?.channels.find(x => x.number === +d.kremove); if (!ch) return;
openSheet(`<div class="title">Remove ${esc(ch.name)}?</div><div class="small" style="margin:8px 0 14px">${ch.number} leaves the guide on ${esc(room())}, with everything it had planned. Your library isn't touched, and you can make it again any time.</div>
<button class="btn gold" data-kremoveyes="${ch.number}">Remove ${esc(ch.name)}</button><button class="btn" data-kremoveno="1" style="margin-top:8px">Keep it</button>`); return; }
if (d.kremoveno) { closeSheet(); return; }
if (d.kremoveyes) { const n = +d.kremoveyes; closeSheet();
api('/api/channels/remove', {number: n}).then(r => { toast(r.message || 'Removed'); load('more'); }).catch(e => toast(e.message)); return; }
api('/api/channels/remove', {number: n}).then(r => { toast(r.message || 'Removed', n); load('more'); }).catch(e => toast(e.message)); return; }
if (d.edit) { const ch = state.channels?.channels.find(x => x.number === +d.edit); if (!ch) return;
api('/api/shows?number=' + ch.number).then(shows => {
// A shaped channel keeps its layout by title; the phone works by item.
@@ -60,7 +60,13 @@ internal class ChannelMaker(
/** Networks and studios by name, with their title counts. */
val studios: suspend (String) -> List<Pair<String, Int>> = { emptyList() },
/** Removes a channel of your own from every guide on this TV; what it says back. */
val remove: suspend (Int) -> String = { "That channel can't be removed here." })
val remove: suspend (Int) -> String = { "That channel can't be removed here." },
/** Turns a channel of your own off (kept, with its place) or on again. */
val power: suspend (Int, Boolean) -> String = { _, _ -> "That channel can't be changed here." },
/** Brings back the channel removed a moment ago, as it was. */
val restore: suspend (Int) -> String = { "That channel can't be brought back." },
/** New titles from a channel's collection: added to it, or set aside as seen. */
val arrivals: suspend (Int, List<String>, Boolean) -> String = { _, _, _ -> "That can't be done here." })
/** One of the library's collections as Orbit read it. [complete] is false when it stopped short of [total]. */
internal class LibraryCollection(val name: String, val members: List<String>, val total: Int, val complete: Boolean)
@@ -179,7 +185,8 @@ internal fun CreateChannelFlow(maker: ChannelMaker, editing: CustomChannel?, onD
// Editing on the TV keeps what the phone set: the season, and a shaped layout while the shows and style stay.
val kept = editing?.takeIf { it.style == style && it.shows.toSet() == chosen.map { c -> c.title }.toSet() }
val channel = CustomChannel(number, name.trim(), style, hours, description.trim(), chosen.map { it.title },
slots = kept?.slots.orEmpty(), core = kept?.core.orEmpty(), season = editing?.season, brand = editing?.brand ?: brandPackFor(name))
slots = kept?.slots.orEmpty(), core = kept?.core.orEmpty(), season = editing?.season, brand = editing?.brand ?: brandPackFor(name),
collection = editing?.collection, seen = editing?.seen.orEmpty())
onDone(runCatching { maker.create(channel, chosen) }.getOrElse { "That channel couldn't be made. Try again." })
}
}
@@ -44,11 +44,17 @@ internal data class CustomChannel(val number: Int, val name: String, val style:
/** On air only through this part of the year, if you chose one (Paul, 7 November 2026: an optional choice, with dates). */
val season: SeasonWindow? = null,
/** An Orbit brand pack it wears ([BrandPacks]), or null for the plain Yours look. */
val brand: String? = null) {
val brand: String? = null,
/**
* The library collection it was made from, and that collection's titles as they were when you last looked, so the
* Director's Chair can offer what has arrived since (Paul, 7 November 2026).
*/
val collection: String? = null, val seen: Set<String> = emptySet()) {
init { require(number in YOURS_FIRST..YOURS_LAST && name.isNotBlank() && name.length <= 40) }
fun toJson(): JSONObject = JSONObject().put("number", number).put("name", name).put("style", style.name).put("description", description)
.put("hours", hours?.let { JSONObject().put("from", it.fromHour).put("to", it.toHour) } ?: JSONObject.NULL).put("shows", JSONArray(shows))
.put("slots", JSONObject(slots.mapValues { it.value.name })).put("core", JSONArray(core.toList())).put("season", season?.toJson() ?: JSONObject.NULL).put("brand", brand ?: JSONObject.NULL)
.put("collection", collection ?: JSONObject.NULL).put("seen", JSONArray(seen.toList()))
companion object {
fun fromJson(o: JSONObject) = CustomChannel(o.getInt("number"), o.getString("name").take(40),
runCatching { PlayStyle.valueOf(o.optString("style")) }.getOrDefault(PlayStyle.Standard),
@@ -56,7 +62,9 @@ internal data class CustomChannel(val number: Int, val name: String, val style:
o.optJSONArray("shows")?.let { a -> (0 until minOf(a.length(), 200)).map { a.getString(it).take(160) } }.orEmpty(),
o.optJSONObject("slots")?.let { m -> m.keys().asSequence().take(200).mapNotNull { k -> runCatching { k.take(160) to Slot.valueOf(m.getString(k)) }.getOrNull() }.toMap() }.orEmpty(),
o.optJSONArray("core")?.let { a -> (0 until minOf(a.length(), 20)).map { a.getString(it).take(160) }.toSet() }.orEmpty(),
SeasonWindow.of(o.optJSONObject("season")), o.optString("brand").takeIf { it in BrandPacks })
SeasonWindow.of(o.optJSONObject("season")), o.optString("brand").takeIf { it in BrandPacks },
o.optString("collection").takeIf { !o.isNull("collection") && it.isNotBlank() }?.take(120),
o.optJSONArray("seen")?.let { a -> (0 until minOf(a.length(), COLLECTION_MAX)).map { a.getString(it) }.filter(EmbyClient::validId).toSet() }.orEmpty())
}
}
@@ -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.89\"") +
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.90\"") +
(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.89\"" +
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.90\"" +
(token?.let { ", Token=\"$it\"" } ?: ""))
}
/** One picture from the provider, or nothing. Same fixed origin and no redirects, and failures are never shown or logged. */
@@ -534,6 +534,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
}
// Create your own from a phone and the Companion: kept here, before any screen returns early, so the phone can make
// and edit channels from every section, not only while Settings is open (Paul, 7 November 2026).
var lastRemoved by remember { mutableStateOf<Pair<CustomChannel, Long>?>(null) }
val channelMaker = remember(session, workspace) { session?.let { active -> ChannelMaker(
suggest = { description, chosen, skipped -> withContext(Dispatchers.IO) {
val wish = wishOf(description)
@@ -573,6 +574,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
},
remove = { number ->
val gone = CustomChannels.of(number) ?: return@ChannelMaker "That channel has already gone."
lastRemoved = gone to System.currentTimeMillis()
withContext(Dispatchers.IO) {
scheduler.setEnabled(active.accountId, number, false)
CustomChannels.remove(workspace.scheduleDir, number)
@@ -583,6 +585,46 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
if (selectedNumber == number) { selectedNumber = lastNumber.takeIf { it != number } ?: 101; channelClockOffset = 0 }
android.util.Log.i("OrbitSchedule", "yours removed channel=$number")
"${gone.name} has been removed from $number."
},
power = { number, on ->
val programming = SmartChannels.firstOrNull { it.number == number }
when {
programming == null -> "That channel has gone."
busy -> "The TV is still planning another channel. Try again in a minute."
on == scheduledChannels.containsKey(number) -> "${programming.name} is already ${if (on) "on" else "off"}."
else -> { setSmartSchedule(programming, on); if (on) "${programming.name} is coming back on. Its programmes are being planned now." else "${programming.name} is off. Its place and shows are kept." }
}
},
restore = { number ->
val (gone, at) = lastRemoved ?: return@ChannelMaker "There's nothing to bring back."
if (gone.number != number || System.currentTimeMillis() - at > 60_000L || CustomChannels.of(number) != null) return@ChannelMaker "That can't be brought back now."
withContext(Dispatchers.IO) { scheduleStore.bringBack(number); CustomChannels.upsert(workspace.scheduleDir, gone) }
lastRemoved = null
android.util.Log.i("OrbitSchedule", "yours restored channel=$number")
SmartChannels.firstOrNull { it.number == number }?.let { setSmartSchedule(it, true) }
"${gone.name} is back on $number."
},
arrivals = { number, ids, add ->
val ch = CustomChannels.of(number) ?: return@ChannelMaker "That channel has gone."
val seen = ch.seen + ids
if (!add) { withContext(Dispatchers.IO) { CustomChannels.upsert(workspace.scheduleDir, ch.copy(seen = seen)) }; return@ChannelMaker "Set aside. The Director won't offer those again." }
val (have, rows) = withContext(Dispatchers.IO) { scheduleStore.loadChoices(active.accountId, number).accepted to catalogue.shapeRows(ids) }
val fresh = rows.filter { r -> have.none { it.id == r.id } }.take((200 - have.size).coerceAtLeast(0))
if (fresh.isEmpty()) { withContext(Dispatchers.IO) { CustomChannels.upsert(workspace.scheduleDir, ch.copy(seen = seen)) }
return@ChannelMaker if (have.size >= 200) "${ch.name} already carries 200 titles. Remove some to make room." else "Those are already on ${ch.name}." }
val shows = have + fresh.map { Suggestion(it.id, it.title, it.year, it.type, "", "New in ${ch.collection}") }
// New titles take the slot the Director would give them; everything already laid out stays where it is.
val slots = if (ch.style != PlayStyle.Shaped || ch.slots.isEmpty()) ch.slots else withContext(Dispatchers.IO) {
val all = catalogue.shapeRows(shows.map { it.id }); val shape = shapeChannel(all); val titleOf = all.associate { it.id to it.title }
ch.slots + fresh.mapNotNull { r -> shape.slots[r.id]?.let { r.title to it } ?: (titleOf[r.id]?.let { it to Slot.Evening }) }.toMap()
}
withContext(Dispatchers.IO) {
CustomChannels.upsert(workspace.scheduleDir, ch.copy(shows = shows.map { it.title }, slots = slots, seen = seen))
scheduleStore.saveChoices(active.accountId, number, ChannelChoices(shows, scheduleStore.loadChoices(active.accountId, number).rejected))
}
android.util.Log.i("OrbitSchedule", "yours arrivals channel=$number added=${fresh.size}")
SmartChannels.firstOrNull { it.number == number }?.takeIf { scheduledChannels.containsKey(number) }?.let { setSmartSchedule(it, true) }
"${fresh.size} added to ${ch.name}. They join as it plans ahead; nothing already booked changes."
}) } }
// The phone page (Create your own from a phone) asks the same of this screen as Settings does, and can tune the TV.
DisposableEffect(channelMaker) {
@@ -332,7 +332,8 @@ internal object PhoneLink {
"GET /api/browse" -> if (r.query["collection"] != null) {
// From a collection: its actual members, as the library lists them, not a guess from its name.
val c = runBlocking { h.maker.collections() }.firstOrNull { it.name == r.query["collection"] } ?: return json(out, 404, JSONObject().put("error", "That collection isn't in the library copy yet."))
val rows = runBlocking { h.maker.rowsOf(c.members.take(1000)) }
// In the Director's order: its picks first, so a channel's 200 are the best of the whole collection.
val rows = directorOrder(runBlocking { h.maker.rowsOf(c.members.take(2000)) }, c.name.hashCode())
json(out, 200, JSONObject().put("complete", c.complete).put("total", c.total).put("found", rows.size).put("items", JSONArray(rows.map { row -> suggestionJson(Suggestion(row.id, row.title, row.year, row.type, "",
listOfNotNull(row.genres.take(2).joinToString(", ").ifEmpty { null }, row.rating.ifEmpty { null }).joinToString(" · ").ifEmpty { "In ${c.name}" })).put("band", ratingBand(row.rating).name) })))
} else {
@@ -379,13 +380,52 @@ internal object PhoneLink {
val titleOf = shows.associate { it.id to it.title }
// An Orbit brand pack: the one chosen, else the one the name matches ("Sakura" wears Orbit Sakura).
val chosenBrand = if (o.has("brand")) o.optString("brand").takeIf { it in BrandPacks } else brandPackFor(channel.name)
val seasoned = channel.copy(season = SeasonWindow.of(o.optJSONObject("season")), brand = chosenBrand)
// Made from a collection: remember it and what it held, so its new arrivals can be offered later. An edit keeps them.
val before = CustomChannels.of(number)
val fromCollection = o.optString("collection").takeIf { it.isNotBlank() }?.let { name -> runBlocking { h.maker.collections() }.firstOrNull { it.name == name } }
val seasoned = channel.copy(season = SeasonWindow.of(o.optJSONObject("season")), brand = chosenBrand,
collection = fromCollection?.name ?: before?.collection, seen = fromCollection?.members?.toSet() ?: before?.seen.orEmpty())
val laidOut = if (seasoned.style != PlayStyle.Shaped) seasoned else seasoned.copy(
slots = o.optJSONObject("slots")?.let { m -> m.keys().asSequence().mapNotNull { id -> titleOf[id]?.let { t -> runCatching { t to Slot.valueOf(m.getString(id)) }.getOrNull() } }.toMap() }.orEmpty(),
core = o.optJSONArray("core")?.let { a -> (0 until minOf(a.length(), 20)).mapNotNull { titleOf[a.getString(it)] }.toSet() }.orEmpty())
val said = runBlocking { withContext(mainDispatcher) { h.maker.create(laidOut, shows) } }
json(out, 200, JSONObject().put("message", said).put("number", number))
}
// Off keeps a channel and its place; on plans it again (Paul, 7 November 2026: an Off switch beside Remove).
"POST /api/channels/power" -> {
if (!OrbitCompanion.grownUp) return json(out, 403, JSONObject().put("error", "Kids is watching. Switch to Adult to change channels."))
val o = runCatching { JSONObject(r.body) }.getOrNull() ?: return json(out, 400, JSONObject())
val number = o.optInt("number").takeIf { n -> CustomChannels.list.any { it.number == n } } ?: return json(out, 404, JSONObject().put("error", "That channel has gone."))
val said = runBlocking { withContext(mainDispatcher) { h.maker.power(number, o.optBoolean("on")) } }
json(out, 200, JSONObject().put("message", said))
}
// Undo, for a few seconds after a removal: the channel and everything it had planned come back as they were.
"POST /api/channels/restore" -> {
if (!OrbitCompanion.grownUp) return json(out, 403, JSONObject().put("error", "Kids is watching. Switch to Adult to change channels."))
val number = runCatching { JSONObject(r.body).getInt("number") }.getOrNull() ?: return json(out, 400, JSONObject())
val said = runBlocking { withContext(mainDispatcher) { h.maker.restore(number) } }
json(out, 200, JSONObject().put("message", said))
}
// New in a channel's collection since you last looked, for the Director's Chair on the phone.
"GET /api/arrivals" -> {
val cols = runBlocking { h.maker.collections() }.associateBy { it.name }
val found = CustomChannels.list.mapNotNull { ch ->
val col = ch.collection?.let { cols[it] } ?: return@mapNotNull null
val fresh = col.members.filter { it !in ch.seen }.take(40)
if (fresh.isEmpty()) null else Triple(ch, col, runBlocking { h.maker.rowsOf(fresh) }.take(12))
}.filter { it.third.isNotEmpty() }
json(out, 200, JSONObject().put("arrivals", JSONArray(found.map { (ch, col, rows) -> JSONObject().put("number", ch.number).put("channel", ch.name)
.put("collection", col.name).put("room", (200 - ch.shows.size).coerceAtLeast(0))
.put("titles", JSONArray(rows.map { row -> suggestionJson(Suggestion(row.id, row.title, row.year, row.type, "", "New in ${col.name}")) })) })))
}
"POST /api/arrivals" -> {
if (!OrbitCompanion.grownUp) return json(out, 403, JSONObject().put("error", "Kids is watching. Switch to Adult for the Director."))
val o = runCatching { JSONObject(r.body) }.getOrNull() ?: return json(out, 400, JSONObject())
val number = o.optInt("number").takeIf { n -> CustomChannels.list.any { it.number == n } } ?: return json(out, 404, JSONObject().put("error", "That channel has gone."))
val ids = runCatching { o.getJSONArray("ids").let { a -> (0 until minOf(a.length(), 40)).map { a.getString(it) }.filter(EmbyClient::validId) } }.getOrDefault(emptyList())
val said = runBlocking { withContext(mainDispatcher) { h.maker.arrivals(number, ids, o.optBoolean("add")) } }
json(out, 200, JSONObject().put("message", said))
}
"POST /api/channels/remove" -> {
if (!OrbitCompanion.grownUp) return json(out, 403, JSONObject().put("error", "Kids is watching. Switch to Adult to remove channels."))
val number = runCatching { JSONObject(r.body).getInt("number") }.getOrNull()?.takeIf { n -> CustomChannels.list.any { it.number == n } }
@@ -244,6 +244,12 @@ internal class ScheduleStore(private val directory: File) {
.map { File(directory, it) }.filter { it.exists() }.forEach { it.renameTo(File(directory, it.name + ".removed")) }
}
/** Undo of [setAside], straight after: the channel's files come back as they were. */
fun bringBack(number: Int) {
directory.listFiles()?.filter { f -> listOf("episodes", "schedule", "progress", "choices").any { f.name.startsWith("$it-$number.json") } && f.name.endsWith(".removed") }
?.forEach { it.renameTo(File(directory, it.name.removeSuffix(".removed"))) }
}
/** Bytes held for a channel, for the measurements. */
fun sizes(number: Int) = listOf("episodes", "schedule", "progress", "choices").associateWith { file(it, number).length() }
@@ -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.89")
next.setRequestProperty("User-Agent", "OrbitTV/0.108.90")
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()) {
@@ -157,6 +157,25 @@ internal fun shapeChannel(rows: List<ShapeRow>): Shape {
}
/** A Christmas channel's season, offered by the Director when most of the picks are Christmas titles; the choice is yours. */
/**
* A big collection in the order the Director would take it (Paul, 7 November 2026: "the Director needs to take control"),
* so the first 200 are its picks rather than the first 200 by name. Series with the most to watch come first, as they carry
* a channel; films are drawn in a mixed order so a run of films isn't A to J; the two are woven together in the
* collection's own proportions. The same collection always comes out in the same order.
*/
internal fun directorOrder(rows: List<ShapeRow>, seed: Int): List<ShapeRow> {
val series = rows.filter { it.type == "Series" }.sortedWith(compareByDescending<ShapeRow> { it.runMs ?: 0L }.thenBy { it.title })
val films = rows.filter { it.type != "Series" }.sortedBy { it.id }.shuffled(java.util.Random(seed.toLong()))
val out = ArrayList<ShapeRow>(rows.size)
var s = 0; var f = 0
while (s < series.size || f < films.size) {
// Whichever kind is furthest behind its share goes next.
val takeSeries = f >= films.size || (s < series.size && s.toDouble() / series.size <= f.toDouble() / films.size)
out += if (takeSeries) series[s++] else films[f++]
}
return out
}
internal fun suggestSeason(rows: List<ShapeRow>): SeasonWindow? {
val festive = rows.count { r -> Regex("(?i)christmas|xmas|holiday|noel|santa|mistletoe|snow").containsMatchIn(r.title) || "Christmas" in r.genres }
return if (rows.size >= 3 && festive >= rows.size * .5) SeasonWindow(11, 1, 12, 31) else null
@@ -108,4 +108,19 @@ class SmartSetupTest {
assertEquals(40, plan.entries.map { it.seriesId }.toSet().size)
assertNotEquals(films.map { it.id }, plan.entries.map { it.seriesId })
}
// "The Director needs to take control" (Paul, 7 November 2026): a big collection's first 200 are the Director's picks,
// the series with the most to watch and films from right across it, in the collection's own mix, the same every time.
@Test fun directorTakesTheBestOfABigCollection() {
val series = (1..300).map { k -> ShapeRow("s$k", "Series", "Show %03d".format(k), 2010, "TV-14", setOf("Anime"), k * 3_600_000L) }
val films = (1..100).map { k -> ShapeRow("f$k", "Movie", "Film %03d".format(k), 2010, "TV-14", setOf("Anime"), 2 * 3_600_000L) }
val order = directorOrder(films + series, 42)
assertEquals(order, directorOrder((series + films).reversed(), 42))
val first = order.take(200)
assertEquals(150, first.count { it.type == "Series" }); assertEquals(50, first.count { it.type == "Movie" })
assertEquals((151..300).map { "s$it" }.toSet(), first.filter { it.type == "Series" }.map { it.id }.toSet())
val filmNumbers = first.filter { it.type == "Movie" }.map { it.id.drop(1).toInt() }
assertTrue(filmNumbers.any { it > 75 } && filmNumbers.any { it <= 25 })
assertEquals(400, order.size)
}
}