This commit is contained in:
4DBug committed 2026-10-27 05:49:38 -05:00
1 parent bcf05e8063
commit f37985b4c8
109 files changed
+22810 -6143

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
/*
views/browse.js — /browse/:type?with_genres=&with_networks=&title= discover grid with infinite scroll.
Without filters it lists popular titles of that type.
*/
import { h } from '../util.js';
import * as tmdb from '../tmdb.js';
import { posterCard, skeletonCard } from '../ui/card.js';
const PASS = ['with_genres', 'with_networks', 'with_companies', 'with_original_language', 'sort_by', 'with_keywords', 'first_air_date_year', 'primary_release_year'];
export function render(root, params) {
const type = params.type === 'tv' ? 'tv' : 'movie';
const q = params.query;
const filters = {};
PASS.forEach((k) => q.get(k) && (filters[k] = q.get(k)));
const title = q.get('title') || (type === 'tv' ? 'Series' : 'Movies');
document.title = `${title} · bug tv`;
const gridEl = h('div.grid', { role: 'list' });
const sentinel = h('div.load-more');
const status = h('p.muted.center');
root.append(h('div.page.page--padded.container',
h('div.page__head', h('div', h('p.page__eyebrow', type === 'tv' ? 'Series' : 'Movies'), h('h1.page__title', title))),
gridEl, status, sentinel));
let page = 0;
let total = 1;
let loading = false;
const seen = new Set();
async function more() {
if (loading || page >= total || page >= 20) return;
loading = true;
const skels = Array.from({ length: 12 }, () => skeletonCard('poster'));
gridEl.append(...skels);
try {
const next = page + 1;
const d = Object.keys(filters).length
? await tmdb.discover(type, { ...filters, page: next, 'vote_count.gte': filters.with_networks ? 20 : 50 })
: await tmdb.popular(type, next);
if (params.signal.aborted) return;
page = next;
total = d.total_pages || 1;
skels.forEach((s) => s.remove());
const items = (d.results || []).map((r) => tmdb.toItem(r, type)).filter((x) => x.poster_path && !seen.has(x.id) && seen.add(x.id));
gridEl.append(...items.map((it) => posterCard(it)));
if (!gridEl.children.length) status.textContent = 'Nothing found.';
} catch (e) {
skels.forEach((s) => s.remove());
status.textContent = e.message;
total = 0;
} finally {
loading = false;
}
// keep filling while the sentinel is still visible
if (sentinel.getBoundingClientRect().top < window.innerHeight + 600) more();
}
const io = new IntersectionObserver((entries) => entries.some((e) => e.isIntersecting) && more(), { rootMargin: '800px 0px' });
io.observe(sentinel);
more();
return () => io.disconnect();
}
+186
View File
@@ -0,0 +1,186 @@
/*
views/home.js — home (/), Movies (/movies) and TV (/tv) browse pages.
params.kind: undefined | 'movie' | 'tv'
*/
import { h, durationLabel } from '../util.js';
import * as tmdb from '../tmdb.js';
import { href } from '../router.js';
import { resume, myList, progressOf } from '../storage.js';
import { billboard } from '../ui/hero.js';
import { row } from '../ui/row.js';
import { posterCard, wideCard, logoCard } from '../ui/card.js';
import { watchHref } from '../ui/actions.js';
import { toast } from '../ui/toast.js';
const NETWORKS = [
{ id: 213, name: 'Netflix' },
{ id: 49, name: 'HBO' },
{ id: 2739, name: 'Disney+' },
{ id: 2552, name: 'Apple TV+' },
{ id: 1024, name: 'Prime Video' },
{ id: 453, name: 'Hulu' },
{ id: 4330, name: 'Paramount+' },
{ id: 3186, name: 'HBO Max' },
];
const GENRES = {
all: [
{ type: 'movie', id: 28, name: 'Action Movies' },
{ type: 'tv', id: 10765, name: 'Sci-Fi & Fantasy Series' },
{ type: 'movie', id: 35, name: 'Comedy Movies' },
{ type: 'tv', id: 80, name: 'Crime Series' },
{ type: 'movie', id: 16, name: 'Animation' },
{ type: 'movie', id: 27, name: 'Horror' },
],
movie: [
{ type: 'movie', id: 28, name: 'Action' },
{ type: 'movie', id: 878, name: 'Science Fiction' },
{ type: 'movie', id: 35, name: 'Comedy' },
{ type: 'movie', id: 53, name: 'Thrillers' },
{ type: 'movie', id: 16, name: 'Animation' },
{ type: 'movie', id: 27, name: 'Horror' },
{ type: 'movie', id: 10749, name: 'Romance' },
{ type: 'movie', id: 99, name: 'Documentaries' },
],
tv: [
{ type: 'tv', id: 18, name: 'Drama' },
{ type: 'tv', id: 10765, name: 'Sci-Fi & Fantasy' },
{ type: 'tv', id: 80, name: 'Crime' },
{ type: 'tv', id: 35, name: 'Comedy' },
{ type: 'tv', id: 16, name: 'Animation' },
{ type: 'tv', id: 10759, name: 'Action & Adventure' },
{ type: 'tv', id: 9648, name: 'Mystery' },
{ type: 'tv', id: 99, name: 'Documentary' },
],
};
const items = (type) => (d) => ((d && d.results) || []).map((r) => tmdb.toItem(r, type)).filter((x) => x.poster_path || x.backdrop_path);
const poster = (it) => posterCard(it);
// Continue Watching record → wide card, backdrop looked up lazily when the record has none
function continueCard(rec, onRemoved) {
const item = { type: rec.type, id: rec.tmdbId, title: rec.show || rec.title || '', backdrop_path: null, rating: 0 };
const left = rec.d ? Math.max(0, rec.d - rec.t) : 0;
const leftText = left ? `${durationLabel(left)} left` : '';
const meta = rec.type === 'tv' ? [`S${rec.season} E${rec.episode}`, leftText].filter(Boolean).join(' · ') : leftText || 'Movie';
const image = rec.backdrop || rec.still || null;
const card = wideCard(item, {
href: watchHref(rec.type, rec.tmdbId, rec.season, rec.episode),
image: image || null,
meta,
kicker: rec.type === 'tv' && rec.title && rec.title !== rec.show ? rec.title : null,
progress: progressOf(rec),
onRemove: (el) => {
resume.removeShow(rec.type, rec.tmdbId);
el.remove();
onRemoved();
toast(`Removed “${item.title}” from Continue Watching`);
},
});
if (!image) {
tmdb.details(rec.type, rec.tmdbId).then((d) => {
const path = d.backdrop_path || d.poster_path;
if (!path) return;
const media = card.querySelector('.card__media');
const im = h('img.card__img', { src: tmdb.img(path, 'w780'), alt: '', loading: 'lazy', decoding: 'async', onload: (e) => e.target.classList.add('is-loaded') });
media.insertBefore(im, media.querySelector('.card__shade'));
}).catch(() => {});
}
return card;
}
export async function render(root, params) {
const kind = params.kind === 'movie' || params.kind === 'tv' ? params.kind : null;
document.title = kind === 'movie' ? 'Movies · bug tv' : kind === 'tv' ? 'Series · bug tv' : 'bug tv';
const heroSlot = h('div.hero-slot', h('div.hero.hero--loading', h('div.hero__skeleton.skeleton')));
const rows = h('div.rows');
root.append(h('div.page.page--home', heroSlot, rows));
let hero = null;
const listeners = [];
// hero: top trending
tmdb.trending(kind || 'all', 'day').then((d) => {
if (params.signal.aborted) return;
const list = items(kind)(d).filter((x) => x.backdrop_path && x.overview).slice(0, 5);
const label = kind === 'movie' ? 'Movies' : kind === 'tv' ? 'TV Shows' : null;
hero = billboard(list, {
eyebrow: (i, it) => `#${i + 1} in ${label || (it.type === 'tv' ? 'TV Shows' : 'Movies')} Today`,
});
heroSlot.replaceChildren(hero.el);
}).catch((e) => {
heroSlot.replaceChildren();
toast(e.message, { error: true });
});
// Continue Watching
const contRecords = () => resume.latestPerShow().filter((r) => !kind || r.type === kind).filter((r) => progressOf(r) < 0.97 || r.type === 'tv');
const cont = row({
title: 'Continue Watching',
variant: 'wide',
items: contRecords(),
render: (rec) => continueCard(rec, () => { if (!cont.querySelector('.card')) cont.hidden = true; }),
});
rows.appendChild(cont);
const onResume = () => cont.setItems(contRecords());
window.addEventListener('bugtv:resume', onResume);
listeners.push(['bugtv:resume', onResume]);
// My List
const listItems = () => myList.all().filter((x) => !kind || x.type === kind).map((x) => tmdb.toItem(x, x.type));
const mine = row({ title: 'My List', moreHref: href('/list'), items: listItems(), render: poster });
rows.appendChild(mine);
const onList = () => mine.setItems(listItems());
window.addEventListener('bugtv:mylist', onList);
listeners.push(['bugtv:mylist', onList]);
const add = (opts) => rows.appendChild(row(opts));
if (!kind) {
add({ title: 'Trending Today', load: () => tmdb.trending('all', 'day').then(items()), render: (it, i) => posterCard(it, { rank: i < 10 ? i + 1 : null }) });
add({ title: 'Popular on Streaming', variant: 'logo', items: NETWORKS.slice(0, 6), render: networkCard, lazy: true });
add({ title: 'Popular Movies', moreHref: href('/browse/movie?title=Popular%20Movies'), load: () => tmdb.popular('movie').then(items('movie')), render: poster });
add({ title: 'Popular Series', variant: 'wide', moreHref: href('/browse/tv?title=Popular%20Series'), load: () => tmdb.popular('tv').then(items('tv')), render: (it) => wideCard(it) });
add({ title: 'Top Rated Movies', load: () => tmdb.topRated('movie').then(items('movie')), render: poster });
add({ title: 'Top Rated Series', load: () => tmdb.topRated('tv').then(items('tv')), render: poster });
} else {
const label = kind === 'movie' ? 'Movies' : 'Series';
add({ title: `Trending ${label}`, load: () => tmdb.trending(kind, 'day').then(items(kind)), render: (it, i) => posterCard(it, { rank: i < 10 ? i + 1 : null }) });
if (kind === 'tv') add({ title: 'Networks', variant: 'logo', items: NETWORKS, render: networkCard, lazy: true });
add({ title: `Popular ${label}`, variant: 'wide', moreHref: href(`/browse/${kind}?title=${encodeURIComponent(`Popular ${label}`)}`), load: () => tmdb.popular(kind).then(items(kind)), render: (it) => wideCard(it) });
add({ title: `Top Rated ${label}`, load: () => tmdb.topRated(kind).then(items(kind)), render: poster });
if (kind === 'movie') {
add({ title: 'Now in Theaters', load: () => tmdb.get('/movie/now_playing', { page: 1 }, { session: true }).then(items('movie')), render: poster });
} else {
add({ title: 'Airing This Week', load: () => tmdb.get('/tv/on_the_air', { page: 1 }, { session: true }).then(items('tv')), render: poster });
}
}
(GENRES[kind || 'all']).forEach((g, i) => {
const more = href(`/browse/${g.type}?with_genres=${g.id}&title=${encodeURIComponent(g.name)}`);
add({
title: g.name,
moreHref: more,
variant: i % 3 === 1 ? 'wide' : 'poster',
load: () => tmdb.discover(g.type, { with_genres: g.id, 'vote_count.gte': 200 }).then(items(g.type)),
render: i % 3 === 1 ? (it) => wideCard(it) : poster,
});
});
return () => {
if (hero) hero.destroy();
listeners.forEach(([n, fn]) => window.removeEventListener(n, fn));
};
}
function networkCard(n) {
const card = logoCard({ name: n.name, logo: null, href: href(`/browse/tv?with_networks=${n.id}&title=${encodeURIComponent(n.name)}`) });
tmdb.network(n.id).then((d) => {
if (!d || !d.logo_path) return;
const media = card.querySelector('.card__media');
const im = h('img.card__logo', { src: tmdb.img(d.logo_path, 'w300'), alt: n.name, decoding: 'async' });
im.addEventListener('load', () => media.replaceChildren(im), { once: true });
}).catch(() => {});
return card;
}
+45
View File
@@ -0,0 +1,45 @@
/*
views/list.js — /list My List (+ Continue Watching shortcut).
*/
import { h } from '../util.js';
import * as tmdb from '../tmdb.js';
import { href } from '../router.js';
import { myList } from '../storage.js';
import { grid, posterCard } from '../ui/card.js';
import { icon } from '../ui/icons.js';
export function render(root) {
document.title = 'My List · bug tv';
const body = h('div');
const filters = h('div.tabs.tabs--pills', { role: 'tablist', 'aria-label': 'Filter' });
let filter = 'all';
const opts = [['all', 'All'], ['movie', 'Movies'], ['tv', 'Series']];
const tabs = opts.map(([k, label]) => h('button.tab', { type: 'button', role: 'tab', onclick: () => { filter = k; paint(); } }, label));
filters.append(...tabs);
function paint() {
tabs.forEach((t, i) => {
t.classList.toggle('is-active', opts[i][0] === filter);
t.setAttribute('aria-selected', opts[i][0] === filter ? 'true' : 'false');
});
const all = myList.all();
const items = all.filter((x) => filter === 'all' || x.type === filter).map((x) => tmdb.toItem(x, x.type));
filters.hidden = !all.length;
if (!items.length) {
body.replaceChildren(h('div.empty',
h('div.empty__icon', icon('bookmark', { size: 28 })),
h('h2.empty__title', all.length ? 'Nothing here' : 'Your list is empty'),
h('p.empty__text', 'Add movies and series with the + My List button and they will show up here.'),
h('a.btn.btn--primary', { href: href('/') }, 'Browse titles')));
return;
}
body.replaceChildren(grid(items, (it) => posterCard(it)));
}
root.append(h('div.page.page--padded.container',
h('div.page__head', h('h1.page__title', 'My List'), filters),
body));
paint();
window.addEventListener('bugtv:mylist', paint);
return () => window.removeEventListener('bugtv:mylist', paint);
}
+92
View File
@@ -0,0 +1,92 @@
/*
views/search.js — /search?q= live TMDB multi-search (movies + tv), URL-synced.
*/
import { h, debounce } from '../util.js';
import * as tmdb from '../tmdb.js';
import { navigate } from '../router.js';
import { grid, posterCard, skeletonCard } from '../ui/card.js';
import { icon } from '../ui/icons.js';
let state = null;
function skeletonGrid(n = 12) {
return h('div.grid', Array.from({ length: n }, () => skeletonCard('poster')));
}
async function run(q) {
const s = state;
if (!s) return;
const my = ++s.req;
s.input.value !== q && document.activeElement !== s.input && (s.input.value = q);
document.title = q ? `“${q}” · Search · bug tv` : 'Search · bug tv';
if (!q.trim()) {
s.heading.textContent = 'Popular right now';
s.results.replaceChildren(skeletonGrid());
try {
const d = await tmdb.trending('all', 'week');
if (my !== s.req) return;
s.results.replaceChildren(grid((d.results || []).map((r) => tmdb.toItem(r)).filter((x) => x.poster_path)));
} catch (e) {
if (my === s.req) s.results.replaceChildren(h('p.muted', e.message));
}
return;
}
s.heading.textContent = `Results for “${q}”`;
s.results.replaceChildren(skeletonGrid());
try {
const [p1, p2] = await Promise.all([tmdb.search(q, 1), tmdb.search(q, 2).catch(() => ({ results: [] }))]);
if (my !== s.req) return;
const seen = new Set();
const list = [...p1.results, ...(p1.total_pages > 1 ? p2.results : [])]
.map((r) => tmdb.toItem(r))
.filter((x) => !seen.has(`${x.type}:${x.id}`) && seen.add(`${x.type}:${x.id}`));
list.sort((a, b) => (b.poster_path ? 1 : 0) - (a.poster_path ? 1 : 0));
if (!list.length) {
s.results.replaceChildren(h('div.empty',
h('div.empty__icon', icon('search', { size: 28 })),
h('h2.empty__title', 'No matches'),
h('p.empty__text', 'Try a different title, or check the spelling.')));
return;
}
s.heading.textContent = `${list.length}${p1.total_results > list.length ? '+' : ''} results for “${q}”`;
s.results.replaceChildren(grid(list, (it) => posterCard(it)));
} catch (e) {
if (my === s.req) s.results.replaceChildren(h('div.empty', h('h2.empty__title', 'Search failed'), h('p.empty__text', e.message)));
}
}
export function render(root, params) {
const q = params.query.get('q') || '';
const input = h('input.search-field__input', {
type: 'search', placeholder: 'Search movies and series', value: q, autocomplete: 'off', spellcheck: 'false', enterkeyhint: 'search', 'aria-label': 'Search',
});
const go = debounce(() => navigate(`/search${input.value.trim() ? `?q=${encodeURIComponent(input.value.trim())}` : ''}`, { replace: true }), 300);
input.addEventListener('input', go);
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
go.cancel();
navigate(`/search?q=${encodeURIComponent(input.value.trim())}`, { replace: true });
input.blur();
}
});
const heading = h('h1.page__title');
const results = h('div.search-results', { 'aria-live': 'polite' });
root.append(h('div.page.page--padded.container',
h('label.search-field.search-field--page', icon('search', { size: 22 }), input),
heading,
results));
state = { input, heading, results, req: 0 };
run(q);
// focus the page input on mobile (header search is hidden there)
if (!q && window.matchMedia('(max-width: 720px)').matches) setTimeout(() => input.focus(), 50);
return () => {
go.cancel();
state = null;
};
}
export function update(params) {
if (!state) return false;
run(params.query.get('q') || '');
return true;
}
+212
View File
@@ -0,0 +1,212 @@
/*
views/settings.js — playback prefs, source providers, API server, TMDB key, local data.
*/
import { h } from '../util.js';
import * as config from '../config.js';
import { resume, myList, prefs } from '../storage.js';
import { testKey } from '../tmdb.js';
import { toast } from '../ui/toast.js';
import { icon } from '../ui/icons.js';
const LANGS = [
['', 'Off'], ['en', 'English'], ['es', 'Spanish'], ['fr', 'French'], ['de', 'German'], ['it', 'Italian'],
['pt', 'Portuguese'], ['nl', 'Dutch'], ['pl', 'Polish'], ['ru', 'Russian'], ['tr', 'Turkish'], ['ar', 'Arabic'],
['hi', 'Hindi'], ['ja', 'Japanese'], ['ko', 'Korean'], ['zh', 'Chinese'], ['sv', 'Swedish'], ['no', 'Norwegian'],
['da', 'Danish'], ['fi', 'Finnish'], ['el', 'Greek'], ['he', 'Hebrew'], ['id', 'Indonesian'], ['vi', 'Vietnamese'],
];
function status() {
const el = h('p.status', { role: 'status' });
el.set = (msg, kind) => {
el.textContent = msg || '';
el.className = `status${kind ? ` status--${kind}` : ''}`;
};
return el;
}
function card(id, title, desc, ...children) {
return h('section.settings-card', { id },
h('header.settings-card__head', h('h2.settings-card__title', title), desc ? h('p.settings-card__desc', desc) : null),
...children);
}
function toggle(label, checked, onchange, hint) {
const input = h('input', { type: 'checkbox', role: 'switch', checked, onchange: (e) => onchange(e.target.checked) });
return h('label.switch-row', h('span.switch-row__text', h('span', label), hint ? h('small', hint) : null), h('span.switch', input, h('span.switch__track')));
}
async function fetchProviders(signal) {
const base = config.getBase();
let res = await fetch(`${base}/v1/providers`, { signal, headers: { Accept: 'application/json' } }).catch((e) => {
throw new Error(`cannot reach ${base}`);
});
if (res.status === 404) {
// v4 server compatibility: { all, enabled }
res = await fetch(`${base}/providers`, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const old = await res.json();
return {
defaults: old.enabled || [],
providers: (old.all || []).map((n) => ({ id: n, name: n, enabled: (old.enabled || []).includes(n) })),
};
}
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
return { defaults: data.defaults || [], providers: data.providers || [] };
}
function healthText(hl) {
if (!hl) return '';
const total = (hl.ok || 0) + (hl.fail || 0) + (hl.timeouts || 0);
if (!total) return 'no data yet';
const pct = Math.round(((hl.ok || 0) / total) * 100);
return `${pct}% ok${hl.avgMs ? ` · ${(hl.avgMs / 1000).toFixed(1)}s avg` : ''}`;
}
function healthLevel(hl) {
if (!hl) return 'none';
const total = (hl.ok || 0) + (hl.fail || 0) + (hl.timeouts || 0);
if (!total) return 'none';
const r = (hl.ok || 0) / total;
return r > 0.7 ? 'good' : r > 0.35 ? 'fair' : 'bad';
}
export function render(root, params) {
document.title = 'Settings · bug tv';
/* ---- playback ---- */
const subSel = h('select.select', { 'aria-label': 'Preferred subtitle language', onchange: (e) => { prefs.set('subtitleLang', e.target.value); toast('Subtitle preference saved'); } },
LANGS.map(([v, l]) => h('option', { value: v, selected: prefs.get('subtitleLang', '') === v }, l)));
const playback = card('playback', 'Playback', 'Applied by the player on every title.',
h('div.field-row', h('label.field-row__label', 'Subtitles'), h('div.select-wrap', subSel, icon('down', { size: 18 }))),
toggle('Autoplay next episode', prefs.get('autoplayNext', true) !== false, (v) => prefs.set('autoplayNext', v), 'Counts down at the end of an episode, then plays the next one.'));
/* ---- sources ---- */
const provStatus = status();
const provList = h('div.provider-grid');
const provFilter = h('input.input.input--sm', { type: 'search', placeholder: 'Filter sources', 'aria-label': 'Filter sources' });
let providers = [];
let defaults = [];
const boxes = new Map();
function effectiveEnabled() {
const custom = config.getProviders();
if (custom) return new Set(custom);
return new Set(defaults.length ? defaults : providers.filter((p) => p.enabled).map((p) => p.id));
}
function persist(msg) {
const map = {};
for (const [id, box] of boxes) map[id] = box.checked;
config.setProviders(map);
summary();
if (msg) toast(msg);
}
function summary() {
const on = [...boxes.values()].filter((b) => b.checked).length;
provStatus.set(`${on} of ${providers.length} enabled — ${config.getProviders() ? 'your selection' : 'server defaults'}`);
}
function paintProviders() {
const enabled = effectiveEnabled();
boxes.clear();
provList.replaceChildren(...providers.map((p) => {
const box = h('input', { type: 'checkbox', checked: enabled.has(p.id), onchange: () => persist(`${p.name || p.id} ${box.checked ? 'enabled' : 'disabled'}`) });
boxes.set(p.id, box);
const tags = [...(p.types || []), p.language].filter(Boolean).slice(0, 3);
return h('label.provider', { dataset: { name: `${p.id} ${p.name || ''}`.toLowerCase() } },
box,
h('span.provider__check', icon('check', { size: 14, stroke: 3 })),
h('span.provider__text',
h('span.provider__name', p.name || p.id),
h('span.provider__meta',
h('i.health', { class: `health--${healthLevel(p.health)}`, title: healthText(p.health) || 'no health data' }),
[healthText(p.health), ...tags].filter(Boolean).join(' · '))));
}));
summary();
}
provFilter.addEventListener('input', () => {
const q = provFilter.value.trim().toLowerCase();
provList.querySelectorAll('.provider').forEach((el) => { el.hidden = q && !el.dataset.name.includes(q); });
});
async function loadProviders() {
provStatus.set('Loading sources…');
try {
const data = await fetchProviders(params.signal);
providers = data.providers;
defaults = data.defaults;
paintProviders();
} catch (e) {
if (params.signal.aborted) return;
provList.replaceChildren();
provStatus.set(`Could not load the provider list: ${e.message}`, 'err');
}
}
const sources = card('sources', 'Sources', 'Which providers the server scrapes for streams. Health comes from the server’s recent results.',
h('div.toolbar',
provFilter,
h('div.toolbar__actions',
h('button.btn.btn--ghost.btn--sm', { type: 'button', onclick: () => { boxes.forEach((b) => { b.checked = true; }); persist('All sources enabled'); } }, 'Enable all'),
h('button.btn.btn--ghost.btn--sm', { type: 'button', onclick: () => { boxes.forEach((b) => { b.checked = false; }); persist('All sources disabled'); } }, 'Disable all'),
h('button.btn.btn--ghost.btn--sm', { type: 'button', onclick: () => { config.clearProviders(); paintProviders(); toast('Using server defaults'); } }, 'Server defaults'))),
provStatus,
provList);
/* ---- server ---- */
const baseInput = h('input.input', { type: 'url', value: config.getBase(), spellcheck: 'false', autocomplete: 'off', placeholder: config.DEFAULT_BASE, 'aria-label': 'API base URL' });
const connStatus = status();
async function testConn() {
connStatus.set('Testing…');
try {
const res = await fetch(`${config.getBase()}/healthz`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
connStatus.set(`Connected to ${config.getBase()}`, 'ok');
return true;
} catch (e) {
connStatus.set(`Not reachable: ${e.message}`, 'err');
return false;
}
}
const server = card('server', 'Server', 'The bug tv API that finds and proxies streams.',
h('div.input-row', baseInput,
h('button.btn.btn--primary', { type: 'button', onclick: async () => { config.setBase(baseInput.value); baseInput.value = config.getBase(); if (await testConn()) toast('API server saved'); loadProviders(); } }, 'Save'),
h('button.btn.btn--ghost', { type: 'button', onclick: async () => { config.clearBase(); baseInput.value = config.getBase(); await testConn(); loadProviders(); } }, 'Reset')),
h('p.hint', `Default: ${config.DEFAULT_BASE}. Add ?api=<url> to any link for a one-off override.`),
connStatus);
/* ---- TMDB ---- */
const keyInput = h('input.input', { type: 'text', value: config.getTmdbKey(), spellcheck: 'false', autocomplete: 'off', placeholder: '32-character TMDB API key', 'aria-label': 'TMDB API key' });
const keyStatus = status();
async function testTmdb(key) {
keyStatus.set('Testing TMDB key…');
try {
await testKey(key);
keyStatus.set('TMDB key works.', 'ok');
} catch (e) {
keyStatus.set(e.message, 'err');
}
}
const tmdbCard = card('tmdb', 'TMDB', 'Catalog, artwork and search come straight from TMDB using this key.',
h('div.input-row', keyInput,
h('button.btn.btn--primary', { type: 'button', onclick: () => { config.setTmdbKey(keyInput.value); keyInput.value = config.getTmdbKey(); testTmdb(config.getTmdbKey()); } }, 'Save'),
h('button.btn.btn--ghost', { type: 'button', onclick: () => testTmdb(keyInput.value.trim()) }, 'Test'),
h('button.btn.btn--ghost', { type: 'button', onclick: () => { config.clearTmdbKey(); keyInput.value = config.getTmdbKey(); testTmdb(config.getTmdbKey()); } }, 'Reset')),
keyStatus);
/* ---- data ---- */
const dataStatus = status();
const data = card('data', 'Your data', 'Stored only in this browser.',
h('div.toolbar__actions',
h('button.btn.btn--ghost', { type: 'button', onclick: () => { if (confirm('Clear all Continue Watching progress?')) { resume.clear(); dataStatus.set('Continue Watching cleared.', 'ok'); } } }, icon('trash', { size: 18 }), 'Clear watch progress'),
h('button.btn.btn--ghost', { type: 'button', onclick: () => { if (confirm('Remove everything from My List?')) { myList.all().forEach((x) => myList.remove(x.type, x.id)); dataStatus.set('My List cleared.', 'ok'); } } }, icon('trash', { size: 18 }), 'Clear My List'),
h('button.btn.btn--ghost', { type: 'button', onclick: () => { config.clearProviders(); paintProviders(); dataStatus.set('Source toggles reset.', 'ok'); } }, 'Reset source toggles')),
dataStatus);
const nav = h('nav.settings-nav', { 'aria-label': 'Settings sections' },
[['playback', 'Playback'], ['sources', 'Sources'], ['server', 'Server'], ['tmdb', 'TMDB'], ['data', 'Your data']].map(([id, label]) =>
h('button.settings-nav__link', { type: 'button', onclick: () => document.getElementById(id).scrollIntoView({ behavior: 'smooth', block: 'start' }) }, label)));
root.append(h('div.page.page--padded.container.settings',
h('div.page__head', h('h1.page__title', 'Settings')),
h('div.settings__layout', nav, h('div.settings__cards', playback, sources, server, tmdbCard, data))));
loadProviders();
}
+177
View File
@@ -0,0 +1,177 @@
/*
views/title.js — /title/:type/:id detail page.
*/
import { h, runtimeLabel, plural, yearOf } from '../util.js';
import * as tmdb from '../tmdb.js';
import { href } from '../router.js';
import { resume } from '../storage.js';
import { icon } from '../ui/icons.js';
import { row } from '../ui/row.js';
import { posterCard } from '../ui/card.js';
import { castRow } from '../ui/cast.js';
import { episodesSection } from '../ui/episodes.js';
import { trailerModal } from '../ui/modal.js';
import { playTarget, myListButton, shareTitle, titlePath } from '../ui/actions.js';
const DAY = 86400000;
function badgeFor(d, type) {
const now = Date.now();
if (type === 'tv') {
if (d.next_episode_to_air) {
const n = d.next_episode_to_air;
return n.episode_number === 1 ? `Season ${n.season_number} coming soon` : 'New episodes weekly';
}
const last = d.last_episode_to_air;
if (last && last.air_date && now - new Date(last.air_date) < 45 * DAY) return `Season ${last.season_number} out now`;
if (d.status === 'Ended') return 'Complete series';
return null;
}
if (d.release_date) {
const age = now - new Date(d.release_date);
if (age < 0) return 'Coming soon';
if (age < 90 * DAY) return 'New release';
}
return null;
}
function skeleton() {
return h('div.page.page--title',
h('section.title-hero.title-hero--loading',
h('div.title-hero__content.container',
h('div.skeleton.skeleton--block', { style: { width: '40%', height: '64px' } }),
h('div.skeleton.skeleton--line', { style: { width: '30%' } }),
h('div.skeleton.skeleton--line', { style: { width: '55%' } }))));
}
function infoList(d, type) {
const rows = [];
const add = (k, v) => v && rows.push(h('div.facts__row', h('dt', k), h('dd', v)));
if (type === 'tv') {
add('Status', d.status);
add('First aired', d.first_air_date && new Date(d.first_air_date).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' }));
add('Seasons', d.number_of_seasons && `${plural(d.number_of_seasons, 'season')} · ${plural(d.number_of_episodes || 0, 'episode')}`);
add('Network', (d.networks || []).map((n) => n.name).join(', '));
add('Created by', (d.created_by || []).map((c) => c.name).join(', '));
} else {
add('Released', d.release_date && new Date(d.release_date).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' }));
add('Runtime', runtimeLabel(d.runtime));
const directors = ((d.credits && d.credits.crew) || []).filter((c) => c.job === 'Director').map((c) => c.name);
add('Director', directors.join(', '));
add('Studio', (d.production_companies || []).slice(0, 2).map((c) => c.name).join(', '));
}
add('Language', (d.spoken_languages || []).slice(0, 3).map((l) => l.english_name || l.name).join(', '));
return rows.length ? h('dl.facts', rows) : null;
}
export async function render(root, params) {
const type = params.type === 'tv' ? 'tv' : 'movie';
const id = params.id;
root.append(skeleton());
let d;
try {
d = await tmdb.details(type, id);
} catch (e) {
if (params.signal.aborted) return;
root.replaceChildren(h('section.page.page--center', h('div.empty',
h('h1.empty__title', 'Could not load this title'),
h('p.empty__text', e.message),
h('a.btn.btn--primary', { href: href('/') }, 'Back to home'))));
return;
}
if (params.signal.aborted) return;
const item = tmdb.toItem(d, type);
document.title = `${item.title} · bug tv`;
const logo = tmdb.logoFor(d);
const cert = tmdb.certificationFor(d);
const badge = badgeFor(d, type);
const trailer = tmdb.trailerFor(d);
const target = playTarget(type, id, d);
const titleText = h('h1.title-hero__title', item.title);
const titleBox = h('div.hero__titlebox.title-hero__titlebox', titleText);
if (logo) {
const im = h('img.hero__logo', { src: tmdb.img(logo.file_path, 'w500'), alt: item.title, decoding: 'async' });
im.addEventListener('load', () => {
titleBox.classList.add('has-logo');
titleText.classList.add('sr-only');
}, { once: true });
im.addEventListener('error', () => im.remove(), { once: true });
titleBox.prepend(im);
}
const genres = (d.genres || []).slice(0, 4).map((g) =>
h('a.meta-link', { href: href(`/browse/${type}?with_genres=${g.id}&title=${encodeURIComponent(g.name)}`) }, g.name));
const extra = type === 'tv' ? (d.number_of_seasons ? plural(d.number_of_seasons, 'Season') : '') : runtimeLabel(d.runtime);
const meta = h('div.hero__meta',
item.rating > 0 ? h('span.rating.rating--lg', icon('star', { size: 16 }), item.rating.toFixed(1)) : null,
yearOf(d.release_date || d.first_air_date) ? h('span', yearOf(d.release_date || d.first_air_date)) : null,
extra ? h('span', extra) : null,
cert ? h('span.chip.chip--outline', cert) : null,
genres.length ? h('span.hero__genres', genres.flatMap((g, i) => (i ? [h('span.dot', '•'), g] : [g]))) : null,
);
const playBtn = h('a.btn.btn--primary.btn--lg', { href: href(target.path) },
icon('play'), h('span', target.label),
target.progress > 0 ? h('span.btn__progress', h('i', { style: { width: `${Math.round(target.progress * 100)}%` } })) : null);
const actions = h('div.hero__actions',
playBtn,
myListButton(item, { className: 'btn btn--glass btn--lg' }),
trailer ? h('button.btn.btn--glass.btn--lg', { type: 'button', onclick: () => trailerModal(trailer.key, item.title) }, icon('trailer'), h('span', 'Trailer')) : null,
h('button.btn.btn--glass.btn--lg.btn--icon', { type: 'button', 'aria-label': 'Share', title: 'Share', onclick: () => shareTitle(item.title, titlePath(type, id)) }, icon('share')),
);
const backdropPath = d.backdrop_path || (d.images && d.images.backdrops && d.images.backdrops[0] && d.images.backdrops[0].file_path);
const hero = h('section.title-hero',
backdropPath ? h('div.hero__media', h('img.hero__img.is-loaded', {
src: tmdb.img(backdropPath, 'w1280'),
srcset: `${tmdb.img(backdropPath, 'w780')} 780w, ${tmdb.img(backdropPath, 'w1280')} 1280w, ${tmdb.img(backdropPath, 'original')} 1920w`,
sizes: '100vw', alt: '', decoding: 'async', fetchpriority: 'high',
})) : null,
h('div.hero__scrim'),
h('div.title-hero__content.container',
badge ? h('span.badge', badge) : null,
titleBox,
meta,
d.tagline ? h('p.title-hero__tagline', d.tagline) : null,
actions,
),
);
const story = h('section.section.story.container',
h('div.story__main',
h('h2.section__title', 'Storyline'),
h('p.story__text', d.overview || 'No synopsis available.')),
infoList(d, type));
const body = h('div.title-body');
const cast = castRow(d.credits);
if (cast) body.appendChild(h('div.container-row', cast));
let eps = null;
if (type === 'tv') {
const last = resume.forShow('tv', id)[0];
const season = params.query.get('season') || (last && last.season);
eps = episodesSection(d, { season });
if (eps) body.appendChild(h('div.container', eps));
}
const similar = ((d.recommendations && d.recommendations.results && d.recommendations.results.length ? d.recommendations : d.similar) || {}).results || [];
const similarItems = similar.map((r) => tmdb.toItem(r, type)).filter((x) => x.poster_path);
if (similarItems.length) body.appendChild(h('div.container-row', row({ title: 'More Like This', items: similarItems, render: (it) => posterCard(it), lazy: false })));
root.replaceChildren(h('div.page.page--title', hero, story, body));
// keep Continue / progress fresh when the player writes resume data (e.g. returning from /watch)
const onResume = () => {
const t = playTarget(type, id, d);
playBtn.href = href(t.path);
playBtn.querySelector('span').textContent = t.label;
if (eps) eps.refresh();
};
window.addEventListener('bugtv:resume', onResume);
return () => window.removeEventListener('bugtv:resume', onResume);
}
File diff suppressed because it is too large. Load diff