/* 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 ''; 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 '
' + esc(ini) + '
'; } function sw(checked, attrs) { return ''; } 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 '
' + esc(eyebrow) + '

' + esc(title) + '

' + (sub ? '

' + esc(sub) + '

' : '') + '
' + (actions || '') + '
'; } // ------------------------------------------------------------ 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 ''; } 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 ''; }).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 ''; }).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 ? '' : ''; return area + ''; }).join(''); return '' + grid + paths + '' + '
' + esc(fmtNum(max, opts.unit)) + '' + esc(fmtNum(min, opts.unit)) + '
'; } /** 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 '' + esc(T(sr.name)) + ' ' + esc(fmtNum(v, (opts || {}).unit)) + ''; }).join(''); return '
' + esc(T(title)) + '
' + cur + '
' + lineChart(series, times, opts) + '
'; } 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 '
' + '
Strength
' + (strength != null ? strength.toFixed(0) + '%' : '–') + '
' + '
' + '
' + (sig.strength_dbm != null ? sig.strength_dbm.toFixed(1) + ' dBm' : '') + '
' + '
SNR
' + (snr != null ? snr.toFixed(1) + ' dB' : snrPct != null ? snrPct.toFixed(0) + '%' : '–') + '
' + '
' + '
Errors (UNC)
' + (sig.uncorrected != null ? sig.uncorrected : '–') + '
' + '
' + (sig.locked ? 'LOCK' : sig.has_signal ? 'signal, no lock' : 'no signal') + '
'; } 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.', '▶ WatchScan channels') + '
' + '

Live

' + [5, 10, 15].map(function (m) { return ''; }).join('') + '
' + '
' + '
' + '

Active clients

0
'; 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 || '
' + esc(T('Collecting data…')) + '
'; 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 '

' + esc(t.name) + '

' + esc(t.id) + ' · ' + esc(t.delivery_systems.join(' / ')) + ' · ' + esc(t.path) + '
' + '
' + (!t.enabled ? 'disabled' : t.busy ? 'scanning' : a ? '' + esc(a.state === 'locked' ? 'LOCK' : a.state) + '' : 'idle') + '
' + (a ? '
Mux' + esc(a.tuning) + (a.network_name ? ' · ' + esc(a.network_name) : '') + '' + 'Clients' + a.subscribers + (a.top_priority ? ' · priority ' + esc(a.top_priority) : '') + '' + 'Stream' + bps(a.bitrate_bps) + ' · ' + dur(a.uptime_secs) + '
' + signalBlock(a.signal) : '
' + (t.last_error ? 'Last error: ' + esc(t.last_error) : 'Tuner is waiting for clients.') + '
') + (charts ? '
' + charts + '
' : '') + '
'; }).join('') || '
No DVB adapters detected. Check /dev/dvb and permissions (group video).
'; 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 = '
Channels
' + c.channels_enabled + ' / ' + c.channels + '
' + c.services + ' services · ' + c.muxes + ' muxes
' + '
EPG – upcoming programmes
' + c.epg_events + '
last grab: ' + (s.epg.last_grab ? dt(s.epg.last_grab) : '–') + '
' + '
Recordings
' + c.recordings_running + ' running
' + c.recordings_scheduled + ' scheduled · ' + c.recordings_total + ' total
' + '
Recordings disk
' + (s.disk && s.disk.free != null ? bytes(s.disk.free) : '–') + '
' + (disk != null ? '
' : '') + '
free · load ' + esc(s.load || '–') + ' · up ' + dur(s.uptime_secs) + '
'; $('#ov-ccount').textContent = s.clients.length; $('#ov-clients').innerHTML = s.clients.length ? '' + s.clients.map(function (x) { return '' + '' + '' + ''; }).join('') + '
ProtocolChannelDeviceAddressAccessProfileSinceDurationRateSent
' + esc(x.protocol) + '' + esc(x.channel_name) + '
' + esc(x.device) + '
' + esc(x.user_agent.length > 70 ? x.user_agent.slice(0, 70) + '…' : x.user_agent) + '
' + esc(x.ip) + '' + esc(x.who) + '' + esc(x.profile) + '' + hm(x.started) + '' + dur(x.duration_secs) + (x.idle_secs > 10 ? '
' + esc(T('idle')) + ' ' + dur(x.idle_secs) + '
' : '') + '
' + bps(x.avg_bps) + '' + bytes(x.bytes) + '
' : '
Nobody is watching right now.
'; } 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 = '
Pick a channel from the list
' + '
'; 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 = '' + (list.length ? list.map(function (c) { return '
' + c.number + '
' + logo(c) + '
' + esc(c.name) + '
' + (c.now ? hm(c.now.start) + ' ' + esc(c.now.title) : (c.kind === 'radio' ? 'radio' : ' ')) + '
' + (c.now ? '
' : '') + '
'; }).join('') : '
No channels – run a scan on the Tuners page.
'); 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 = '
' + esc(c.number + ' · ' + c.name) + '
' + (n ? '

' + esc(n.title) + '

' + hm(n.start) + '–' + hm(n.stop) + (n.genre ? ' · ' + esc(n.genre) : '') + '
' + '
' + esc(n.description || n.summary || '') + '
' : '

' + esc(c.name) + '

No EPG data for this moment.
') + (nx ? '
Next: ' + hm(nx.start) + ' ' + esc(nx.title) + '
' : '') + '
' + (n && isAdmin() ? '' : '') + '
'; 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 = '

Schedule

EPG grid
' + (evs.length ? evs.map(function (e) { var cls = e.stop < t ? 'past' : e.start <= t ? 'cur' : ''; return '
' + hm(e.start) + '' + esc(e.title) + '' + (e.start > t && isAdmin() ? '' : '') + '
'; }).join('') : '
No EPG yet. Data appears after EIT is collected from the mux or XMLTV is imported.
') + '
'; $$('[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 '' + esc(x) + ' ' + (ok ? '✓' : '✗') + ''; }).join(' '); var why = window.SDVB.explain(svc.video, svc.audio); $('#tv-tools').innerHTML = '

Stream

' + esc(svc.video || (c.kind === 'radio' ? 'radio' : '?')) + ' · ' + esc((svc.audio || []).join(', ') || '–') + '
' + '
Mux' + esc(c.mux || '–') + 'Profile active: ' + esc(active || '') + '
' + '
' + esc(T('Browser')) + '' + (capsHtml || '–') + 'ffmpeg' + (noFfmpeg ? '' + esc(T('not installed')) + '' : '' + esc(T('available')) + '') + '
' + (why ? '

' + esc(why) + (noFfmpeg ? ' ' + esc(T('Without ffmpeg on the server use VLC or a browser/device that decodes these codecs.')) : '') + '

' : '') + '
' + esc(location.origin + '/hls/' + c.id + '/index.m3u8') + '
' + '
' + esc(location.origin + '/stream/channelid/' + c.id + '?profile=pass') + '
' + '' + '

' + esc(T('Shortcuts: ↑/↓ channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.')) + '

' + '

The “Automatic” profile checks which codecs your browser supports (e.g. HEVC, AC-3) and enables ffmpeg transcoding when needed.

'; $('#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 = '
' + esc(c.number + ' · ' + c.name) + '
' + '
'; $('#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', '
' + [['↑ / ↓', '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 '' + esc(x[0]) + '' + esc(x[1]) + ''; }).join('') + '
'); } 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/ after a reload or history navigation) only selects // the channel; playback starts on click, from an explicit ▶ link (#/tv//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, '
Channel' + esc(ch ? ch.number + ' · ' + ch.name : '') + 'Time' + dt(e.start) + ' – ' + hm(e.stop) + ' (' + dur(e.stop - e.start) + ')' + (e.genre ? 'Genre' + esc(e.genre) + '' : '') + (e.rating ? 'Age' + e.rating + '+' : '') + 'Source' + esc(e.source === 'xmltv' ? 'XMLTV' : 'EIT (broadcast)') + '
' + (e.summary ? '

' + esc(e.summary) + '

' : '') + '

' + esc(e.description || '') + '

' + ''); 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.', '' + (isAdmin() ? '' : '')) + '
'; 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 += '
' + hm(t) + (new Date(t * 1000).getHours() === 0 && new Date(t * 1000).getMinutes() === 0 ? ' · ' + dmy(t) : '') + '
'; 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 '
' + '
' + esc(e.title) + '
' + hm(e.start) + '–' + hm(e.stop) + '
'; }).join(''); return '
' + c.number + '' + logo(c) + '' + esc(c.name) + '
' + items + '
'; }).join(''); var nowX = (now() - start) / 60 * PX; $('#epg').innerHTML = chans.length ? '
' + hh + '
' + rows + (nowX > 0 && nowX < width ? '
' : '') + '
' : '
No channels.
'; 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() ? '' : '') + '
'; 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 ''; }; var chk = function (k, label, n) { return ''; }; $('#ch-filters').innerHTML = '' + '' + '' + '' + 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; })) + '' + (isAdmin() && count(unknownStreams) ? '' : '') + (isAdmin() ? '' : ''); 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 ? '
No channels. Run a scan on the Tuners page.
' : !list.length ? '
No channels match the filters.
' : '' + list.map(function (c) { var s = c.service || {}; var pr = problem(c); return '' + '' + '' + '' + '' + ''; }).join('') + '
No.LogoNameGroupCodecsMuxNowEnabledPublic link
⠿' + c.number + '' + logo(c) + '' + esc(c.name) + '' + (pr ? ' ' + esc(T(pr)) + '' : '') + (!pr && unknownStreams(c) ? ' ' + esc(T('streams unknown')) + '' : '') + (s.scrambled ? ' scrambled' : '') + (c.kind === 'radio' ? ' radio' : '') + '' + esc(c.grp) + '' + esc([s.video].concat(s.audio || []).filter(Boolean).join(' · ')) + '' + esc(c.mux || '') + '' + (c.now ? esc(c.now.title) : '–') + '' + sw(c.enabled, 'data-en="' + c.id + '"' + (isAdmin() ? '' : ' disabled')) + '' + sw(c.share_enabled, 'data-sh="' + c.id + '"' + (isAdmin() ? '' : ' disabled')) + (c.share_enabled && c.share_token ? ' ' : '') + '▶ VLC' + (isAdmin() ? ' ' : '') + '
'; 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, '
' + '' + '' + '' + '' + '' + '
' + logo(c) + '' + (c.icon ? '' : '') + '
' + '' + ''); 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 ''; }).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 ? '

Services without a channel:

' + free.map(function (s) { return ''; }).join('') + '
' + esc(s.name) + '' + esc(s.provider) + '' + esc(s.kind) + '' + (s.scrambled ? ' scrambled' : '') + '' + esc([s.video].concat(s.audio).filter(Boolean).join(' · ')) + '
' : '
All services already have channels.
'); 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() ? '' : '') + '
'; 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 = '
' + esc(T('Nothing scheduled. Pick a programme in the TV guide or add a rule.')) + '
'; 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 = '

' + esc(T('Each bar is one recording (padding included); colours mark the multiplex – recordings on the same multiplex share one tuner.')) + ' ' + esc(T('Tuners:')) + ' ' + r.adapters + '' + (r.conflicts ? ' · ' + esc(T('conflicts:')) + ' ' + r.conflicts + '' : '') + '

'; 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 += '
' + names[d.getDay()] + ' ' + dmy(day) + '
' + '
' + [0, 3, 6, 9, 12, 15, 18, 21].map(function (h) { return '' + pad(h) + ':00'; }).join('') + (t >= day && t < day + 86400 ? '' : '') + 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 '
' + (x.conflict ? '⚠ ' : '') + esc(x.title) + ' ' + esc(x.channel_name) + '
'; }).join('') + '
'; }); html += '' + list.map(function (x) { var st = REC_STATUS[x.status] || [x.status, '']; return ''; }).join('') + '
StartEndTitleChannelStatus
' + dt(x.start) + '' + hm(x.stop) + '' + esc(x.title) + '' + esc(x.channel_name) + '' + st[0] + '' + (x.conflict ? ' ' + esc(T('conflict')) + '' : '') + '
'; $('#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 = '

A rule schedules recordings of every EPG programme (next 48 h) whose title matches the pattern – a title fragment or a regular expression.

' + (isAdmin() ? '
' : '') + (rules.length ? '' + rules.map(function (x) { return '' + ''; }).join('') + '
NamePatternChannelActive
' + esc(x.name) + '' + esc(x.pattern) + '' + (x.channel_id ? esc(chName(x.channel_id)) : T('all')) + '' + sw(x.enabled, 'data-rule-en="' + x.id + '"' + (isAdmin() ? '' : ' disabled')) + '' + (isAdmin() ? ' ' : '') + '
' : '
No rules. Add e.g. “Teleexpress” or “^News$”.
'); function edit(rule) { rule = rule || { name: '', pattern: '', channel_id: null, enabled: true }; var body = modal(rule.id ? 'Edit rule' : 'New rule', '
' + '' + '
' + '
Matching programmes (48 h)
' + ''); 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 '
' + hm(e.start) + '' + esc(e.title) + ' ' + esc(chName(e.channel_id)) + ' · ' + dmy(e.start) + '
'; }).join('') : '
' + esc(T('No matching programmes in the EPG.')) + '
'; }).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 ? '' + list.map(function (r) { var st = REC_STATUS[r.status] || [r.status, '']; return '' + '' + ''; }).join('') + '
StatusTitleChannelStartEndTimeSize
' + st[0] + '' + esc(r.title) + '' + (r.error ? '
' + esc(r.error) + '
' : '') + '
' + esc(r.channel_name) + '' + dt(r.start) + '' + hm(r.stop) + '' + (r.duration ? dur(r.duration) : dur(r.stop - r.start)) + '' + (r.size ? bytes(r.size) : '–') + '' + (r.autorec_id ? 'R ' : '') + (r.file && r.size ? ' Download ' : '') + (isAdmin() && (r.status === 'scheduled' || r.status === 'recording') ? ' ' : '') + (isAdmin() ? '' : '') + '
' : '
No recordings in this category.
'; $$('[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, '

' + dt(r.start) + ' · ' + dur(r.duration) + ' · ' + bytes(r.size) + '

', 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', '
' + '' + '
'); $('#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() ? '' : '') + '

Adapters

' + '

Scanning

' + '

Muxes

' + (isAdmin() ? '' : '') + '
'; var presets = []; function adapters() { api('GET', '/api/adapters').then(function (list) { $('#ad-list').innerHTML = list.length ? '' + list.map(function (a) { return '' + '' + ''; }).join('') + '
' + esc(a.name) + '
' + esc(a.id + ' · ' + a.path) + '
' + esc(a.delivery_systems.join(' / ')) + '' + (a.active ? '' + esc(a.active.tuning) + '' : a.busy ? 'scanning' : 'idle') + '' + sw(a.enabled, 'data-ad="' + esc(a.id) + '"' + (isAdmin() ? '' : ' disabled')) + '
' : '
No DVB cards detected. Check ls /dev/dvb, the driver and firmware (for Si2168: dvb-demod-si2168-*.fw) and membership in group video.
'; $$('[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 = '
' + '' + '' + '
' + '' + '' + '
' + '
' + '
' + '

'; 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 ? '' + esc(T('background')) + ' ' : ''; $('#scan-pill').innerHTML = running ? bg + '' + pct + '% · ' + esc(s.current) + '' : s.finished ? bg + 'finished ' + hm(s.finished) + '' : ''; 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 ? '
' : '') + '
Muxes found: ' + s.muxes_found + ' · services: ' + s.services_found + ' · new channels: ' + s.channels_created + '' + (s.error ? ' · ' + esc(s.error) + '' : '') + '
' + '
' + esc(s.log.join('\n') || 'Waiting for first results…') + '
'; 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 ? '' + list.map(function (m) { return '' + '' + '' + '' + ''; }).join('') + '
FrequencyUHF channelSystemNetworkTSIDServicesLast scanEPGEnabled
' + (m.frequency_hz / 1e6).toFixed(1) + ' MHz' + (m.tuned ? ' active' : '') + '' + (m.uhf_channel || '–') + '' + 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' ? ' ' + (m.symbol_rate / 1000) + ' kS/s ' + esc((m.modulation || 'auto').toUpperCase()) + '' : '') + '' + esc(m.network_name || '') + '' + (m.ts_id == null ? '–' : m.ts_id) + '' + m.services + '' + dt(m.last_scan) + '' + dt(m.last_epg) + '' + 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')) + '' + (isAdmin() ? '' : '') + '
' : '
No muxes – run a scan.
'; $$('[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', '
' + svcs.map(function (s) { return '' + ''; }).join('') + '
SIDLCNNameProviderTypeStreamsChannel
' + s.sid + '' + (s.lcn == null ? '–' : s.lcn) + '' + esc(s.name) + '' + (s.scrambled ? ' scrambled' : '') + '' + esc(s.provider) + '' + esc(s.kind) + '' + s.streams.map(function (x) { return esc(x.kind + ':' + x.pid + (x.lang ? '/' + x.lang : '')); }).join(' ') + '' + (s.channel_id ? 'yes' : '–') + '
', 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', '
' + '' + '' + '
' + ''); $('#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.') + '

Playlists & EPG

' + '

Access tokens

' + (isAdmin() ? '' : '') + '
' + '

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.

' + '

Panel users

' + (isAdmin() ? '' : '') + '
' + '
' + (isAdmin() ? '

Access control (ACL)

' : ''); function links() { api('GET', '/api/links').then(function (r) { var portNote = r.stream_port && !r.stream_port_active ? '
' + 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.')) + '
' : ''; $('#links').innerHTML = portNote + '

Default M3U format: ' + esc(r.default_format.toUpperCase()) + ' (change it in Settings). Add &format=hls or &format=ts, and for transcoding &profile=aac / &profile=h264.

' + r.links.map(function (l) { return '
' + esc(l.name) + '
' + '
M3U' + esc(l.m3u) + '
' + '
HLS' + esc(l.m3u_hls) + '
' + '
EPG' + esc(l.epg) + '
' + '
TVH' + esc(l.tvh_playlist) + '
' + '
TVH' + esc(l.tvh_xmltv) + '
'; }).join('') + (r.htsp_port ? '
HTSP
HTSP' + esc(location.hostname + ':' + r.htsp_port) + '' + (r.htsp_port_active ? '' : ' ' + esc(T('port taken (tvheadend?)')) + '') + '
' + '

' + 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.')) + '

' : '') + '

' + esc(T('TVH = tvheadend-compatible URLs (stream port, 9981 by default): /playlist, /xmltv/channels, /stream/channelid/, /imagecache/, auth= / ticket= parameters and HTTP Basic login. An app configured for tvheadend works after changing just the server address.')) + '

'; $$('[data-c]', $('#links')).forEach(function (b) { b.addEventListener('click', function () { copy(b.parentNode.querySelector('code').textContent); }); }); }).catch(fail); } function tokens() { if (!isAdmin()) { $('#tokens').innerHTML = '
Administrators only.
'; return; } api('GET', '/api/tokens').then(function (list) { $('#tokens').innerHTML = list.length ? '' + list.map(function (t) { return '' + '' + ''; }).join('') + '
NameNetworksLast usedActive
' + esc(t.name) + '
' + esc(t.token.slice(0, 6)) + '…
' + esc(t.allow_cidrs || 'all') + '' + dt(t.last_used) + '' + sw(t.enabled, 'data-tok-en="' + t.id + '" data-tok=\'' + esc(JSON.stringify({ name: t.name, allow_cidrs: t.allow_cidrs })) + '\'') + '
' : '
No tokens.
'; $$('[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 = '
Signed in as ' + esc(app.me.username) + '.
'; return; } api('GET', '/api/users').then(function (list) { $('#users').innerHTML = '' + list.map(function (u) { return '' + ''; }).join('') + '
LoginRoleCreated
' + esc(u.username) + '' + (u.id === app.me.id ? ' you' : '') + '' + dmy(u.created_at) + ' ' + (u.id !== app.me.id ? '' : '') + '
'; $$('[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 '
' + esc(T('DDNS host names now resolve to:')) + ' ' + hosts.map(function (h) { return '' + esc(h) + ' → ' + esc((m[h] || []).join(', ') || T('not resolved')) + ''; }).join(' · ') + '
'; } function acl() { if (!isAdmin()) return; api('GET', '/api/settings').then(function (s) { $('#acl').innerHTML = '' + '' + aclResolved(s.acl_resolved) + ''; $('#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', '
'); $('#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', '
'); $('#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', '
'); $('#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.', '⤓ Download') + '
' + '
' + '
' + '
'; var cat = sessionStorage.getItem('sdvb-logcat') || '', level = '', q = '', since = 0, entries = [], cats = []; function renderCats() { $('#log-cats').innerHTML = '' + cats.map(function (c) { return ''; }).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 '
' + dmy(e.t_ms / 1000) + ' ' + ts + '' + e.level.toUpperCase() + '' + esc(T(CAT_NAMES[e.category] || e.category)) + '' + esc(e.message) + '' + esc(e.target.replace(/^simply_dvb::/, '')) + '
'; } 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 = '
' + esc(T('No entries match.')) + '
'; } }).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 '
' + opts.map(function (o) { return ''; }).join('') + '
'; } function row(label, ctl) { return '
' + esc(label) + '
' + ctl + '
'; } 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 = '

Appearance

' + '

Interface preferences are stored in this browser.

' + row('Language', langSelect('pref-lang', false)) + row('Theme', seg('theme', [['dark', 'Dark'], ['midnight', 'Midnight (OLED)'], ['light', 'Light'], ['system', 'System default']])) + row('Accent colour', '
' + P.accents.map(function (a) { return ''; }).join('') + '
') + 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', '
' + [['auto', 'Automatic'], ['pass', 'Original'], ['aac', 'Audio → AAC'], ['h264', 'H.264 720p']].map(function (o) { return ''; }).join('') + '
') + 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() ? '' : '') + '
'; renderPrefs(); var cur = null; function field(name, label, type, hint, extra) { var v = cur[name]; var input = type === 'bool' ? '' : type === 'select' ? '' : '' + esc(label) + ''; return type === 'bool' ? '
' + input + (hint ? '
' + esc(hint) + '
' : '') + '
' : input.replace(/<\/label>$/, (hint ? '' + esc(hint) + '' : '') + ''); } function render() { $('#set-body').innerHTML = '

General

' + 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') + '
' + '

Streaming (HLS / TS)

' + 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)']]) + '
' + '

Transcoding (ffmpeg)

' + 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.') + '
' + '

EPG

' + (isAdmin() ? '
' : '') + '
' + 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') + '' + '
' + '

Channel icons

' + '

Recording

' + 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') + '
' + '

Scanning

' + 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”') + '
' + (isAdmin() ? '

Backup

Muxes, services, channels (order, groups, links), recording rules, tokens and settings. Without user accounts, EPG, icons and recording files.

' + '
' : ''); 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(); })();