diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 3a71908a..0df2f680 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -9,8 +9,8 @@ android { applicationId = "tv.orbit.classic" minSdk = 26 targetSdk = 36 - versionCode = 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 diff --git a/android/app/src/main/assets/phone/companion.html b/android/app/src/main/assets/phone/companion.html index 1588028e..55707bf1 100644 --- a/android/app/src/main/assets/phone/companion.html +++ b/android/app/src/main/assets/phone/companion.html @@ -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} @@ -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 += `
Your channels
${(yours?.channels || []).map(c => `
+
${esc((c.styleTitle || '').replace(' by the Director', ''))}
Edit
+
`).join('')} ${!yours || yours.next ? `` : ''}
`; const line = (label, value, attr, first) => ``; @@ -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() {
Collection · ${(k.total || 0).toLocaleString()} titles
${k.complete ? 'Read in full from your library' : 'Still being read: more will appear'}
${(k.found || 0).toLocaleString()} in your library copy
- + ${k.refineOpen ? `
Type
${chip('type', '', 'Both')}${chip('type', 'Series', 'Shows')}${chip('type', 'Movie', 'Films')}
Age
${chip('band', '', 'Any')}${chip('band', 'Kids', 'Kids')}${chip('band', 'Family', 'Family')}${chip('band', 'Teen', 'Teen')}${chip('band', 'Adult', 'Grown-up')}${chip('band', 'Unknown', 'Unrated')}
` : ''} ${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) ? `` : ''}` + - 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') + `
Hours
` + HOURS.map(([h, l], i) => ``).join('') + seasonPicker() + note + @@ -368,19 +378,21 @@ function create() { return ''; } +const dropBtn = x => ``; function shapeView() { const c = state.create, d = c.draft, sh = c.shape; - if (d.style !== 'Shaped') return `
${esc(STYLES.find(s => s[0] === d.style)[1])}: ${esc(STYLES.find(s => s[0] === d.style)[2])}. Change the style on Review.
`; + if (d.style !== 'Shaped') return `
${esc(STYLES.find(s => s[0] === d.style)[1])}: ${esc(STYLES.find(s => s[0] === d.style)[2])}. Change the style on Review.
` + + d.shows.map(x => `
${esc(x.title)}
${x.type === 'Movie' ? 'Film' : 'Series'}${x.year ? ' · ' + x.year : ''}
${dropBtn(x)}
`).join(''); if (!sh) return '
The Director is laying out the day…
'; let h = ''; if (sh.suggestedCore?.length && !d.core.length && !c.coreSet) h += `
The Director would star ${sh.suggestedCore.map(id => esc(d.shows.find(x => x.id === id)?.title || '')).join(', ')} to come round more often.
`; if (!Object.keys(d.slots).length) return h + `
Your picks are all one kind, so they play all day rather than being split into daytime, evening and late.
` + - d.shows.map(x => `
${esc(x.title)}
`).join(''); - h += `
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(' ')) : ''}
`; + d.shows.map(x => `
${esc(x.title)}
${dropBtn(x)}
`).join(''); + h += `
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(' ')) : ''}
`; 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 += `
${esc(x.title)}
-
`).join('') + ${dropBtn(x)}`).join('') : '
Nothing here: these hours share the daytime and evening shows.
') : ''}`; } 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() {
${esc(i.format)} · ${esc(i.evening)}
${i.films.map(f => `
${esc(f)}
`).join('')}
${i.reasons.length ? `
${esc(i.reasons[0])}
` : ''} ${i.decision === 'approved' ? '' : `
`}`).join(''); + if (state.arrivals?.length) h += '
New in your collections
' + state.arrivals.map(a => `

${titles(a.titles.length)} new for ${esc(a.channel)}

+
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` : ''}
+
${a.titles.slice(0, 6).map(t => `
${esc(t.title)}${t.year ? ` ${t.year}` : ''}
`).join('')}${a.titles.length > 6 ? `
and ${a.titles.length - 6} more
` : ''}
+
`).join(''); h += '
Titles for your channels
'; h += r.choices.length ? r.choices.map(c => `

${esc(c.title)}

${c.type === 'Movie' ? 'Film' : 'Series'}${c.year ? ' · ' + c.year : ''}${c.line ? ' · ' + esc(c.line) : ''}
${c.options.map((o, k) => ``).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(`
Remove ${esc(ch.name)}?
${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.
`); 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. diff --git a/android/app/src/main/java/tv/orbit/classic/CreateChannel.kt b/android/app/src/main/java/tv/orbit/classic/CreateChannel.kt index fd52ddbd..e8961a66 100644 --- a/android/app/src/main/java/tv/orbit/classic/CreateChannel.kt +++ b/android/app/src/main/java/tv/orbit/classic/CreateChannel.kt @@ -60,7 +60,13 @@ internal class ChannelMaker( /** Networks and studios by name, with their title counts. */ val studios: suspend (String) -> List> = { 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, 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, 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." }) } } diff --git a/android/app/src/main/java/tv/orbit/classic/CustomChannels.kt b/android/app/src/main/java/tv/orbit/classic/CustomChannels.kt index 02592ad1..8f86993d 100644 --- a/android/app/src/main/java/tv/orbit/classic/CustomChannels.kt +++ b/android/app/src/main/java/tv/orbit/classic/CustomChannels.kt @@ -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 = 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()) } } diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt b/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt index 0516de8e..ccc08e21 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyClient.kt @@ -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 = 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. */ diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt index d1a984e3..47e33210 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt @@ -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?>(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) { diff --git a/android/app/src/main/java/tv/orbit/classic/PhoneLink.kt b/android/app/src/main/java/tv/orbit/classic/PhoneLink.kt index 66473a2d..237b260c 100644 --- a/android/app/src/main/java/tv/orbit/classic/PhoneLink.kt +++ b/android/app/src/main/java/tv/orbit/classic/PhoneLink.kt @@ -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 } } diff --git a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt index fbdab331..2fa74715 100644 --- a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt @@ -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() } diff --git a/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt b/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt index 811c1c45..c347a7c6 100644 --- a/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt +++ b/android/app/src/main/java/tv/orbit/classic/SecureMediaDataSource.kt @@ -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()) { diff --git a/android/app/src/main/java/tv/orbit/classic/SmartSetup.kt b/android/app/src/main/java/tv/orbit/classic/SmartSetup.kt index d1214a3c..20a23b00 100644 --- a/android/app/src/main/java/tv/orbit/classic/SmartSetup.kt +++ b/android/app/src/main/java/tv/orbit/classic/SmartSetup.kt @@ -157,6 +157,25 @@ internal fun shapeChannel(rows: List): 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, seed: Int): List { + val series = rows.filter { it.type == "Series" }.sortedWith(compareByDescending { 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(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): 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 diff --git a/android/app/src/test/java/tv/orbit/classic/SmartSetupTest.kt b/android/app/src/test/java/tv/orbit/classic/SmartSetupTest.kt index a42ab9ac..684a0284 100644 --- a/android/app/src/test/java/tv/orbit/classic/SmartSetupTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/SmartSetupTest.kt @@ -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) + } }