Eerste versie: IPTV-app met zenderfilter, tv-gids en eigen Homebrew-bron

This commit is contained in:
Frank committed 2026-10-27 19:41:57 +01:00
commit 94dffa122f
26 files changed
+1740

No files matched your search

+196
View File
@@ -0,0 +1,196 @@
/* Tv-gids (XMLTV). Grote gidsbestanden (tientallen MB, ook .gz) worden in stukjes gelezen,
en alleen programma's van je gekozen zenders worden bewaard. Zo blijft het geheugen van de tv klein. */
(function (App) {
'use strict';
var KEEP_BEFORE = 3 * 3600e3; // programma's tot 3 uur terug
var KEEP_AFTER = 2 * 86400e3; // en tot 2 dagen vooruit
var MAX_AGE = 6 * 3600e3; // gids na 6 uur verversen
var Epg = { data: {}, map: {}, at: 0, loading: false };
App.Epg = Epg;
/* "20261027203000 +0100" -> ms */
Epg.parseTime = function (s) {
var m = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})?\s*([+-]\d{2}):?(\d{2})?/.exec(String(s || '').trim());
if (!m) return NaN;
var t = Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +(m[6] || 0));
if (m[7]) {
var sign = m[7].charAt(0) === '-' ? -1 : 1;
var off = sign * (Math.abs(parseInt(m[7], 10)) * 60 + parseInt(m[8] || '0', 10));
t -= off * 60000;
}
return t;
};
function attr(tag, name) {
var m = new RegExp('\\s' + name + '\\s*=\\s*"([^"]*)"').exec(tag) || new RegExp('\\s' + name + "\\s*=\\s*'([^']*)'").exec(tag);
return m ? m[1] : '';
}
function inner(xml, name) {
var m = new RegExp('<' + name + '(?:\\s[^>]*)?>([\\s\\S]*?)</' + name + '>').exec(xml);
return m ? App.xmlText(m[1]) : '';
}
/* Leest XMLTV-tekst die in brokken binnenkomt */
function Scanner(wantedIds, wantedNames, now) {
this.buf = '';
this.wantedIds = wantedIds; // epg-id (kleine letters) -> true
this.wantedNames = wantedNames; // genormaliseerde naam -> [zendersleutel]
this.nameIds = {}; // epg-id gevonden via naam -> true
this.nameMap = {}; // zendersleutel -> epg-id
this.data = {};
this.kept = 0;
this.min = now - KEEP_BEFORE;
this.max = now + KEEP_AFTER;
}
Scanner.prototype.push = function (text) {
this.buf += text;
var buf = this.buf, pos = 0, ci = -2, pi = -2;
for (;;) {
// zoekresultaten hergebruiken: anders wordt de buffer per element opnieuw doorzocht
if (ci !== -1 && ci < pos) ci = buf.indexOf('<channel', pos);
if (pi !== -1 && pi < pos) pi = buf.indexOf('<programme', pos);
var start, isProg;
if (pi >= 0 && (ci < 0 || pi < ci)) { start = pi; isProg = true; }
else if (ci >= 0) { start = ci; isProg = false; }
else { this.buf = buf.slice(Math.max(pos, buf.length - 16)); return; }
var gt = buf.indexOf('>', start);
if (gt < 0) { this.buf = buf.slice(start); return; }
var open = buf.slice(start, gt + 1), elem, next;
if (buf.charAt(gt - 1) === '/') { elem = open; next = gt + 1; }
else {
var closeTag = isProg ? '</programme>' : '</channel>';
var end = buf.indexOf(closeTag, gt);
if (end < 0) { this.buf = buf.slice(start); return; }
next = end + closeTag.length;
elem = buf.slice(start, next);
}
if (isProg) this.programme(open, elem); else this.channel(open, elem);
pos = next;
}
};
Scanner.prototype.channel = function (open, elem) {
var id = attr(open, 'id').toLowerCase();
if (!id) return;
var re = /<display-name[^>]*>([\s\S]*?)<\/display-name>/g, m;
while ((m = re.exec(elem)) !== null) {
var keys = this.wantedNames[App.normName(App.xmlText(m[1]))];
if (!keys) continue;
for (var i = 0; i < keys.length; i++) if (!this.nameMap[keys[i]]) this.nameMap[keys[i]] = id;
this.nameIds[id] = true;
}
};
Scanner.prototype.programme = function (open, elem) {
var id = attr(open, 'channel').toLowerCase();
if (!this.wantedIds[id] && !this.nameIds[id]) return;
var s = Epg.parseTime(attr(open, 'start')), e = Epg.parseTime(attr(open, 'stop'));
if (isNaN(s)) return;
if (isNaN(e)) e = s + 30 * 60000;
if (e < this.min || s > this.max) return;
var desc = inner(elem, 'desc');
if (desc.length > 400) desc = desc.slice(0, 397) + '…';
(this.data[id] || (this.data[id] = [])).push([s, e, inner(elem, 'title') || '(zonder titel)', desc]);
this.kept++;
};
/* Haal de gids op voor de gekozen zenders */
Epg.load = function (url, channels, onProgress) {
if (!url) return Promise.reject(new Error('Geen EPG-URL bekend. Vul er een in bij Instellingen.'));
var wantedIds = {}, wantedNames = {};
channels.forEach(function (c) {
if (c.tvgId) wantedIds[c.tvgId.toLowerCase()] = true;
var n = App.normName(c.name);
(wantedNames[n] || (wantedNames[n] = [])).push(c.key);
});
var sc = new Scanner(wantedIds, wantedNames, Date.now());
var bytes = 0, decoder = new TextDecoder('utf-8'), inflator = null, first = true;
Epg.loading = true;
function feedRaw(chunk) {
bytes += chunk.length;
if (first) {
first = false;
if (chunk[0] === 0x1f && chunk[1] === 0x8b) {
inflator = new pako.Inflate();
inflator.onData = function (out) { sc.push(decoder.decode(out, { stream: true })); };
}
}
if (inflator) {
inflator.push(chunk, false);
if (inflator.err) throw new Error('Gids uitpakken mislukt: ' + inflator.msg);
} else sc.push(decoder.decode(chunk, { stream: true }));
if (onProgress) onProgress(bytes, sc.kept);
}
function finish() {
if (inflator) inflator.push(new Uint8Array(0), true);
sc.push(decoder.decode());
var map = {};
channels.forEach(function (c) {
var id = c.tvgId ? c.tvgId.toLowerCase() : '';
if (id && sc.data[id]) map[c.key] = id;
else if (sc.nameMap[c.key] && sc.data[sc.nameMap[c.key]]) map[c.key] = sc.nameMap[c.key];
});
Object.keys(sc.data).forEach(function (id) { sc.data[id].sort(function (a, b) { return a[0] - b[0]; }); });
Epg.data = sc.data; Epg.map = map; Epg.at = Date.now(); Epg.loading = false;
Epg.save();
return { programmes: sc.kept, matched: Object.keys(map).length, total: channels.length, mb: bytes / 1048576 };
}
return App.fetchWithTimeout(url, 300000).then(function (r) {
if (!r.ok) throw new Error('HTTP ' + r.status + ' bij gids');
if (r.body && r.body.getReader) {
var reader = r.body.getReader();
var pump = function () {
return reader.read().then(function (res) {
if (res.done) return finish();
feedRaw(res.value);
return pump();
});
};
return pump();
}
return r.arrayBuffer().then(function (buf) { feedRaw(new Uint8Array(buf)); return finish(); });
}).catch(function (e) { Epg.loading = false; throw e; });
};
Epg.save = function () {
var payload = { at: Epg.at, map: Epg.map, data: Epg.data };
if (App.store.set('epg', payload)) return;
// te groot: beschrijvingen weglaten
var slim = {};
Object.keys(Epg.data).forEach(function (id) {
slim[id] = Epg.data[id].map(function (p) { return [p[0], p[1], p[2], '']; });
});
App.store.set('epg', { at: Epg.at, map: Epg.map, data: slim });
};
Epg.restore = function () {
var c = App.store.get('epg', null);
if (!c || !c.data) return;
var min = Date.now() - KEEP_BEFORE;
Object.keys(c.data).forEach(function (id) {
c.data[id] = c.data[id].filter(function (p) { return p[1] > min; });
});
Epg.data = c.data; Epg.map = c.map || {}; Epg.at = c.at || 0;
};
Epg.isStale = function () { return !Epg.at || Date.now() - Epg.at > MAX_AGE; };
Epg.list = function (ch) {
var id = ch ? Epg.map[ch.key] : null;
return (id && Epg.data[id]) || [];
};
/* Huidig en volgend programma */
Epg.nowNext = function (ch, t) {
var l = Epg.list(ch);
t = t || Date.now();
for (var i = 0; i < l.length; i++) {
if (l[i][0] <= t && l[i][1] > t) return { now: l[i], next: l[i + 1] || null };
if (l[i][0] > t) return { now: null, next: l[i] };
}
return { now: null, next: null };
};
})(window.App);
+115
View File
@@ -0,0 +1,115 @@
/* Opstarten, zappen en de afstandsbediening. */
(function (App) {
'use strict';
var $ = App.$, K = App.KEY;
App.state = {
view: 'tv',
cfg: App.store.get('cfg', { type: 'm3u', output: 'm3u8' }),
channels: App.store.get('channels', []),
idx: App.store.get('idx', 0)
};
App.allChannels = null;
App.saveChannels = function () { App.store.set('channels', App.state.channels); };
App.epgUrl = function () {
var c = App.state.cfg;
if (c.epg) return c.epg;
if (c.type === 'xtream' && c.server && c.user) return App.xtreamEpgUrl(c);
return App.store.get('srcEpg', '');
};
App.loadEpg = function (onProgress) {
return App.Epg.load(App.epgUrl(), App.state.channels, onProgress);
};
function epgInBackground() {
if (App.Epg.loading || !App.state.channels.length || !App.epgUrl() || !App.Epg.isStale()) return;
App.loadEpg().then(function (r) {
console.log('gids geladen', r);
if (App.state.view === 'guide') App.Guide.render();
if (App.state.view === 'list') App.List.render();
}).catch(function (e) { console.warn('gids laden mislukt', e); });
}
/* Naar zender idx */
App.tune = function (idx, force) {
var st = App.state, n = st.channels.length;
if (!n) return;
idx = ((idx % n) + n) % n;
if (idx === st.idx && !force && App.Player.current()) { App.OSD.show(); return; }
st.idx = idx;
App.store.set('idx', idx);
App.Player.play(st.channels[idx]);
App.OSD.show();
};
/* Nummer intikken: na 2 seconden naar die zender */
var numBuf = '', numTimer = null;
function digit(d) {
numBuf = (numBuf + d).slice(-4);
var ne = $('numentry');
ne.textContent = numBuf; ne.classList.remove('hidden');
clearTimeout(numTimer);
numTimer = setTimeout(function () {
ne.classList.add('hidden');
var n = parseInt(numBuf, 10); numBuf = '';
if (n >= 1 && n <= App.state.channels.length) App.tune(n - 1);
else App.showMessage('Zender ' + n + ' bestaat niet.', 2000);
}, 2000);
}
var backArmed = 0;
function tvKey(k) {
if (k === K.UP || k === K.CH_UP) App.tune(App.state.idx + 1);
else if (k === K.DOWN || k === K.CH_DOWN) App.tune(App.state.idx - 1);
else if (k === K.OK) App.List.open();
else if (k === K.RED || k === K.GUIDE || k === K.RIGHT) App.Guide.open();
else if (k === K.GREEN || k === K.INFO || k === K.LEFT) { if (App.OSD.visible()) App.OSD.hide(); else App.OSD.show(8000); }
else if (k === K.BLUE) App.Settings.open();
else if (k >= 48 && k <= 57) digit(k - 48);
else if (App.isBack(k)) {
if (App.OSD.visible()) { App.OSD.hide(); return; }
if (Date.now() - backArmed < 3000) { App.Player.stop(); window.close(); return; }
backArmed = Date.now();
App.showMessage('Druk nogmaals op Terug om af te sluiten', 3000);
}
}
document.addEventListener('keydown', function (ev) {
var k = ev.keyCode, v = App.state.view;
var typing = document.activeElement && document.activeElement.tagName === 'INPUT';
// tijdens typen: gewone toetsen aan het invoerveld laten
if (typing && !(App.isBack(k) || k === K.OK || k === K.UP || k === K.DOWN)) return;
if (typing && k === K.BACKSPACE) return;
if (v === 'tv') tvKey(k);
else if (v === 'list') App.List.key(k);
else if (v === 'guide') App.Guide.key(k);
else if (v === 'settings') App.Settings.key(k);
else if (v === 'picker') App.Picker.key(k);
ev.preventDefault();
});
/* App naar de achtergrond: stream stoppen; terug: verder kijken */
document.addEventListener('visibilitychange', function () {
if (document.hidden) App.Player.stop();
else if (App.state.view === 'tv' && App.state.channels.length) App.tune(App.state.idx, true);
});
function boot() {
App.Player.init();
App.Epg.restore();
if (App.state.channels.length) {
App.state.view = 'tv';
App.tune(Math.min(App.state.idx, App.state.channels.length - 1), true);
} else {
App.Settings.open();
}
epgInBackground();
setInterval(epgInBackground, 30 * 60000);
setInterval(function () { if (App.OSD.visible()) $('osd-clock').textContent = App.fmtTime(Date.now()); }, 15000);
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
})(window.App);
+98
View File
@@ -0,0 +1,98 @@
/* Afspelen. HLS (.m3u8) eerst via de ingebouwde speler van webOS, met hls.js als terugval.
MPEG-TS via mpegts.js. Bij een fout wordt automatisch de andere methode geprobeerd. */
(function (App) {
'use strict';
var video, hls = null, ts = null, current = null, attempt = 0, stallTimer = null;
function isHls(url) { return /\.m3u8(\?|$)/i.test(url); }
function isTs(url) { return /\.ts(\?|$)/i.test(url) || /\/live\/[^/]+\/[^/]+\/\d+$/.test(url); }
function teardown() {
clearTimeout(stallTimer);
if (hls) { try { hls.destroy(); } catch (e) { /* niets */ } hls = null; }
if (ts) { try { ts.pause(); ts.unload(); ts.detachMediaElement(); ts.destroy(); } catch (e) { /* niets */ } ts = null; }
video.removeAttribute('src');
try { video.load(); } catch (e) { /* niets */ }
}
/* Volgorde van methodes per soort stream */
function methods(url) {
var nativeHls = !!video.canPlayType('application/vnd.apple.mpegurl');
var hlsJs = window.Hls && Hls.isSupported();
var tsJs = window.mpegts && mpegts.getFeatureList().mseLivePlayback;
var list = [];
if (isHls(url)) {
if (nativeHls) list.push('native');
if (hlsJs) list.push('hlsjs');
} else if (isTs(url)) {
if (tsJs) list.push('mpegts');
list.push('native');
} else {
list.push('native');
if (hlsJs) list.push('hlsjs');
if (tsJs) list.push('mpegts');
}
return list;
}
function start(method, url) {
App.Player.method = method;
if (method === 'native') {
video.src = url;
video.play().catch(function () { /* autoplay-weigering negeren; error-event volgt bij echte fouten */ });
} else if (method === 'hlsjs') {
hls = new Hls({ lowLatencyMode: false, liveSyncDurationCount: 3, enableWorker: true });
hls.on(Hls.Events.ERROR, function (ev, data) { if (data.fatal) failed('hls.js: ' + data.details); });
hls.loadSource(url);
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, function () { video.play().catch(function () {}); });
} else if (method === 'mpegts') {
ts = mpegts.createPlayer({ type: 'mpegts', isLive: true, url: url },
{ enableWorker: false, lazyLoad: false, liveBufferLatencyChasing: true, liveBufferLatencyMaxLatency: 6 });
ts.on(mpegts.Events.ERROR, function (type, detail) { failed('mpegts: ' + type + ' ' + detail); });
ts.attachMediaElement(video);
ts.load();
var p = ts.play(); if (p && p.catch) p.catch(function () {});
}
// na 15 s nog geen beeld: volgende methode proberen
clearTimeout(stallTimer);
stallTimer = setTimeout(function () { if (video.readyState < 2) failed('geen beeld na 15 s'); }, 15000);
}
function failed(reason) {
if (!current) return;
console.warn('afspelen mislukt (' + App.Player.method + '): ' + reason);
var list = methods(current.url);
attempt++;
teardown();
if (attempt < list.length) start(list[attempt], current.url);
else {
App.Player.method = null;
App.showMessage('Deze zender speelt niet af.\n' + reason, 6000);
}
}
App.Player = {
method: null,
init: function () {
video = App.$('video');
video.addEventListener('error', function () {
// alleen fouten van de huidige stream tellen (niet van een vorige die net is gestopt)
if (App.Player.method === 'native' && current && video.getAttribute('src') === current.url) {
failed('mediafout ' + (video.error ? video.error.code : '?'));
}
});
video.addEventListener('playing', function () { clearTimeout(stallTimer); App.hideMessage(); });
},
play: function (ch) {
teardown();
current = ch; attempt = 0;
var list = methods(ch.url);
if (!list.length) { App.showMessage('Dit streamformaat wordt niet ondersteund.', 5000); return; }
start(list[0], ch.url);
},
stop: function () { current = null; teardown(); },
current: function () { return current; }
};
})(window.App);
+105
View File
@@ -0,0 +1,105 @@
/* Zenders ophalen: M3U-afspeellijst of Xtream Codes-API. Alleen live-tv, geen films/series. */
(function (App) {
'use strict';
function chKey(c) { return c.tvgId ? 'id:' + c.tvgId.toLowerCase() : 'nm:' + App.normName(c.name) + '|' + (c.group || ''); }
App.chKey = chKey;
/* Zet een M3U-tekst om naar { epgUrl, channels[] } */
App.parseM3U = function (text) {
var lines = text.split(/\r?\n/);
var out = [], epgUrl = '', cur = null, grp = '';
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim();
if (!line) continue;
if (line.indexOf('#EXTM3U') === 0) {
var m = /(?:x-tvg-url|url-tvg)="([^"]+)"/.exec(line);
if (m) epgUrl = m[1].split(',')[0].trim();
} else if (line.indexOf('#EXTINF') === 0) {
var attrs = {}, re = /([\w-]+)="([^"]*)"/g, a;
while ((a = re.exec(line)) !== null) attrs[a[1].toLowerCase()] = a[2];
var comma = line.lastIndexOf('",');
var name = comma >= 0 ? line.slice(comma + 2) : line.slice(line.indexOf(',') + 1);
cur = {
name: (name || attrs['tvg-name'] || '').trim(),
tvgId: (attrs['tvg-id'] || '').trim(),
logo: attrs['tvg-logo'] || '',
group: attrs['group-title'] || ''
};
} else if (line.indexOf('#EXTGRP:') === 0) {
grp = line.slice(8).trim();
} else if (line.charAt(0) !== '#') {
if (cur) {
cur.url = line;
if (!cur.group) cur.group = grp || 'Overig';
if (!/\/(movie|series)\//i.test(line) && !/\.(mp4|mkv|avi)(\?|$)/i.test(line)) {
cur.key = chKey(cur);
out.push(cur);
}
}
cur = null; grp = '';
}
}
return { epgUrl: epgUrl, channels: dedupe(out) };
};
/* Twee zenders met dezelfde sleutel krijgen een volgnummer, zodat ze apart te kiezen zijn */
function dedupe(list) {
var seen = {};
list.forEach(function (c) {
if (seen[c.key]) { seen[c.key]++; c.key = c.key + '#' + seen[c.key]; } else seen[c.key] = 1;
});
return list;
}
function trimSlash(s) { return String(s || '').trim().replace(/\/+$/, ''); }
App.xtreamEpgUrl = function (cfg) {
return trimSlash(cfg.server) + '/xmltv.php?username=' + encodeURIComponent(cfg.user) +
'&password=' + encodeURIComponent(cfg.pass);
};
/* Xtream Codes: live-categorieën en -zenders via player_api.php (veel kleiner dan de m3u_plus-lijst) */
App.loadXtream = function (cfg) {
var base = trimSlash(cfg.server);
if (!/^https?:\/\//i.test(base)) base = 'http://' + base;
var api = base + '/player_api.php?username=' + encodeURIComponent(cfg.user) + '&password=' + encodeURIComponent(cfg.pass);
var ext = cfg.output === 'ts' ? 'ts' : 'm3u8';
return App.fetchText(api, 30000).then(function (t) {
var info = JSON.parse(t);
if (info && info.user_info && String(info.user_info.auth) === '0') throw new Error('Inloggen geweigerd: controleer gebruikersnaam en wachtwoord.');
return Promise.all([
App.fetchText(api + '&action=get_live_categories', 60000),
App.fetchText(api + '&action=get_live_streams', 120000)
]);
}).then(function (res) {
var cats = {}, list = [];
(JSON.parse(res[0]) || []).forEach(function (c) { cats[c.category_id] = c.category_name; });
(JSON.parse(res[1]) || []).forEach(function (s) {
var c = {
name: String(s.name || '').trim(),
tvgId: String(s.epg_channel_id || '').trim(),
logo: s.stream_icon || '',
group: cats[s.category_id] || 'Overig',
url: base + '/live/' + encodeURIComponent(cfg.user) + '/' + encodeURIComponent(cfg.pass) + '/' + s.stream_id + '.' + ext
};
c.key = 'xt:' + s.stream_id;
list.push(c);
});
return { epgUrl: App.xtreamEpgUrl(cfg), channels: list };
});
};
/* Haal de volledige lijst op volgens de instellingen */
App.loadSource = function (cfg) {
if (cfg.type === 'xtream') {
if (!cfg.server || !cfg.user) return Promise.reject(new Error('Vul server, gebruikersnaam en wachtwoord in.'));
return App.loadXtream(cfg);
}
if (!cfg.m3u) return Promise.reject(new Error('Vul de M3U-URL in.'));
return App.fetchText(cfg.m3u, 120000).then(function (t) {
if (t.indexOf('#EXTINF') < 0) throw new Error('Dit lijkt geen M3U-afspeellijst te zijn.');
return App.parseM3U(t);
});
};
})(window.App);
+83
View File
@@ -0,0 +1,83 @@
/* Hulpfuncties. Bewust ES2017 (geen ?. of ??): de BX draait webOS 5 met Chromium 68. */
var App = window.App || {};
window.App = App;
App.$ = function (id) { return document.getElementById(id); };
App.KEY = {
LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, OK: 13,
BACK: 461, ESC: 27, BACKSPACE: 8,
CH_UP: 33, CH_DOWN: 34,
RED: 403, GREEN: 404, YELLOW: 405, BLUE: 406,
INFO: 457, GUIDE: 458
};
App.isBack = function (k) { return k === App.KEY.BACK || k === App.KEY.ESC || k === App.KEY.BACKSPACE; };
App.pad = function (n) { return (n < 10 ? '0' : '') + n; };
App.fmtTime = function (ms) { var d = new Date(ms); return App.pad(d.getHours()) + ':' + App.pad(d.getMinutes()); };
App.DAYS = ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'];
App.MONTHS = ['jan', 'feb', 'mrt', 'apr', 'mei', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'];
App.fmtDay = function (ms) {
var d = new Date(ms);
return App.DAYS[d.getDay()] + ' ' + d.getDate() + ' ' + App.MONTHS[d.getMonth()];
};
App.esc = function (s) {
return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) {
return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c];
});
};
/* XML-entiteiten en CDATA terug naar tekst */
App.xmlText = function (s) {
if (!s) return '';
s = s.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1');
return s.replace(/&(#x[0-9a-fA-F]+|#\d+|amp|lt|gt|quot|apos);/g, function (m, e) {
if (e === 'amp') return '&';
if (e === 'lt') return '<';
if (e === 'gt') return '>';
if (e === 'quot') return '"';
if (e === 'apos') return "'";
var code = e.charAt(1) === 'x' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
try { return String.fromCodePoint(code); } catch (err) { return ''; }
}).trim();
};
/* Namen vergelijken: "NPO 1 HD" == "npo1" */
App.normName = function (s) {
return String(s || '').toLowerCase()
.replace(/\b(hd|fhd|uhd|4k|sd|hevc|h265|backup)\b/g, '')
.replace(/^[a-z]{2,3}\s*[:|]\s*/, '') // landprefix zoals "NL: " of "UK | "
.replace(/[^a-z0-9]/g, '');
};
/* localStorage met vangnet (vol of geblokkeerd) */
App.store = {
get: function (k, def) {
try { var v = localStorage.getItem('iptv.' + k); return v == null ? def : JSON.parse(v); }
catch (e) { return def; }
},
set: function (k, v) {
try { localStorage.setItem('iptv.' + k, JSON.stringify(v)); return true; }
catch (e) { console.warn('opslaan mislukt', k, e); return false; }
},
del: function (k) { try { localStorage.removeItem('iptv.' + k); } catch (e) { /* niets */ } }
};
App.fetchText = function (url, timeoutMs) {
return App.fetchWithTimeout(url, timeoutMs || 60000).then(function (r) {
if (!r.ok) throw new Error('HTTP ' + r.status + ' bij ' + url);
return r.text();
});
};
App.fetchWithTimeout = function (url, timeoutMs) {
var ctrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
var t = setTimeout(function () { if (ctrl) ctrl.abort(); }, timeoutMs || 60000);
return fetch(url, ctrl ? { signal: ctrl.signal } : {}).then(function (r) {
clearTimeout(t); return r;
}, function (e) {
clearTimeout(t);
throw new Error((e && e.name === 'AbortError') ? 'Time-out bij ' + url : 'Kan ' + url + ' niet bereiken (' + e.message + ')');
});
};
+423
View File
@@ -0,0 +1,423 @@
/* Schermen: zenderinfo (OSD), zenderlijst, tv-gids, instellingen en zenders kiezen. */
(function (App) {
'use strict';
var $ = App.$, K = App.KEY;
/* ---------------- meldingen ---------------- */
var msgTimer = null;
App.showMessage = function (text, ms) {
var m = $('message');
m.textContent = text; m.classList.remove('hidden');
clearTimeout(msgTimer);
if (ms) msgTimer = setTimeout(App.hideMessage, ms);
};
App.hideMessage = function () { clearTimeout(msgTimer); $('message').classList.add('hidden'); };
/* ---------------- OSD ---------------- */
var osdTimer = null;
App.OSD = {
visible: function () { return !$('osd').classList.contains('hidden'); },
show: function (ms) {
var st = App.state, ch = st.channels[st.idx];
if (!ch) return;
$('osd-num').textContent = st.idx + 1;
$('osd-name').textContent = ch.name;
var logo = $('osd-logo');
if (ch.logo) { logo.src = ch.logo; logo.classList.remove('hidden'); } else logo.classList.add('hidden');
logo.onerror = function () { logo.classList.add('hidden'); };
$('osd-clock').textContent = App.fmtTime(Date.now());
var nn = App.Epg.nowNext(ch), now = Date.now();
if (nn.now) {
$('osd-now-time').textContent = App.fmtTime(nn.now[0]) + ' – ' + App.fmtTime(nn.now[1]);
$('osd-now-title').textContent = nn.now[2];
$('osd-progress').style.width = Math.min(100, Math.max(0, (now - nn.now[0]) / (nn.now[1] - nn.now[0]) * 100)) + '%';
} else {
$('osd-now-time').textContent = '';
$('osd-now-title').textContent = App.Epg.at ? 'Geen gidsinformatie' : 'Gids wordt geladen…';
$('osd-progress').style.width = '0';
}
$('osd-next-time').textContent = nn.next ? App.fmtTime(nn.next[0]) : '';
$('osd-next-title').textContent = nn.next ? nn.next[2] : '';
$('osd').classList.remove('hidden');
clearTimeout(osdTimer);
osdTimer = setTimeout(App.OSD.hide, ms || 5000);
},
hide: function () { clearTimeout(osdTimer); $('osd').classList.add('hidden'); }
};
/* ---------------- zenderlijst ---------------- */
var ROWS_LIST = 10;
App.List = {
sel: 0,
open: function () { App.OSD.hide(); this.sel = App.state.idx; $('list').classList.remove('hidden'); App.state.view = 'list'; this.render(); },
close: function () { $('list').classList.add('hidden'); App.state.view = 'tv'; },
render: function () {
var chs = App.state.channels, top = Math.max(0, Math.min(this.sel - 4, chs.length - ROWS_LIST)), html = '';
for (var i = top; i < Math.min(chs.length, top + ROWS_LIST); i++) {
var nn = App.Epg.nowNext(chs[i]);
html += '<div class="li' + (i === this.sel ? ' focus' : '') + (i === App.state.idx ? ' playing' : '') + '">' +
'<span class="n">' + (i + 1) + '</span><div class="t"><div>' + App.esc(chs[i].name) + '</div>' +
'<div class="sub">' + (nn.now ? App.fmtTime(nn.now[0]) + ' ' + App.esc(nn.now[2]) : '&nbsp;') + '</div></div></div>';
}
$('list-items').innerHTML = html;
},
key: function (k) {
var n = App.state.channels.length;
if (k === K.UP) this.sel = (this.sel - 1 + n) % n;
else if (k === K.DOWN) this.sel = (this.sel + 1) % n;
else if (k === K.CH_UP) this.sel = Math.max(0, this.sel - ROWS_LIST);
else if (k === K.CH_DOWN) this.sel = Math.min(n - 1, this.sel + ROWS_LIST);
else if (k === K.OK) { this.close(); App.tune(this.sel); return; }
else if (App.isBack(k) || k === K.LEFT) { this.close(); return; }
else if (k === K.RED || k === K.GUIDE) { this.close(); App.Guide.open(); return; }
else if (k === K.BLUE) { this.close(); App.Settings.open(); return; }
this.render();
}
};
/* ---------------- tv-gids ---------------- */
var HALF = 30 * 60000, WIN = 2 * 3600e3, ROWS_GUIDE = 8;
function floorHalf(t) { return Math.floor(t / HALF) * HALF; }
App.Guide = {
row: 0, top: 0, winStart: 0, focusTime: 0,
open: function () {
App.OSD.hide();
this.row = App.state.idx;
this.top = Math.max(0, this.row - 2);
this.winStart = floorHalf(Date.now());
this.focusTime = Date.now();
$('guide').classList.remove('hidden');
App.state.view = 'guide';
this.render();
},
close: function () { $('guide').classList.add('hidden'); App.state.view = 'tv'; },
/* programma's van een zender binnen het venster; lege stukken worden opgevuld */
blocks: function (ch) {
var l = App.Epg.list(ch), ws = this.winStart, we = ws + WIN, out = [];
for (var i = 0; i < l.length; i++) if (l[i][1] > ws && l[i][0] < we) out.push({ s: l[i][0], e: l[i][1], t: l[i][2], d: l[i][3] });
if (!out.length) out.push({ s: ws, e: we, t: 'Geen gidsinformatie', d: '', empty: true });
return out;
},
focused: function () {
var b = this.blocks(App.state.channels[this.row]), ft = this.focusTime;
for (var i = 0; i < b.length; i++) if (b[i].s <= ft && b[i].e > ft) return { list: b, i: i };
for (i = 0; i < b.length; i++) if (b[i].s > ft) return { list: b, i: i };
return { list: b, i: b.length - 1 };
},
key: function (k) {
var n = App.state.channels.length, f, p, minStart = floorHalf(Date.now()) - 2 * HALF, maxStart = Date.now() + 40 * 3600e3;
if (k === K.UP) this.row = Math.max(0, this.row - 1);
else if (k === K.DOWN) this.row = Math.min(n - 1, this.row + 1);
else if (k === K.CH_UP) this.row = Math.max(0, this.row - ROWS_GUIDE);
else if (k === K.CH_DOWN) this.row = Math.min(n - 1, this.row + ROWS_GUIDE);
else if (k === K.RIGHT) {
f = this.focused(); p = f.list[f.i + 1];
if (p && !p.empty) {
this.focusTime = p.s;
if (p.s >= this.winStart + WIN - HALF) this.winStart = Math.min(maxStart, floorHalf(p.s) - HALF);
} else if (this.winStart < maxStart) {
// geen volgend programma in beeld: venster een half uur opschuiven
this.winStart += HALF;
var nxt = this.firstAfter(f.list[f.i].e - 1);
this.focusTime = nxt ? nxt.s : Math.max(this.focusTime, this.winStart);
}
} else if (k === K.LEFT) {
f = this.focused(); p = f.i > 0 ? f.list[f.i - 1] : null;
if (p && !p.empty) {
this.focusTime = Math.max(p.s, this.winStart);
} else if (this.winStart > minStart) {
this.winStart -= HALF;
var prev = this.lastBefore(f.list[f.i].s);
this.focusTime = prev ? Math.max(prev.s, this.winStart) : this.winStart;
}
} else if (k === K.OK) { this.close(); App.tune(this.row); return; }
else if (App.isBack(k) || k === K.RED || k === K.GUIDE) { this.close(); return; }
else if (k === K.BLUE) { this.close(); App.Settings.open(); return; }
if (this.row < this.top) this.top = this.row;
if (this.row >= this.top + ROWS_GUIDE) this.top = this.row - ROWS_GUIDE + 1;
this.render();
},
firstAfter: function (t) {
var l = App.Epg.list(App.state.channels[this.row]);
for (var i = 0; i < l.length; i++) if (l[i][0] > t) return { s: l[i][0] };
return null;
},
lastBefore: function (t) {
var l = App.Epg.list(App.state.channels[this.row]);
for (var i = l.length - 1; i >= 0; i--) if (l[i][0] < t) return { s: l[i][0] };
return null;
},
render: function () {
var chs = App.state.channels, ws = this.winStart, now = Date.now();
var width = 1920 - 100 - 390, px = width / WIN, html = '', i;
$('guide-day').textContent = App.fmtDay(Math.max(ws, now));
var times = '';
for (i = 0; i < 4; i++) times += '<span style="left:' + Math.round(i * HALF * px) + 'px">' + App.fmtTime(ws + i * HALF) + '</span>';
$('guide-times').innerHTML = times;
var f = this.focused(), fp = f.list[f.i];
for (var r = this.top; r < Math.min(chs.length, this.top + ROWS_GUIDE); r++) {
var ch = chs[r], b = r === this.row ? f.list : this.blocks(ch);
html += '<div class="g-row"><div class="g-ch"><span class="n">' + (r + 1) + '</span>' +
(ch.logo ? '<img src="' + App.esc(ch.logo) + '" onerror="this.style.display=\'none\'">' : '') +
'<span class="nm">' + App.esc(ch.name) + '</span></div><div class="g-progs">';
for (i = 0; i < b.length; i++) {
var s = Math.max(b[i].s, ws), e = Math.min(b[i].e, ws + WIN);
var cls = 'g-p' + (b[i].empty ? ' empty' : '') + (b[i].s <= now && b[i].e > now ? ' live' : '') +
(r === this.row && i === f.i ? ' focus' : '');
html += '<div class="' + cls + '" style="left:' + Math.round((s - ws) * px) + 'px;width:' +
Math.max(4, Math.round((e - s) * px)) + 'px">' + App.esc(b[i].t) + '</div>';
}
if (now >= ws && now < ws + WIN) html += '<div class="g-now" style="left:' + Math.round((now - ws) * px) + 'px"></div>';
html += '</div></div>';
}
$('guide-rows').innerHTML = html;
$('gd-title').textContent = fp.t;
var meta = fp.empty ? chs[this.row].name : App.fmtTime(fp.s) + ' – ' + App.fmtTime(fp.e) + ' · ' + chs[this.row].name;
if (!fp.empty && fp.s <= now && fp.e > now) meta += ' · nog ' + Math.round((fp.e - now) / 60000) + ' min';
else if (!fp.empty && fp.s > now && new Date(fp.s).getDate() !== new Date(now).getDate()) meta += ' · ' + App.fmtDay(fp.s);
$('gd-meta').textContent = meta;
$('gd-desc').textContent = fp.d || '';
}
};
/* ---------------- instellingen ---------------- */
App.Settings = {
idx: 0,
open: function () {
App.OSD.hide();
var c = App.state.cfg;
$('f-m3u').value = c.m3u || ''; $('f-server').value = c.server || '';
$('f-user').value = c.user || ''; $('f-pass').value = c.pass || ''; $('f-epg').value = c.epg || '';
this.applyType();
$('settings').classList.remove('hidden');
App.state.view = 'settings';
this.idx = 0; this.render();
this.status(App.state.channels.length ? App.state.channels.length + ' zenders gekozen.' + this.epgInfo() : 'Vul je IPTV-gegevens in en kies "Zenders laden en kiezen".');
},
close: function () {
if (document.activeElement && document.activeElement.blur) document.activeElement.blur();
$('settings').classList.add('hidden');
},
epgInfo: function () {
if (!App.Epg.at) return '\nGids: nog niet geladen.';
return '\nGids: bijgewerkt om ' + App.fmtTime(App.Epg.at) + ', ' + Object.keys(App.Epg.map).length + ' van de ' + App.state.channels.length + ' zenders met gids.';
},
status: function (t, err) { var s = $('settings-status'); s.textContent = t; s.className = 'status' + (err ? ' err' : ''); },
applyType: function () {
var c = App.state.cfg, x = c.type === 'xtream';
Array.prototype.forEach.call(document.querySelectorAll('.only-m3u'), function (e) { e.classList.toggle('hidden', x); });
Array.prototype.forEach.call(document.querySelectorAll('.only-xtream'), function (e) { e.classList.toggle('hidden', !x); });
Array.prototype.forEach.call($('src-type').children, function (e) { e.classList.toggle('on', e.getAttribute('data-v') === (c.type || 'm3u')); });
Array.prototype.forEach.call($('f-output').children, function (e) { e.classList.toggle('on', e.getAttribute('data-v') === (c.output || 'm3u8')); });
},
items: function () {
return Array.prototype.filter.call(document.querySelectorAll('#settings [data-nav]'), function (e) { return e.offsetParent !== null; });
},
render: function () {
var it = this.items();
this.idx = Math.max(0, Math.min(this.idx, it.length - 1));
it.forEach(function (e, i) { e.classList.toggle('focus', i === this.idx); }, this);
},
readFields: function () {
var c = App.state.cfg;
c.m3u = $('f-m3u').value.trim(); c.server = $('f-server').value.trim();
c.user = $('f-user').value.trim(); c.pass = $('f-pass').value; c.epg = $('f-epg').value.trim();
App.store.set('cfg', c);
},
key: function (k) {
var it = this.items(), cur = it[this.idx], ae = document.activeElement;
if (ae && ae.tagName === 'INPUT' && ae.closest('#settings')) {
// aan het typen: alleen Terug, OK, omhoog/omlaag onderscheppen
if (App.isBack(k) || k === K.OK) { ae.blur(); this.readFields(); return; }
if (k === K.UP || k === K.DOWN) { ae.blur(); this.readFields(); } else return;
}
var isBtn = cur && cur.tagName === 'BUTTON';
if (k === K.DOWN) {
if (isBtn) return;
this.idx++;
} else if (k === K.UP) {
if (isBtn) { var firstBtn = it.indexOf($('b-load')); this.idx = firstBtn - 1; }
else this.idx--;
} else if (k === K.LEFT || k === K.RIGHT) {
if (isBtn) this.idx += (k === K.RIGHT ? 1 : -1);
else if (cur && cur.classList.contains('toggle')) this.toggle(cur);
if (it[this.idx] && it[this.idx].tagName !== 'BUTTON' && isBtn) this.idx -= (k === K.RIGHT ? 1 : -1);
} else if (k === K.OK) {
if (!cur) return;
if (cur.tagName === 'INPUT') { cur.focus(); return; }
if (cur.classList.contains('toggle')) { this.toggle(cur); return; }
if (cur.id === 'b-load') return this.loadChannels();
if (cur.id === 'b-epg') return this.refreshEpg();
if (cur.id === 'b-back') return this.toTv();
} else if (App.isBack(k)) {
return this.toTv();
}
this.render();
},
toggle: function (el) {
var c = App.state.cfg;
if (el.id === 'src-type') c.type = c.type === 'xtream' ? 'm3u' : 'xtream';
if (el.id === 'f-output') c.output = c.output === 'ts' ? 'm3u8' : 'ts';
App.store.set('cfg', c);
this.applyType(); this.render();
},
toTv: function () {
this.readFields();
if (!App.state.channels.length) { this.status('Kies eerst zenders met "Zenders laden en kiezen".', true); return; }
this.close();
App.state.view = 'tv';
App.tune(Math.min(App.state.idx, App.state.channels.length - 1), true);
},
loadChannels: function () {
var self = this;
this.readFields();
this.status('Zenders ophalen…');
App.loadSource(App.state.cfg).then(function (res) {
App.allChannels = res.channels;
App.store.set('srcEpg', res.epgUrl || '');
// gekozen zenders bijwerken met de nieuwste stream-URL en logo
var byKey = {};
res.channels.forEach(function (c) { byKey[c.key] = c; });
App.state.channels.forEach(function (c) { var n = byKey[c.key]; if (n) { c.url = n.url; c.logo = n.logo; c.tvgId = n.tvgId; } });
App.saveChannels();
self.status(res.channels.length + ' live-zenders gevonden.');
self.close();
App.Picker.open();
}).catch(function (e) { self.status('Ophalen mislukt: ' + e.message, true); });
},
refreshEpg: function () {
var self = this;
this.readFields();
if (!App.state.channels.length) { this.status('Kies eerst zenders, dan kan de gids geladen worden.', true); return; }
this.status('Gids laden…');
App.loadEpg(function (bytes, kept) {
self.status('Gids laden… ' + (bytes / 1048576).toFixed(1) + ' MB gelezen, ' + kept + ' programma\'s bewaard');
}).then(function (r) {
self.status('Gids geladen: ' + r.programmes + ' programma\'s, ' + r.matched + ' van de ' + r.total + ' zenders gevonden in de gids.');
}).catch(function (e) { self.status('Gids laden mislukt: ' + e.message, true); });
}
};
/* ---------------- zenders kiezen ---------------- */
var ROWS_PK = 11;
App.Picker = {
col: 'groups', gi: 0, ci: 0, groups: [], chans: [], query: '',
open: function () {
this.col = 'groups'; this.gi = 0; this.ci = 0; this.query = '';
$('pk-search').value = '';
this.buildGroups();
$('picker').classList.remove('hidden');
App.state.view = 'picker';
var self = this;
$('pk-search').oninput = function () { self.query = this.value.trim().toLowerCase(); self.ci = 0; self.filter(); self.render(); };
this.filter(); this.render();
},
close: function () {
$('pk-search').blur();
$('picker').classList.add('hidden');
App.saveChannels();
App.Settings.open();
App.Settings.status(App.state.channels.length + ' zenders gekozen. De gids wordt nu geladen…');
App.Settings.refreshEpg();
},
buildGroups: function () {
var counts = {}, order = [];
(App.allChannels || []).forEach(function (c) {
if (!counts[c.group]) { counts[c.group] = 0; order.push(c.group); }
counts[c.group]++;
});
this.groups = [{ name: '★ Mijn zenders', id: 'sel' }, { name: 'Alle zenders', id: 'all', n: (App.allChannels || []).length }]
.concat(order.map(function (g) { return { name: g, id: 'g', n: counts[g] }; }));
},
isSel: function (key) {
var l = App.state.channels;
for (var i = 0; i < l.length; i++) if (l[i].key === key) return i;
return -1;
},
filter: function () {
var g = this.groups[this.gi], q = this.query, all = App.allChannels || [];
var list = g.id === 'sel' ? App.state.channels.slice() : (g.id === 'all' || q ? all : all.filter(function (c) { return c.group === g.name; }));
if (q) list = list.filter(function (c) { return c.name.toLowerCase().indexOf(q) >= 0; });
this.chans = list;
this.ci = Math.max(0, Math.min(this.ci, list.length - 1));
},
toggle: function (c) {
var i = this.isSel(c.key);
if (i >= 0) App.state.channels.splice(i, 1);
else App.state.channels.push({ key: c.key, name: c.name, url: c.url, logo: c.logo, group: c.group, tvgId: c.tvgId });
},
key: function (k) {
var ae = document.activeElement;
if (ae === $('pk-search')) {
if (App.isBack(k) || k === K.OK || k === K.DOWN) { ae.blur(); this.col = 'chans'; this.render(); }
return;
}
if (this.col === 'search') {
if (k === K.OK) { $('pk-search').focus(); return; }
if (k === K.DOWN) this.col = 'groups';
else if (App.isBack(k)) return this.close();
this.render(); return;
}
var g = this.groups[this.gi];
if (this.col === 'groups') {
if (k === K.UP) { if (this.gi === 0) this.col = 'search'; else { this.gi--; this.ci = 0; this.filter(); } }
else if (k === K.DOWN) { if (this.gi < this.groups.length - 1) { this.gi++; this.ci = 0; this.filter(); } }
else if (k === K.RIGHT || k === K.OK) { if (this.chans.length) this.col = 'chans'; }
else if (k === K.CH_UP) { this.gi = Math.max(0, this.gi - ROWS_PK); this.ci = 0; this.filter(); }
else if (k === K.CH_DOWN) { this.gi = Math.min(this.groups.length - 1, this.gi + ROWS_PK); this.ci = 0; this.filter(); }
else if (App.isBack(k)) return this.close();
} else {
var c = this.chans[this.ci];
if (k === K.UP) { if (this.ci === 0) this.col = 'search'; else this.ci--; }
else if (k === K.DOWN) this.ci = Math.min(this.chans.length - 1, this.ci + 1);
else if (k === K.CH_UP) this.ci = Math.max(0, this.ci - ROWS_PK);
else if (k === K.CH_DOWN) this.ci = Math.min(this.chans.length - 1, this.ci + ROWS_PK);
else if (k === K.LEFT) this.col = 'groups';
else if (k === K.OK && c) { this.toggle(c); if (g.id === 'sel') this.filter(); }
else if ((k === K.YELLOW || k === K.BLUE) && g.id === 'sel' && !this.query && c) {
// volgorde aanpassen in "Mijn zenders"
var l = App.state.channels, to = this.ci + (k === K.YELLOW ? -1 : 1);
if (to >= 0 && to < l.length) { var tmp = l[to]; l[to] = l[this.ci]; l[this.ci] = tmp; this.ci = to; this.filter(); }
}
else if (App.isBack(k)) return this.close();
}
this.render();
},
render: function () {
var self = this, html = '', i, top;
$('pk-count').textContent = '(' + App.state.channels.length + ' gekozen)';
$('pk-search').classList.toggle('focus', this.col === 'search');
this.groups[0].n = App.state.channels.length;
top = Math.max(0, Math.min(this.gi - 5, this.groups.length - ROWS_PK));
for (i = top; i < Math.min(this.groups.length, top + ROWS_PK); i++) {
var g = this.groups[i];
html += '<div class="pk-item' + (i === this.gi ? ' focus' : '') + '"><span class="nm">' + App.esc(g.name) + '</span><span class="gc">' + (g.n || 0) + '</span></div>';
}
$('pk-groups').innerHTML = html;
$('pk-groups').classList.toggle('active', this.col === 'groups');
html = '';
top = Math.max(0, Math.min(this.ci - 5, this.chans.length - ROWS_PK));
var sel = this.groups[this.gi].id === 'sel';
for (i = top; i < Math.min(this.chans.length, top + ROWS_PK); i++) {
var c = this.chans[i], on = self.isSel(c.key) >= 0;
html += '<div class="pk-item' + (on ? ' sel' : '') + (i === this.ci && this.col === 'chans' ? ' focus' : '') + '">' +
'<span class="box">' + (sel ? (i + 1) : (on ? '☑' : '☐')) + '</span><span class="nm">' + App.esc(c.name) + '</span>' +
'<span class="gc">' + App.esc(this.query || this.groups[this.gi].id !== 'g' ? c.group : '') + '</span></div>';
}
if (!this.chans.length) html = '<div class="pk-item"><span class="nm">' + (sel ? 'Nog geen zenders gekozen. Kies links een groep.' : 'Geen zenders gevonden.') + '</span></div>';
$('pk-chans').innerHTML = html;
$('pk-chans').classList.toggle('active', this.col === 'chans');
$('pk-hint').textContent = sel
? 'OK verwijderen · Geel omhoog · Blauw omlaag · ▲ bovenaan = zoeken · Terug klaar'
: 'OK aan/uit · ◀ ▶ kolom · CH+/− pagina · ▲ bovenaan = zoeken · Terug klaar';
}
};
})(window.App);