Files
2026-10-27 05:49:38 -05:00

213 lines
11 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
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();
}