/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.',
'◀ 6 h Now 6 h ▶ ' +
(isAdmin() ? 'Grab EPG now ' : '')) + '
';
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 ? '' + 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() ? 'Find icons + Add from services Renumber 1..n ' : '') +
'';
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 '' + esc(T(label)) + ' '; };
var chk = function (k, label, n) { return ' ' + esc(T(label)) + ' (' + n + ') '; };
$('#ch-filters').innerHTML = ' ' +
'' + opt('', 'All types', F.kind) + opt('tv', 'TV', F.kind) + opt('radio', 'Radio', F.kind) + opt('other', 'Other / data', F.kind) + ' ' +
'' + opt('', 'All groups', F.grp) + groups.map(function (g) { return opt(g, g, F.grp); }).join('') + ' ' +
'' + opt('', 'Enabled and disabled', F.state) + opt('on', 'Enabled only', F.state) + opt('off', 'Disabled only', F.state) + ' ' +
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) ? '' + esc(T('Detect streams')) + ' (' + count(unknownStreams) + ') ' : '') +
(isAdmin() ? 'Enable shown Disable shown Delete shown ' : '');
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.
' :
'No. Logo Name Group Codecs Mux Now Enabled Public link ' +
list.map(function (c) {
var s = c.service || {};
var pr = problem(c);
return '⠿ ' + 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 ? ' Copy link ' : '') + ' ' +
'▶ VLC ' + (isAdmin() ? ' Edit ' : '') + ' ';
}).join('') + '
';
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,
'' +
'TV Radio Information Sport Children Movies ' +
'');
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 '' + esc(x.names.join(' / ')) + ' '; }).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:
' : '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() ? '+ New recording ' : '') +
'Scheduled & running Schedule Finished Failed / cancelled Rules (series)
';
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 += 'Start End Title Channel Status ' + list.map(function (x) {
var st = REC_STATUS[x.status] || [x.status, ''];
return '' + dt(x.start) + ' ' + hm(x.stop) + ' ' + esc(x.title) + ' ' + esc(x.channel_name) + ' ' + st[0] + ' ' + (x.conflict ? ' ' + esc(T('conflict')) + ' ' : '') + ' ';
}).join('') + '
';
$('#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() ? '+ New rule
' : '') +
(rules.length ? 'Name Pattern Channel Active ' + rules.map(function (x) {
return '' + 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() ? 'Edit Delete ' : '') + ' ';
}).join('') + '
' : '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',
'Name ' +
'Channelall ' + chs.map(function (c) { return '' + c.number + ' · ' + esc(c.name) + ' '; }).join('') + ' ' +
'Title pattern
' +
'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 ? 'Status Title Channel Start End Time Size ' +
list.map(function (r) {
var st = REC_STATUS[r.status] || [r.status, ''];
return '' + 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 ? '▶ Play Download ' : '') +
(isAdmin() && (r.status === 'scheduled' || r.status === 'recording') ? '' + (r.status === 'recording' ? '■ Stop' : 'Cancel') + ' ' : '') +
(isAdmin() ? 'Delete ' : '') + ' ';
}).join('') + '
' : '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', 'Channel' + chs.map(function (c) { return '' + c.number + ' · ' + esc(c.name) + ' '; }).join('') + ' ' +
'Title Starts ' +
'End
');
$('#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() ? 'Detect adapters ' : '') +
'' +
'Muxes ' + (isAdmin() ? '+ Add manually ' : '') + '
';
var presets = [];
function adapters() {
api('GET', '/api/adapters').then(function (list) {
$('#ad-list').innerHTML = list.length ? '' + list.map(function (a) {
return '' + 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')) + ' ';
}).join('') + '
' : '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 = '' +
'Start scan Stop
' +
'
';
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 ? 'Frequency UHF channel System Network TSID Services Last scan EPG Enabled ' +
list.map(function (m) {
return '' + (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() ? 'Delete ' : '') + ' ';
}).join('') + '
' : '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', 'SID LCN Name Provider Type Streams Channel ' + svcs.map(function (s) {
return '' + 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 ' : '–') + ' ';
}).join('') + '
', 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', 'SystemDVB-T2 DVB-T DVB-C ' +
'Frequency (MHz) Bandwidth (MHz)8 7 6 ' +
'PLP (DVB-T2, optional) ' +
'Symbol rate (kS/s, DVB-C) Modulation (DVB-C)auto QAM-256 QAM-128 QAM-64
' +
'');
$('#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.') +
'' +
'Access tokens ' + (isAdmin() ? '+ New token ' : '') + '
' +
'
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() ? '+ New user ' : '') + '
' +
'
Change my password
' +
(isAdmin() ? 'Access control (ACL) Save 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) + 'Copy
' +
'
HLS ' + esc(l.m3u_hls) + 'Copy
' +
'
EPG ' + esc(l.epg) + 'Copy
' +
'
TVH ' + esc(l.tvh_playlist) + 'Copy
' +
'
TVH ' + esc(l.tvh_xmltv) + 'Copy
';
}).join('') +
(r.htsp_port ? 'HTSP
HTSP ' + esc(location.hostname + ':' + r.htsp_port) + 'Copy ' +
(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 ? 'Name Networks Last used Active ' + list.map(function (t) {
return '' + 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 })) + '\'') + ' ' +
'Copy token Delete ';
}).join('') + '
' : '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 = 'Login Role Created ' + list.map(function (u) {
return '' + esc(u.username) + ' ' + (u.id === app.me.id ? ' you ' : '') + 'administrator viewer ' +
'' + dmy(u.created_at) + ' Password ' + (u.id !== app.me.id ? 'Delete ' : '') + ' ';
}).join('') + '
';
$$('[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 = 'Networks with token-free access to streams, M3U and EPGOne 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. ' +
'Networks allowed to reach the panelNetworks, addresses or DDNS host names. Empty = panel reachable from anywhere (login still required). ' +
aclResolved(s.acl_resolved) +
'Trusted reverse proxiesX-Forwarded-For / X-Forwarded-Proto are honoured only from these addresses (e.g. RustProxy). ';
$('#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', 'Current password New 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', 'Name Allowed networks (optional)
');
$('#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', 'Login Roleviewer (watch only) administrator Password
');
$('#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 Clear view ') +
'';
var cat = sessionStorage.getItem('sdvb-logcat') || '', level = '', q = '', since = 0, entries = [], cats = [];
function renderCats() {
$('#log-cats').innerHTML = '' + esc(T('All')) + ' ' + cats.map(function (c) {
return '' + esc(T(CAT_NAMES[c.id] || c.id)) + ' ' + c.count + ' ' + (c.problems ? ' ' + c.problems + ' ' : '') + ' ';
}).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 '' + esc(o[1]) + ' ';
}).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 Reset to defaults ' +
'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 '' + esc(o[1]) + ' ';
}).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() ? 'Save settings ' : '') +
'
';
renderPrefs();
var cur = null;
function field(name, label, type, hint, extra) {
var v = cur[name];
var input = type === 'bool' ? ' ' + esc(label) + ' '
: type === 'select' ? '' + esc(label) + '' + extra.map(function (o) { return '' + esc(o[1]) + ' '; }).join('') + ' '
: '' + esc(label) + ' ';
return type === 'bool' ? '' + input + (hint ? '
' + esc(hint) + '
' : '') + '
' : input.replace(/<\/label>$/, (hint ? '' + esc(hint) + ' ' : '') + '');
}
function render() {
$('#set-body').innerHTML =
'' +
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') + '
' +
'' +
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)']]) + '
' +
'' + 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() ? 'Import XMLTV now
' : '') + ' ' +
'Icon URL templates' +
'{slug} is replaced with the channel name, e.g. “tvp-1”, “polsat-news”. First hit wins; icons are stored locally.
' +
'' + 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') + '
' +
'' + 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() ? '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();
})();