Files

197 lines
7.8 KiB
JavaScript

/* 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);