Repository Public
1import crypto from "node:crypto";2import { all, get, now, run } from "./db";3import { index, userSets, type Channel } from "./catalog";45// Personal M3U playlists for the TV apps at home (TiviMate, IPTV Smarters, VLC, Kodi, Apple TV players…).6// A playlist is a saved selection; its content is generated from the live catalogue at every request, so it follows7// the daily synchronisation and the availability tests. It lists the public stream addresses themselves — SP TV relays8// nothing — and is reached through a long random token, because a TV app cannot sign in.910export interface PlaylistFilter {11 lists: number[]; countries: string[]; categories: string[]; languages: string[];12 onlyUp: boolean; best: boolean; group: "category" | "country"; max: number;13}14export const DEFAULT_FILTER: PlaylistFilter = { lists: [1], countries: [], categories: [], languages: [], onlyUp: true, best: true, group: "category", max: 2000 };15export function cleanFilter(f: Partial<PlaylistFilter> | undefined): PlaylistFilter {16 const arr = (v: unknown, re: RegExp) => (Array.isArray(v) ? [...new Set(v.map(String).filter((x) => re.test(x)))].slice(0, 60) : []);17 return {18 lists: Array.isArray(f?.lists) ? [...new Set(f!.lists.map(Number).filter((n) => Number.isInteger(n) && n > 0))].slice(0, 50) : [],19 countries: arr(f?.countries, /^[A-Z]{2}$/), categories: arr(f?.categories, /^[a-z]{2,20}$/), languages: arr(f?.languages, /^[a-z]{3}$/),20 onlyUp: f?.onlyUp !== false, best: f?.best !== false, group: f?.group === "country" ? "country" : "category",21 max: Math.min(5000, Math.max(1, Number(f?.max) || 2000)),22 };23}2425export interface Row { id: number; name: string; token: string; filter: string; created_at: number; last_used_at: number | null; last_used_by: string | null; hits: number }26export const listPlaylists = () => all<Row>("SELECT * FROM playlists ORDER BY id");27export const newToken = () => crypto.randomBytes(24).toString("base64url");28export function createPlaylist(name: string, filter: PlaylistFilter): Row {29 const id = Number(run("INSERT INTO playlists(name, token, filter, created_at) VALUES(?,?,?,?)", name, newToken(), JSON.stringify(filter), now()).lastInsertRowid);30 return get<Row>("SELECT * FROM playlists WHERE id = ?", id)!;31}32export function byToken(token: string): Row | undefined {33 if (!/^[A-Za-z0-9_-]{32}$/.test(token)) return undefined;34 return get<Row>("SELECT * FROM playlists WHERE token = ?", token);35}36export function touch(id: number, by: string | null) { run("UPDATE playlists SET last_used_at = ?, last_used_by = ?, hits = hits + 1 WHERE id = ?", now(), by?.slice(0, 160) ?? null, id); }3738interface StreamRow { id: number; channel_id: string; url: string; quality: string | null; status: string; referrer: string | null; user_agent: string | null; labels: string }39export interface Entry { channel: Channel; group: string; streamId: number; url: string; referrer: string | null; userAgent: string | null; alt: number }4041const CAT_FR: Record<string, string> = { animation: "Animation", auto: "Auto", business: "Affaires", classic: "Classiques", comedy: "Humour", cooking: "Cuisine", culture: "Culture", documentary: "Documentaires", education: "Éducation", entertainment: "Divertissement",42 family: "Famille", general: "Généraliste", kids: "Jeunesse", legislative: "Parlementaire", lifestyle: "Art de vivre", movies: "Films", music: "Musique", news: "Actualités", outdoor: "Plein air", public: "Service public", relax: "Détente", religious: "Religion",43 science: "Science", series: "Séries", shop: "Téléachat", sports: "Sports", travel: "Voyage", weather: "Météo" };4445/** Channels and streams of a playlist, in the order a TV should list them. */46export function buildEntries(f: PlaylistFilter): Entry[] {47 const { list } = index(); const sets = userSets();48 const countryName = new Map(all<{ code: string; name: string }>("SELECT code, name FROM countries").map((c) => [c.code, c.name]));49 // Favourite lists, in their own order, come first.50 const favOrder = new Map<string, { pos: number; list: string }>();51 if (f.lists.length) {52 const rows = all<{ channel_id: string; name: string }>(`SELECT i.channel_id, l.name FROM list_items i JOIN lists l ON l.id = i.list_id WHERE i.list_id IN (${f.lists.map(() => "?").join(",")}) ORDER BY l.position, l.id, i.position, i.added_at`, ...f.lists);53 rows.forEach((r, i) => { if (!favOrder.has(r.channel_id)) favOrder.set(r.channel_id, { pos: i, list: r.name }); });54 }55 const hasFilter = f.countries.length || f.categories.length || f.languages.length;56 const matches = (c: Channel) => (!f.countries.length || (!!c.country && f.countries.includes(c.country))) && (!f.categories.length || c.categories.some((x) => f.categories.includes(x))) && (!f.languages.length || c.languages.some((x) => f.languages.includes(x)));57 const everything = !f.lists.length && !hasFilter;58 const home = (c: Channel) => (c.country === "CA" ? (c.languages.includes("fra") ? 0 : 1) : c.languages.includes("fra") ? 2 : 3);59 const chosen = list.filter((c) => !sets.hidden.has(c.id) && (favOrder.has(c.id) || everything || (hasFilter && matches(c))))60 .sort((a, b) => (favOrder.get(a.id)?.pos ?? 1e9) - (favOrder.get(b.id)?.pos ?? 1e9) || home(a) - home(b) || a.name.localeCompare(b.name, "fr"));61 // A TV app is not a browser: plain HTTP, missing CORS headers and required Referer / User-Agent are all fine there62 // (the latter are written in the playlist). Only the last availability test and the quality order the streams.63 const streams = new Map<string, StreamRow[]>();64 for (const s of all<StreamRow>("SELECT id, channel_id, url, quality, status, referrer, user_agent, labels FROM streams")) { const l = streams.get(s.channel_id); if (l) l.push(s); else streams.set(s.channel_id, [s]); }65 const rank = (s: StreamRow) => (s.status === "up" ? 0 : s.status === "unknown" ? 1 : 2) * 10_000 + (/geo/i.test(s.labels) ? 500 : 0) - (parseInt(s.quality ?? "0", 10) || 0) + (s.url.startsWith("http:") ? 5 : 0);66 const out: Entry[] = [];67 for (const c of chosen) {68 const ss = (streams.get(c.id) ?? []).filter((s) => !f.onlyUp || s.status === "up").sort((a, b) => rank(a) - rank(b));69 if (!ss.length) continue;70 // Favourites keep their list name as group (shown first on the TV); the rest is grouped by category or by country.71 const fav = favOrder.get(c.id);72 const group = fav ? fav.list : f.group === "country" ? countryName.get(c.country ?? "") ?? "Autres pays" : CAT_FR[c.categories[0]] ?? c.categories[0] ?? "Autres";73 (f.best ? ss.slice(0, 1) : ss.slice(0, 4)).forEach((s, i) => out.push({ channel: c, group, streamId: s.id, url: s.url, referrer: s.referrer, userAgent: s.user_agent, alt: i }));74 if (out.length >= f.max) break;75 }76 return out.slice(0, f.max);77}7879const attr = (s: string) => s.replace(/"/g, "'").replace(/[\r\n]+/g, " ");80export function renderM3u(entries: Entry[], epgUrl: string, providerBase?: string): string {81 const lines = [`#EXTM3U url-tvg="${epgUrl}" x-tvg-url="${epgUrl}"`];82 entries.forEach((e, n) => {83 const c = e.channel; const name = attr(c.name.replace(/,/g, " ")) + (e.alt ? ` (source ${e.alt + 1})` : "");84 lines.push(`#EXTINF:-1 tvg-id="${attr(c.id)}" tvg-name="${name}" tvg-chno="${n + 1}"${c.logo ? ` tvg-logo="${attr(c.logo)}"` : ""}${c.country ? ` tvg-country="${c.country}"` : ""}${e.userAgent ? ` http-user-agent="${attr(e.userAgent)}"` : ""}${e.referrer ? ` http-referrer="${attr(e.referrer)}"` : ""} group-title="${attr(e.group)}",${name}`);85 if (e.referrer) lines.push(`#EXTVLCOPT:http-referrer=${e.referrer}`);86 if (e.userAgent) lines.push(`#EXTVLCOPT:http-user-agent=${e.userAgent}`);87 // A provider stream goes through this playlist's own tokenised address: the provider credentials are not written in the file.88 lines.push(e.url.startsWith("provider://") ? `${providerBase ?? ""}/${e.streamId}.m3u8` : e.url);89 });90 return lines.join("\n") + "\n";91}9293const x = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);94const xt = (t: number) => { const d = new Date(t); const p = (n: number) => String(n).padStart(2, "0"); return `${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())} +0000`; };95/** XMLTV guide of the same channels, from the programmes SP TV already holds (real data only). */96export function renderXmltv(entries: Entry[]): string {97 const ids = [...new Set(entries.map((e) => e.channel.id))]; const byId = new Map(entries.map((e) => [e.channel.id, e.channel]));98 const out = ['<?xml version="1.0" encoding="UTF-8"?>', '<tv generator-info-name="SP TV">'];99 const withData: string[] = [];100 const progs: string[] = [];101 for (const id of ids) {102 const rows = all<{ start: number; stop: number; title: string; subtitle: string | null; description: string | null; category: string | null }>("SELECT start, stop, title, subtitle, description, category FROM programs WHERE channel_id = ? AND stop > ? ORDER BY start", id, now() - 3600_000);103 if (!rows.length) continue; withData.push(id);104 for (const p of rows) progs.push(`<programme start="${xt(p.start)}" stop="${xt(p.stop)}" channel="${x(id)}"><title>${x(p.title)}</title>${p.subtitle ? `<sub-title>${x(p.subtitle)}</sub-title>` : ""}${p.description ? `<desc>${x(p.description)}</desc>` : ""}${p.category ? `<category>${x(p.category)}</category>` : ""}</programme>`);105 }106 for (const id of withData) { const c = byId.get(id)!; out.push(`<channel id="${x(id)}"><display-name>${x(c.name)}</display-name>${c.logo ? `<icon src="${x(c.logo)}"/>` : ""}</channel>`); }107 return out.concat(progs, "</tv>").join("\n") + "\n";108}109