1560 lines
120 KiB
JavaScript
1560 lines
120 KiB
JavaScript
/* simply-dvb – web panel (vanilla JS, no dependencies) */
|
||
(function () {
|
||
'use strict';
|
||
if (!document.getElementById('shell')) return; // public /watch page – player only
|
||
|
||
// ------------------------------------------------------------ helpers
|
||
var $ = function (s, r) { return (r || document).querySelector(s); };
|
||
var $$ = function (s, r) { return Array.prototype.slice.call((r || document).querySelectorAll(s)); };
|
||
function esc(s) {
|
||
return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
|
||
return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c];
|
||
});
|
||
}
|
||
function pad(n) { return (n < 10 ? '0' : '') + n; }
|
||
function hm(t) { var d = new Date(t * 1000); return pad(d.getHours()) + ':' + pad(d.getMinutes()); }
|
||
function dmy(t) { var d = new Date(t * 1000); return pad(d.getDate()) + '.' + pad(d.getMonth() + 1) + '.' + d.getFullYear(); }
|
||
function dt(t) { return t ? dmy(t) + ' ' + hm(t) : '–'; }
|
||
function now() { return Math.floor(Date.now() / 1000); }
|
||
function bytes(n) {
|
||
if (n == null) return '–';
|
||
var u = ['B', 'KiB', 'MiB', 'GiB', 'TiB'], i = 0;
|
||
while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
|
||
return (i ? n.toFixed(1) : n) + ' ' + u[i];
|
||
}
|
||
function bps(n) {
|
||
if (!n) return '0 b/s';
|
||
if (n > 1e6) return (n / 1e6).toFixed(2) + ' Mb/s';
|
||
return (n / 1e3).toFixed(0) + ' kb/s';
|
||
}
|
||
function dur(s) {
|
||
s = Math.max(0, Math.round(s || 0));
|
||
var h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), x = s % 60;
|
||
return h ? h + ' h ' + pad(m) + ' min' : m ? m + ' min ' + pad(x) + ' s' : x + ' s';
|
||
}
|
||
function toLocalInput(t) {
|
||
var d = new Date(t * 1000);
|
||
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + 'T' + pad(d.getHours()) + ':' + pad(d.getMinutes());
|
||
}
|
||
function fromLocalInput(v) { return Math.floor(new Date(v).getTime() / 1000); }
|
||
function copy(text) {
|
||
if (navigator.clipboard && window.isSecureContext) {
|
||
navigator.clipboard.writeText(text).then(function () { toast('Copied to clipboard'); });
|
||
} else {
|
||
var t = document.createElement('textarea');
|
||
t.value = text; document.body.appendChild(t); t.select();
|
||
try { document.execCommand('copy'); toast('Copied to clipboard'); } catch (e) { toast('Copy failed', true); }
|
||
t.remove();
|
||
}
|
||
}
|
||
function toast(msg, err) {
|
||
var t = document.createElement('div');
|
||
t.className = 'toast' + (err ? ' err' : '');
|
||
t.textContent = msg;
|
||
$('#toasts').appendChild(t);
|
||
setTimeout(function () { t.remove(); }, err ? 7000 : 3200);
|
||
}
|
||
function logo(c, cls) {
|
||
if (c.icon_url) return '<img class="' + (cls || 'logo') + '" loading="lazy" src="' + esc(c.icon_url) + '" alt="">';
|
||
var ini = String(c.name || '?').replace(/[^A-Za-z0-9ĄĆĘŁŃÓŚŹŻąćęłńóśźż ]/g, '').split(' ').filter(Boolean).slice(0, 2).map(function (w) { return w[0]; }).join('').toUpperCase();
|
||
return '<div class="logo-ph">' + esc(ini) + '</div>';
|
||
}
|
||
function sw(checked, attrs) {
|
||
return '<label class="switch"><input type="checkbox" ' + (checked ? 'checked ' : '') + (attrs || '') + '><span></span></label>';
|
||
}
|
||
function progressPct(ev) {
|
||
if (!ev) return 0;
|
||
return Math.max(0, Math.min(100, (now() - ev.start) * 100 / Math.max(1, ev.stop - ev.start)));
|
||
}
|
||
|
||
// ------------------------------------------------------------ API
|
||
function api(method, path, body, raw) {
|
||
var o = { method: method, headers: { 'X-Requested-With': 'simply-dvb' }, credentials: 'same-origin' };
|
||
if (body !== undefined) {
|
||
if (raw) { o.body = body; } else { o.headers['Content-Type'] = 'application/json'; o.body = JSON.stringify(body); }
|
||
}
|
||
return fetch(path, o).then(function (r) {
|
||
return r.text().then(function (t) {
|
||
var data = null;
|
||
try { data = t ? JSON.parse(t) : null; } catch (e) { data = { error: t }; }
|
||
if (r.status === 401 && path !== '/api/login') { showLogin(); throw new Error('Session expired – please sign in again'); }
|
||
if (!r.ok) throw new Error((data && data.error) || ('HTTP ' + r.status));
|
||
setLive(true);
|
||
return data;
|
||
});
|
||
}, function (e) { setLive(false); throw e; });
|
||
}
|
||
function fail(e) { toast(e.message || String(e), true); }
|
||
function setLive(on) { var d = $('#live-dot'); if (d) d.className = 'live-dot ' + (on ? 'on' : 'off'); }
|
||
|
||
// ------------------------------------------------------------ modal
|
||
function modal(title, html, wide) {
|
||
$('#modal-title').textContent = title;
|
||
$('#modal-body').innerHTML = html;
|
||
$('.modal-card').classList.toggle('wide', !!wide);
|
||
$('#modal').classList.remove('hidden');
|
||
return $('#modal-body');
|
||
}
|
||
function closeModal() {
|
||
if (app.modalCleanup) { app.modalCleanup(); app.modalCleanup = null; }
|
||
$('#modal').classList.add('hidden');
|
||
$('#modal-body').innerHTML = '';
|
||
}
|
||
var T = function (x) { return window.I18N ? window.I18N.tr(x) : x; };
|
||
var P = window.SDVB_PREFS;
|
||
function confirmBox(msg) { return window.confirm(T(msg)); }
|
||
function promptBox(msg) { return window.prompt(T(msg)); }
|
||
|
||
// ------------------------------------------------------------ state
|
||
var app = { me: null, info: null, timers: [], cleanup: [], player: null, modalCleanup: null };
|
||
/** Periodic refresh that pauses while the browser tab is hidden (no needless server work). */
|
||
function every(ms, fn) {
|
||
fn();
|
||
app.timers.push(setInterval(function () { if (!document.hidden) fn(); }, ms));
|
||
var onVis = function () { if (!document.hidden) fn(); };
|
||
document.addEventListener('visibilitychange', onVis);
|
||
app.cleanup.push(function () { document.removeEventListener('visibilitychange', onVis); });
|
||
}
|
||
function resetPage() {
|
||
app.timers.forEach(clearInterval); app.timers = [];
|
||
app.cleanup.forEach(function (f) { try { f(); } catch (e) {} }); app.cleanup = [];
|
||
}
|
||
var isAdmin = function () { return app.me && app.me.role === 'admin'; };
|
||
|
||
var routes = {
|
||
overview: ['Overview', pageOverview],
|
||
tv: ['TV', pageTv],
|
||
epg: ['TV guide', pageEpg],
|
||
channels: ['Channels', pageChannels],
|
||
recordings: ['Recordings', pageRecordings],
|
||
tuners: ['Tuners & scanning', pageTuners],
|
||
access: ['Access & sharing', pageAccess],
|
||
logs: ['Logs', pageLogs],
|
||
settings: ['Settings', pageSettings]
|
||
};
|
||
|
||
function route() {
|
||
var parts = (location.hash.replace(/^#\/?/, '') || P.get('start') || 'overview').split('/');
|
||
var key = routes[parts[0]] ? parts[0] : 'overview';
|
||
resetPage();
|
||
$$('#sidebar a[data-route]').forEach(function (a) { a.classList.toggle('active', a.getAttribute('data-route') === key); });
|
||
$('#crumb').textContent = routes[key][0];
|
||
var view = $('#view');
|
||
view.innerHTML = '';
|
||
routes[key][1](view, parts.slice(1));
|
||
}
|
||
|
||
function head(eyebrow, title, sub, actions) {
|
||
return '<div class="page-head"><div><div class="eyebrow">' + esc(eyebrow) + '</div><h1>' + esc(title) + '</h1>' +
|
||
(sub ? '<p>' + esc(sub) + '</p>' : '') + '</div><div class="actions">' + (actions || '') + '</div></div>';
|
||
}
|
||
|
||
// ------------------------------------------------------------ login
|
||
function showLogin() {
|
||
resetPage();
|
||
$('#shell').classList.add('hidden');
|
||
$('#login').classList.remove('hidden');
|
||
}
|
||
function boot() {
|
||
renderLangSwitch();
|
||
applyClock();
|
||
api('GET', '/api/info').then(function (i) {
|
||
app.info = i;
|
||
document.title = i.name;
|
||
$('#server-name').textContent = i.name;
|
||
}).catch(function () {});
|
||
api('GET', '/api/me').then(function (me) {
|
||
app.me = me;
|
||
$('#who').textContent = me.username + ' · ' + (me.role === 'admin' ? 'administrator' : 'viewer');
|
||
$('#login').classList.add('hidden');
|
||
$('#shell').classList.remove('hidden');
|
||
route();
|
||
}).catch(function () {});
|
||
}
|
||
$('#login-form').addEventListener('submit', function (e) {
|
||
e.preventDefault();
|
||
var f = e.target;
|
||
$('#login-error').textContent = '';
|
||
api('POST', '/api/login', { username: f.username.value, password: f.password.value })
|
||
.then(function () { f.password.value = ''; boot(); })
|
||
.catch(function (err) { $('#login-error').textContent = err.message; });
|
||
});
|
||
$('#logout').addEventListener('click', function () { api('POST', '/api/logout').then(showLogin).catch(showLogin); });
|
||
var THEMES = ['dark', 'midnight', 'light', 'system'];
|
||
$('#theme-toggle').addEventListener('click', function () {
|
||
var i = THEMES.indexOf(P.get('theme'));
|
||
P.set('theme', THEMES[(i + 1) % THEMES.length]);
|
||
var names = { dark: 'Dark', midnight: 'Midnight (OLED)', light: 'Light', system: 'System default' };
|
||
toast(T('Theme') + ': ' + T(names[P.get('theme')]));
|
||
});
|
||
/** Language picker built from the packs embedded at build time (langs/*.json). */
|
||
function langSelect(id, short) {
|
||
return '<select class="lang-select" id="' + id + '" data-no-i18n title="Language">' + window.I18N.languages().map(function (l) {
|
||
var label = short ? l.short + ' · ' + l.name : l.name + (l.name !== l.english ? ' (' + l.english + ')' : '');
|
||
return '<option value="' + esc(l.code) + '"' + (l.code === window.I18N.lang ? ' selected' : '') + '>' + esc(label) + '</option>';
|
||
}).join('') + '</select>';
|
||
}
|
||
function bindLang(sel) {
|
||
if (sel) sel.addEventListener('change', function () { if (sel.value !== window.I18N.lang) window.I18N.setLang(sel.value); });
|
||
}
|
||
function renderLangSwitch() {
|
||
var box = $('#lang-switch');
|
||
box.innerHTML = window.I18N.languages().length > 1 ? langSelect('lang-top', true) : '';
|
||
bindLang($('#lang-top'));
|
||
}
|
||
var clockTimer = null;
|
||
function applyClock() {
|
||
var c = $('#clock');
|
||
if (clockTimer) { clearInterval(clockTimer); clockTimer = null; }
|
||
c.classList.toggle('hidden', !P.get('clock'));
|
||
if (!P.get('clock')) return;
|
||
var tick = function () { var d = new Date(); c.textContent = pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()); };
|
||
tick();
|
||
clockTimer = setInterval(tick, 1000);
|
||
}
|
||
$('#modal-close').addEventListener('click', closeModal);
|
||
$('#modal').addEventListener('click', function (e) { if (e.target.id === 'modal') closeModal(); });
|
||
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !$('#modal').classList.contains('hidden')) closeModal(); });
|
||
window.addEventListener('hashchange', function () { if (app.me) route(); });
|
||
|
||
// ------------------------------------------------------------ OVERVIEW
|
||
// ---- live charts (history from /api/stats, sampled by the server every 2 s)
|
||
var CHART_COLORS = ['var(--accent)', 'var(--blue)', 'var(--green)', 'var(--yellow)', 'var(--red)'];
|
||
function fmtNum(v, unit) {
|
||
if (v == null || isNaN(v)) return '–';
|
||
if (unit === 'Bps') return bps(v * 8);
|
||
if (unit === 'B') return bytes(v);
|
||
if (unit === '%') return v.toFixed(v < 10 ? 1 : 0) + '%';
|
||
if (unit === '°C') return v.toFixed(1) + ' °C';
|
||
if (unit === 'dB') return v.toFixed(1) + ' dB';
|
||
if (unit === 'dBm') return v.toFixed(1) + ' dBm';
|
||
if (unit === 'bps') return bps(v);
|
||
return (Math.round(v * 100) / 100) + (unit ? ' ' + unit : '');
|
||
}
|
||
/**
|
||
* Multi-series line chart. series: [{name, values: [num|null], color}], times: [unix],
|
||
* opts: {unit, min, max, bars}.
|
||
*/
|
||
function lineChart(series, times, opts) {
|
||
opts = opts || {};
|
||
var W = 320, H = 92, n = times.length;
|
||
var all = [];
|
||
series.forEach(function (sr) { sr.values.forEach(function (v) { if (v != null && !isNaN(v)) all.push(v); }); });
|
||
var max = opts.max != null ? opts.max : Math.max.apply(null, all.concat([opts.floor || 1]));
|
||
var min = opts.min != null ? opts.min : Math.min.apply(null, opts.auto && all.length ? all : all.concat([0]));
|
||
if (opts.auto && all.length && opts.max == null) { max = Math.max.apply(null, all) + 1; min -= 1; }
|
||
if (opts.max == null) {
|
||
max = max + (max - min) * 0.12;
|
||
if (opts.unit === '%' && max > 100 && all.every(function (v) { return v <= 100; })) max = 100;
|
||
if (!opts.unit) max = Math.ceil(max);
|
||
}
|
||
if (max <= min) max = min + 1;
|
||
var x = function (i) { return n < 2 ? W : (i * W / (n - 1)); };
|
||
var y = function (v) { return H - 4 - (v - min) / (max - min) * (H - 10); };
|
||
var grid = [0.25, 0.5, 0.75].map(function (g) { var yy = (4 + g * (H - 10)).toFixed(1); return '<line class="g" x1="0" x2="' + W + '" y1="' + yy + '" y2="' + yy + '"/>'; }).join('');
|
||
var paths = series.map(function (sr, si) {
|
||
var color = sr.color || CHART_COLORS[si % CHART_COLORS.length];
|
||
if (opts.bars) {
|
||
var bw = Math.max(1, W / Math.max(n, 1) - 0.5);
|
||
return sr.values.map(function (v, i) {
|
||
if (!v) return '';
|
||
var yy = y(v);
|
||
return '<rect x="' + (x(i) - bw / 2).toFixed(1) + '" y="' + yy.toFixed(1) + '" width="' + bw.toFixed(1) + '" height="' + Math.max(0.5, H - 4 - yy).toFixed(1) + '" style="fill:' + color + '"/>';
|
||
}).join('');
|
||
}
|
||
var d = '', pen = false, first = null, last = null;
|
||
sr.values.forEach(function (v, i) {
|
||
if (v == null || isNaN(v)) { pen = false; return; }
|
||
d += (pen ? ' L' : ' M') + x(i).toFixed(1) + ',' + y(v).toFixed(1);
|
||
if (first == null) first = i;
|
||
last = i;
|
||
pen = true;
|
||
});
|
||
if (!d) return '';
|
||
var area = si === 0 && !opts.noArea && first != null ? '<path class="area" style="fill:' + color + '" d="' + d + ' L' + x(last).toFixed(1) + ',' + (H - 4) + ' L' + x(first).toFixed(1) + ',' + (H - 4) + ' Z"/>' : '';
|
||
return area + '<path class="ln" style="stroke:' + color + '" d="' + d + '"/>';
|
||
}).join('');
|
||
return '<svg class="chart" viewBox="0 0 ' + W + ' ' + H + '" preserveAspectRatio="none">' + grid + paths +
|
||
'<line class="cursor hidden" x1="0" x2="0" y1="0" y2="' + H + '"/></svg>' +
|
||
'<div class="chart-scale"><span>' + esc(fmtNum(max, opts.unit)) + '</span><span>' + esc(fmtNum(min, opts.unit)) + '</span></div>';
|
||
}
|
||
/** A chart panel: title, current values and the chart; hovering shows the value at that time. */
|
||
function chartCard(id, title, series, times, opts) {
|
||
var cur = series.map(function (sr, si) {
|
||
var v = null;
|
||
for (var i = sr.values.length - 1; i >= 0; i--) if (sr.values[i] != null) { v = sr.values[i]; break; }
|
||
return '<span class="cv"><i style="background:' + (sr.color || CHART_COLORS[si % CHART_COLORS.length]) + '"></i>' + esc(T(sr.name)) + ' <b>' + esc(fmtNum(v, (opts || {}).unit)) + '</b></span>';
|
||
}).join('');
|
||
return '<div class="panel chart-card" data-chart="' + esc(id) + '"><div class="chart-head"><div class="label">' + esc(T(title)) + '</div><div class="chart-vals">' + cur + '</div></div>' +
|
||
lineChart(series, times, opts) + '<div class="chart-hover small muted mono"></div></div>';
|
||
}
|
||
function bindChartHover(root, data) {
|
||
$$('[data-chart]', root).forEach(function (card) {
|
||
var d = data[card.getAttribute('data-chart')];
|
||
var svg = $('svg', card), cursor = $('.cursor', card), out = $('.chart-hover', card);
|
||
if (!d || !svg) return;
|
||
svg.addEventListener('mousemove', function (e) {
|
||
var r = svg.getBoundingClientRect(), n = d.times.length;
|
||
if (!n) return;
|
||
var i = Math.max(0, Math.min(n - 1, Math.round((e.clientX - r.left) / r.width * (n - 1))));
|
||
var xx = n < 2 ? 320 : i * 320 / (n - 1);
|
||
cursor.setAttribute('x1', xx); cursor.setAttribute('x2', xx); cursor.classList.remove('hidden');
|
||
var tt = new Date(d.times[i] * 1000);
|
||
out.textContent = pad(tt.getHours()) + ':' + pad(tt.getMinutes()) + ':' + pad(tt.getSeconds()) + ' ' + d.series.map(function (sr) { return T(sr.name) + ' ' + fmtNum(sr.values[i], d.unit); }).join(' · ');
|
||
});
|
||
svg.addEventListener('mouseleave', function () { cursor.classList.add('hidden'); out.textContent = ''; });
|
||
});
|
||
}
|
||
|
||
function signalBlock(sig) {
|
||
if (!sig) return '';
|
||
var strength = sig.strength_pct != null ? sig.strength_pct : null;
|
||
var snr = sig.snr_db;
|
||
var snrPct = snr != null ? Math.min(100, Math.max(0, snr * 100 / 30)) : sig.snr_pct;
|
||
return '<div class="sig">' +
|
||
'<div><div class="label">Strength</div><div class="value">' + (strength != null ? strength.toFixed(0) + '%' : '–') + '</div>' +
|
||
'<div class="meter ' + (strength > 50 ? 'good' : strength > 25 ? '' : 'bad') + '"><i style="width:' + (strength || 0) + '%"></i></div>' +
|
||
'<div class="small muted mono">' + (sig.strength_dbm != null ? sig.strength_dbm.toFixed(1) + ' dBm' : '') + '</div></div>' +
|
||
'<div><div class="label">SNR</div><div class="value">' + (snr != null ? snr.toFixed(1) + ' dB' : snrPct != null ? snrPct.toFixed(0) + '%' : '–') + '</div>' +
|
||
'<div class="meter blue"><i style="width:' + (snrPct || 0) + '%"></i></div></div>' +
|
||
'<div><div class="label">Errors (UNC)</div><div class="value">' + (sig.uncorrected != null ? sig.uncorrected : '–') + '</div>' +
|
||
'<div class="small muted mono">' + (sig.locked ? 'LOCK' : sig.has_signal ? 'signal, no lock' : 'no signal') + '</div></div></div>';
|
||
}
|
||
|
||
function pageOverview(view) {
|
||
var windowMin = +P.get('chartWindow') || 10;
|
||
view.innerHTML = head('Connected to server', 'Television, in focus.', 'Tuners, streams, clients and EPG in one place.',
|
||
'<a class="btn" href="#/tv">▶ Watch</a><a class="btn" href="#/tuners">Scan channels</a>') +
|
||
'<div class="grid g4" id="ov-stats"></div>' +
|
||
'<div class="section-head"><h2>Live</h2><div class="seg" id="ov-window">' + [5, 10, 15].map(function (m) {
|
||
return '<button data-w="' + m + '"' + (m === windowMin ? ' class="on"' : '') + '>' + m + ' min</button>';
|
||
}).join('') + '</div></div>' +
|
||
'<div class="grid g3" id="ov-charts"></div>' +
|
||
'<div class="grid g2" style="margin-top:10px" id="ov-tuners"></div>' +
|
||
'<div class="panel" style="margin-top:10px"><header><h2>Active clients</h2><span class="pill" id="ov-ccount">0</span></header><div class="table-wrap" id="ov-clients"></div></div>';
|
||
var hist = { samples: [], tuners: {} }, lastT = 0, status = null;
|
||
$$('#ov-window button').forEach(function (b) {
|
||
b.addEventListener('click', function () {
|
||
windowMin = +b.getAttribute('data-w'); P.set('chartWindow', windowMin);
|
||
$$('#ov-window button').forEach(function (x) { x.classList.toggle('on', x === b); });
|
||
renderCharts();
|
||
});
|
||
});
|
||
function trim(list) {
|
||
var from = now() - windowMin * 60;
|
||
return list.filter(function (x) { return x.t >= from; });
|
||
}
|
||
function pick(list, k, f) { return list.map(function (x) { var v = x[k]; return v == null ? null : (f ? f(v) : v); }); }
|
||
function renderCharts() {
|
||
var S = trim(hist.samples), times = S.map(function (x) { return x.t; });
|
||
var data = {}, html = '';
|
||
function add(id, title, series, opts) {
|
||
if (!series.some(function (sr) { return sr.values.some(function (v) { return v != null; }); })) return;
|
||
data[id] = { times: times, series: series, unit: (opts || {}).unit };
|
||
html += chartCard(id, title, series, times, opts);
|
||
}
|
||
add('cpu', 'CPU', [{ name: 'system', values: pick(S, 'cpu') }, { name: 'simply-dvb', values: pick(S, 'proc_cpu') }], { unit: '%', min: 0, floor: 10 });
|
||
add('mem', 'Memory', [{ name: 'used', values: pick(S, 'mem') }], { unit: '%', min: 0, max: 100 });
|
||
add('rss', 'Process memory (RSS)', [{ name: 'RSS', values: pick(S, 'rss') }], { unit: 'B', min: 0 });
|
||
add('stream', 'Streaming throughput', [{ name: 'to clients', values: pick(S, 'out_bps') }, { name: 'recordings', values: pick(S, 'rec_bps') }], { unit: 'Bps', min: 0, floor: 1000 });
|
||
add('net', 'Network', [{ name: 'out', values: pick(S, 'net_tx') }, { name: 'in', values: pick(S, 'net_rx') }], { unit: 'Bps', min: 0, floor: 1000 });
|
||
add('clients', 'Clients & sessions', [{ name: 'clients', values: pick(S, 'clients') }, { name: 'HLS sessions', values: pick(S, 'hls_sessions') }, { name: 'active tuners', values: pick(S, 'tuners_active') }], { min: 0, floor: 2, noArea: true });
|
||
add('temp', 'Temperature', [{ name: 'max', values: pick(S, 'temp') }], { unit: '°C', auto: true });
|
||
add('load', 'Load average (1 min)', [{ name: 'load', values: pick(S, 'load1') }], { min: 0, floor: 1 });
|
||
$('#ov-charts').innerHTML = html || '<div class="panel"><div class="empty">' + esc(T('Collecting data…')) + '</div></div>';
|
||
bindChartHover($('#ov-charts'), data);
|
||
renderTuners();
|
||
}
|
||
function renderTuners() {
|
||
if (!status) return;
|
||
var tdata = {};
|
||
$('#ov-tuners').className = 'grid ' + (status.tuners.length > 1 ? 'g2' : 'g1');
|
||
$('#ov-tuners').innerHTML = status.tuners.map(function (t) {
|
||
var a = t.active;
|
||
var TS = trim(hist.tuners[t.id] || []), times = TS.map(function (x) { return x.t; });
|
||
var charts = '';
|
||
function add(id, title, series, opts) {
|
||
if (!series.some(function (sr) { return sr.values.some(function (v) { return v != null && v !== 0; }); })) return;
|
||
var key = t.id + ':' + id;
|
||
tdata[key] = { times: times, series: series, unit: (opts || {}).unit };
|
||
charts += chartCard(key, title, series, times, opts);
|
||
}
|
||
add('br', 'Multiplex bitrate', [{ name: 'bitrate', values: pick(TS, 'bitrate') }], { unit: 'bps', min: 0, floor: 1e6 });
|
||
add('sig', 'Signal strength', [{ name: '%', values: pick(TS, 'strength') }], { unit: '%', min: 0, max: 100 });
|
||
add('dbm', 'Signal level', [{ name: 'dBm', values: pick(TS, 'strength_dbm') }], { unit: 'dBm', auto: true, noArea: true });
|
||
add('snr', 'SNR', [{ name: 'SNR', values: pick(TS, 'snr') }], { unit: 'dB', min: 0, floor: 10 });
|
||
add('unc', 'Uncorrected blocks', [{ name: 'per 2 s', values: pick(TS, 'unc') }], { min: 0, floor: 1, bars: true });
|
||
return '<div class="panel tuner"><div class="t-head"><div><h3>' + esc(t.name) + '</h3><div class="t-meta">' + esc(t.id) + ' · ' + esc(t.delivery_systems.join(' / ')) + ' · ' + esc(t.path) + '</div></div>' +
|
||
'<div class="actions">' + (!t.enabled ? '<span class="pill">disabled</span>' : t.busy ? '<span class="pill warn">scanning</span>' :
|
||
a ? '<span class="pill ' + (a.state === 'locked' ? 'ok' : a.state === 'tuning' ? 'warn' : 'err') + '">' + esc(a.state === 'locked' ? 'LOCK' : a.state) + '</span>' : '<span class="pill">idle</span>') + '</div></div>' +
|
||
(a ? '<div class="kv"><span>Mux</span><span>' + esc(a.tuning) + (a.network_name ? ' · ' + esc(a.network_name) : '') + '</span>' +
|
||
'<span>Clients</span><span>' + a.subscribers + (a.top_priority ? ' · priority ' + esc(a.top_priority) : '') + '</span>' +
|
||
'<span>Stream</span><span class="mono">' + bps(a.bitrate_bps) + ' · ' + dur(a.uptime_secs) + '</span></div>' + signalBlock(a.signal)
|
||
: '<div class="muted small">' + (t.last_error ? 'Last error: ' + esc(t.last_error) : 'Tuner is waiting for clients.') + '</div>') +
|
||
(charts ? '<div class="grid ' + (status.tuners.length > 1 ? 'g2' : 'g4') + ' tuner-charts">' + charts + '</div>' : '') +
|
||
'</div>';
|
||
}).join('') || '<div class="panel"><div class="empty">No DVB adapters detected. Check /dev/dvb and permissions (group <code>video</code>).</div></div>';
|
||
bindChartHover($('#ov-tuners'), tdata);
|
||
}
|
||
function renderStatus(s) {
|
||
var c = s.counts;
|
||
var disk = s.disk && s.disk.total ? (100 - s.disk.free * 100 / s.disk.total) : null;
|
||
$('#ov-stats').innerHTML =
|
||
'<div class="panel stat"><div class="label">Channels</div><div class="value">' + c.channels_enabled + ' <span class="muted small">/ ' + c.channels + '</span></div><div class="sub">' + c.services + ' services · ' + c.muxes + ' muxes</div></div>' +
|
||
'<div class="panel stat"><div class="label">EPG – upcoming programmes</div><div class="value">' + c.epg_events + '</div><div class="sub">last grab: ' + (s.epg.last_grab ? dt(s.epg.last_grab) : '–') + '</div></div>' +
|
||
'<div class="panel stat"><div class="label">Recordings</div><div class="value">' + c.recordings_running + ' <span class="muted small">running</span></div><div class="sub">' + c.recordings_scheduled + ' scheduled · ' + c.recordings_total + ' total</div></div>' +
|
||
'<div class="panel stat"><div class="label">Recordings disk</div><div class="value">' + (s.disk && s.disk.free != null ? bytes(s.disk.free) : '–') + '</div>' +
|
||
(disk != null ? '<div class="meter ' + (disk > 90 ? 'bad' : '') + '"><i style="width:' + disk.toFixed(0) + '%"></i></div>' : '') +
|
||
'<div class="sub">free · load ' + esc(s.load || '–') + ' · up ' + dur(s.uptime_secs) + '</div></div>';
|
||
$('#ov-ccount').textContent = s.clients.length;
|
||
$('#ov-clients').innerHTML = s.clients.length ? '<table><thead><tr><th>Protocol</th><th>Channel</th><th>Device</th><th>Address</th><th>Access</th><th>Profile</th><th>Since</th><th class="num">Duration</th><th class="num">Rate</th><th class="num">Sent</th></tr></thead><tbody>' +
|
||
s.clients.map(function (x) {
|
||
return '<tr><td><span class="pill ' + (x.kind === 'recording' ? 'err' : x.kind === 'hls' ? 'blue' : x.kind === 'htsp' ? 'ok' : 'acc') + '">' + esc(x.protocol) + '</span></td><td><b>' + esc(x.channel_name) + '</b></td>' +
|
||
'<td><div>' + esc(x.device) + '</div><div class="muted small mono" title="' + esc(x.user_agent) + '">' + esc(x.user_agent.length > 70 ? x.user_agent.slice(0, 70) + '…' : x.user_agent) + '</div></td>' +
|
||
'<td class="mono small">' + esc(x.ip) + '</td><td class="small">' + esc(x.who) + '</td><td class="mono small">' + esc(x.profile) + '</td><td class="mono small">' + hm(x.started) + '</td>' +
|
||
'<td class="num mono small">' + dur(x.duration_secs) + (x.idle_secs > 10 ? '<div class="muted">' + esc(T('idle')) + ' ' + dur(x.idle_secs) + '</div>' : '') + '</td><td class="num mono small">' + bps(x.avg_bps) + '</td><td class="num">' + bytes(x.bytes) + '</td></tr>';
|
||
}).join('') + '</tbody></table>' : '<div class="empty">Nobody is watching right now.</div>';
|
||
}
|
||
function poll() {
|
||
Promise.all([api('GET', '/api/status'), api('GET', '/api/stats?since=' + lastT)]).then(function (r) {
|
||
status = r[0];
|
||
var h = r[1];
|
||
hist.samples = hist.samples.concat(h.samples).slice(-450);
|
||
Object.keys(h.tuners).forEach(function (k) { hist.tuners[k] = (hist.tuners[k] || []).concat(h.tuners[k]).slice(-450); });
|
||
if (h.samples.length) lastT = h.samples[h.samples.length - 1].t;
|
||
renderStatus(status);
|
||
renderCharts();
|
||
}).catch(function () {});
|
||
}
|
||
every(2000, poll);
|
||
}
|
||
|
||
// ------------------------------------------------------------ TV
|
||
function loadChannels() { return api('GET', '/api/channels'); }
|
||
|
||
function pageTv(view, args) {
|
||
view.innerHTML = '<div class="tv"><div class="panel tv-list" id="tv-list"></div><div><div class="player" id="tv-player"><div class="overlay"><div>Pick a channel from the list</div></div></div>' +
|
||
'<div class="panel" id="tv-info" style="margin-top:10px"></div><div class="grid g2" style="margin-top:10px"><div class="panel" id="tv-day"></div><div class="panel" id="tv-tools"></div></div></div></div>';
|
||
var channels = [], current = null, filter = '', group = '';
|
||
try { group = localStorage.getItem('sdvb-group') || ''; } catch (e) {}
|
||
var wantProfile = 'auto';
|
||
try { wantProfile = localStorage.getItem('sdvb-profile') || 'auto'; } catch (e) {}
|
||
|
||
function renderList() {
|
||
var f = filter.toLowerCase();
|
||
var groups = [];
|
||
channels.forEach(function (c) { if (c.enabled && c.grp && groups.indexOf(c.grp) < 0) groups.push(c.grp); });
|
||
if (group && groups.indexOf(group) < 0) group = '';
|
||
var list = channels.filter(function (c) { return c.enabled && (!group || c.grp === group) && (!f || c.name.toLowerCase().indexOf(f) >= 0 || String(c.number) === f); });
|
||
$('#tv-list').classList.toggle('hide-logos', !P.get('logos'));
|
||
$('#tv-list').classList.toggle('hide-progress', !P.get('progress'));
|
||
$('#tv-list').innerHTML = '<div class="search"><input id="tv-search" placeholder="Search channel…" value="' + esc(filter) + '">' +
|
||
(groups.length > 1 ? '<select id="tv-group"><option value="">' + esc(T('All')) + '</option>' + groups.map(function (g) { return '<option' + (g === group ? ' selected' : '') + '>' + esc(g) + '</option>'; }).join('') + '</select>' : '') + '</div>' +
|
||
(list.length ? list.map(function (c) {
|
||
return '<div class="ch-item' + (current && current.id === c.id ? ' active' : '') + '" data-id="' + c.id + '"><div class="n">' + c.number + '</div>' + logo(c) +
|
||
'<div class="t"><div class="name">' + esc(c.name) + '</div><div class="now">' + (c.now ? hm(c.now.start) + ' ' + esc(c.now.title) : (c.kind === 'radio' ? 'radio' : ' ')) + '</div>' +
|
||
(c.now ? '<div class="meter"><i style="width:' + progressPct(c.now) + '%"></i></div>' : '') + '</div></div>';
|
||
}).join('') : '<div class="empty">No channels – run a scan on the Tuners page.</div>');
|
||
var gs = $('#tv-group');
|
||
if (gs) gs.addEventListener('change', function () { group = gs.value; try { localStorage.setItem('sdvb-group', group); } catch (e) {} renderList(); });
|
||
var s = $('#tv-search');
|
||
s.addEventListener('input', function () { filter = s.value; var pos = s.selectionStart; renderList(); var n = $('#tv-search'); n.focus(); n.setSelectionRange(pos, pos); });
|
||
$$('.ch-item', $('#tv-list')).forEach(function (e) { e.addEventListener('click', function () { play(+e.getAttribute('data-id')); }); });
|
||
}
|
||
|
||
function renderInfo() {
|
||
var c = current;
|
||
if (!c) return;
|
||
var n = c.now, nx = c.next;
|
||
$('#tv-info').innerHTML = '<div class="np"><div><div class="eyebrow">' + esc(c.number + ' · ' + c.name) + '</div>' +
|
||
(n ? '<h2>' + esc(n.title) + '</h2><div class="time">' + hm(n.start) + '–' + hm(n.stop) + (n.genre ? ' · ' + esc(n.genre) : '') + '</div><div class="meter"><i style="width:' + progressPct(n) + '%"></i></div>' +
|
||
'<div class="desc">' + esc(n.description || n.summary || '') + '</div>' : '<h2>' + esc(c.name) + '</h2><div class="muted">No EPG data for this moment.</div>') +
|
||
(nx ? '<div class="small muted" style="margin-top:8px">Next: <b>' + hm(nx.start) + '</b> ' + esc(nx.title) + '</div>' : '') +
|
||
'</div><div class="actions" style="align-items:flex-start">' +
|
||
(n && isAdmin() ? '<button class="btn" id="tv-rec">● Record programme</button>' : '') +
|
||
'<button class="btn" id="tv-pip" title="Picture-in-picture (P)">⧉ PiP</button><button class="btn" id="tv-full" title="F">⛶ Fullscreen</button></div></div>';
|
||
var r = $('#tv-rec');
|
||
if (r) r.addEventListener('click', function () { api('POST', '/api/recordings', { event_id: n.id }).then(function () { toast('Recording scheduled: ' + n.title); }).catch(fail); });
|
||
$('#tv-full').addEventListener('click', fullscreen);
|
||
$('#tv-pip').addEventListener('click', pip);
|
||
}
|
||
|
||
function renderDay() {
|
||
var c = current;
|
||
if (!c) return;
|
||
var from = now() - 2 * 3600;
|
||
api('GET', '/api/epg?channel=' + c.id + '&from=' + from + '&to=' + (from + 16 * 3600)).then(function (evs) {
|
||
var t = now();
|
||
$('#tv-day').innerHTML = '<header><h2>Schedule</h2><a class="btn small" href="#/epg">EPG grid</a></header><div class="day-list">' +
|
||
(evs.length ? evs.map(function (e) {
|
||
var cls = e.stop < t ? 'past' : e.start <= t ? 'cur' : '';
|
||
return '<div class="ev ' + cls + '"><span class="tm">' + hm(e.start) + '</span><span>' + esc(e.title) + '</span>' +
|
||
(e.start > t && isAdmin() ? '<button class="btn small ghost" data-rec="' + e.id + '" title="Record">●</button>' : '<span></span>') + '</div>';
|
||
}).join('') : '<div class="muted">No EPG yet. Data appears after EIT is collected from the mux or XMLTV is imported.</div>') + '</div>';
|
||
$$('[data-rec]', $('#tv-day')).forEach(function (b) {
|
||
b.addEventListener('click', function () { api('POST', '/api/recordings', { event_id: +b.getAttribute('data-rec') }).then(function () { toast('Recording scheduled'); renderDay(); }).catch(fail); });
|
||
});
|
||
}).catch(fail);
|
||
}
|
||
|
||
function renderTools(active) {
|
||
var c = current;
|
||
if (!c) return;
|
||
var svc = c.service || {};
|
||
var profiles = [['auto', 'Automatic'], ['pass', 'Original'], ['aac', 'Audio → AAC'], ['h264', 'H.264 720p']];
|
||
var noFfmpeg = app.info && app.info.ffmpeg === false;
|
||
var caps = [svc.video].concat((svc.audio || []).map(function (a) { return a.replace(/ \(.*\)$/, ''); })).filter(function (x, i, a) { return x && a.indexOf(x) === i; });
|
||
var capsHtml = caps.map(function (x) {
|
||
var ok = window.SDVB.codecSupported(x);
|
||
return '<span class="pill ' + (ok ? 'ok' : 'err') + '" title="' + esc(T(ok ? 'Supported by this browser' : 'Not supported by this browser')) + '">' + esc(x) + ' ' + (ok ? '✓' : '✗') + '</span>';
|
||
}).join(' ');
|
||
var why = window.SDVB.explain(svc.video, svc.audio);
|
||
$('#tv-tools').innerHTML = '<header><h2>Stream</h2><span class="pill">' + esc(svc.video || (c.kind === 'radio' ? 'radio' : '?')) + ' · ' + esc((svc.audio || []).join(', ') || '–') + '</span></header>' +
|
||
'<div class="kv"><span>Mux</span><span>' + esc(c.mux || '–') + '</span><span>Profile</span><span><select id="tv-profile">' +
|
||
profiles.map(function (p) {
|
||
var needs = noFfmpeg && (p[0] === 'aac' || p[0] === 'h264');
|
||
return '<option value="' + p[0] + '"' + (p[0] === wantProfile ? ' selected' : '') + (needs ? ' disabled' : '') + '>' + esc(T(p[1])) + (needs ? ' – ' + esc(T('needs ffmpeg')) : '') + '</option>';
|
||
}).join('') +
|
||
'</select> <span class="muted small">active: <b id="tv-active-profile">' + esc(active || '') + '</b></span></span></div>' +
|
||
'<div class="kv" style="margin-top:6px"><span>' + esc(T('Browser')) + '</span><span>' + (capsHtml || '–') + '</span><span>ffmpeg</span><span>' +
|
||
(noFfmpeg ? '<span class="pill warn">' + esc(T('not installed')) + '</span>' : '<span class="pill ok">' + esc(T('available')) + '</span>') + '</span></div>' +
|
||
(why ? '<p class="hint">' + esc(why) + (noFfmpeg ? ' ' + esc(T('Without ffmpeg on the server use VLC or a browser/device that decodes these codecs.')) : '') + '</p>' : '') +
|
||
'<div style="margin-top:10px" class="copy-row"><code>' + esc(location.origin + '/hls/' + c.id + '/index.m3u8') + '</code><button class="btn small" data-copy="hls">HLS</button></div>' +
|
||
'<div class="copy-row"><code>' + esc(location.origin + '/stream/channelid/' + c.id + '?profile=pass') + '</code><button class="btn small" data-copy="ts">TS</button></div>' +
|
||
'<div class="row" style="margin-top:6px"><a class="btn small" href="/playlist/channelid/' + c.id + '" download="' + esc(c.name) + '.m3u">▶ VLC (.m3u)</a></div>' +
|
||
'<p class="hint">' + esc(T('Shortcuts: ↑/↓ channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.')) + '</p>' +
|
||
'<p class="hint">The “Automatic” profile checks which codecs your browser supports (e.g. HEVC, AC-3) and enables ffmpeg transcoding when needed.</p>';
|
||
$('#tv-profile').addEventListener('change', function (e) {
|
||
wantProfile = e.target.value;
|
||
try { localStorage.setItem('sdvb-profile', wantProfile); } catch (x) {}
|
||
if (app.player) app.player.setProfile(wantProfile);
|
||
});
|
||
$$('[data-copy]', $('#tv-tools')).forEach(function (b) {
|
||
b.addEventListener('click', function () { copy(b.parentNode.querySelector('code').textContent); });
|
||
});
|
||
}
|
||
|
||
function select(id) {
|
||
var c = channels.filter(function (x) { return x.id === id; })[0];
|
||
if (!c) return;
|
||
current = c;
|
||
if (app.player) { app.player.destroy(); app.player = null; }
|
||
$('#tv-player').innerHTML = '<div class="overlay"><div style="text-align:center"><div class="eyebrow">' + esc(c.number + ' · ' + c.name) + '</div>' +
|
||
'<button class="btn primary" id="tv-start" style="margin-top:10px">▶ ' + esc(T('Play')) + '</button></div></div>';
|
||
$('#tv-start').addEventListener('click', function () { play(c.id); });
|
||
renderList(); renderInfo(); renderDay(); renderTools('');
|
||
}
|
||
|
||
function play(id) {
|
||
var c = channels.filter(function (x) { return x.id === id; })[0];
|
||
if (!c) return;
|
||
current = c;
|
||
if (location.hash !== '#/tv/' + id) history.replaceState(null, '', '#/tv/' + id);
|
||
setTimeout(function () { osd(c.number + ' ' + c.name); }, 50);
|
||
if (app.player) app.player.destroy();
|
||
var svc = c.service || {};
|
||
app.player = window.SDVB.createPlayer($('#tv-player'), {
|
||
channelId: c.id,
|
||
video: svc.video,
|
||
audio: svc.audio || [],
|
||
transcode: !(app.info && app.info.ffmpeg === false),
|
||
vlcUrl: '/playlist/channelid/' + c.id,
|
||
profile: wantProfile,
|
||
onProfile: function (p) { var e = $('#tv-active-profile'); if (e) e.textContent = p; }
|
||
});
|
||
renderList(); renderInfo(); renderDay(); renderTools(app.player.profile);
|
||
}
|
||
|
||
function fullscreen() {
|
||
var box = $('#tv-player');
|
||
if (document.fullscreenElement) document.exitFullscreen(); else if (box && box.requestFullscreen) box.requestFullscreen();
|
||
}
|
||
function pip() {
|
||
var v = $('#tv-player video');
|
||
if (!v) return;
|
||
if (document.pictureInPictureElement) document.exitPictureInPicture(); else if (v.requestPictureInPicture) v.requestPictureInPicture().catch(fail);
|
||
}
|
||
function visible() { return channels.filter(function (c) { return c.enabled && (!group || c.grp === group); }); }
|
||
function zap(delta) {
|
||
var list = visible();
|
||
if (!list.length) return;
|
||
var i = current ? list.findIndex(function (c) { return c.id === current.id; }) : -1;
|
||
play(list[(i + delta + list.length) % list.length].id);
|
||
}
|
||
var digits = '', digitTimer = null;
|
||
function osd(text) {
|
||
var box = $('#tv-player');
|
||
var o = $('.osd', box);
|
||
if (!o) { o = document.createElement('div'); o.className = 'osd'; box.appendChild(o); }
|
||
o.textContent = text;
|
||
o.classList.add('show');
|
||
clearTimeout(o._t);
|
||
o._t = setTimeout(function () { o.classList.remove('show'); }, 1500);
|
||
}
|
||
function onKey(e) {
|
||
if (e.target && /INPUT|SELECT|TEXTAREA/.test(e.target.tagName)) return;
|
||
if (!$('#modal').classList.contains('hidden') || e.ctrlKey || e.metaKey || e.altKey) return;
|
||
var v = $('#tv-player video');
|
||
var k = e.key;
|
||
if (k === 'ArrowUp' || k === 'PageUp') { zap(-1); e.preventDefault(); }
|
||
else if (k === 'ArrowDown' || k === 'PageDown') { zap(1); e.preventDefault(); }
|
||
else if (k === 'f' || k === 'F') fullscreen();
|
||
else if (k === 'p' || k === 'P') pip();
|
||
else if ((k === 'm' || k === 'M') && v) { v.muted = !v.muted; osd(v.muted ? '🔇' : '🔊'); }
|
||
else if (k === ' ' && v) { if (v.paused) v.play(); else v.pause(); e.preventDefault(); }
|
||
else if (k === '?') shortcutsHelp();
|
||
else if (/^[0-9]$/.test(k)) {
|
||
digits += k;
|
||
osd(digits);
|
||
clearTimeout(digitTimer);
|
||
digitTimer = setTimeout(function () {
|
||
var c = visible().filter(function (x) { return String(x.number) === digits; })[0];
|
||
digits = '';
|
||
if (c) play(c.id); else osd('—');
|
||
}, 1200);
|
||
}
|
||
}
|
||
function shortcutsHelp() {
|
||
modal('Keyboard shortcuts', '<div class="kv">' + [['↑ / ↓', 'Previous / next channel'], ['0–9', 'Select channel by number'], ['F', 'Fullscreen'], ['P', 'Picture-in-picture'], ['M', 'Mute'], ['Space', 'Pause / resume'], ['?', 'This help']].map(function (x) {
|
||
return '<span>' + esc(x[0]) + '</span><span>' + esc(x[1]) + '</span>';
|
||
}).join('') + '</div>');
|
||
}
|
||
document.addEventListener('keydown', onKey);
|
||
app.cleanup.push(function () { document.removeEventListener('keydown', onKey); });
|
||
app.cleanup.push(function () { if (app.player) { app.player.destroy(); app.player = null; } });
|
||
loadChannels().then(function (list) {
|
||
channels = list;
|
||
renderList();
|
||
var id = +(args[0] || 0) || (function () { try { return +localStorage.getItem('sdvb-last') || 0; } catch (e) { return 0; } })();
|
||
if (id && channels.some(function (c) { return c.id === id; })) {
|
||
// the TV tab (also #/tv/<id> after a reload or history navigation) only selects
|
||
// the channel; playback starts on click, from an explicit ▶ link (#/tv/<id>/play)
|
||
// or when autoplay is on in Preferences – so visiting the tab does not take a tuner
|
||
if (args[1] === 'play' || P.get('autoplay')) play(id); else select(id);
|
||
}
|
||
}).catch(fail);
|
||
app.cleanup.push(function () { if (current) try { localStorage.setItem('sdvb-last', current.id); } catch (e) {} });
|
||
app.timers.push(setInterval(function () {
|
||
if (document.hidden) return;
|
||
loadChannels().then(function (list) {
|
||
channels = list;
|
||
if (current) current = channels.filter(function (x) { return x.id === current.id; })[0] || current;
|
||
renderList(); renderInfo();
|
||
}).catch(function () {});
|
||
}, 60000));
|
||
}
|
||
|
||
// ------------------------------------------------------------ EPG
|
||
function eventModal(e, ch) {
|
||
var body = modal(e.title,
|
||
'<div class="kv"><span>Channel</span><span>' + esc(ch ? ch.number + ' · ' + ch.name : '') + '</span><span>Time</span><span>' + dt(e.start) + ' – ' + hm(e.stop) + ' (' + dur(e.stop - e.start) + ')</span>' +
|
||
(e.genre ? '<span>Genre</span><span>' + esc(e.genre) + '</span>' : '') + (e.rating ? '<span>Age</span><span>' + e.rating + '+</span>' : '') +
|
||
'<span>Source</span><span>' + esc(e.source === 'xmltv' ? 'XMLTV' : 'EIT (broadcast)') + '</span></div>' +
|
||
(e.summary ? '<p><b>' + esc(e.summary) + '</b></p>' : '') + '<p style="white-space:pre-line">' + esc(e.description || '') + '</p>' +
|
||
'<div class="modal-foot">' + (ch ? '<a class="btn" href="#/tv/' + ch.id + '/play">▶ Watch channel</a>' : '') + (isAdmin() && e.stop > now() ? '<button class="btn primary" id="ev-rec">● Record</button>' : '') + '</div>');
|
||
var r = $('#ev-rec', body);
|
||
if (r) r.addEventListener('click', function () {
|
||
api('POST', '/api/recordings', { event_id: e.id }).then(function () { toast('Recording scheduled: ' + e.title); closeModal(); }).catch(fail);
|
||
});
|
||
$$('a', body).forEach(function (a) { a.addEventListener('click', closeModal); });
|
||
}
|
||
|
||
function pageEpg(view) {
|
||
var PX = +P.get('epgZoom') || 4; // px per minute
|
||
var start = Math.floor((now() - 3600) / 1800) * 1800;
|
||
var hours = 12;
|
||
view.innerHTML = head('Electronic programme guide', 'TV guide', 'EPG from the broadcast (EIT) and external XMLTV sources.',
|
||
'<button class="btn" id="epg-prev">◀ 6 h</button><button class="btn" id="epg-now">Now</button><button class="btn" id="epg-next">6 h ▶</button>' +
|
||
(isAdmin() ? '<button class="btn" id="epg-grab">Grab EPG now</button>' : '')) + '<div class="epg" id="epg"></div>';
|
||
function render() {
|
||
var end = start + hours * 3600;
|
||
Promise.all([loadChannels(), api('GET', '/api/epg?from=' + start + '&to=' + end), api('GET', '/api/recordings')]).then(function (r) {
|
||
var chans = r[0].filter(function (c) { return c.enabled; });
|
||
var evs = r[1], recs = r[2];
|
||
var byCh = {};
|
||
evs.forEach(function (e) { (byCh[e.channel_id] = byCh[e.channel_id] || []).push(e); });
|
||
var recSet = {};
|
||
recs.forEach(function (x) { if (x.status === 'scheduled' || x.status === 'recording') recSet[x.channel_id + ':' + x.start] = 1; });
|
||
var width = hours * 60 * PX;
|
||
var hh = '';
|
||
for (var t = start; t < end; t += 1800) hh += '<div class="h" style="left:' + ((t - start) / 60 * PX) + 'px">' + hm(t) + (new Date(t * 1000).getHours() === 0 && new Date(t * 1000).getMinutes() === 0 ? ' · ' + dmy(t) : '') + '</div>';
|
||
var rows = chans.map(function (c) {
|
||
var items = (byCh[c.id] || []).map(function (e) {
|
||
var s = Math.max(e.start, start), x = (s - start) / 60 * PX, w = (Math.min(e.stop, end) - s) / 60 * PX - 2;
|
||
if (w < 2) return '';
|
||
var cur = e.start <= now() && e.stop > now();
|
||
return '<div class="epg-ev' + (cur ? ' cur' : '') + (recSet[c.id + ':' + e.start] ? ' rec' : '') + '" data-e="' + e.id + '" style="left:' + x + 'px;width:' + w + 'px" title="' + esc(hm(e.start) + ' ' + e.title) + '">' +
|
||
'<div class="tt">' + esc(e.title) + '</div><div class="tm">' + hm(e.start) + '–' + hm(e.stop) + '</div></div>';
|
||
}).join('');
|
||
return '<div class="epg-row"><div class="epg-ch" data-ch="' + c.id + '"><span class="n">' + c.number + '</span>' + logo(c) + '<span class="nm">' + esc(c.name) + '</span></div><div class="epg-track" style="width:' + width + 'px">' + items + '</div></div>';
|
||
}).join('');
|
||
var nowX = (now() - start) / 60 * PX;
|
||
$('#epg').innerHTML = chans.length ? '<div class="epg-inner" style="width:' + (width + 170) + 'px"><div class="epg-head"><div class="corner"></div><div class="hours" style="width:' + width + 'px">' + hh + '</div></div>' + rows +
|
||
(nowX > 0 && nowX < width ? '<div class="epg-now" style="left:' + (170 + nowX) + 'px"></div>' : '') + '</div>' : '<div class="empty">No channels.</div>';
|
||
var map = {};
|
||
evs.forEach(function (e) { map[e.id] = e; });
|
||
var chMap = {};
|
||
chans.forEach(function (c) { chMap[c.id] = c; });
|
||
$$('.epg-ev', $('#epg')).forEach(function (d) { d.addEventListener('click', function () { var e = map[d.getAttribute('data-e')]; eventModal(e, chMap[e.channel_id]); }); });
|
||
$$('.epg-ch', $('#epg')).forEach(function (d) { d.addEventListener('click', function () { location.hash = '#/tv/' + d.getAttribute('data-ch') + '/play'; }); });
|
||
if (nowX > 0) $('#epg').scrollLeft = Math.max(0, nowX - 200);
|
||
}).catch(fail);
|
||
}
|
||
$('#epg-prev').addEventListener('click', function () { start -= 6 * 3600; render(); });
|
||
$('#epg-next').addEventListener('click', function () { start += 6 * 3600; render(); });
|
||
$('#epg-now').addEventListener('click', function () { start = Math.floor((now() - 3600) / 1800) * 1800; render(); });
|
||
var g = $('#epg-grab');
|
||
if (g) g.addEventListener('click', function () { api('POST', '/api/epg/grab').then(function () { toast('EPG grabbing will start when tuners are free'); }).catch(fail); });
|
||
render();
|
||
}
|
||
|
||
// ------------------------------------------------------------ CHANNELS
|
||
function pageChannels(view) {
|
||
view.innerHTML = head('Channel list', 'Channels', 'Drag rows to reorder. Numbers can also be typed in.',
|
||
isAdmin() ? '<button class="btn" id="ch-icons">Find icons</button><button class="btn" id="ch-add">+ Add from services</button><button class="btn" id="ch-renum">Renumber 1..n</button>' : '') +
|
||
'<div class="panel"><div class="filters" id="ch-filters"></div><div class="table-wrap" id="ch-table"></div></div>';
|
||
var channels = [];
|
||
var F = { q: '', kind: '', grp: '', state: '', hideScrambled: false, hideBroken: false, noIcon: false, noEpg: false };
|
||
try { Object.assign(F, JSON.parse(localStorage.getItem('sdvb-chfilter') || '{}'), { q: '' }); } catch (e) {}
|
||
/** Why a channel cannot play: no bound service. */
|
||
function problem(c) {
|
||
if (c.service_id == null || !c.service) return 'no service';
|
||
return '';
|
||
}
|
||
/** The scan timed out before the service's PMT arrived – codecs are not known yet (the channel may play fine). */
|
||
function unknownStreams(c) {
|
||
var s = c.service;
|
||
return !!s && !s.video && !(s.audio || []).length;
|
||
}
|
||
function shown() {
|
||
var q = F.q.toLowerCase();
|
||
return channels.filter(function (c) {
|
||
var s = c.service || {};
|
||
if (q && c.name.toLowerCase().indexOf(q) < 0 && String(c.number) !== q) return false;
|
||
if (F.kind && (c.kind || 'other') !== F.kind && !(F.kind === 'other' && c.kind !== 'tv' && c.kind !== 'radio')) return false;
|
||
if (F.grp && c.grp !== F.grp) return false;
|
||
if (F.state === 'on' && !c.enabled) return false;
|
||
if (F.state === 'off' && c.enabled) return false;
|
||
if (F.hideScrambled && s.scrambled) return false;
|
||
if (F.hideBroken && problem(c)) return false;
|
||
if (F.noIcon && c.icon) return false;
|
||
if (F.noEpg && c.now) return false;
|
||
return true;
|
||
});
|
||
}
|
||
function saveFilters() { try { localStorage.setItem('sdvb-chfilter', JSON.stringify(F)); } catch (e) {} }
|
||
function renderFilters() {
|
||
var groups = [];
|
||
channels.forEach(function (c) { if (c.grp && groups.indexOf(c.grp) < 0) groups.push(c.grp); });
|
||
var count = function (fn) { return channels.filter(fn).length; };
|
||
var opt = function (v, label, cur) { return '<option value="' + esc(v) + '"' + (v === cur ? ' selected' : '') + '>' + esc(T(label)) + '</option>'; };
|
||
var chk = function (k, label, n) { return '<label class="check"><input type="checkbox" data-f="' + k + '"' + (F[k] ? ' checked' : '') + '> ' + esc(T(label)) + ' <span class="muted">(' + n + ')</span></label>'; };
|
||
$('#ch-filters').innerHTML = '<input id="chf-q" placeholder="' + esc(T('Search channel…')) + '" value="' + esc(F.q) + '">' +
|
||
'<select data-s="kind">' + opt('', 'All types', F.kind) + opt('tv', 'TV', F.kind) + opt('radio', 'Radio', F.kind) + opt('other', 'Other / data', F.kind) + '</select>' +
|
||
'<select data-s="grp">' + opt('', 'All groups', F.grp) + groups.map(function (g) { return opt(g, g, F.grp); }).join('') + '</select>' +
|
||
'<select data-s="state">' + opt('', 'Enabled and disabled', F.state) + opt('on', 'Enabled only', F.state) + opt('off', 'Disabled only', F.state) + '</select>' +
|
||
chk('hideScrambled', 'Hide scrambled', count(function (c) { return (c.service || {}).scrambled; })) +
|
||
chk('hideBroken', 'Hide broken', count(function (c) { return !!problem(c); })) +
|
||
chk('noIcon', 'Only without icon', count(function (c) { return !c.icon; })) +
|
||
chk('noEpg', 'Only without EPG now', count(function (c) { return !c.now; })) +
|
||
'<span class="spacer"></span><span class="muted small mono" id="chf-count"></span>' +
|
||
(isAdmin() && count(unknownStreams) ? '<button class="btn small" id="ch-probe">' + esc(T('Detect streams')) + ' (' + count(unknownStreams) + ')</button>' : '') +
|
||
(isAdmin() ? '<button class="btn small" data-bulk="on">Enable shown</button><button class="btn small" data-bulk="off">Disable shown</button><button class="btn small danger" data-bulk="del">Delete shown</button>' : '');
|
||
var q = $('#chf-q');
|
||
q.addEventListener('input', function () { F.q = q.value; renderTable(); });
|
||
$$('[data-s]', $('#ch-filters')).forEach(function (sel) { sel.addEventListener('change', function () { F[sel.getAttribute('data-s')] = sel.value; saveFilters(); renderTable(); }); });
|
||
$$('[data-f]', $('#ch-filters')).forEach(function (i) { i.addEventListener('change', function () { F[i.getAttribute('data-f')] = i.checked; saveFilters(); renderTable(); }); });
|
||
$$('[data-bulk]', $('#ch-filters')).forEach(function (b) { b.addEventListener('click', function () { bulk(b.getAttribute('data-bulk')); }); });
|
||
var pb = $('#ch-probe');
|
||
if (pb) pb.addEventListener('click', function () {
|
||
pb.disabled = true;
|
||
api('POST', '/api/channels/probe').then(function (r) {
|
||
if (!r.channels) { toast(T('Stream detection is already running')); return; }
|
||
toast(T('Detecting streams of') + ' ' + r.channels + ' ' + T('channels on') + ' ' + r.muxes + ' ' + T('muxes…'));
|
||
setTimeout(reload, (r.muxes * 7 + 4) * 1000);
|
||
}).catch(fail);
|
||
});
|
||
}
|
||
function bulk(action) {
|
||
var list = shown();
|
||
if (!list.length) return;
|
||
if (action === 'del' && !confirmBox('Delete ' + list.length + ' channels? (services stay in the database)')) return;
|
||
var jobs = list.filter(function (c) { return action === 'del' || c.enabled !== (action === 'on'); }).map(function (c) {
|
||
return action === 'del' ? api('DELETE', '/api/channels/' + c.id) : api('PUT', '/api/channels/' + c.id, { enabled: action === 'on' });
|
||
});
|
||
Promise.all(jobs).then(function () { toast(T('Updated channels:') + ' ' + jobs.length); reload(); }).catch(fail);
|
||
}
|
||
function render() { renderFilters(); renderTable(); }
|
||
function renderTable() {
|
||
var list = shown();
|
||
var cnt = $('#chf-count');
|
||
if (cnt) cnt.textContent = list.length + ' / ' + channels.length;
|
||
$('#ch-table').innerHTML = !channels.length ? '<div class="empty">No channels. Run a scan on the <a href="#/tuners">Tuners</a> page.</div>' :
|
||
!list.length ? '<div class="empty">No channels match the filters.</div>' :
|
||
'<table><thead><tr><th></th><th class="num">No.</th><th>Logo</th><th>Name</th><th>Group</th><th>Codecs</th><th>Mux</th><th>Now</th><th>Enabled</th><th>Public link</th><th></th></tr></thead><tbody>' +
|
||
list.map(function (c) {
|
||
var s = c.service || {};
|
||
var pr = problem(c);
|
||
return '<tr data-id="' + c.id + '" draggable="' + (isAdmin() ? 'true' : 'false') + '"' + (c.enabled ? '' : ' class="off"') + '><td class="drag">⠿</td><td class="num">' + c.number + '</td><td>' + logo(c) + '</td><td><b>' + esc(c.name) + '</b>' +
|
||
(pr ? ' <span class="pill err">' + esc(T(pr)) + '</span>' : '') + (!pr && unknownStreams(c) ? ' <span class="pill" title="' + esc(T('The scan did not see this service\'s stream list in time. It is filled in when the channel is played or with “Detect streams”.')) + '">' + esc(T('streams unknown')) + '</span>' : '') + (s.scrambled ? ' <span class="pill warn">scrambled</span>' : '') + (c.kind === 'radio' ? ' <span class="pill">radio</span>' : '') + '</td><td>' + esc(c.grp) + '</td>' +
|
||
'<td class="small mono">' + esc([s.video].concat(s.audio || []).filter(Boolean).join(' · ')) + '</td><td class="small muted">' + esc(c.mux || '') + '</td>' +
|
||
'<td class="small">' + (c.now ? esc(c.now.title) : '<span class="muted">–</span>') + '</td>' +
|
||
'<td>' + sw(c.enabled, 'data-en="' + c.id + '"' + (isAdmin() ? '' : ' disabled')) + '</td>' +
|
||
'<td>' + sw(c.share_enabled, 'data-sh="' + c.id + '"' + (isAdmin() ? '' : ' disabled')) + (c.share_enabled && c.share_token ? ' <button class="btn small" data-shcopy="' + esc(c.share_token) + '">Copy link</button>' : '') + '</td>' +
|
||
'<td class="actions-cell"><a class="btn small" href="#/tv/' + c.id + '/play">▶</a> <a class="btn small" href="/playlist/channelid/' + c.id + '" download="' + esc(c.name) + '.m3u" title="VLC">VLC</a>' + (isAdmin() ? ' <button class="btn small" data-edit="' + c.id + '">Edit</button>' : '') + '</td></tr>';
|
||
}).join('') + '</tbody></table>';
|
||
bind();
|
||
}
|
||
function reload() { return loadChannels().then(function (l) { channels = l; render(); }).catch(fail); }
|
||
function bind() {
|
||
$$('[data-en]').forEach(function (i) { i.addEventListener('change', function () { api('PUT', '/api/channels/' + i.getAttribute('data-en'), { enabled: i.checked }).then(reload).catch(fail); }); });
|
||
$$('[data-sh]').forEach(function (i) {
|
||
i.addEventListener('change', function () {
|
||
api('POST', '/api/channels/' + i.getAttribute('data-sh') + '/share', { enabled: i.checked }).then(function (r) {
|
||
if (r.enabled) { copy(location.origin + '/watch/' + r.token); toast('Public link enabled and copied'); }
|
||
reload();
|
||
}).catch(fail);
|
||
});
|
||
});
|
||
$$('[data-shcopy]').forEach(function (b) { b.addEventListener('click', function () { copy(location.origin + '/watch/' + b.getAttribute('data-shcopy')); }); });
|
||
$$('[data-edit]').forEach(function (b) { b.addEventListener('click', function () { editChannel(channels.filter(function (c) { return c.id === +b.getAttribute('data-edit'); })[0]); }); });
|
||
// drag and drop
|
||
var dragId = null;
|
||
$$('#ch-table tr[data-id]').forEach(function (tr) {
|
||
tr.addEventListener('dragstart', function (e) { dragId = +tr.getAttribute('data-id'); tr.classList.add('dragging'); e.dataTransfer.effectAllowed = 'move'; });
|
||
tr.addEventListener('dragend', function () { tr.classList.remove('dragging'); $$('.drop-target').forEach(function (x) { x.classList.remove('drop-target'); }); });
|
||
tr.addEventListener('dragover', function (e) { e.preventDefault(); $$('.drop-target').forEach(function (x) { x.classList.remove('drop-target'); }); tr.classList.add('drop-target'); });
|
||
tr.addEventListener('drop', function (e) {
|
||
e.preventDefault();
|
||
var target = +tr.getAttribute('data-id');
|
||
if (dragId == null || dragId === target) return;
|
||
var ids = channels.map(function (c) { return c.id; }).filter(function (x) { return x !== dragId; });
|
||
ids.splice(ids.indexOf(target), 0, dragId);
|
||
api('POST', '/api/channels/order', { ids: ids }).then(function () { toast('Order saved'); reload(); }).catch(fail);
|
||
});
|
||
});
|
||
}
|
||
function editChannel(c) {
|
||
api('GET', '/api/services').then(function (services) {
|
||
var body = modal('Channel: ' + c.name,
|
||
'<div class="form-grid"><label>Number<input type="number" name="number" value="' + c.number + '" min="0"></label>' +
|
||
'<label>Name<input name="name" value="' + esc(c.name) + '"></label><label>Group<input name="grp" value="' + esc(c.grp) + '" list="grp-list"></label>' +
|
||
'<label class="full">Service (source)<select name="service_id"><option value="">— none —</option>' + services.map(function (s) {
|
||
return '<option value="' + s.id + '"' + (s.id === c.service_id ? ' selected' : '') + '>' + esc(s.name + ' · SID ' + s.sid + ' · ' + s.kind + (s.video ? ' · ' + s.video : '')) + '</option>';
|
||
}).join('') + '</select></label>' +
|
||
'<label class="full">EPG ID (XMLTV)<input name="epg_id" list="xmltv-ids" value="' + esc(c.epg_id) + '" placeholder="empty = automatic match by name"></label>' +
|
||
'<datalist id="xmltv-ids"></datalist>' +
|
||
'<label class="full">Icon URL<input name="icon" value="' + esc(c.icon === 'local' ? '' : c.icon) + '" placeholder="https://… or upload a file below"></label>' +
|
||
'<div class="full row">' + logo(c) + '<input type="file" id="icon-file" accept="image/*"><button class="btn small" id="icon-find">Find automatically</button>' + (c.icon ? '<button class="btn small danger" id="icon-del">Remove icon</button>' : '') + '</div></div>' +
|
||
'<datalist id="grp-list"><option>TV</option><option>Radio</option><option>Information</option><option>Sport</option><option>Children</option><option>Movies</option></datalist>' +
|
||
'<div class="modal-foot"><button class="btn danger" id="ch-del">Delete channel</button><span style="flex:1"></span><button class="btn" id="ch-cancel">Cancel</button><button class="btn primary" id="ch-save">Save</button></div>');
|
||
var v = function (n) { return $('[name=' + n + ']', body).value; };
|
||
api('GET', '/api/epg/xmltv/channels').then(function (list) {
|
||
var dl = $('#xmltv-ids', body);
|
||
if (dl) dl.innerHTML = list.slice(0, 5000).map(function (x) { return '<option value="' + esc(x.id) + '">' + esc(x.names.join(' / ')) + '</option>'; }).join('');
|
||
}).catch(function () {});
|
||
$('#ch-cancel', body).addEventListener('click', closeModal);
|
||
$('#ch-save', body).addEventListener('click', function () {
|
||
var icon = v('icon').trim();
|
||
var data = { number: +v('number'), name: v('name'), grp: v('grp'), epg_id: v('epg_id'), service_id: v('service_id') ? +v('service_id') : null };
|
||
if (icon || c.icon !== 'local') data.icon = icon;
|
||
var file = $('#icon-file', body).files[0];
|
||
api('PUT', '/api/channels/' + c.id, data).then(function () {
|
||
if (file) return file.arrayBuffer().then(function (buf) { return api('POST', '/api/channels/' + c.id + '/icon', buf, true); });
|
||
}).then(function () { toast('Saved'); closeModal(); reload(); }).catch(fail);
|
||
});
|
||
$('#ch-del', body).addEventListener('click', function () {
|
||
if (!confirmBox('Delete channel “' + c.name + '”? (the service stays in the database)')) return;
|
||
api('DELETE', '/api/channels/' + c.id).then(function () { closeModal(); reload(); }).catch(fail);
|
||
});
|
||
$('#icon-find', body).addEventListener('click', function () {
|
||
api('POST', '/api/channels/icons/search', { ids: [c.id], overwrite: true }).then(function (r) {
|
||
if (r.found.length) { toast('Icon found'); closeModal(); reload(); } else toast('No icon found for “' + c.name + '”', true);
|
||
}).catch(fail);
|
||
});
|
||
var d = $('#icon-del', body);
|
||
if (d) d.addEventListener('click', function () { api('DELETE', '/api/channels/' + c.id + '/icon').then(function () { closeModal(); reload(); }).catch(fail); });
|
||
}).catch(fail);
|
||
}
|
||
if (isAdmin()) {
|
||
var iconBtn = $('#ch-icons');
|
||
function pollIcons() {
|
||
api('GET', '/api/channels/icons/search').then(function (j) {
|
||
if (!$('#ch-icons')) return;
|
||
if (j.running) {
|
||
iconBtn.disabled = true;
|
||
iconBtn.textContent = T('Finding icons…') + ' ' + j.done + '/' + j.total;
|
||
// show icons as they arrive
|
||
if (j.found.length !== lastFound) { lastFound = j.found.length; reload(); }
|
||
setTimeout(pollIcons, 1500);
|
||
return;
|
||
}
|
||
iconBtn.disabled = false;
|
||
iconBtn.textContent = T('Find icons');
|
||
if (iconsStarted) {
|
||
iconsStarted = false;
|
||
toast('Found ' + j.found.length + ' icons' + (j.missing.length ? '\nWithout icon: ' + j.missing.join(', ') : ''), !j.found.length && j.missing.length);
|
||
reload();
|
||
}
|
||
}).catch(function () { iconBtn.disabled = false; });
|
||
}
|
||
var iconsStarted = false, lastFound = 0;
|
||
iconBtn.addEventListener('click', function () {
|
||
iconBtn.disabled = true;
|
||
iconsStarted = true; lastFound = 0;
|
||
api('POST', '/api/channels/icons/search', {}).then(pollIcons).catch(function (e) { iconBtn.disabled = false; fail(e); });
|
||
});
|
||
pollIcons();
|
||
$('#ch-renum').addEventListener('click', function () {
|
||
if (!confirmBox('Assign numbers 1..n in the current order?')) return;
|
||
api('POST', '/api/channels/order', { ids: channels.map(function (c) { return c.id; }) }).then(reload).catch(fail);
|
||
});
|
||
$('#ch-add').addEventListener('click', function () {
|
||
api('GET', '/api/services').then(function (services) {
|
||
var free = services.filter(function (s) { return s.channel_id == null; });
|
||
var body = modal('Add channels from services', free.length ? '<p class="muted">Services without a channel:</p><div class="table-wrap"><table><tbody>' + free.map(function (s) {
|
||
return '<tr><td><input type="checkbox" value="' + s.id + '"></td><td><b>' + esc(s.name) + '</b></td><td class="small">' + esc(s.provider) + '</td><td><span class="pill">' + esc(s.kind) + '</span>' + (s.scrambled ? ' <span class="pill warn">scrambled</span>' : '') + '</td><td class="small mono">' + esc([s.video].concat(s.audio).filter(Boolean).join(' · ')) + '</td></tr>';
|
||
}).join('') + '</tbody></table></div><div class="modal-foot"><button class="btn primary" id="svc-add">Add selected</button></div>' : '<div class="empty">All services already have channels.</div>');
|
||
var b = $('#svc-add', body);
|
||
if (b) b.addEventListener('click', function () {
|
||
var ids = $$('input:checked', body).map(function (i) { return +i.value; });
|
||
api('POST', '/api/channels', { service_ids: ids }).then(function (r) { toast('Added ' + r.ids.length + ' channels'); closeModal(); reload(); }).catch(fail);
|
||
});
|
||
}).catch(fail);
|
||
});
|
||
}
|
||
reload();
|
||
}
|
||
|
||
// ------------------------------------------------------------ RECORDINGS
|
||
var REC_STATUS = { scheduled: ['scheduled', 'blue'], recording: ['recording', 'err'], completed: ['completed', 'ok'], failed: ['error', 'err'], cancelled: ['cancelled', ''] };
|
||
function pageRecordings(view) {
|
||
view.innerHTML = head('Video recorder', 'Recordings', 'Schedule from the EPG or manually. Play finished recordings in the browser or download them as .ts.',
|
||
isAdmin() ? '<button class="btn primary" id="rec-new">+ New recording</button>' : '') +
|
||
'<div class="panel"><div class="tabs" id="rec-tabs"><button data-t="upcoming" class="active">Scheduled & running</button><button data-t="schedule">Schedule</button><button data-t="done">Finished</button><button data-t="failed">Failed / cancelled</button><button data-t="rules">Rules (series)</button></div><div class="table-wrap" id="rec-table"></div></div>';
|
||
var tab = 'upcoming', recs = [];
|
||
/** Timeline of upcoming recordings, one row per day, with tuner-conflict warnings. */
|
||
function renderSchedule() {
|
||
api('GET', '/api/recordings/schedule').then(function (r) {
|
||
var list = r.recordings.slice().sort(function (a, b) { return a.start - b.start; });
|
||
if (!list.length) { $('#rec-table').innerHTML = '<div class="empty">' + esc(T('Nothing scheduled. Pick a programme in the TV guide or add a rule.')) + '</div>'; return; }
|
||
var days = {};
|
||
list.forEach(function (x) {
|
||
var d = new Date((x.start - x.pre_padding) * 1000); d.setHours(0, 0, 0, 0);
|
||
var key = d.getTime() / 1000;
|
||
(days[key] = days[key] || []).push(x);
|
||
// a recording crossing midnight also appears on the next day
|
||
var end = x.stop + x.post_padding;
|
||
if (end > key + 86400) (days[key + 86400] = days[key + 86400] || []).push(x);
|
||
});
|
||
var t = now();
|
||
var muxColors = {}, palette = ['var(--accent)', 'var(--blue)', 'var(--green)', 'var(--yellow)', '#c084fc', '#f472b6', '#2dd4bf'];
|
||
var color = function (m) { if (!(m in muxColors)) muxColors[m] = palette[Object.keys(muxColors).length % palette.length]; return muxColors[m]; };
|
||
var html = '<p class="hint">' + esc(T('Each bar is one recording (padding included); colours mark the multiplex – recordings on the same multiplex share one tuner.')) + ' ' +
|
||
esc(T('Tuners:')) + ' <b>' + r.adapters + '</b>' + (r.conflicts ? ' · <span class="error-text">' + esc(T('conflicts:')) + ' <b>' + r.conflicts + '</b></span>' : '') + '</p>';
|
||
Object.keys(days).sort().forEach(function (k) {
|
||
var day = +k;
|
||
var lanes = [];
|
||
days[k].forEach(function (x) {
|
||
var s0 = Math.max(x.start - x.pre_padding, day), s1 = Math.min(x.stop + x.post_padding, day + 86400);
|
||
var lane = 0;
|
||
while (lanes[lane] && lanes[lane] > s0) lane++;
|
||
lanes[lane] = s1;
|
||
x._lane = lane; x._s0 = s0; x._s1 = s1;
|
||
});
|
||
var d = new Date(day * 1000);
|
||
var names = [T('Sunday'), T('Monday'), T('Tuesday'), T('Wednesday'), T('Thursday'), T('Friday'), T('Saturday')];
|
||
html += '<div class="sched-day"><div class="sched-head"><b>' + names[d.getDay()] + '</b> <span class="muted">' + dmy(day) + '</span></div>' +
|
||
'<div class="sched-grid" style="height:' + (lanes.length * 26 + 18) + 'px">' +
|
||
[0, 3, 6, 9, 12, 15, 18, 21].map(function (h) { return '<span class="sched-tick" style="left:' + (h / 24 * 100) + '%">' + pad(h) + ':00</span>'; }).join('') +
|
||
(t >= day && t < day + 86400 ? '<span class="sched-now" style="left:' + ((t - day) / 864) + '%"></span>' : '') +
|
||
days[k].map(function (x) {
|
||
var left = (x._s0 - day) / 864, width = Math.max(0.4, (x._s1 - x._s0) / 864);
|
||
var cls = 'sched-bar' + (x.conflict ? ' conflict' : '') + (x.status === 'recording' ? ' live' : '');
|
||
return '<div class="' + cls + '" style="left:' + left + '%;width:' + width + '%;top:' + (x._lane * 26 + 16) + 'px;--c:' + color(x.mux_id) + '" title="' + esc(x.title + '\n' + x.channel_name + '\n' + hm(x.start) + '–' + hm(x.stop) + (x.conflict ? '\n' + T('Conflict: not enough tuners') : '')) + '">' +
|
||
(x.conflict ? '⚠ ' : '') + esc(x.title) + ' <span class="muted">' + esc(x.channel_name) + '</span></div>';
|
||
}).join('') + '</div></div>';
|
||
});
|
||
html += '<table style="margin-top:12px"><thead><tr><th>Start</th><th>End</th><th>Title</th><th>Channel</th><th>Status</th></tr></thead><tbody>' + list.map(function (x) {
|
||
var st = REC_STATUS[x.status] || [x.status, ''];
|
||
return '<tr' + (x.conflict ? ' class="row-warn"' : '') + '><td class="mono small">' + dt(x.start) + '</td><td class="mono small">' + hm(x.stop) + '</td><td><b>' + esc(x.title) + '</b></td><td>' + esc(x.channel_name) + '</td><td><span class="pill ' + st[1] + '">' + st[0] + '</span>' + (x.conflict ? ' <span class="pill err">' + esc(T('conflict')) + '</span>' : '') + '</td></tr>';
|
||
}).join('') + '</tbody></table>';
|
||
$('#rec-table').innerHTML = html;
|
||
}).catch(fail);
|
||
}
|
||
function renderRules() {
|
||
Promise.all([api('GET', '/api/autorec'), loadChannels()]).then(function (r) {
|
||
var rules = r[0], chs = r[1];
|
||
var chName = function (id) { var c = chs.filter(function (x) { return x.id === id; })[0]; return c ? c.name : '—'; };
|
||
$('#rec-table').innerHTML = '<p class="hint">A rule schedules recordings of every EPG programme (next 48 h) whose title matches the pattern – a title fragment or a regular expression.</p>' +
|
||
(isAdmin() ? '<div class="row" style="margin:8px 0"><button class="btn small primary" id="rule-add">+ New rule</button></div>' : '') +
|
||
(rules.length ? '<table><thead><tr><th>Name</th><th>Pattern</th><th>Channel</th><th>Active</th><th></th></tr></thead><tbody>' + rules.map(function (x) {
|
||
return '<tr><td><b>' + esc(x.name) + '</b></td><td class="mono small">' + esc(x.pattern) + '</td><td>' + (x.channel_id ? esc(chName(x.channel_id)) : T('all')) + '</td>' +
|
||
'<td>' + sw(x.enabled, 'data-rule-en="' + x.id + '"' + (isAdmin() ? '' : ' disabled')) + '</td><td class="actions-cell">' +
|
||
(isAdmin() ? '<button class="btn small" data-rule-edit="' + x.id + '">Edit</button> <button class="btn small danger" data-rule-del="' + x.id + '">Delete</button>' : '') + '</td></tr>';
|
||
}).join('') + '</tbody></table>' : '<div class="empty">No rules. Add e.g. “Teleexpress” or “^News$”.</div>');
|
||
function edit(rule) {
|
||
rule = rule || { name: '', pattern: '', channel_id: null, enabled: true };
|
||
var body = modal(rule.id ? 'Edit rule' : 'New rule',
|
||
'<div class="form-grid"><label>Name<input name="name" value="' + esc(rule.name) + '"></label>' +
|
||
'<label>Channel<select name="ch"><option value="">all</option>' + chs.map(function (c) { return '<option value="' + c.id + '"' + (c.id === rule.channel_id ? ' selected' : '') + '>' + c.number + ' · ' + esc(c.name) + '</option>'; }).join('') + '</select></label>' +
|
||
'<label class="full">Title pattern<input name="pattern" value="' + esc(rule.pattern) + '" placeholder="e.g. Teleexpress or ^News$"></label></div>' +
|
||
'<div class="label" style="margin-top:12px">Matching programmes (48 h)</div><div id="rule-prev" class="day-list"></div>' +
|
||
'<div class="modal-foot"><button class="btn primary" id="rule-save">Save</button></div>');
|
||
var timer = null;
|
||
function preview() {
|
||
var pat = $('[name=pattern]', body).value, ch = $('[name=ch]', body).value;
|
||
if (!pat.trim()) { $('#rule-prev', body).innerHTML = ''; return; }
|
||
api('GET', '/api/autorec/preview?pattern=' + encodeURIComponent(pat) + (ch ? '&channel_id=' + ch : '')).then(function (evs) {
|
||
$('#rule-prev', body).innerHTML = evs.length ? evs.map(function (e) { return '<div class="ev"><span class="tm">' + hm(e.start) + '</span><span>' + esc(e.title) + ' <span class="muted small">' + esc(chName(e.channel_id)) + ' · ' + dmy(e.start) + '</span></span><span></span></div>'; }).join('') : '<div class="muted small">' + esc(T('No matching programmes in the EPG.')) + '</div>';
|
||
}).catch(function () {});
|
||
}
|
||
['input', 'change'].forEach(function (ev) { body.addEventListener(ev, function () { clearTimeout(timer); timer = setTimeout(preview, 300); }); });
|
||
preview();
|
||
$('#rule-save', body).addEventListener('click', function () {
|
||
var ch = $('[name=ch]', body).value;
|
||
var data = { name: $('[name=name]', body).value, pattern: $('[name=pattern]', body).value, channel_id: ch ? +ch : null, enabled: rule.enabled };
|
||
api(rule.id ? 'PUT' : 'POST', '/api/autorec' + (rule.id ? '/' + rule.id : ''), data).then(function (r) {
|
||
toast(T('Rule saved') + (r.scheduled ? ' · ' + T('recordings scheduled:') + ' ' + r.scheduled : ''));
|
||
closeModal(); renderRules();
|
||
}).catch(fail);
|
||
});
|
||
}
|
||
var add = $('#rule-add');
|
||
if (add) add.addEventListener('click', function () { edit(null); });
|
||
$$('[data-rule-edit]').forEach(function (b) { b.addEventListener('click', function () { edit(rules.filter(function (x) { return x.id === +b.getAttribute('data-rule-edit'); })[0]); }); });
|
||
$$('[data-rule-del]').forEach(function (b) {
|
||
b.addEventListener('click', function () { if (confirmBox('Delete the rule? Recordings scheduled by it will be cancelled.')) api('DELETE', '/api/autorec/' + b.getAttribute('data-rule-del')).then(function () { renderRules(); reload(); }).catch(fail); });
|
||
});
|
||
$$('[data-rule-en]').forEach(function (i) {
|
||
i.addEventListener('change', function () {
|
||
var x = rules.filter(function (y) { return y.id === +i.getAttribute('data-rule-en'); })[0];
|
||
api('PUT', '/api/autorec/' + x.id, { name: x.name, pattern: x.pattern, channel_id: x.channel_id, enabled: i.checked }).then(renderRules).catch(fail);
|
||
});
|
||
});
|
||
}).catch(fail);
|
||
}
|
||
function render() {
|
||
if (tab === 'rules') return;
|
||
if (tab === 'schedule') { renderSchedule(); return; }
|
||
var list = recs.filter(function (r) {
|
||
return tab === 'upcoming' ? (r.status === 'scheduled' || r.status === 'recording') : tab === 'done' ? r.status === 'completed' : (r.status === 'failed' || r.status === 'cancelled');
|
||
});
|
||
if (tab === 'upcoming') list.sort(function (a, b) { return a.start - b.start; });
|
||
$('#rec-table').innerHTML = list.length ? '<table><thead><tr><th>Status</th><th>Title</th><th>Channel</th><th>Start</th><th>End</th><th class="num">Time</th><th class="num">Size</th><th></th></tr></thead><tbody>' +
|
||
list.map(function (r) {
|
||
var st = REC_STATUS[r.status] || [r.status, ''];
|
||
return '<tr><td><span class="pill ' + st[1] + '">' + st[0] + '</span></td><td><b>' + esc(r.title) + '</b>' + (r.error ? '<div class="small error-text">' + esc(r.error) + '</div>' : '') + '</td><td>' + esc(r.channel_name) + '</td>' +
|
||
'<td class="mono small">' + dt(r.start) + '</td><td class="mono small">' + hm(r.stop) + '</td><td class="num">' + (r.duration ? dur(r.duration) : dur(r.stop - r.start)) + '</td><td class="num">' + (r.size ? bytes(r.size) : '–') + '</td>' +
|
||
'<td class="actions-cell">' + (r.autorec_id ? '<span class="pill blue" title="' + esc(T('From a rule')) + '">R</span> ' : '') + (r.file && r.size ? '<button class="btn small" data-play="' + r.id + '">▶ Play</button> <a class="btn small" href="/recordings/' + r.id + '/file" download>Download</a> ' : '') +
|
||
(isAdmin() && (r.status === 'scheduled' || r.status === 'recording') ? '<button class="btn small" data-stop="' + r.id + '">' + (r.status === 'recording' ? '■ Stop' : 'Cancel') + '</button> ' : '') +
|
||
(isAdmin() ? '<button class="btn small danger" data-del="' + r.id + '">Delete</button>' : '') + '</td></tr>';
|
||
}).join('') + '</tbody></table>' : '<div class="empty">No recordings in this category.</div>';
|
||
$$('[data-play]').forEach(function (b) {
|
||
b.addEventListener('click', function () {
|
||
var r = recs.filter(function (x) { return x.id === +b.getAttribute('data-play'); })[0];
|
||
var body = modal(r.title + ' · ' + r.channel_name, '<div class="player" id="rec-player"></div><p class="muted small">' + dt(r.start) + ' · ' + dur(r.duration) + ' · ' + bytes(r.size) + '</p>', true);
|
||
var p = window.SDVB.createPlayer($('#rec-player', body), { src: '/recordings/' + r.id + '/index.m3u8', live: false, profile: 'pass' });
|
||
app.modalCleanup = function () { p.destroy(); };
|
||
});
|
||
});
|
||
$$('[data-stop]').forEach(function (b) { b.addEventListener('click', function () { api('POST', '/api/recordings/' + b.getAttribute('data-stop') + '/stop').then(reload).catch(fail); }); });
|
||
$$('[data-del]').forEach(function (b) {
|
||
b.addEventListener('click', function () {
|
||
if (!confirmBox('Delete the recording together with its file?')) return;
|
||
api('DELETE', '/api/recordings/' + b.getAttribute('data-del')).then(reload).catch(fail);
|
||
});
|
||
});
|
||
}
|
||
function reload() { return api('GET', '/api/recordings').then(function (l) { recs = l; render(); }).catch(fail); }
|
||
$$('#rec-tabs button').forEach(function (b) {
|
||
b.addEventListener('click', function () { tab = b.getAttribute('data-t'); $$('#rec-tabs button').forEach(function (x) { x.classList.toggle('active', x === b); }); if (tab === 'rules') renderRules(); else render(); });
|
||
});
|
||
(function () {
|
||
var h = location.hash.split('/')[2];
|
||
if (h && $('#rec-tabs [data-t="' + h + '"]')) $('#rec-tabs [data-t="' + h + '"]').click();
|
||
})();
|
||
|
||
var nb = $('#rec-new');
|
||
if (nb) nb.addEventListener('click', function () {
|
||
loadChannels().then(function (chs) {
|
||
var t = now();
|
||
var body = modal('New recording', '<div class="form-grid"><label class="full">Channel<select name="ch">' + chs.map(function (c) { return '<option value="' + c.id + '">' + c.number + ' · ' + esc(c.name) + '</option>'; }).join('') + '</select></label>' +
|
||
'<label class="full">Title<input name="title" value="' + esc(T('Manual recording')) + '"></label><label>Starts<input type="datetime-local" name="start" value="' + toLocalInput(t) + '"></label>' +
|
||
'<label>End<input type="datetime-local" name="stop" value="' + toLocalInput(t + 3600) + '"></label></div><div class="modal-foot"><button class="btn primary" id="rec-save">Schedule recording</button></div>');
|
||
$('#rec-save', body).addEventListener('click', function () {
|
||
api('POST', '/api/recordings', { channel_id: +$('[name=ch]', body).value, title: $('[name=title]', body).value, start: fromLocalInput($('[name=start]', body).value), stop: fromLocalInput($('[name=stop]', body).value) })
|
||
.then(function () { toast('Scheduled'); closeModal(); reload(); }).catch(fail);
|
||
});
|
||
}).catch(fail);
|
||
});
|
||
reload();
|
||
app.timers.push(setInterval(function () { if (!document.hidden) reload(); }, 5000));
|
||
}
|
||
|
||
// ------------------------------------------------------------ TUNERS
|
||
function pageTuners(view) {
|
||
view.innerHTML = head('Hardware & muxes', 'Tuners & scanning', 'DVB-T/T2/C cards (e.g. Si2168), frequency scanning and saved muxes.',
|
||
isAdmin() ? '<button class="btn" id="ad-refresh">Detect adapters</button>' : '') +
|
||
'<div class="grid g2"><div class="panel"><header><h2>Adapters</h2></header><div id="ad-list"></div></div>' +
|
||
'<div class="panel"><header><h2>Scanning</h2><span id="scan-pill"></span></header><div id="scan-box"></div></div></div>' +
|
||
'<div class="panel"><header><h2>Muxes</h2>' + (isAdmin() ? '<button class="btn small" id="mux-add">+ Add manually</button>' : '') + '</header><div class="table-wrap" id="mux-table"></div></div>';
|
||
var presets = [];
|
||
function adapters() {
|
||
api('GET', '/api/adapters').then(function (list) {
|
||
$('#ad-list').innerHTML = list.length ? '<table><tbody>' + list.map(function (a) {
|
||
return '<tr><td><b>' + esc(a.name) + '</b><div class="small muted mono">' + esc(a.id + ' · ' + a.path) + '</div></td><td class="small">' + esc(a.delivery_systems.join(' / ')) + '</td>' +
|
||
'<td>' + (a.active ? '<span class="pill ok">' + esc(a.active.tuning) + '</span>' : a.busy ? '<span class="pill warn">scanning</span>' : '<span class="pill">idle</span>') + '</td>' +
|
||
'<td>' + sw(a.enabled, 'data-ad="' + esc(a.id) + '"' + (isAdmin() ? '' : ' disabled')) + '</td></tr>';
|
||
}).join('') + '</tbody></table>' : '<div class="empty">No DVB cards detected. Check <code>ls /dev/dvb</code>, the driver and firmware (for Si2168: <code>dvb-demod-si2168-*.fw</code>) and membership in group <code>video</code>.</div>';
|
||
$$('[data-ad]').forEach(function (i) { i.addEventListener('change', function () { api('PUT', '/api/adapters/' + i.getAttribute('data-ad'), { enabled: i.checked }).then(adapters).catch(fail); }); });
|
||
scanForm(list);
|
||
}).catch(fail);
|
||
}
|
||
var formBuilt = false;
|
||
function scanForm(list) {
|
||
if (formBuilt || !isAdmin()) return;
|
||
formBuilt = true;
|
||
$('#scan-box').innerHTML = '<div class="form-grid"><label>Adapter<select name="adapter"><option value="">automatic</option>' + list.map(function (a) { return '<option value="' + esc(a.id) + '">' + esc(a.id + ' – ' + a.name) + '</option>'; }).join('') + '</select></label>' +
|
||
'<label>Frequency list<select name="preset">' + presets.map(function (p) { return '<option value="' + p.id + '">' + esc(p.name) + '</option>'; }).join('') + '<option value="known">Rescan: saved muxes</option></select></label>' +
|
||
'<label class="full hidden" id="freq-box">Frequencies (MHz, comma separated)<input name="freqs" placeholder="474, 538, 618"></label>' +
|
||
'<div class="full row"><label class="check"><input type="checkbox" name="t2" checked> DVB-T2</label><label class="check"><input type="checkbox" name="t" checked> DVB-T</label>' +
|
||
'<label class="check"><input type="checkbox" name="c"> DVB-C</label>' +
|
||
'<label class="check">Bandwidth <select name="bw"><option>8</option><option>7</option><option>6</option></select> MHz</label>' +
|
||
'<label class="check"><input type="checkbox" name="nit" checked> Follow further muxes from the NIT</label></div>' +
|
||
'<div class="full row hidden" id="dvbc-box"><label>Symbol rate (kS/s)<input name="sr" value="6900, 6875"></label>' +
|
||
'<label>Modulation<select name="mod"><option value="auto">auto</option><option value="qam256">QAM-256</option><option value="qam128">QAM-128</option><option value="qam64">QAM-64</option><option value="all">QAM-64/128/256</option></select></label></div></div>' +
|
||
'<div class="row" style="margin-top:10px"><button class="btn primary" id="scan-go">Start scan</button><button class="btn danger hidden" id="scan-stop">Stop</button></div>' +
|
||
'<div id="scan-progress" style="margin-top:10px"></div><p class="hint" id="idle-scan-info"></p>';
|
||
lastScanJson = '';
|
||
var sel = $('[name=preset]');
|
||
function syncScanForm() {
|
||
$('#freq-box').classList.toggle('hidden', sel.value !== 'custom');
|
||
if (sel.value === 'dvbc-eu') { $('[name=c]').checked = true; $('[name=t2]').checked = false; $('[name=t]').checked = false; }
|
||
$('#dvbc-box').classList.toggle('hidden', !$('[name=c]').checked);
|
||
}
|
||
sel.addEventListener('change', syncScanForm);
|
||
$('[name=c]').addEventListener('change', syncScanForm);
|
||
$('#scan-go').addEventListener('click', function () {
|
||
lastScanJson = '';
|
||
var systems = [];
|
||
if ($('[name=t2]').checked) systems.push('dvbt2');
|
||
if ($('[name=t]').checked) systems.push('dvbt');
|
||
if ($('[name=c]').checked) systems.push('dvbc');
|
||
var mod = $('[name=mod]').value;
|
||
var req = { adapter: $('[name=adapter]').value || null, preset: sel.value, systems: systems, bandwidth_mhz: +$('[name=bw]').value,
|
||
frequencies_mhz: $('[name=freqs]').value.split(/[ ,;]+/).filter(Boolean).map(Number), follow_nit: $('[name=nit]').checked,
|
||
symbol_rates_ksps: $('[name=sr]').value.split(/[ ,;]+/).filter(Boolean).map(Number),
|
||
modulations: mod === 'all' ? ['qam256', 'qam64', 'qam128'] : [mod] };
|
||
api('POST', '/api/scan', req).then(function () { toast('Scan started'); clearTimeout(scanTimer); scanLoop(); }).catch(fail);
|
||
});
|
||
$('#scan-stop').addEventListener('click', function () { api('DELETE', '/api/scan').catch(fail); });
|
||
}
|
||
var lastScanRunning = false;
|
||
var lastScanJson = '';
|
||
function scanStatus() {
|
||
return api('GET', '/api/scan').then(function (s) {
|
||
var key = JSON.stringify(s);
|
||
var running = s.running;
|
||
if (key !== lastScanJson) {
|
||
// re-render only when something changed (keeps the log scroll position and selection)
|
||
lastScanJson = key;
|
||
var pct = s.total ? Math.round(s.done * 100 / s.total) : 0;
|
||
var bg = s.idle ? '<span class="pill blue">' + esc(T('background')) + '</span> ' : '';
|
||
$('#scan-pill').innerHTML = running ? bg + '<span class="pill warn">' + pct + '% · ' + esc(s.current) + '</span>' : s.finished ? bg + '<span class="pill ok">finished ' + hm(s.finished) + '</span>' : '';
|
||
var box = $('#scan-progress');
|
||
if (box && (running || s.log.length)) {
|
||
var log = box.querySelector('.log');
|
||
var atBottom = !log || log.scrollTop + log.clientHeight >= log.scrollHeight - 4;
|
||
box.innerHTML = (running ? '<div class="meter"><i style="width:' + pct + '%"></i></div>' : '') +
|
||
'<div class="small muted">Muxes found: <b>' + s.muxes_found + '</b> · services: <b>' + s.services_found + '</b> · new channels: <b>' + s.channels_created + '</b>' + (s.error ? ' · <span class="error-text">' + esc(s.error) + '</span>' : '') + '</div>' +
|
||
'<div class="log">' + esc(s.log.join('\n') || 'Waiting for first results…') + '</div>';
|
||
log = box.querySelector('.log');
|
||
if (atBottom) log.scrollTop = log.scrollHeight;
|
||
}
|
||
var idle = $('#idle-scan-info');
|
||
if (idle && s.idle_scan) {
|
||
idle.textContent = s.idle_scan.enabled
|
||
? T('Background scan of saved muxes when tuners are idle: every') + ' ' + s.idle_scan.every_hours + ' h · ' + T('last:') + ' ' + (s.idle_scan.last ? dt(s.idle_scan.last) : '–')
|
||
: T('Background scanning is off (Settings → Scanning).');
|
||
}
|
||
var go = $('#scan-go'), stop = $('#scan-stop');
|
||
// a manual scan may replace a background one
|
||
if (go) { go.disabled = running && !s.idle; stop.classList.toggle('hidden', !running); }
|
||
}
|
||
if (lastScanRunning && !running) { muxes(); adapters(); }
|
||
lastScanRunning = running;
|
||
return running;
|
||
}).catch(function () { return false; });
|
||
}
|
||
var scanTimer = null;
|
||
function scanLoop() {
|
||
scanStatus().then(function (running) { scanTimer = setTimeout(scanLoop, running ? 1500 : 6000); });
|
||
}
|
||
app.cleanup.push(function () { clearTimeout(scanTimer); });
|
||
function muxes() {
|
||
api('GET', '/api/muxes').then(function (list) {
|
||
$('#mux-table').innerHTML = list.length ? '<table><thead><tr><th>Frequency</th><th>UHF channel</th><th>System</th><th>Network</th><th class="num">TSID</th><th class="num">Services</th><th>Last scan</th><th>EPG</th><th>Enabled</th><th></th></tr></thead><tbody>' +
|
||
list.map(function (m) {
|
||
return '<tr><td class="mono"><b>' + (m.frequency_hz / 1e6).toFixed(1) + ' MHz</b>' + (m.tuned ? ' <span class="pill ok">active</span>' : '') + '</td><td class="mono">' + (m.uhf_channel || '–') + '</td>' +
|
||
'<td>' + esc({ dvbt2: 'DVB-T2', dvbt: 'DVB-T', dvbc: 'DVB-C' }[m.delsys] || m.delsys) + (m.plp_id != null ? ' PLP ' + m.plp_id : '') +
|
||
(m.delsys === 'dvbc' ? ' <span class="small mono muted">' + (m.symbol_rate / 1000) + ' kS/s ' + esc((m.modulation || 'auto').toUpperCase()) + '</span>' : '') + '</td><td>' + esc(m.network_name || '') + '</td><td class="num">' + (m.ts_id == null ? '–' : m.ts_id) + '</td>' +
|
||
'<td class="num"><a href="#" data-svc="' + m.id + '">' + m.services + '</a></td><td class="small mono">' + dt(m.last_scan) + '</td><td class="small mono">' + dt(m.last_epg) + '</td>' +
|
||
'<td>' + sw(m.enabled, 'data-mux-en="' + m.id + '" data-mux=\'' + esc(JSON.stringify({ delsys: m.delsys, frequency_mhz: m.frequency_hz / 1e6, bandwidth_mhz: m.bandwidth_hz / 1e6, plp_id: m.plp_id, symbol_rate_ksps: m.symbol_rate ? m.symbol_rate / 1000 : null, modulation: m.modulation })) + '\'' + (isAdmin() ? '' : ' disabled')) + '</td>' +
|
||
'<td class="actions-cell">' + (isAdmin() ? '<button class="btn small danger" data-mux-del="' + m.id + '">Delete</button>' : '') + '</td></tr>';
|
||
}).join('') + '</tbody></table>' : '<div class="empty">No muxes – run a scan.</div>';
|
||
$$('[data-mux-en]').forEach(function (i) {
|
||
i.addEventListener('change', function () {
|
||
var d = JSON.parse(i.getAttribute('data-mux')); d.enabled = i.checked;
|
||
api('PUT', '/api/muxes/' + i.getAttribute('data-mux-en'), d).then(muxes).catch(fail);
|
||
});
|
||
});
|
||
$$('[data-mux-del]').forEach(function (b) {
|
||
b.addEventListener('click', function () {
|
||
if (!confirmBox('Delete the mux with its services? Channels will lose their source.')) return;
|
||
api('DELETE', '/api/muxes/' + b.getAttribute('data-mux-del')).then(muxes).catch(fail);
|
||
});
|
||
});
|
||
$$('[data-svc]').forEach(function (a) {
|
||
a.addEventListener('click', function (e) {
|
||
e.preventDefault();
|
||
api('GET', '/api/services?mux=' + a.getAttribute('data-svc')).then(function (svcs) {
|
||
modal('Mux services', '<div class="table-wrap"><table><thead><tr><th class="num">SID</th><th class="num">LCN</th><th>Name</th><th>Provider</th><th>Type</th><th>Streams</th><th>Channel</th></tr></thead><tbody>' + svcs.map(function (s) {
|
||
return '<tr><td class="num">' + s.sid + '</td><td class="num">' + (s.lcn == null ? '–' : s.lcn) + '</td><td><b>' + esc(s.name) + '</b>' + (s.scrambled ? ' <span class="pill warn">scrambled</span>' : '') + '</td><td>' + esc(s.provider) + '</td><td>' + esc(s.kind) + '</td>' +
|
||
'<td class="small mono">' + s.streams.map(function (x) { return esc(x.kind + ':' + x.pid + (x.lang ? '/' + x.lang : '')); }).join(' ') + '</td><td>' + (s.channel_id ? '<span class="pill ok">yes</span>' : '–') + '</td></tr>';
|
||
}).join('') + '</tbody></table></div>', true);
|
||
}).catch(fail);
|
||
});
|
||
});
|
||
}).catch(fail);
|
||
}
|
||
api('GET', '/api/scan/presets').then(function (p) { presets = p; adapters(); }).catch(fail);
|
||
muxes();
|
||
scanLoop();
|
||
if (isAdmin()) {
|
||
$('#ad-refresh').addEventListener('click', function () { api('POST', '/api/adapters/refresh').then(function (r) { toast('Adapters detected: ' + r.count); formBuilt = false; adapters(); }).catch(fail); });
|
||
$('#mux-add').addEventListener('click', function () {
|
||
var body = modal('New mux', '<div class="form-grid"><label>System<select name="delsys"><option value="dvbt2">DVB-T2</option><option value="dvbt">DVB-T</option><option value="dvbc">DVB-C</option></select></label>' +
|
||
'<label>Frequency (MHz)<input name="f" type="number" step="0.001" placeholder="538"></label><label>Bandwidth (MHz)<select name="bw"><option>8</option><option>7</option><option>6</option></select></label>' +
|
||
'<label>PLP (DVB-T2, optional)<input name="plp" type="number" min="0" max="255"></label>' +
|
||
'<label>Symbol rate (kS/s, DVB-C)<input name="sr" type="number" value="6900"></label><label>Modulation (DVB-C)<select name="mod"><option value="auto">auto</option><option value="qam256">QAM-256</option><option value="qam128">QAM-128</option><option value="qam64">QAM-64</option></select></label></div>' +
|
||
'<div class="modal-foot"><button class="btn primary" id="mux-save">Add</button></div>');
|
||
$('#mux-save', body).addEventListener('click', function () {
|
||
var plp = $('[name=plp]', body).value;
|
||
api('POST', '/api/muxes', { delsys: $('[name=delsys]', body).value, frequency_mhz: +$('[name=f]', body).value, bandwidth_mhz: +$('[name=bw]', body).value, plp_id: plp === '' ? null : +plp,
|
||
symbol_rate_ksps: +$('[name=sr]', body).value || 6900, modulation: $('[name=mod]', body).value })
|
||
.then(function () { toast('Added – use “Rescan: saved muxes” to read its services'); closeModal(); muxes(); }).catch(fail);
|
||
});
|
||
});
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------ ACCESS
|
||
function pageAccess(view) {
|
||
view.innerHTML = head('Security', 'Access & sharing', 'Playlists for TVs, tokens, access control (ACL) and panel accounts.') +
|
||
'<div class="panel"><header><h2>Playlists & EPG</h2></header><div id="links"></div></div>' +
|
||
'<div class="grid g2" style="margin-top:10px"><div class="panel"><header><h2>Access tokens</h2>' + (isAdmin() ? '<button class="btn small" id="tok-add">+ New token</button>' : '') + '</header><div id="tokens"></div>' +
|
||
'<p class="hint">A token allows playing streams from outside the local network (e.g. a TV at your family’s place). It can be limited to selected addresses/networks.</p></div>' +
|
||
'<div class="panel"><header><h2>Panel users</h2>' + (isAdmin() ? '<button class="btn small" id="usr-add">+ New user</button>' : '') + '</header><div id="users"></div>' +
|
||
'<div class="row" style="margin-top:10px"><button class="btn small" id="pw-change">Change my password</button></div></div></div>' +
|
||
(isAdmin() ? '<div class="panel"><header><h2>Access control (ACL)</h2><button class="btn small primary" id="acl-save">Save ACL</button></header><div class="form-grid" id="acl"></div></div>' : '');
|
||
|
||
function links() {
|
||
api('GET', '/api/links').then(function (r) {
|
||
var portNote = r.stream_port && !r.stream_port_active
|
||
? '<div class="notice">' + esc(T('Stream port') + ' ' + r.stream_port + ' ' + T('is still taken (tvheadend?). The links below use the panel port; simply-dvb takes the stream port over automatically once it is free.')) + '</div>'
|
||
: '';
|
||
$('#links').innerHTML = portNote + '<p class="hint">Default M3U format: <b>' + esc(r.default_format.toUpperCase()) + '</b> (change it in Settings). Add <code>&format=hls</code> or <code>&format=ts</code>, and for transcoding <code>&profile=aac</code> / <code>&profile=h264</code>.</p>' +
|
||
r.links.map(function (l) {
|
||
return '<div style="margin-top:10px"><div class="label">' + esc(l.name) + '</div>' +
|
||
'<div class="copy-row"><span class="pill acc">M3U</span><code>' + esc(l.m3u) + '</code><button class="btn small" data-c>Copy</button></div>' +
|
||
'<div class="copy-row"><span class="pill blue">HLS</span><code>' + esc(l.m3u_hls) + '</code><button class="btn small" data-c>Copy</button></div>' +
|
||
'<div class="copy-row"><span class="pill ok">EPG</span><code>' + esc(l.epg) + '</code><button class="btn small" data-c>Copy</button></div>' +
|
||
'<div class="copy-row"><span class="pill warn">TVH</span><code>' + esc(l.tvh_playlist) + '</code><button class="btn small" data-c>Copy</button></div>' +
|
||
'<div class="copy-row"><span class="pill warn">TVH</span><code>' + esc(l.tvh_xmltv) + '</code><button class="btn small" data-c>Copy</button></div></div>';
|
||
}).join('') +
|
||
(r.htsp_port ? '<div style="margin-top:14px"><div class="label">HTSP</div><div class="copy-row"><span class="pill ok">HTSP</span><code>' + esc(location.hostname + ':' + r.htsp_port) + '</code><button class="btn small" data-c>Copy</button>' +
|
||
(r.htsp_port_active ? '' : ' <span class="pill warn">' + esc(T('port taken (tvheadend?)')) + '</span>') + '</div>' +
|
||
'<p class="hint">' + esc(T('For apps that speak tvheadend’s HTSP protocol (Kodi “Tvheadend HTSP Client”, TVHClient, PVR apps on Android/Sony TV): server = this address, HTSP port as above, HTTP port = the stream port. On the local network no login is needed; from elsewhere use any user name and an access token as the password.')) + '</p></div>' : '') +
|
||
'<p class="hint" style="margin-top:12px">' + esc(T('TVH = tvheadend-compatible URLs (stream port, 9981 by default): /playlist, /xmltv/channels, /stream/channelid/<id>, /imagecache/<id>, auth= / ticket= parameters and HTTP Basic login. An app configured for tvheadend works after changing just the server address.')) + '</p>';
|
||
$$('[data-c]', $('#links')).forEach(function (b) { b.addEventListener('click', function () { copy(b.parentNode.querySelector('code').textContent); }); });
|
||
}).catch(fail);
|
||
}
|
||
function tokens() {
|
||
if (!isAdmin()) { $('#tokens').innerHTML = '<div class="muted">Administrators only.</div>'; return; }
|
||
api('GET', '/api/tokens').then(function (list) {
|
||
$('#tokens').innerHTML = list.length ? '<table><thead><tr><th>Name</th><th>Networks</th><th>Last used</th><th>Active</th><th></th></tr></thead><tbody>' + list.map(function (t) {
|
||
return '<tr><td><b>' + esc(t.name) + '</b><div class="small mono muted">' + esc(t.token.slice(0, 6)) + '…</div></td><td class="small mono">' + esc(t.allow_cidrs || 'all') + '</td><td class="small mono">' + dt(t.last_used) + '</td>' +
|
||
'<td>' + sw(t.enabled, 'data-tok-en="' + t.id + '" data-tok=\'' + esc(JSON.stringify({ name: t.name, allow_cidrs: t.allow_cidrs })) + '\'') + '</td>' +
|
||
'<td class="actions-cell"><button class="btn small" data-tok-copy="' + esc(t.token) + '">Copy token</button> <button class="btn small danger" data-tok-del="' + t.id + '">Delete</button></td></tr>';
|
||
}).join('') + '</tbody></table>' : '<div class="empty">No tokens.</div>';
|
||
$$('[data-tok-copy]').forEach(function (b) { b.addEventListener('click', function () { copy(b.getAttribute('data-tok-copy')); }); });
|
||
$$('[data-tok-del]').forEach(function (b) { b.addEventListener('click', function () { if (confirmBox('Delete the token? Devices using it will lose access.')) api('DELETE', '/api/tokens/' + b.getAttribute('data-tok-del')).then(function () { tokens(); links(); }).catch(fail); }); });
|
||
$$('[data-tok-en]').forEach(function (i) {
|
||
i.addEventListener('change', function () { var d = JSON.parse(i.getAttribute('data-tok')); d.enabled = i.checked; api('PUT', '/api/tokens/' + i.getAttribute('data-tok-en'), d).then(function () { tokens(); links(); }).catch(fail); });
|
||
});
|
||
}).catch(fail);
|
||
}
|
||
function users() {
|
||
if (!isAdmin()) { $('#users').innerHTML = '<div class="muted">Signed in as ' + esc(app.me.username) + '.</div>'; return; }
|
||
api('GET', '/api/users').then(function (list) {
|
||
$('#users').innerHTML = '<table><thead><tr><th>Login</th><th>Role</th><th>Created</th><th></th></tr></thead><tbody>' + list.map(function (u) {
|
||
return '<tr><td><b>' + esc(u.username) + '</b>' + (u.id === app.me.id ? ' <span class="pill acc">you</span>' : '') + '</td><td><select data-role="' + u.id + '"' + (u.id === app.me.id ? ' disabled' : '') + '><option value="admin"' + (u.role === 'admin' ? ' selected' : '') + '>administrator</option><option value="viewer"' + (u.role === 'viewer' ? ' selected' : '') + '>viewer</option></select></td>' +
|
||
'<td class="small mono">' + dmy(u.created_at) + '</td><td class="actions-cell"><button class="btn small" data-pw="' + u.id + '">Password</button> ' + (u.id !== app.me.id ? '<button class="btn small danger" data-udel="' + u.id + '">Delete</button>' : '') + '</td></tr>';
|
||
}).join('') + '</tbody></table>';
|
||
$$('[data-role]').forEach(function (s) { s.addEventListener('change', function () { api('PUT', '/api/users/' + s.getAttribute('data-role'), { role: s.value }).then(function () { toast('Role changed'); }).catch(fail); }); });
|
||
$$('[data-udel]').forEach(function (b) { b.addEventListener('click', function () { if (confirmBox('Delete the user?')) api('DELETE', '/api/users/' + b.getAttribute('data-udel')).then(users).catch(fail); }); });
|
||
$$('[data-pw]').forEach(function (b) {
|
||
b.addEventListener('click', function () {
|
||
var pw = promptBox('New password (min. 8 characters):');
|
||
if (pw) api('PUT', '/api/users/' + b.getAttribute('data-pw'), { password: pw }).then(function () { toast('Password changed'); }).catch(fail);
|
||
});
|
||
});
|
||
}).catch(fail);
|
||
}
|
||
function aclResolved(m) {
|
||
var hosts = Object.keys(m || {});
|
||
if (!hosts.length) return '';
|
||
return '<div class="full small muted">' + esc(T('DDNS host names now resolve to:')) + ' ' + hosts.map(function (h) {
|
||
return '<span class="mono">' + esc(h) + ' → ' + esc((m[h] || []).join(', ') || T('not resolved')) + '</span>';
|
||
}).join(' · ') + '</div>';
|
||
}
|
||
function acl() {
|
||
if (!isAdmin()) return;
|
||
api('GET', '/api/settings').then(function (s) {
|
||
$('#acl').innerHTML = '<label class="full">Networks with token-free access to streams, M3U and EPG<textarea name="stream_open_cidrs">' + esc(s.stream_open_cidrs.join('\n')) + '</textarea><span class="hint">One entry per line: a network (192.168.0.0/16), an address or a DDNS host name (myhome.ddns.net, re-resolved every minute). Empty = a token or panel session is always required.</span></label>' +
|
||
'<label class="full">Networks allowed to reach the panel<textarea name="panel_allow_cidrs">' + esc(s.panel_allow_cidrs.join('\n')) + '</textarea><span class="hint">Networks, addresses or DDNS host names. Empty = panel reachable from anywhere (login still required).</span></label>' +
|
||
aclResolved(s.acl_resolved) +
|
||
'<label class="full">Trusted reverse proxies<textarea name="trusted_proxies">' + esc(s.trusted_proxies.join('\n')) + '</textarea><span class="hint">X-Forwarded-For / X-Forwarded-Proto are honoured only from these addresses (e.g. RustProxy).</span></label>';
|
||
$('#acl-save').onclick = function () {
|
||
var lines = function (n) { return $('[name=' + n + ']').value.split(/[\s,]+/).filter(Boolean); };
|
||
s.stream_open_cidrs = lines('stream_open_cidrs'); s.panel_allow_cidrs = lines('panel_allow_cidrs'); s.trusted_proxies = lines('trusted_proxies');
|
||
delete s.profiles; delete s.data_dir; delete s.acl_resolved;
|
||
api('PUT', '/api/settings', s).then(function () { toast('ACL saved'); links(); }).catch(fail);
|
||
};
|
||
}).catch(fail);
|
||
}
|
||
links(); tokens(); users(); acl();
|
||
$('#pw-change').addEventListener('click', function () {
|
||
var body = modal('Change password', '<div class="form-grid"><label class="full">Current password<input type="password" name="cur" autocomplete="current-password"></label><label class="full">New password<input type="password" name="new" autocomplete="new-password"></label></div><div class="modal-foot"><button class="btn primary" id="pw-save">Change</button></div>');
|
||
$('#pw-save', body).addEventListener('click', function () {
|
||
api('POST', '/api/me/password', { current: $('[name=cur]', body).value, new: $('[name=new]', body).value }).then(function () { toast('Password changed – please sign in again'); closeModal(); showLogin(); }).catch(fail);
|
||
});
|
||
});
|
||
if (isAdmin()) {
|
||
$('#tok-add').addEventListener('click', function () {
|
||
var body = modal('New token', '<div class="form-grid"><label class="full">Name<input name="name" placeholder="e.g. Living room Sony TV"></label><label class="full">Allowed networks (optional)<input name="cidrs" placeholder="e.g. 83.1.2.3, 10.8.0.0/24, myhome.ddns.net"></label></div><div class="modal-foot"><button class="btn primary" id="tok-save">Create</button></div>');
|
||
$('#tok-save', body).addEventListener('click', function () {
|
||
api('POST', '/api/tokens', { name: $('[name=name]', body).value, allow_cidrs: $('[name=cidrs]', body).value }).then(function () { closeModal(); tokens(); links(); }).catch(fail);
|
||
});
|
||
});
|
||
$('#usr-add').addEventListener('click', function () {
|
||
var body = modal('New user', '<div class="form-grid"><label>Login<input name="u" autocomplete="off"></label><label>Role<select name="r"><option value="viewer">viewer (watch only)</option><option value="admin">administrator</option></select></label><label class="full">Password<input type="password" name="p" autocomplete="new-password"></label></div><div class="modal-foot"><button class="btn primary" id="usr-save">Create</button></div>');
|
||
$('#usr-save', body).addEventListener('click', function () {
|
||
api('POST', '/api/users', { username: $('[name=u]', body).value, password: $('[name=p]', body).value, role: $('[name=r]', body).value }).then(function () { closeModal(); users(); }).catch(fail);
|
||
});
|
||
});
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------ LOGS
|
||
function pageLogs(view) {
|
||
view.innerHTML = head('Diagnostics', 'Logs', 'What the server is doing: tuners, streams, access, EPG and recordings. The last 4000 entries are kept in memory.',
|
||
'<a class="btn" href="/api/logs/download" download>⤓ Download</a><button class="btn" id="log-clear">Clear view</button>') +
|
||
'<div class="panel"><div class="tabs" id="log-cats"></div>' +
|
||
'<div class="filters" style="border:0;padding:8px 0 4px"><select id="log-level"><option value="">' + esc(T('All levels')) + '</option><option value="info">info+</option><option value="warn">' + esc(T('warnings and errors')) + '</option><option value="error">' + esc(T('errors only')) + '</option></select>' +
|
||
'<input id="log-q" placeholder="' + esc(T('Search…')) + '"><label class="check"><input type="checkbox" id="log-follow" checked> ' + esc(T('Follow')) + '</label><span class="spacer"></span><span class="muted small mono" id="log-count"></span></div>' +
|
||
'<div class="log log-view" id="log-view"></div></div>';
|
||
var cat = sessionStorage.getItem('sdvb-logcat') || '', level = '', q = '', since = 0, entries = [], cats = [];
|
||
function renderCats() {
|
||
$('#log-cats').innerHTML = '<button data-c=""' + (cat === '' ? ' class="active"' : '') + '>' + esc(T('All')) + '</button>' + cats.map(function (c) {
|
||
return '<button data-c="' + c.id + '"' + (c.id === cat ? ' class="active"' : '') + ' title="' + esc(T(c.description)) + '">' + esc(T(CAT_NAMES[c.id] || c.id)) + ' <span class="muted">' + c.count + '</span>' + (c.problems ? ' <span class="pill err">' + c.problems + '</span>' : '') + '</button>';
|
||
}).join('');
|
||
$$('#log-cats button').forEach(function (b) {
|
||
b.addEventListener('click', function () { cat = b.getAttribute('data-c'); sessionStorage.setItem('sdvb-logcat', cat); restart(); });
|
||
});
|
||
}
|
||
var CAT_NAMES = { app: 'Application', tuner: 'Tuners & devices', stream: 'Streaming', access: 'Access', epg: 'EPG', recorder: 'Recording', system: 'System' };
|
||
function line(e) {
|
||
var d = new Date(e.t_ms);
|
||
var ts = pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) + '.' + String(d.getMilliseconds()).padStart(3, '0');
|
||
return '<div class="log-line lv-' + e.level + '"><span class="log-ts">' + dmy(e.t_ms / 1000) + ' ' + ts + '</span><span class="log-lv">' + e.level.toUpperCase() + '</span><span class="log-cat">' + esc(T(CAT_NAMES[e.category] || e.category)) + '</span><span class="log-msg">' + esc(e.message) + '</span><span class="log-target" title="' + esc(e.target) + '">' + esc(e.target.replace(/^simply_dvb::/, '')) + '</span></div>';
|
||
}
|
||
function draw(append) {
|
||
var v = $('#log-view');
|
||
if (!append) v.innerHTML = entries.map(line).join('');
|
||
$('#log-count').textContent = entries.length + ' ' + T('entries');
|
||
if ($('#log-follow').checked) v.scrollTop = v.scrollHeight;
|
||
}
|
||
function poll() {
|
||
api('GET', '/api/logs?since=' + since + '&category=' + encodeURIComponent(cat) + '&level=' + level + '&q=' + encodeURIComponent(q) + '&limit=500').then(function (r) {
|
||
cats = r.categories; renderCats();
|
||
if (r.entries.length) {
|
||
since = r.entries[r.entries.length - 1].seq;
|
||
var v = $('#log-view');
|
||
var append = entries.length > 0;
|
||
entries = entries.concat(r.entries).slice(-2000);
|
||
if (append) { v.insertAdjacentHTML('beforeend', r.entries.map(line).join('')); while (v.children.length > 2000) v.removeChild(v.firstChild); }
|
||
draw(append);
|
||
} else if (!entries.length) {
|
||
$('#log-view').innerHTML = '<div class="muted small">' + esc(T('No entries match.')) + '</div>';
|
||
}
|
||
}).catch(function () {});
|
||
}
|
||
function restart() { since = 0; entries = []; $('#log-view').innerHTML = ''; poll(); }
|
||
$('#log-level').addEventListener('change', function () { level = this.value; restart(); });
|
||
var qt = null;
|
||
$('#log-q').addEventListener('input', function () { clearTimeout(qt); q = this.value; qt = setTimeout(restart, 300); });
|
||
$('#log-clear').addEventListener('click', function () { entries = []; $('#log-view').innerHTML = ''; $('#log-count').textContent = ''; });
|
||
every(2000, poll);
|
||
}
|
||
|
||
// ------------------------------------------------------------ PERSONALIZATION
|
||
function renderPrefs() {
|
||
var box = $('#prefs');
|
||
function seg(key, opts) {
|
||
return '<div class="seg" data-pref="' + key + '">' + opts.map(function (o) {
|
||
return '<button data-v="' + esc(String(o[0])) + '"' + (String(P.get(key)) === String(o[0]) ? ' class="on"' : '') + '>' + esc(o[1]) + '</button>';
|
||
}).join('') + '</div>';
|
||
}
|
||
function row(label, ctl) { return '<div class="pref-row"><span>' + esc(label) + '</span><div>' + ctl + '</div></div>'; }
|
||
var accentNames = { orange: 'Orange', green: 'Green', blue: 'Blue', violet: 'Violet', red: 'Red', teal: 'Teal', amber: 'Amber' };
|
||
var profile = 'auto';
|
||
try { profile = localStorage.getItem('sdvb-profile') || 'auto'; } catch (e) {}
|
||
box.innerHTML = '<header><h2>Appearance</h2><button class="btn small" id="prefs-reset">Reset to defaults</button></header>' +
|
||
'<p class="hint" style="margin-top:-4px">Interface preferences are stored in this browser.</p>' +
|
||
row('Language', langSelect('pref-lang', false)) +
|
||
row('Theme', seg('theme', [['dark', 'Dark'], ['midnight', 'Midnight (OLED)'], ['light', 'Light'], ['system', 'System default']])) +
|
||
row('Accent colour', '<div class="swatches">' + P.accents.map(function (a) {
|
||
return '<button class="swatch' + (P.get('accent') === a ? ' on' : '') + '" data-accent="' + a + '" title="' + esc(accentNames[a]) + '" style="background:' + P.accentColor(a) + '"></button>';
|
||
}).join('') + '</div>') +
|
||
row('Density', seg('density', [['comfortable', 'Comfortable'], ['compact', 'Compact']])) +
|
||
row('Interface scale', seg('scale', [[90, '90%'], [100, '100%'], [110, '110%'], [125, '125%']])) +
|
||
row('Sidebar', seg('sidebar', [['hover', 'Expand on hover'], ['pinned', 'Always expanded']])) +
|
||
row('Start page', seg('start', [['overview', 'Overview'], ['tv', 'TV'], ['epg', 'TV guide'], ['channels', 'Channels']])) +
|
||
row('Default player profile', '<div class="seg" id="pref-profile">' + [['auto', 'Automatic'], ['pass', 'Original'], ['aac', 'Audio → AAC'], ['h264', 'H.264 720p']].map(function (o) {
|
||
return '<button data-p="' + o[0] + '"' + (profile === o[0] ? ' class="on"' : '') + '>' + esc(o[1]) + '</button>';
|
||
}).join('') + '</div>') +
|
||
row('EPG grid zoom', seg('epgZoom', [[3, 'Narrow'], [4, 'Normal'], [6, 'Wide']])) +
|
||
row('Start playback when opening the TV page', sw(P.get('autoplay'), 'data-bool="autoplay"')) +
|
||
row('Logos in the channel list', sw(P.get('logos'), 'data-bool="logos"')) +
|
||
row('Programme progress in the channel list', sw(P.get('progress'), 'data-bool="progress"')) +
|
||
row('Show clock in the top bar', sw(P.get('clock'), 'data-bool="clock"')) +
|
||
row('Animations', sw(P.get('motion'), 'data-bool="motion"'));
|
||
$$('[data-pref]', box).forEach(function (g) {
|
||
$$('button', g).forEach(function (b) {
|
||
b.addEventListener('click', function () {
|
||
var v = b.getAttribute('data-v');
|
||
P.set(g.getAttribute('data-pref'), /^\d+$/.test(v) ? +v : v);
|
||
renderPrefs();
|
||
});
|
||
});
|
||
});
|
||
$$('[data-accent]', box).forEach(function (b) { b.addEventListener('click', function () { P.set('accent', b.getAttribute('data-accent')); renderPrefs(); }); });
|
||
$$('[data-bool]', box).forEach(function (i) { i.addEventListener('change', function () { P.set(i.getAttribute('data-bool'), i.checked); applyClock(); }); });
|
||
bindLang($('#pref-lang', box));
|
||
$$('#pref-profile button', box).forEach(function (b) {
|
||
b.addEventListener('click', function () { try { localStorage.setItem('sdvb-profile', b.getAttribute('data-p')); } catch (e) {} renderPrefs(); });
|
||
});
|
||
$('#prefs-reset', box).addEventListener('click', function () { P.reset(); applyClock(); renderPrefs(); toast('Interface preferences reset'); });
|
||
}
|
||
|
||
// ------------------------------------------------------------ SETTINGS
|
||
function pageSettings(view) {
|
||
view.innerHTML = head('Configuration', 'Settings', 'Changes apply immediately (to new stream sessions).', isAdmin() ? '<button class="btn primary" id="set-save">Save settings</button>' : '') +
|
||
'<div class="panel" id="prefs"></div><div id="set-body"></div>';
|
||
renderPrefs();
|
||
var cur = null;
|
||
function field(name, label, type, hint, extra) {
|
||
var v = cur[name];
|
||
var input = type === 'bool' ? '<label class="check"><input type="checkbox" name="' + name + '"' + (v ? ' checked' : '') + '> ' + esc(label) + '</label>'
|
||
: type === 'select' ? '<label>' + esc(label) + '<select name="' + name + '">' + extra.map(function (o) { return '<option value="' + o[0] + '"' + (o[0] === v ? ' selected' : '') + '>' + esc(o[1]) + '</option>'; }).join('') + '</select></label>'
|
||
: '<label' + (type === 'wide' ? ' class="full"' : '') + '>' + esc(label) + '<input name="' + name + '" type="' + (type === 'number' ? 'number' : 'text') + '" value="' + esc(v) + '"></label>';
|
||
return type === 'bool' ? '<div>' + input + (hint ? '<div class="hint">' + esc(hint) + '</div>' : '') + '</div>' : input.replace(/<\/label>$/, (hint ? '<span class="hint">' + esc(hint) + '</span>' : '') + '</label>');
|
||
}
|
||
function render() {
|
||
$('#set-body').innerHTML =
|
||
'<div class="panel"><header><h2>General</h2></header><div class="form-grid">' +
|
||
field('server_name', 'Server name') + field('public_url', 'Public URL (for links)', 'text', 'e.g. https://tv.example.com – empty = from the Host header') +
|
||
field('session_hours', 'Panel session lifetime (h)', 'number') + '</div></div>' +
|
||
'<div class="panel"><header><h2>Streaming (HLS / TS)</h2></header><div class="form-grid">' +
|
||
field('hls_segment_seconds', 'HLS segment length (s)', 'number', 'Cut on keyframes – actual length depends on the broadcaster’s GOP') +
|
||
field('hls_window', 'Segments in playlist', 'number') + field('hls_idle_seconds', 'Close idle HLS session after (s)', 'number') +
|
||
field('tuner_linger_seconds', 'Keep tuner after last client (s)', 'number', 'Faster zapping between channels of the same mux') +
|
||
field('m3u_format', 'Default M3U format', 'select', 'TS – lightest for TVs, HLS – for apps that require HLS', [['ts', 'MPEG-TS (continuous stream)'], ['hls', 'HLS (m3u8)']]) + '</div></div>' +
|
||
'<div class="panel"><header><h2>Transcoding (ffmpeg)</h2></header><div class="form-grid">' + field('ffmpeg_path', 'ffmpeg path') +
|
||
field('ffmpeg_h264_args', 'H.264 profile arguments', 'wide', 'Used by the “h264” profile (e.g. HEVC in browsers without a hardware decoder). Hardware acceleration can be added: -c:v h264_vaapi etc.') + '</div></div>' +
|
||
'<div class="panel"><header><h2>EPG</h2>' + (isAdmin() ? '<div class="actions"><button class="btn small" id="xmltv-now">Import XMLTV now</button></div>' : '') + '</header><div class="form-grid">' +
|
||
field('epg_ota_enabled', 'Collect EPG from the broadcast (EIT)', 'bool', 'While watching and periodically from every mux') +
|
||
field('epg_grab_interval_hours', 'Grab all muxes every (h)', 'number', '0 = only while watching') + field('epg_grab_seconds', 'Grab time per mux (s)', 'number') +
|
||
field('epg_keep_past_hours', 'Keep past programmes (h)', 'number') + field('xmltv_interval_hours', 'Import XMLTV every (h)', 'number') +
|
||
'<label class="full">XMLTV sources (one URL per line, .xml or .xml.gz)<textarea name="xmltv_sources" placeholder="https://epg.ovh/pl.xml">' + esc(cur.xmltv_sources.map(function (s) { return (s.enabled ? '' : '# ') + s.url; }).join('\n')) + '</textarea>' +
|
||
'<span class="hint">Channels are matched by the channel’s “EPG ID” or by name. A line starting with # is disabled. XMLTV data takes precedence over EIT.</span></label>' +
|
||
'<div class="full small muted" id="xmltv-status"></div></div></div>' +
|
||
'<div class="panel"><header><h2>Channel icons</h2></header><div class="form-grid"><label class="full">Icon URL templates<textarea name="icon_sources">' + esc(cur.icon_sources.join('\n')) + '</textarea>' +
|
||
'<span class="hint">{slug} is replaced with the channel name, e.g. “tvp-1”, “polsat-news”. First hit wins; icons are stored locally.</span></label></div></div>' +
|
||
'<div class="panel"><header><h2>Recording</h2></header><div class="form-grid">' + field('recordings_dir', 'Recordings directory', 'text', 'Empty = ' + cur.data_dir + '/recordings') +
|
||
field('recording_pre_padding_min', 'Padding before (min)', 'number') + field('recording_post_padding_min', 'Padding after (min)', 'number') +
|
||
field('recordings_keep_days', 'Delete recordings older than (days)', 'number', '0 = never') +
|
||
field('recordings_min_free_gb', 'Minimum free space (GiB)', 'number', 'Below this threshold the oldest recordings are deleted; 0 = disabled') + '</div></div>' +
|
||
'<div class="panel"><header><h2>Scanning</h2></header><div class="form-grid">' + field('scan_create_channels', 'Create channels automatically', 'bool') +
|
||
field('scan_include_radio', 'Add radio stations', 'bool') + field('scan_include_scrambled', 'Add scrambled channels', 'bool') +
|
||
field('scan_lock_timeout_ms', 'Lock timeout (ms)', 'number', 'Si2168 usually locks DVB-T2 within ~1–2 s') +
|
||
field('idle_scan_hours', 'Background scan every (h)', 'number', 'Rescans saved muxes (and the NIT) on an idle adapter; stops as soon as someone starts watching or recording. 0 = off') +
|
||
field('idle_scan_quiet_minutes', 'Start after all tuners are idle for (min)', 'number') +
|
||
field('idle_scan_follow_nit', 'Background scan: follow the NIT to new muxes', 'bool') +
|
||
field('idle_scan_create_channels', 'Background scan: create channels for new services', 'bool', 'Off = new services only appear in “Add from services”') + '</div></div>' +
|
||
(isAdmin() ? '<div class="panel"><header><h2>Backup</h2></header><p class="hint">Muxes, services, channels (order, groups, links), recording rules, tokens and settings. Without user accounts, EPG, icons and recording files.</p>' +
|
||
'<div class="row"><a class="btn" href="/api/backup" download>⤓ Download backup (JSON)</a><label class="btn">⤒ Restore from file<input type="file" id="restore-file" accept="application/json,.json" class="hidden"></label>' +
|
||
'<a class="btn ghost" href="/metrics" target="_blank">Prometheus metrics</a></div></div>' : '');
|
||
api('GET', '/api/epg/status').then(function (s) {
|
||
var e = $('#xmltv-status');
|
||
if (e) e.textContent = (s.status.last_xmltv ? T('Last XMLTV import:') + ' ' + dt(s.status.last_xmltv) + '\n' + T(s.status.xmltv_result || '') : '') + ' · ' + T('programmes in database:') + ' ' + s.events;
|
||
}).catch(function () {});
|
||
var rf = $('#restore-file');
|
||
if (rf) rf.addEventListener('change', function () {
|
||
var f = rf.files[0];
|
||
if (!f || !confirmBox('Restore configuration from the backup? Current channels, muxes, rules and tokens will be replaced.')) return;
|
||
f.text().then(function (txt) { return api('POST', '/api/restore', JSON.parse(txt)); })
|
||
.then(function (r) { toast(T('Backup restored') + ': ' + r.channels + ' / ' + r.muxes); return api('GET', '/api/settings'); })
|
||
.then(function (s) { cur = s; render(); }).catch(fail);
|
||
});
|
||
var x = $('#xmltv-now');
|
||
if (x) x.addEventListener('click', function () {
|
||
x.disabled = true;
|
||
api('POST', '/api/epg/xmltv').then(function (s) { toast(s.xmltv_result || 'Imported'); }).catch(fail).then(function () { x.disabled = false; });
|
||
});
|
||
if (!isAdmin()) $$('#set-body input, #set-body select, #set-body textarea').forEach(function (i) { i.disabled = true; });
|
||
}
|
||
function collect() {
|
||
var s = JSON.parse(JSON.stringify(cur));
|
||
delete s.profiles; delete s.data_dir; delete s.acl_resolved;
|
||
$$('#set-body [name]').forEach(function (i) {
|
||
var n = i.name;
|
||
if (n === 'xmltv_sources') {
|
||
s[n] = i.value.split('\n').map(function (l) { return l.trim(); }).filter(Boolean).map(function (l) {
|
||
var dis = l.charAt(0) === '#';
|
||
return { url: l.replace(/^#\s*/, ''), enabled: !dis };
|
||
});
|
||
} else if (n === 'icon_sources') {
|
||
s[n] = i.value.split('\n').map(function (l) { return l.trim(); }).filter(Boolean);
|
||
} else if (i.type === 'checkbox') {
|
||
s[n] = i.checked;
|
||
} else if (i.type === 'number') {
|
||
s[n] = +i.value;
|
||
} else {
|
||
s[n] = i.value;
|
||
}
|
||
});
|
||
return s;
|
||
}
|
||
api('GET', '/api/settings').then(function (s) { cur = s; render(); }).catch(fail);
|
||
var sv = $('#set-save');
|
||
if (sv) sv.addEventListener('click', function () {
|
||
api('PUT', '/api/settings', collect()).then(function () { toast('Settings saved'); return api('GET', '/api/settings'); }).then(function (s) { cur = s; render(); }).catch(fail);
|
||
});
|
||
}
|
||
|
||
boot();
|
||
})();
|