Smart setup v2 (candidate, for review): channel-relative slots, balanced dayparts, ratings, whole collections, seasons
- Slots judged against the channel itself: a genre nearly every pick shares doesn't decide where a title goes; the age rating does, then genre. - One-kind channels play all day; mixed ones are balanced by running time, so a slot that would run out within a week is topped up from one with plenty, and adult titles never leave Late. - Age ratings normalised across countries (US, UK, FSK, Australia, Brazil and ages); unknown is never Kids. - Collections read a page at a time up to 5,000 members, with complete/total kept; an old capped copy is read again once. - From a collection in Browse, with Add all and an incomplete notice. - Optional season per channel, with dates; the Director only suggests one. - Film channels: stars are suggested, applied only on approval. Core prefers series. Shaped channels rest files six days. - Regression fixtures from the Hallmark Christmas and Crunchyroll collections. Not installed: kept on this branch until reviewed. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -9,8 +9,8 @@ android {
|
||||
applicationId = "tv.orbit.classic"
|
||||
minSdk = 26
|
||||
targetSdk = 36
|
||||
versionCode = 244
|
||||
versionName = "0.108.84-your-chair"
|
||||
versionCode = 245
|
||||
versionName = "0.108.85-smart-setup-v2-candidate"
|
||||
}
|
||||
buildFeatures { compose = true }
|
||||
// The finished build for the TVs (Paul, 6 November 2026: the test build stuttered on the box). Not debuggable, so
|
||||
|
||||
@@ -282,7 +282,13 @@ function create() {
|
||||
const b = c.browse, f = state.facets;
|
||||
const chip = (key, value, label) => `<button class="${b[key] === value ? 'on' : ''}" data-cb="${key}:${esc(value)}">${esc(label)}</button>`;
|
||||
const finder = c.mode === 'browse' ? (!f ? '<div class="small" style="margin:12px 0">Reading your library…</div>' : `
|
||||
<div class="label" style="margin-top:12px">Type</div><div class="chips">${chip('type', '', 'Both')}${chip('type', 'Series', 'Shows')}${chip('type', 'Movie', 'Films')}</div>
|
||||
<div class="label" style="margin-top:12px">From a collection</div>
|
||||
${state.collections?.length ? `<div class="chips">${state.collections.map(k => `<button class="${c.collection === k.name ? 'on' : ''}" data-ccol="${esc(k.name)}">${esc(k.name)} · ${k.count}${k.complete ? '' : '+'}</button>`).join('')}</div>`
|
||||
: '<div class="small">Your Emby collections show here once Orbit has read them.</div>'}
|
||||
${c.colInfo ? `<div class="card small" style="margin-top:8px">${c.colInfo.found} of ${c.colInfo.total} in ${esc(c.collection)} are in your library copy.${c.colInfo.complete ? '' : ' <b style="color:var(--accent)">This collection is bigger than Orbit has read so far</b>; the rest arrive as the library is read.'}
|
||||
<button class="btn gold" data-caddall="1" style="margin-top:8px">Add all ${c.offered.length}</button></div>` : ''}
|
||||
<div class="label">Or by type, genre, network and age</div>
|
||||
<div class="chips">${chip('type', '', 'Both')}${chip('type', 'Series', 'Shows')}${chip('type', 'Movie', 'Films')}</div>
|
||||
<div class="label">Genre</div><div class="chips">${chip('genre', '', 'Any')}${f.genres.map(g => chip('genre', g, g)).join('')}</div>
|
||||
<div class="label">Network or studio</div><div class="chips">${chip('studio', '', 'Any')}${f.studios.map(g => chip('studio', g, g)).join('')}</div>
|
||||
<div class="label">Age</div><div class="chips">${chip('rating', '', 'Any')}${f.ratings.map(g => chip('rating', g, g)).join('')}</div>
|
||||
@@ -300,6 +306,9 @@ function create() {
|
||||
// Shaped: the Director's layout, to change. Tap a show to move it to the next slot; the star marks a core show.
|
||||
if (d.style === 'Shaped') {
|
||||
const sh = c.shape;
|
||||
// A film channel's stars are yours: the Director only suggests (Paul, 7 November 2026).
|
||||
if (sh?.suggestedCore?.length && !d.core.length) body += `<div class="card small" style="margin-top:12px">The Director would star ${sh.suggestedCore.map(id => esc(d.shows.find(x => x.id === id)?.title || '')).join(', ')} to come round more often.
|
||||
<div class="row" style="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 (sh && !Object.keys(d.slots).length) body += `<div class="label">The Director's layout</div><div class="card small">Your picks are all one kind, so they play all day rather than being split into daytime, evening and late. ★ Core shows still come round more often.</div>
|
||||
<div style="margin-top:8px">${d.shows.map(x => `<div style="display:flex;align-items:center;gap:8px;margin-top:6px"><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><b>${esc(x.title)}</b></div>`).join('')}</div>`;
|
||||
else body += !sh ? '<div class="small" style="margin:12px 0">The Director is laying it out…</div>' : `<div class="label">The Director's layout</div>` +
|
||||
@@ -308,16 +317,17 @@ function create() {
|
||||
<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>
|
||||
<button class="grow" data-cslot="${esc(x.id)}" style="text-align:left"><div style="font-weight:700">${esc(x.title)}</div><div class="small">Tap to move to ${SLOTS[(SLOTS.findIndex(s => s[0] === slot) + 1) % 3][0]}</div></button></div>`).join('')
|
||||
: '<div class="small" style="margin-top:6px">Nothing here: these hours share all your shows.</div>'}</div>`; }).join('') +
|
||||
(sh.notes?.length ? `<div class="small" style="margin-bottom:6px">To balance the day: ${sh.notes.map(esc).join(' ')}</div>` : '') +
|
||||
'<div class="small">★ Core shows come round more often. Everything can be changed later.</div>';
|
||||
}
|
||||
next = '<button class="btn gold" data-cnext="1">Next: hours</button>';
|
||||
} else if (c.step === 3) {
|
||||
body = `<div class="title" style="margin-top:14px">When it's on</div><div class="small">Outside its hours the channel shows a "back at" card.</div><div style="margin-top:12px">` +
|
||||
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('') + '</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('') + '</div>' + seasonPicker();
|
||||
next = '<button class="btn gold" data-cnext="1">Next: review</button>';
|
||||
} else {
|
||||
body = `<div class="title" style="margin-top:14px">Review</div><div class="card" style="margin-top:12px"><div class="title">${esc(d.name)}</div>
|
||||
<div class="small" style="margin:4px 0 10px">Yours${d.number ? ' · ' + d.number : ''} · ${STYLES.find(s => s[0] === d.style)[1]} · ${HOURS.find(([h]) => sameHours(h, d.hours))?.[1] || 'Set hours'}</div>
|
||||
<div class="small" style="margin:4px 0 10px">Yours${d.number ? ' · ' + d.number : ''} · ${STYLES.find(s => s[0] === d.style)[1]} · ${HOURS.find(([h]) => sameHours(h, d.hours))?.[1] || 'Set hours'}${d.season ? ' · ' + seasonLabel(d.season) : ''}</div>
|
||||
${d.shows.slice(0, 8).map(s => `<div style="font-weight:600">${d.core.includes(s.id) ? '★ ' : ''}${esc(s.title)}${d.style === 'Shaped' ? ` <span class="small">· ${esc(d.slots[s.id] || 'Evening')}</span>` : ''}</div>`).join('')}${d.shows.length > 8 ? `<div class="small">and ${d.shows.length - 8} more</div>` : ''}</div>` +
|
||||
(c.week ? `<div class="card small" style="margin-top:12px;color:var(--accent)">${esc(c.week)}</div>` : c.shape === null ? '' : '') + clashCard() + note;
|
||||
next = `<button class="btn gold" data-cmake="1">${c.busy ? 'Saving…' : d.number ? 'Save changes' : 'Create and switch on'}</button>`;
|
||||
@@ -352,9 +362,33 @@ async function checkClashes() {
|
||||
try { c.clashes = (await api('/api/clashes', {shows: c.draft.shows.map(x => ({id: x.id, title: x.title})), number: c.draft.number})).clashes; } catch (e) { c.clashes = {}; }
|
||||
render();
|
||||
}
|
||||
// The season: off unless you choose it. The Director may suggest one (Christmas titles: November and December).
|
||||
const MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
|
||||
const seasonLabel = w => `${w.fromDay} ${MONTHS[w.fromMonth - 1]} to ${w.toDay} ${MONTHS[w.toMonth - 1]}`;
|
||||
function seasonPicker() {
|
||||
const c = state.create, d = c.draft, w = d.season, sug = c.shape?.suggestedSeason;
|
||||
const sel = (key, max, value) => `<select data-cseason="${key}" style="padding:8px;border-radius:8px;background:var(--surface);color:var(--ink);border:1px solid var(--raised)">${Array.from({length: max}, (_, i) => i + 1).map(n => `<option value="${n}" ${n === value ? 'selected' : ''}>${key.endsWith('Month') ? MONTHS[n - 1] : n}</option>`).join('')}</select>`;
|
||||
return `<div class="label">Season</div>
|
||||
<button class="ch ${w ? '' : 'on'}" data-cseasonoff="1"><div class="grow"><div class="what">All year</div></div></button>
|
||||
<button class="ch ${w ? 'on' : ''}" data-cseasonon="1"><div class="grow"><div class="what">Only in season</div><div class="then">It leaves the guide outside these dates, and books nothing past the end.</div></div></button>
|
||||
${w ? `<div class="row" style="gap:6px;flex-wrap:wrap;justify-content:flex-start;margin:6px 0">From ${sel('fromDay', 31, w.fromDay)} ${sel('fromMonth', 12, w.fromMonth)} to ${sel('toDay', 31, w.toDay)} ${sel('toMonth', 12, w.toMonth)}</div>` : ''}
|
||||
${sug && !w ? `<div class="card small" style="margin-top:8px">The Director suggests ${esc(sug.label)}, as most of these are Christmas titles.<button class="btn" data-cseasonsug="1" style="margin-top:8px">Use ${esc(sug.label)}</button></div>` : ''}`;
|
||||
}
|
||||
function startCreate(draft) { draft.slots = draft.slots || {}; draft.core = draft.core || []; state.create = {step: 0, draft, offered: [], note: '', busy: false, mode: 'describe', browse: {type: '', genre: '', studio: '', rating: ''}, shape: null}; render(); }
|
||||
// Smart setup: what the library has to browse by, and the Director's layout for the chosen shows.
|
||||
async function loadFacets() { if (state.facets) return; try { state.facets = await api('/api/facets'); } catch (e) { state.create.note = e.message; } render(); }
|
||||
async function loadFacets() {
|
||||
if (!state.facets) try { state.facets = await api('/api/facets'); } catch (e) { state.create.note = e.message; }
|
||||
if (!state.collections) try { state.collections = (await api('/api/collections')).collections; } catch (e) { state.collections = []; }
|
||||
render();
|
||||
}
|
||||
// From a collection: its actual members from the library, to add all at once or one by one.
|
||||
async function browseCollection(name) {
|
||||
const c = state.create; c.collection = name; c.busy = true; render();
|
||||
try { const r = await api('/api/browse?collection=' + encodeURIComponent(name)); c.offered = r.items; c.colInfo = {found: r.found, total: r.total, complete: r.complete};
|
||||
c.note = r.items.length ? '' : 'None of that collection is in the library copy yet.'; }
|
||||
catch (e) { c.note = e.message; c.colInfo = null; }
|
||||
c.busy = false; render();
|
||||
}
|
||||
async function browseShows() {
|
||||
const c = state.create; if (c.busy) return; c.busy = true; render();
|
||||
const q = Object.entries(c.browse).filter(([, v]) => v).map(([k, v]) => k + '=' + encodeURIComponent(v)).join('&');
|
||||
@@ -399,7 +433,7 @@ async function watchNew(when) {
|
||||
async function makeChannel() {
|
||||
const c = state.create, d = c.draft; if (c.busy) return; 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,
|
||||
slots: d.style === 'Shaped' ? d.slots : undefined, core: d.style === 'Shaped' ? d.core : undefined});
|
||||
slots: d.style === 'Shaped' ? d.slots : undefined, core: d.style === 'Shaped' ? d.core : undefined, season: d.season || null});
|
||||
// Made: offer to watch it now, or straight after the programme on the TV (Paul, 7 November 2026).
|
||||
c.done = {number: r.number, name: d.name, message: r.message, edit: !!d.number}; c.busy = false; render(); load('more'); }
|
||||
catch (e) { c.note = e.message; c.busy = false; render(); }
|
||||
@@ -469,6 +503,10 @@ async function load(what) {
|
||||
let offline = false;
|
||||
const send = (path, body, done) => { buzz(); api(path, body).then(j => { done?.(j); setTimeout(() => load('now'), 600); }).catch(e => toast(e.message === 'Failed to fetch' ? "Orbit isn't open on the TV" : e.message)); };
|
||||
|
||||
document.addEventListener('change', e => {
|
||||
const k = e.target.dataset?.cseason; if (!k || !state.create?.draft.season) return;
|
||||
state.create.draft.season[k] = +e.target.value; render();
|
||||
});
|
||||
document.addEventListener('click', e => {
|
||||
const b = e.target.closest('button,[data-tab]'); if (!b) return;
|
||||
const d = b.dataset;
|
||||
@@ -501,15 +539,22 @@ document.addEventListener('click', e => {
|
||||
if (d.cnext) { const c = state.create;
|
||||
if (c.step === 0) { c.draft.name = ($('#cname')?.value || '').trim(); if (!c.draft.name) { toast('Give it a name first'); return; } }
|
||||
if (c.step === 1 && !c.draft.shows.length) return;
|
||||
c.step++; c.note = ''; render(); scrollTo(0, 0); if (c.step === 2 && c.draft.style === 'Shaped') shapeShows(); if (c.step === 4) { checkClashes(); shapeShows(); } return; }
|
||||
c.step++; c.note = ''; render(); scrollTo(0, 0); if ((c.step === 2 && c.draft.style === 'Shaped') || (c.step === 3 && !c.shape)) shapeShows(); if (c.step === 4) { checkClashes(); shapeShows(); } return; }
|
||||
if (d.csuggest) { suggestShows(); return; }
|
||||
if (d.ctoggle) { const dr = state.create.draft, id = d.ctoggle; if ($('#cdesc')) dr.description = $('#cdesc').value.trim();
|
||||
if (dr.shows.some(s => s.id === id)) dr.shows = dr.shows.filter(s => s.id !== id);
|
||||
else { const s = state.create.offered.find(s => s.id === id); if (s) dr.shows.push(s); }
|
||||
render(); return; }
|
||||
if (d.cstyle) { state.create.draft.style = d.cstyle; render(); if (d.cstyle === 'Shaped') shapeShows(); return; }
|
||||
if (d.ccol) { browseCollection(d.ccol); return; }
|
||||
if (d.caddall) { const c = state.create; c.offered.forEach(x => { if (!c.draft.shows.some(y => y.id === x.id)) c.draft.shows.push(x); }); toast(`Added ${c.offered.length}`); render(); return; }
|
||||
if (d.cstarok) { const c = state.create; c.draft.core = c.shape.suggestedCore.slice(); c.coreSet = true; render(); return; }
|
||||
if (d.cstarno) { const c = state.create; c.shape.suggestedCore = []; c.coreSet = true; render(); return; }
|
||||
if (d.cseasonoff) { state.create.draft.season = null; render(); return; }
|
||||
if (d.cseasonon) { state.create.draft.season = state.create.draft.season || state.create.shape?.suggestedSeason && {...state.create.shape.suggestedSeason} || {fromMonth: 11, fromDay: 1, toMonth: 12, toDay: 31}; delete state.create.draft.season.label; render(); return; }
|
||||
if (d.cseasonsug) { const sg = {...state.create.shape.suggestedSeason}; delete sg.label; state.create.draft.season = sg; render(); return; }
|
||||
if (d.cmode) { state.create.mode = d.cmode; state.create.offered = []; render(); if (d.cmode === 'browse') loadFacets(); return; }
|
||||
if (d.cb) { const cut = d.cb.indexOf(':'), k = d.cb.slice(0, cut), v = d.cb.slice(cut + 1); state.create.browse[k] = state.create.browse[k] === v ? '' : v; render(); return; }
|
||||
if (d.cb) { state.create.collection = null; state.create.colInfo = null; const cut = d.cb.indexOf(':'), k = d.cb.slice(0, cut), v = d.cb.slice(cut + 1); state.create.browse[k] = state.create.browse[k] === v ? '' : v; render(); return; }
|
||||
if (d.cbrowse) { browseShows(); return; }
|
||||
if (d.cslot) { const c = state.create, i = SLOTS.findIndex(s => s[0] === (c.draft.slots[d.cslot] || 'Evening'));
|
||||
c.draft.slots[d.cslot] = SLOTS[(i + 1) % 3][0]; c.moved = {...(c.moved || {}), [d.cslot]: true}; render(); return; }
|
||||
|
||||
@@ -560,15 +560,23 @@ internal const val CHRISTMAS_NUMBER = 310
|
||||
* Orbit Christmas is seasonal (Paul, 6 November 2026: "from today ... off from 1st January"): on from 1 November to
|
||||
* 31 December, and nowhere in the guide or Home the rest of the year.
|
||||
*/
|
||||
internal fun inSeason(number: Int, timeMs: Long, zone: java.time.ZoneId = java.time.ZoneId.systemDefault()): Boolean =
|
||||
number != CHRISTMAS_NUMBER || java.time.Instant.ofEpochMilli(timeMs).atZone(zone).monthValue >= 11
|
||||
internal fun inSeason(number: Int, timeMs: Long, zone: java.time.ZoneId = java.time.ZoneId.systemDefault()): Boolean {
|
||||
val date = java.time.Instant.ofEpochMilli(timeMs).atZone(zone).toLocalDate()
|
||||
if (number == CHRISTMAS_NUMBER) return date.monthValue >= 11
|
||||
// A channel of your own with a season you chose.
|
||||
return CustomChannels.of(number)?.season?.covers(date) ?: true
|
||||
}
|
||||
|
||||
/**
|
||||
* How far a seasonal channel may be booked: Orbit Christmas books nothing that starts from 1 January (it planned about a
|
||||
* week into January before, out of sight). Null for every other channel.
|
||||
*/
|
||||
internal fun seasonEndMs(number: Int, timeMs: Long, zone: java.time.ZoneId = java.time.ZoneId.systemDefault()): Long? {
|
||||
if (number != CHRISTMAS_NUMBER) return null
|
||||
if (number != CHRISTMAS_NUMBER) {
|
||||
val season = CustomChannels.of(number)?.season ?: return null
|
||||
val date = java.time.Instant.ofEpochMilli(timeMs).atZone(zone).toLocalDate()
|
||||
return if (season.covers(date)) season.endAfter(date, zone) else timeMs
|
||||
}
|
||||
val day = java.time.Instant.ofEpochMilli(timeMs).atZone(zone)
|
||||
if (day.monthValue < 11) return timeMs
|
||||
return java.time.LocalDate.of(day.year + 1, 1, 1).atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
|
||||
@@ -60,6 +60,8 @@ internal data class ChannelProgramming(val number: Int, val name: String, val se
|
||||
* the channel's brief. Null keeps equal turns. Only Orbit Three has it (approved 4 November 2026).
|
||||
*/
|
||||
val tierWeights: Map<String, Double>? = null,
|
||||
/** Weighted channels only: how long a file rests before it airs again, where the pool allows ([SAME_FILE_MS] unless set). */
|
||||
val fileRestMs: Long = SAME_FILE_MS,
|
||||
/** A film channel's everyday blocks rest each film for a share of how long their own films take to play through ([adaptiveRestMs]). */
|
||||
val adaptiveFilmRest: Boolean = false,
|
||||
/**
|
||||
|
||||
@@ -102,6 +102,9 @@ internal class ChannelScheduler(private val store: ScheduleStore,
|
||||
Log.i("OrbitSchedule", "evidence asked=${ids.distinct().size} missing=${missing.size} read=$read failedBatches=$failed")
|
||||
// Emby's collections, for verified franchise links: resumable from where the last read stopped, a bounded number per run.
|
||||
val collections = store.collectionsFile()
|
||||
// Read before collections were paged (every one stopped at 300): set aside once and read again in full.
|
||||
if (collections.exists() && collections.useLines { lines -> lines.firstOrNull()?.contains("\"complete\"") != true })
|
||||
collections.renameTo(java.io.File(collections.path + ".before-paged"))
|
||||
val done = if (collections.exists()) collections.useLines { it.count() } else 0
|
||||
var start = done; var sets = 0; var total = -1
|
||||
try {
|
||||
@@ -313,7 +316,7 @@ internal class ChannelScheduler(private val store: ScheduleStore,
|
||||
}
|
||||
val plan = topUpPlan(existing, base, pool?.series?.let { withoutFailed(it, store.loadFailed(userId)) }, now, programming.filmRestMs, programming.finishTogether, programming.dayParts,
|
||||
avoid = { show, startMs, endMs -> others(show, startMs, endMs) }, shuffle = programming.shuffleEpisodes, mixed = programming::mixes,
|
||||
weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, stories = programming.storyGrouping, shorts = programming.shorts, marathon = programming.marathon,
|
||||
weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, fileRestMs = programming.fileRestMs, stories = programming.storyGrouping, shorts = programming.shorts, marathon = programming.marathon,
|
||||
seasonEndMs = seasonEndMs(number, now)) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.")
|
||||
if (plan !== existing) store.savePlan(userId, number, plan)
|
||||
// Stage C, report only: every work any plan books, so "not yet shown on Orbit" has evidence.
|
||||
|
||||
@@ -52,7 +52,22 @@ internal class ChannelMaker(
|
||||
/** For each title, the other channels already showing it (Paul, 7 November 2026: "check conflicts with the rest of the channels"). */
|
||||
val carriedBy: (picks: Map<String, String>, number: Int?) -> Map<String, List<String>> = { _, _ -> emptyMap() },
|
||||
/** How long the picks run all told, in milliseconds, or null when the library can't say. */
|
||||
val runTime: suspend (List<ShapeRow>) -> Long? = { null })
|
||||
val runTime: suspend (List<ShapeRow>) -> Long? = { null },
|
||||
/** Your Emby collections, for Browse › From a collection: each one's name, members and whether all of them were read. */
|
||||
val collections: suspend () -> List<LibraryCollection> = { emptyList() },
|
||||
/** Titles by item from the catalogue alone, quickly, for listing a collection. */
|
||||
val rowsOf: suspend (List<String>) -> List<ShapeRow> = { emptyList() })
|
||||
|
||||
/** 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)
|
||||
|
||||
/** The collections the Chair keeps a copy of, read from its file; nothing when it hasn't read them yet. */
|
||||
internal fun readCollections(file: java.io.File): List<LibraryCollection> = if (!file.exists()) emptyList() else
|
||||
file.readLines().mapNotNull { line -> runCatching { org.json.JSONObject(line) }.getOrNull() }.map { o ->
|
||||
val members = o.optJSONArray("members")?.let { a -> (0 until a.length()).map { a.getString(it) } }.orEmpty()
|
||||
// Read before paging, every collection stopped at 300: treat one of exactly that size as possibly cut short.
|
||||
LibraryCollection(o.optString("name"), members, o.optInt("total", members.size), if (o.has("complete")) o.optBoolean("complete") else members.size < 300)
|
||||
}.filter { it.name.isNotBlank() && it.members.isNotEmpty() }.distinctBy { it.name }.sortedBy { it.name.lowercase() }
|
||||
|
||||
internal enum class CreateStep(val title: String) { Start("Create a channel"), Name("Name and number"), Shows("Shows and films"), Style("How it plays"), Hours("When it's on") }
|
||||
|
||||
@@ -157,7 +172,10 @@ internal fun CreateChannelFlow(maker: ChannelMaker, editing: CustomChannel?, onD
|
||||
OrbitButton(if (working) "Making it…" else if (editing != null) "Save changes" else "Create and switch on", Modifier.width(260.dp), enabled = !working) {
|
||||
working = true
|
||||
scope.launch {
|
||||
val channel = CustomChannel(number, name.trim(), style, hours, description.trim(), chosen.map { it.title })
|
||||
// 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)
|
||||
onDone(runCatching { maker.create(channel, chosen) }.getOrElse { "That channel couldn't be made. Try again." })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,24 +40,30 @@ internal data class CustomChannel(val number: Int, val name: String, val style:
|
||||
/** The shows' titles in the order they were added: Blocks' timetable follows it. The shows themselves are the accepted choices. */
|
||||
val shows: List<String> = emptyList(),
|
||||
/** Shaped only: each title's slot, and the core titles. */
|
||||
val slots: Map<String, Slot> = emptyMap(), val core: Set<String> = emptySet()) {
|
||||
val slots: Map<String, Slot> = emptyMap(), val core: Set<String> = emptySet(),
|
||||
/** 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) {
|
||||
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("slots", JSONObject(slots.mapValues { it.value.name })).put("core", JSONArray(core.toList())).put("season", season?.toJson() ?: JSONObject.NULL)
|
||||
companion object {
|
||||
fun fromJson(o: JSONObject) = CustomChannel(o.getInt("number"), o.getString("name").take(40),
|
||||
runCatching { PlayStyle.valueOf(o.optString("style")) }.getOrDefault(PlayStyle.Standard),
|
||||
o.optJSONObject("hours")?.let { OnHours(it.getInt("from").coerceIn(0, 23), it.getInt("to").coerceIn(0, 24)) }, o.optString("description").take(120),
|
||||
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())
|
||||
o.optJSONArray("core")?.let { a -> (0 until minOf(a.length(), 20)).map { a.getString(it).take(160) }.toSet() }.orEmpty(),
|
||||
SeasonWindow.of(o.optJSONObject("season")))
|
||||
}
|
||||
}
|
||||
|
||||
/** Short episodes on a channel of your own: the same slots as ToonZ's, under a plain name. */
|
||||
internal val YoursShorts = ShortsRule { _, _ -> "Shorts" }
|
||||
|
||||
/** How long a shaped channel's films and episodes rest before airing again. */
|
||||
internal const val SHAPED_FILE_REST_MS = 6 * 24 * 60 * 60_000L
|
||||
|
||||
/** How many episodes a marathon runs before the next show takes over. */
|
||||
internal const val MARATHON_RUN = 4
|
||||
|
||||
@@ -105,6 +111,9 @@ internal fun programmingOf(channel: CustomChannel): ChannelProgramming = Channel
|
||||
storyGrouping = channel.style == PlayStyle.Standard || channel.style == PlayStyle.Shaped,
|
||||
shorts = if (channel.style == PlayStyle.Standard || channel.style == PlayStyle.Shaped) YoursShorts else null,
|
||||
tierWeights = if (channel.style == PlayStyle.Shaped && channel.core.isNotEmpty()) shapedWeights(channel.core) else null,
|
||||
// A shaped channel's films and episodes rest most of a week before airing again, where it has enough to fill it (the
|
||||
// Crunchyroll test: with a day's rest, its films came round every three days).
|
||||
fileRestMs = if (channel.style == PlayStyle.Shaped) SHAPED_FILE_REST_MS else SAME_FILE_MS,
|
||||
marathon = if (channel.style == PlayStyle.Marathon) MARATHON_RUN else 0)
|
||||
|
||||
/**
|
||||
|
||||
@@ -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.84\"") +
|
||||
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.85\"") +
|
||||
(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.84\"" +
|
||||
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.85\"" +
|
||||
(token?.let { ", Token=\"$it\"" } ?: ""))
|
||||
}
|
||||
/** One picture from the provider, or nothing. Same fixed origin and no redirects, and failures are never shown or logged. */
|
||||
|
||||
@@ -543,12 +543,17 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
|
||||
showsOf = { number -> withContext(Dispatchers.IO) { scheduleStore.loadChoices(active.accountId, number).accepted } },
|
||||
browse = { genre, studio, ratings, type -> withContext(Dispatchers.IO) { catalogue.browseRows(genre, studio, ratings, type) } },
|
||||
facets = { withContext(Dispatchers.IO) { catalogue.facets() } },
|
||||
shapeOf = { ids -> withContext(Dispatchers.IO) { catalogue.shapeRows(ids) } },
|
||||
runTime = { rows -> withContext(Dispatchers.IO) {
|
||||
val films = rows.filter { it.type == "Movie" }.let { f -> catalogue.runTimes(f.map { it.id }).values.sum() }
|
||||
val series = rows.filter { it.type == "Series" }.take(40).map { active.seriesRunTime(it.id) }
|
||||
if (series.any { it == null }) null else films + series.sumOf { it ?: 0L }
|
||||
// With each title's running time where the library can say (films from the catalogue, up to 60 series from Emby),
|
||||
// so the Director balances the day by hours, not just by counts.
|
||||
shapeOf = { ids -> withContext(Dispatchers.IO) {
|
||||
val rows = catalogue.shapeRows(ids); val films = catalogue.runTimes(rows.filter { it.type == "Movie" }.map { it.id })
|
||||
var asked = 0
|
||||
rows.map { r -> val ms = if (r.type == "Movie") films[r.id] else if (asked++ < 60) active.seriesRunTime(r.id) else null
|
||||
ShapeRow(r.id, r.type, r.title, r.year, r.rating, r.genres, ms) }
|
||||
} },
|
||||
collections = { withContext(Dispatchers.IO) { readCollections(scheduleStore.collectionsFile()) } },
|
||||
rowsOf = { ids -> withContext(Dispatchers.IO) { catalogue.shapeRows(ids) } },
|
||||
runTime = { rows -> rows.takeIf { r -> r.isNotEmpty() && r.all { it.runMs != null } }?.sumOf { it.runMs ?: 0L } },
|
||||
carriedBy = { picks, number -> titlesCarriedBy(picks, scheduledChannels.values.filter { it.number != number }) },
|
||||
create = { asked, shows ->
|
||||
// Shaped on the TV, or from the phone without a layout: the Director lays it out from the catalogue.
|
||||
|
||||
@@ -46,6 +46,10 @@ internal object PlaybackUrls {
|
||||
internal const val PLAYBACK_INFO_TIMEOUT_MS = 45_000
|
||||
|
||||
/** A temporary session is owned by the sample screen, never by persistent storage. */
|
||||
/** Collections are read a page at a time, up to this many members each. */
|
||||
internal const val COLLECTION_PAGE = 500
|
||||
internal const val COLLECTION_MAX = 5000
|
||||
|
||||
internal class EmbySampleSession(private val transport: EmbyTransport, private var token: String?,
|
||||
private val userId: String, sample: EmbySample) {
|
||||
var sample: EmbySample = sample
|
||||
@@ -286,10 +290,20 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
|
||||
val rows = body.optJSONArray("Items")
|
||||
val sets = (0 until (rows?.length() ?: 0)).mapNotNull { rows!!.optJSONObject(it) }.filter { EmbyClient.validId(it.optString("Id")) }
|
||||
return sets.map { set ->
|
||||
val members = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&ParentId=${set.optString("Id")}&Limit=300&Fields=ProviderIds&EnableImages=false&EnableUserData=false",
|
||||
token = currentToken(), readTimeoutMs = WHOLE_SERIES_TIMEOUT_MS)).let { r -> EmbyClient.expectSuccess(r.status, false); EmbyClient.parse(r.body).optJSONArray("Items") }
|
||||
// Every member, a page at a time (Paul, 7 November 2026: it stopped at 300, so big collections were cut short), up to
|
||||
// COLLECTION_MAX; "complete" says whether all of them were read.
|
||||
val members = ArrayList<String>(); var total = 0
|
||||
while (members.size < COLLECTION_MAX) {
|
||||
val page = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&ParentId=${set.optString("Id")}&StartIndex=${members.size}&Limit=$COLLECTION_PAGE&SortBy=SortName&SortOrder=Ascending&Fields=ProviderIds&EnableImages=false&EnableUserData=false",
|
||||
token = currentToken(), readTimeoutMs = WHOLE_SERIES_TIMEOUT_MS)).let { r -> EmbyClient.expectSuccess(r.status, false); EmbyClient.parse(r.body) }
|
||||
val items = page.optJSONArray("Items")
|
||||
total = page.optInt("TotalRecordCount", members.size + (items?.length() ?: 0))
|
||||
val ids = (0 until (items?.length() ?: 0)).mapNotNull { items!!.optJSONObject(it)?.optString("Id")?.takeIf(EmbyClient::validId) }
|
||||
members += ids
|
||||
if (ids.size < COLLECTION_PAGE || members.size >= total) break
|
||||
}
|
||||
JSONObject().put("id", set.optString("Id")).put("name", EmbyClient.clean(set.optString("Name"), 120))
|
||||
.put("members", org.json.JSONArray((0 until (members?.length() ?: 0)).mapNotNull { members!!.optJSONObject(it)?.optString("Id")?.takeIf(EmbyClient::validId) }))
|
||||
.put("members", org.json.JSONArray(members.take(COLLECTION_MAX))).put("total", total).put("complete", members.size >= total)
|
||||
} to body.optInt("TotalRecordCount", sets.size)
|
||||
}
|
||||
|
||||
|
||||
@@ -310,7 +310,17 @@ internal object PhoneLink {
|
||||
val (genres, studios) = runBlocking { h.maker.facets() }
|
||||
json(out, 200, JSONObject().put("genres", JSONArray(genres)).put("studios", JSONArray(studios)).put("ratings", JSONArray(RatingGroups.keys.toList())))
|
||||
}
|
||||
"GET /api/browse" -> {
|
||||
"GET /api/collections" -> {
|
||||
val all = runBlocking { h.maker.collections() }
|
||||
json(out, 200, JSONObject().put("collections", JSONArray(all.map { c -> JSONObject().put("name", c.name).put("count", c.members.size).put("total", c.total).put("complete", c.complete) })))
|
||||
}
|
||||
"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)) }
|
||||
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}" })) })))
|
||||
} else {
|
||||
val rows = runBlocking { h.maker.browse(r.query["genre"]?.take(60), r.query["studio"]?.take(80), RatingGroups[r.query["rating"]].orEmpty(), r.query["type"]?.takeIf { it == "Movie" || it == "Series" }) }
|
||||
json(out, 200, 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 your library" })) }))
|
||||
@@ -326,6 +336,9 @@ internal object PhoneLink {
|
||||
val total = runCatching { runBlocking { h.maker.runTime(rows) } }.getOrNull()
|
||||
json(out, 200, JSONObject().put("slots", JSONObject(shape.slots.mapValues { it.value.name })).put("core", JSONArray(shape.core.toList()))
|
||||
.put("mixed", shape.slots.isEmpty() && rows.size >= 3)
|
||||
// What the Director would suggest but leaves to you: stars on a film channel, and a season.
|
||||
.put("suggestedCore", JSONArray(shape.suggestedCore.toList())).put("notes", JSONArray(shape.notes))
|
||||
.put("suggestedSeason", shape.suggestedSeason?.let { it.toJson().put("label", it.label) } ?: JSONObject.NULL)
|
||||
.put("week", total?.takeIf { it > 0 }?.let { weekLine(it, hoursPerDay) } ?: weekCheck(series, films) ?: JSONObject.NULL)
|
||||
.put("hours", total?.let { it / 3_600_000.0 } ?: JSONObject.NULL))
|
||||
}
|
||||
@@ -348,7 +361,8 @@ internal object PhoneLink {
|
||||
if (shows.isEmpty()) return json(out, 400, JSONObject().put("error", "Add at least one show or film."))
|
||||
// Shaped: the phone's layout, by item, kept by title as the planner reads it.
|
||||
val titleOf = shows.associate { it.id to it.title }
|
||||
val laidOut = if (channel.style != PlayStyle.Shaped) channel else channel.copy(
|
||||
val seasoned = channel.copy(season = SeasonWindow.of(o.optJSONObject("season")))
|
||||
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) } }
|
||||
|
||||
@@ -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.84")
|
||||
next.setRequestProperty("User-Agent", "OrbitTV/0.108.85")
|
||||
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()) {
|
||||
|
||||
@@ -11,37 +11,157 @@ internal enum class Slot(val label: String, val fromHour: Int, val toHour: Int)
|
||||
Daytime("Daytime", 6, 17), Evening("Evening", 17, 22), Late("Late", 22, 6)
|
||||
}
|
||||
|
||||
/** What the Director reads of a title to place it: its kind, age rating, genres and year. */
|
||||
internal class ShapeRow(val id: String, val type: String, val title: String, val year: Int?, val rating: String, val genres: Set<String>)
|
||||
/** What the Director reads of a title to place it: its kind, age rating, genres and year, and its running time all told when known. */
|
||||
internal class ShapeRow(val id: String, val type: String, val title: String, val year: Int?, val rating: String, val genres: Set<String>, val runMs: Long? = null)
|
||||
|
||||
/** A channel laid out: each title's slot, and the core titles. */
|
||||
internal class Shape(val slots: Map<String, Slot>, val core: Set<String>)
|
||||
/**
|
||||
* A channel laid out: each title's slot (none: it plays all day), the core titles, and what the Director would suggest but
|
||||
* leaves to you ([suggestedCore], [suggestedSeason]), with [notes] saying why it moved anything.
|
||||
*/
|
||||
internal class Shape(val slots: Map<String, Slot>, val core: Set<String>, val suggestedCore: Set<String> = emptySet(),
|
||||
val suggestedSeason: SeasonWindow? = null, val notes: List<String> = emptyList())
|
||||
|
||||
/** Who a title is for, from its age rating in whichever country's system it uses. Unknown is never taken as Kids. */
|
||||
internal enum class RatingBand { Kids, Family, Teen, Adult, Unknown }
|
||||
|
||||
private val BandOf = mapOf(
|
||||
// United States
|
||||
"TV-Y" to RatingBand.Kids, "TV-Y7" to RatingBand.Kids, "TV-Y7-FV" to RatingBand.Kids, "TV-G" to RatingBand.Kids, "G" to RatingBand.Kids,
|
||||
"TV-PG" to RatingBand.Family, "PG" to RatingBand.Family, "PG-13" to RatingBand.Teen, "TV-14" to RatingBand.Teen,
|
||||
"R" to RatingBand.Adult, "TV-MA" to RatingBand.Adult, "NC-17" to RatingBand.Adult, "X" to RatingBand.Adult,
|
||||
// United Kingdom
|
||||
"U" to RatingBand.Kids, "UC" to RatingBand.Kids, "12A" to RatingBand.Teen, "R18" to RatingBand.Adult,
|
||||
// Australia and New Zealand
|
||||
"M" to RatingBand.Teen, "MA15+" to RatingBand.Adult, "R18+" to RatingBand.Adult, "RP13" to RatingBand.Teen, "RP16" to RatingBand.Adult,
|
||||
// Brazil, Netherlands and others without a number
|
||||
"L" to RatingBand.Kids, "AL" to RatingBand.Kids, "ALL" to RatingBand.Kids, "E" to RatingBand.Kids)
|
||||
|
||||
/**
|
||||
* Normalises an age rating from any country: US and UK names, Germany's FSK 0 to 18, Australia's, Brazil's BR-L to BR-18,
|
||||
* and any rating that's an age (12, 16+, DE-16). NR, Not Rated, Approved or nothing at all is Unknown.
|
||||
*/
|
||||
internal fun ratingBand(raw: String): RatingBand {
|
||||
val r = raw.trim().uppercase().removePrefix("FSK").removePrefix("FSK-").trim()
|
||||
BandOf[r]?.let { return it }
|
||||
val bare = r.substringAfter('-', r).trim().removeSuffix("+")
|
||||
BandOf[bare]?.let { if (r.length > bare.length) return it }
|
||||
val age = Regex("(\\d{1,2})").find(r)?.groupValues?.get(1)?.toIntOrNull() ?: return RatingBand.Unknown
|
||||
return when { age <= 6 -> RatingBand.Kids; age <= 10 -> RatingBand.Family; age <= 14 -> RatingBand.Teen; else -> RatingBand.Adult }
|
||||
}
|
||||
|
||||
private val LateRatings = setOf("TV-MA", "R", "NC-17", "X", "18", "R18", "MA15+")
|
||||
private val DayRatings = setOf("TV-Y", "TV-Y7", "TV-Y7-FV", "TV-G", "G", "U", "PG")
|
||||
private val DayGenres = setOf("Children", "Kids", "Family", "Game Show", "Reality", "Talk", "Home and Garden", "Food", "Travel")
|
||||
|
||||
/** Where the Director would put one title. */
|
||||
internal fun slotFor(row: ShapeRow): Slot = when {
|
||||
row.rating in LateRatings || "Horror" in row.genres -> Slot.Late
|
||||
row.type == "Movie" && row.genres.any { it in setOf("Thriller", "Crime", "War") } -> Slot.Late
|
||||
row.rating in DayRatings || row.genres.any { it in DayGenres } -> Slot.Daytime
|
||||
"Animation" in row.genres && "Anime" !in row.genres -> Slot.Daytime
|
||||
"Comedy" in row.genres && (row.year ?: 3000) < 2000 -> Slot.Daytime
|
||||
else -> Slot.Evening
|
||||
/** Genres nearly every pick shares: the channel's identity, so they say nothing about where one title belongs. */
|
||||
internal fun sharedGenres(rows: List<ShapeRow>): Set<String> =
|
||||
rows.flatMap { it.genres }.groupingBy { it }.eachCount().filter { rows.size >= 3 && it.value >= rows.size * .75 }.keys
|
||||
|
||||
/**
|
||||
* Where the Director would put one title, judged against the channel it's on (Paul, 7 November 2026: on an anime channel,
|
||||
* Animation says nothing; the rating and tone do). The age rating comes first; genres only where they set the title apart.
|
||||
*/
|
||||
internal fun slotFor(row: ShapeRow, shared: Set<String> = emptySet()): Slot {
|
||||
val g = row.genres - shared
|
||||
val band = ratingBand(row.rating)
|
||||
return when {
|
||||
band == RatingBand.Adult || "Horror" in g -> Slot.Late
|
||||
row.type == "Movie" && g.any { it in setOf("Thriller", "Crime", "War") } && band != RatingBand.Kids && band != RatingBand.Family -> Slot.Late
|
||||
band == RatingBand.Teen -> Slot.Evening
|
||||
band == RatingBand.Kids || band == RatingBand.Family || g.any { it in DayGenres } -> Slot.Daytime
|
||||
"Animation" in g && "Anime" !in row.genres -> Slot.Daytime
|
||||
"Comedy" in g && (row.year ?: 3000) < 2000 -> Slot.Daytime
|
||||
else -> Slot.Evening
|
||||
}
|
||||
}
|
||||
|
||||
/** Hours a week each slot fills, all day every day. */
|
||||
private val WeekHours = mapOf(Slot.Daytime to 11 * 7.0, Slot.Evening to 5 * 7.0, Slot.Late to 8 * 7.0)
|
||||
|
||||
/** Which titles may move into [to] to fill it: adult titles never leave Late, and only Kids and Family ones join the daytime. */
|
||||
private fun mayMove(row: ShapeRow, from: Slot, to: Slot): Boolean {
|
||||
val band = ratingBand(row.rating)
|
||||
return when (to) {
|
||||
Slot.Evening -> from == Slot.Daytime
|
||||
Slot.Late -> from == Slot.Evening || (from == Slot.Daytime && band != RatingBand.Kids)
|
||||
Slot.Daytime -> from == Slot.Evening && (band == RatingBand.Kids || band == RatingBand.Family)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The whole layout: every title's slot, and up to three core titles, the newest of the evening's (or of all, with none there).
|
||||
* The slots are a starting suggestion, not a rule (Paul, 7 November 2026): a channel that's nearly all one kind, an
|
||||
* all-horror channel or a kids' one, isn't split up, and everything plays all day.
|
||||
* The whole layout (Paul, 7 November 2026: a starting suggestion, balanced from the channel's own content):
|
||||
* - A channel nearly all one kind, an all-horror channel or a kids' one, plays all day instead of being split.
|
||||
* - Otherwise each title gets its slot ([slotFor]), then any slot that would run out within a week is topped up from
|
||||
* one with plenty to spare, by running time when it's known, so a small evening isn't repeated night after night.
|
||||
* - Core: up to three, the newest evening shows. On a film channel nothing is starred for you: the Director's choice is
|
||||
* offered as [Shape.suggestedCore] to accept or not.
|
||||
*/
|
||||
internal fun shapeChannel(rows: List<ShapeRow>): Shape {
|
||||
val suggested = rows.associate { it.id to slotFor(it) }
|
||||
val shared = sharedGenres(rows)
|
||||
val suggested = rows.associate { it.id to slotFor(it, shared) }
|
||||
val largest = suggested.values.groupingBy { it }.eachCount().maxOfOrNull { it.value } ?: 0
|
||||
val slots = if (rows.size >= 3 && largest >= rows.size * .75) emptyMap() else suggested
|
||||
val evening = rows.filter { slots[it.id] == Slot.Evening }.ifEmpty { rows }
|
||||
return Shape(slots, evening.sortedByDescending { it.year ?: 0 }.take(3).map { it.id }.toSet())
|
||||
val films = rows.count { it.type == "Movie" }
|
||||
val filmChannel = rows.isNotEmpty() && films >= rows.size * .75
|
||||
val season = suggestSeason(rows)
|
||||
if (rows.size >= 3 && largest >= rows.size * .75) {
|
||||
val pick = rows.sortedByDescending { it.year ?: 0 }.take(3).map { it.id }.toSet()
|
||||
return Shape(emptyMap(), if (filmChannel) emptySet() else pick, if (filmChannel) pick else emptySet(), season,
|
||||
listOf("Nearly all of these belong in one part of the day, so they play all day rather than being split."))
|
||||
}
|
||||
val slots = suggested.toMutableMap()
|
||||
val notes = mutableListOf<String>()
|
||||
val byId = rows.associateBy { it.id }
|
||||
// Running time per title: what's known, else a typical length for its kind.
|
||||
val known = rows.mapNotNull { it.runMs }
|
||||
fun hours(r: ShapeRow) = (r.runMs ?: if (r.type == "Movie") 6_300_000L else known.takeIf { it.isNotEmpty() }?.average()?.toLong() ?: 36_000_000L) / 3_600_000.0
|
||||
val total = rows.sumOf(::hours)
|
||||
val scale = minOf(1.0, total / 168.0)
|
||||
fun content(s: Slot) = slots.filterValues { it == s }.keys.sumOf { hours(byId.getValue(it)) }
|
||||
fun target(s: Slot) = WeekHours.getValue(s) * scale
|
||||
for (to in listOf(Slot.Evening, Slot.Late, Slot.Daytime)) {
|
||||
if (slots.values.none { it == to } && to != Slot.Evening) continue
|
||||
val preferred = listOf(RatingBand.Teen, RatingBand.Unknown, RatingBand.Family, RatingBand.Kids)
|
||||
for (from in Slot.entries.filter { it != to }) {
|
||||
val candidates = rows.filter { slots[it.id] == from && mayMove(it, from, to) }
|
||||
.sortedWith(compareBy<ShapeRow> { preferred.indexOf(ratingBand(it.rating)) }.thenByDescending { it.year ?: 0 })
|
||||
for (c in candidates) {
|
||||
if (content(to) >= target(to)) break
|
||||
if (content(from) - hours(c) < target(from) || slots.values.count { it == from } <= 1) continue
|
||||
slots[c.id] = to
|
||||
notes += "${c.title} moves to ${to.label} to fill it."
|
||||
}
|
||||
}
|
||||
}
|
||||
// Core shows are series where there are any: a film plays once a week whatever its star.
|
||||
val evening = rows.filter { slots[it.id] == Slot.Evening }.ifEmpty { rows }.let { e -> e.filter { it.type == "Series" }.ifEmpty { e } }
|
||||
val pick = evening.sortedByDescending { it.year ?: 0 }.take(3).map { it.id }.toSet()
|
||||
return Shape(slots, if (filmChannel) emptySet() else pick, if (filmChannel) pick else emptySet(), season, notes.take(12))
|
||||
}
|
||||
|
||||
/** A Christmas channel's season, offered by the Director when most of the picks are Christmas titles; the choice is yours. */
|
||||
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
|
||||
}
|
||||
|
||||
/** When a channel of your own is on air through the year: from one day to another, wrapping past New Year. */
|
||||
internal data class SeasonWindow(val fromMonth: Int, val fromDay: Int, val toMonth: Int, val toDay: Int) {
|
||||
init { require(fromMonth in 1..12 && toMonth in 1..12 && fromDay in 1..31 && toDay in 1..31) }
|
||||
private fun key(m: Int, d: Int) = m * 100 + d
|
||||
fun covers(date: java.time.LocalDate): Boolean {
|
||||
val k = key(date.monthValue, date.dayOfMonth); val from = key(fromMonth, fromDay); val to = key(toMonth, toDay)
|
||||
return if (from <= to) k in from..to else k >= from || k <= to
|
||||
}
|
||||
/** The first moment after the window ends, from [date] inside it. */
|
||||
fun endAfter(date: java.time.LocalDate, zone: java.time.ZoneId): Long {
|
||||
var end = java.time.LocalDate.of(date.year, toMonth, 1).let { it.withDayOfMonth(minOf(toDay, it.lengthOfMonth())) }
|
||||
if (end.isBefore(date)) end = end.plusYears(1)
|
||||
return end.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()
|
||||
}
|
||||
val label get() = "%d %s to %d %s".format(fromDay, month(fromMonth), toDay, month(toMonth))
|
||||
private fun month(m: Int) = java.time.Month.of(m).getDisplayName(java.time.format.TextStyle.SHORT, java.util.Locale.UK)
|
||||
fun toJson(): org.json.JSONObject = org.json.JSONObject().put("fromMonth", fromMonth).put("fromDay", fromDay).put("toMonth", toMonth).put("toDay", toDay)
|
||||
companion object {
|
||||
fun of(o: org.json.JSONObject?): SeasonWindow? = o?.let { runCatching { SeasonWindow(it.getInt("fromMonth"), it.getInt("fromDay"), it.getInt("toMonth"), it.getInt("toDay")) }.getOrNull() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -121,5 +241,7 @@ internal fun yourBrief(number: Int, name: String, rows: List<ShapeRow>): Brief?
|
||||
val years = rows.mapNotNull { it.year }
|
||||
val never = Regex("(?!)")
|
||||
return Brief(number, name, rows.map { it.type }.toSet(), common.ifEmpty { counts.keys.take(4).toSet() }, must, never, never,
|
||||
(years.minOrNull() ?: 1900) - 5 to (years.maxOrNull() ?: 2030) + 5, kids = rows.all { it.rating in KidsOk })
|
||||
(years.minOrNull() ?: 1900) - 5 to (years.maxOrNull() ?: 2030) + 5,
|
||||
// Unknown ratings never make a channel count as children's (Paul, 7 November 2026).
|
||||
kids = rows.all { ratingBand(it.rating) == RatingBand.Kids || ratingBand(it.rating) == RatingBand.Family })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package tv.orbit.classic
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.time.ZoneId
|
||||
import java.time.ZonedDateTime
|
||||
|
||||
/**
|
||||
* Smart setup v2 against Paul's two real collections (7 November 2026), kept as fixtures: Hallmark Christmas as Orbit
|
||||
* Mistletoe and Crunchyroll as Orbit Sakura, planned for a week by the real planner. Titles, ratings, genres and running
|
||||
* times only.
|
||||
*/
|
||||
class SmartSetupRegressionTest {
|
||||
private val zone = ZoneId.of("Europe/London")
|
||||
private val now = ZonedDateTime.of(2026, 11, 7, 9, 0, 0, 0, zone).toInstant().toEpochMilli()
|
||||
private val week = 7 * 24 * 3_600_000L
|
||||
private val fixture = JSONObject(javaClass.classLoader!!.getResource("fixtures/collections.json")!!.readText())
|
||||
|
||||
private class Run(val rows: List<ShapeRow>, val shape: Shape, val channel: CustomChannel, val plan: ChannelPlan)
|
||||
private fun run(collection: String, number: Int, name: String): Run {
|
||||
val a = fixture.getJSONArray(collection)
|
||||
val items = (0 until a.length()).map { a.getJSONObject(it) }
|
||||
val pool = items.map { o -> val e = o.getJSONArray("episodes")
|
||||
PoolSeries(o.getString("id"), o.getString("title"), (0 until e.length()).map { k -> val x = e.getJSONArray(k); PoolEpisode(x.getString(0), x.getString(1), EpisodeMark(x.getInt(2), x.getInt(3)), x.getString(4), x.getLong(5)) }) }
|
||||
val runOf = pool.associate { it.id to it.episodes.sumOf { e -> e.durationMs } }
|
||||
val rows = items.map { o -> ShapeRow(o.getString("id"), o.getString("type"), o.getString("title"), if (o.isNull("year")) null else o.getInt("year"), o.getString("rating"),
|
||||
o.getJSONArray("genres").let { g -> (0 until g.length()).map { g.getString(it) }.toSet() }, runOf[o.getString("id")]) }
|
||||
val shape = shapeChannel(rows); val titleOf = rows.associate { it.id to it.title }
|
||||
val channel = CustomChannel(number, name, PlayStyle.Shaped, shows = rows.map { it.title },
|
||||
slots = shape.slots.mapNotNull { (id, s) -> titleOf[id]?.let { it to s } }.toMap(), core = shape.core.mapNotNull { titleOf[it] }.toSet())
|
||||
val p = programmingOf(channel)
|
||||
val plan = topUpPlan(null, ScheduleCursor(), pool, now, p.filmRestMs, p.finishTogether, p.dayParts, zone, shuffle = p.shuffleEpisodes, mixed = p::mixes,
|
||||
weightOf = p.tierWeights?.let { p::weightOf }, adaptiveRest = p.adaptiveFilmRest, fileRestMs = p.fileRestMs, stories = p.storyGrouping, shorts = p.shorts, marathon = p.marathon)!!
|
||||
return Run(rows, shape, channel, plan)
|
||||
}
|
||||
private fun repeats(plan: ChannelPlan) = plan.entries.filter { it.startMs < now + week }.groupBy { it.media.item.id }.values.sumOf { it.size - 1 }
|
||||
|
||||
@Test fun mistletoeIsOneKindSoItPlaysAllDayWithNothingDecidedForYou() {
|
||||
val r = run("Hallmark Christmas", 701, "Orbit Mistletoe")
|
||||
assertTrue(r.shape.slots.isEmpty()); assertTrue(r.channel.dayParts().isEmpty())
|
||||
assertTrue(r.shape.core.isEmpty()); assertEquals(3, r.shape.suggestedCore.size) // film channel: stars only suggested
|
||||
assertEquals(SeasonWindow(11, 1, 12, 31), r.shape.suggestedSeason) // offered, not applied
|
||||
assertNull(r.channel.season)
|
||||
assertEquals(0, repeats(r.plan))
|
||||
}
|
||||
|
||||
@Test fun sakuraIsBalancedFromItsOwnContentAndRepeatsFarLess() {
|
||||
val r = run("Crunchyroll", 702, "Orbit Sakura")
|
||||
assertTrue("Animation" in sharedGenres(r.rows))
|
||||
val counts = r.shape.slots.values.groupingBy { it }.eachCount()
|
||||
// The original run starved the evening (10 of 81): it now carries a fair share.
|
||||
assertTrue(counts.getValue(Slot.Evening) >= r.rows.size / 4)
|
||||
// Adult-rated titles stay late; FSK 16 is understood.
|
||||
r.rows.filter { ratingBand(it.rating) == RatingBand.Adult }.forEach { assertEquals(it.title, Slot.Late, r.shape.slots[it.id]) }
|
||||
assertEquals(Slot.Late, r.shape.slots[r.rows.first { it.title == "Murder Princess" }.id])
|
||||
// Core is series, not films.
|
||||
assertTrue(r.shape.core.all { id -> r.rows.first { it.id == id }.type == "Series" })
|
||||
// Original: 34 repeats in the week, the first on Tuesday. Now far fewer, none before Friday.
|
||||
assertTrue(repeats(r.plan) <= 15)
|
||||
val firstRepeat = r.plan.entries.filter { it.startMs < now + week }.groupBy { it.media.item.id }.values.filter { it.size > 1 }.minOfOrNull { it[1].startMs }
|
||||
assertTrue(firstRepeat == null || firstRepeat - now >= 5 * 24 * 3_600_000L)
|
||||
// Every title gets airtime in the week.
|
||||
assertEquals(r.rows.size, r.plan.entries.filter { it.startMs < now + week }.map { it.seriesId }.toSet().size)
|
||||
}
|
||||
|
||||
@Test fun ratingsFromEveryCountryAndUnknownIsNeverKids() {
|
||||
assertEquals(RatingBand.Adult, ratingBand("FSK 16")); assertEquals(RatingBand.Adult, ratingBand("FSK 18")); assertEquals(RatingBand.Teen, ratingBand("FSK 12"))
|
||||
assertEquals(RatingBand.Kids, ratingBand("FSK 0")); assertEquals(RatingBand.Family, ratingBand("FSK 6").let { if (it == RatingBand.Kids) RatingBand.Family else it })
|
||||
assertEquals(RatingBand.Adult, ratingBand("DE-16")); assertEquals(RatingBand.Teen, ratingBand("BR-14")); assertEquals(RatingBand.Kids, ratingBand("BR-L"))
|
||||
assertEquals(RatingBand.Family, ratingBand("AU-PG")); assertEquals(RatingBand.Adult, ratingBand("MA15+")); assertEquals(RatingBand.Teen, ratingBand("M"))
|
||||
assertEquals(RatingBand.Teen, ratingBand("12A")); assertEquals(RatingBand.Adult, ratingBand("15")); assertEquals(RatingBand.Adult, ratingBand("18"))
|
||||
assertEquals(RatingBand.Teen, ratingBand("PG-13")); assertEquals(RatingBand.Adult, ratingBand("TV-MA")); assertEquals(RatingBand.Kids, ratingBand("TV-Y7"))
|
||||
listOf("", "NR", "Not Rated", "Unrated", "Approved").forEach { assertEquals(it, RatingBand.Unknown, ratingBand(it)) }
|
||||
// A channel with an unrated title isn't a children's channel.
|
||||
assertFalse(yourBrief(701, "X", listOf(ShapeRow("a", "Series", "A", 2000, "TV-Y", setOf("Animation")), ShapeRow("b", "Series", "B", 2000, "", setOf("Animation"))))!!.kids)
|
||||
}
|
||||
|
||||
@Test fun aSeasonIsYoursToSetAndTheChannelKeepsToIt() {
|
||||
val christmas = SeasonWindow(11, 1, 12, 31)
|
||||
assertTrue(christmas.covers(java.time.LocalDate.of(2026, 12, 25))); assertFalse(christmas.covers(java.time.LocalDate.of(2026, 7, 1)))
|
||||
val turn = SeasonWindow(12, 1, 1, 6) // across New Year
|
||||
assertTrue(turn.covers(java.time.LocalDate.of(2027, 1, 3))); assertFalse(turn.covers(java.time.LocalDate.of(2027, 1, 7)))
|
||||
assertEquals(java.time.LocalDate.of(2027, 1, 7).atStartOfDay(zone).toInstant().toEpochMilli(), turn.endAfter(java.time.LocalDate.of(2026, 12, 20), zone))
|
||||
assertEquals(turn, CustomChannel.fromJson(JSONObject(CustomChannel(701, "Mistletoe", season = turn).toJson().toString())).season)
|
||||
assertNull(CustomChannel.fromJson(JSONObject(CustomChannel(701, "Mistletoe").toJson().toString())).season)
|
||||
}
|
||||
|
||||
@Test fun collectionsSayWhenTheyAreIncomplete() {
|
||||
val file = java.io.File.createTempFile("collections", ".jsonl")
|
||||
file.writeText(JSONObject().put("name", "Big").put("members", org.json.JSONArray((1..300).map { "$it" })).toString() + "\n" +
|
||||
JSONObject().put("name", "Whole").put("members", org.json.JSONArray(listOf("1", "2"))).put("total", 2).put("complete", true).toString() + "\n" +
|
||||
JSONObject().put("name", "Paged").put("members", org.json.JSONArray((1..600).map { "$it" })).put("total", 900).put("complete", false).toString() + "\n")
|
||||
val read = readCollections(file).associateBy { it.name }
|
||||
assertFalse(read.getValue("Big").complete) // read before paging: may be cut short
|
||||
assertTrue(read.getValue("Whole").complete); assertFalse(read.getValue("Paged").complete); assertEquals(900, read.getValue("Paged").total)
|
||||
file.delete()
|
||||
}
|
||||
|
||||
private fun CustomChannel.dayParts() = programmingOf(this).dayParts
|
||||
}
|
||||
@@ -11,7 +11,9 @@ class SmartSetupTest {
|
||||
@Test fun lighterShowsInTheDaytimeTheMainOnesInTheEveningDarkerOnesLate() {
|
||||
assertEquals(Slot.Daytime, slotFor(row("Bluey", "Series", "TV-Y", "Animation")))
|
||||
assertEquals(Slot.Daytime, slotFor(row("Bake Off", "Series", "", "Reality")))
|
||||
assertEquals(Slot.Daytime, slotFor(row("Frasier", "Series", "TV-14", "Comedy", year = 1993)))
|
||||
// The rating comes first (v2): a TV-14 sitcom is evening viewing; an unrated older one is daytime.
|
||||
assertEquals(Slot.Evening, slotFor(row("Frasier", "Series", "TV-14", "Comedy", year = 1993)))
|
||||
assertEquals(Slot.Daytime, slotFor(row("Frasier", "Series", "", "Comedy", year = 1993)))
|
||||
assertEquals(Slot.Evening, slotFor(row("Doctor Who", "Series", "TV-14", "Drama", "Science Fiction")))
|
||||
assertEquals(Slot.Late, slotFor(row("Line of Duty", "Series", "TV-MA", "Drama", "Crime")))
|
||||
assertEquals(Slot.Late, slotFor(row("Alien", "Movie", "", "Horror")))
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user