SPB Git

Repository Public

engine.ts 5.7 KB 69 lines typescript

1import { z } from "zod";2import { all, get, getSetting, log, now } from "../db";3import * as E from "../engine";4import { enqueue } from "../jobs";5import { unsign } from "../auth";6import { HttpError, route, type Ctx } from "./core";78// Universal source engine — administration. Credentials go in (once, over HTTPS) and never come back out.9const wrap = <T,>(fn: () => T): T => { try { return fn(); } catch (e) { if (e instanceof E.EngineError) throw new HttpError(400, e.message); throw e; } };10const Fields = z.record(z.string().max(40), z.string().max(21 * 1024 * 1024));1112route("GET", "/admin/engine", () => {13  const n = (sql: string) => get<{ n: number }>(sql)!.n;14  return {15    types: E.TYPES, instances: E.instances(),16    totals: {17      channels: n("SELECT COUNT(*) n FROM channels WHERE active = 1"), streams: n("SELECT COUNT(*) n FROM streams"),18      // The figure that matters: distinct channels with at least one stream that answered its last test.19      playableChannels: n("SELECT COUNT(DISTINCT channel_id) n FROM streams WHERE status = 'up'"),20      playableCA: n("SELECT COUNT(DISTINCT s.channel_id) n FROM streams s JOIN channels c ON c.id = s.channel_id WHERE s.status = 'up' AND c.country = 'CA'"),21      playableFrench: n("SELECT COUNT(DISTINCT s.channel_id) n FROM streams s JOIN channels c ON c.id = s.channel_id WHERE s.status = 'up' AND c.languages LIKE '%fra%'"),22      multiSource: n("SELECT COUNT(*) n FROM (SELECT channel_id FROM streams GROUP BY channel_id HAVING COUNT(*) > 1)"),23      movies: n("SELECT COUNT(*) n FROM titles t WHERE active = 1 AND kind = 'movie' AND EXISTS(SELECT 1 FROM media m WHERE m.title_id = t.id)"),24      series: n("SELECT COUNT(*) n FROM titles t WHERE active = 1 AND kind = 'series' AND EXISTS(SELECT 1 FROM media m WHERE m.title_id = t.id)"),25      guideChannels: n(`SELECT COUNT(DISTINCT channel_id) n FROM programs WHERE stop > ${now()}`),26    },27    // Channels that probably are the same one under two identifiers (same name, same country): candidates for a manual look.28    duplicates: all<{ name: string; country: string | null; n: number; ids: string }>(`SELECT MIN(name) name, country, COUNT(*) n, GROUP_CONCAT(id, ' · ') ids FROM channels WHERE active = 1 GROUP BY LOWER(REPLACE(REPLACE(REPLACE(name, ' ', ''), '-', ''), 'HD', '')), country HAVING n > 1 ORDER BY (country = 'CA') DESC, n DESC LIMIT 40`),29    duplicateCount: get<{ n: number }>(`SELECT COUNT(*) n FROM (SELECT 1 FROM channels WHERE active = 1 GROUP BY LOWER(REPLACE(REPLACE(REPLACE(name, ' ', ''), '-', ''), 'HD', '')), country HAVING COUNT(*) > 1)`)!.n,30    lastSourcesAt: Number(getSetting("last_sources_at") ?? 0) || null,31  };32});33route("POST", "/admin/engine/test", async (c) => { const b = await c.body(z.object({ type: z.string().max(30), fields: Fields })); return E.test(b.type, b.fields); });34route("POST", "/admin/engine", async (c) => {35  const b = await c.body(z.object({ type: z.string().max(30), fields: Fields, consent: z.boolean().optional() }));36  const def = E.TYPES.find((t) => t.type === b.type);37  if (def?.consent && b.consent !== true) throw new HttpError(400, "Confirmez la déclaration d'autorisation pour ajouter cette source");38  const uid = wrap(() => E.create(b.type, b.fields));39  log("info", "sources", `Source ajoutée (${def?.label ?? b.type}) : ${b.fields.name ?? ""}`); // never the fields themselves: they may hold credentials40  // Import it right away.41  const fam = uid.split(":")[0]; const job = fam === "live" ? enqueue("sync", "manual") : fam === "guide" ? enqueue("epg", "manual") : enqueue("sources", "manual");42  if (b.type === "xtream") enqueue("sources", "manual");43  return { uid, job };44});45route("PATCH", "/admin/engine/:uid", async (c) => {46  const b = await c.body(z.object({ enabled: z.boolean().optional(), priority: z.number().int().min(1).max(999).optional() }));47  wrap(() => { if (b.enabled !== undefined) E.setEnabled(c.params[0], b.enabled); if (b.priority !== undefined) E.setPriority(c.params[0], b.priority); });48});49route("DELETE", "/admin/engine/:uid", (c) => { wrap(() => E.remove(c.params[0])); log("info", "sources", `Source supprimée : ${c.params[0]}`); });5051// Provider playback: the browser asks this server, which answers with a redirect to the provider. The address — and the52// credentials some providers put inside it — is never part of an API answer, a page or the journal.53const redirect = (url: string) => new Response(null, { status: 302, headers: { location: url, "cache-control": "no-store", "referrer-policy": "no-referrer" } });54// hls.js follows that redirect across origins, which browsers only allow for requests made without cookies. These two55// routes therefore also accept a short-lived signed ticket issued with the play information, instead of the session.56const allowed = (c: Ctx, scope: string) => { if (c.session || unsign(c.url.searchParams.get("t") ?? undefined) === scope) return; throw new HttpError(401, "Authentification requise"); };57route("GET", "/provider/stream/:id", async (c) => {58  allowed(c, `s:${c.params[0]}`);59  const s = get<{ url: string }>("SELECT url FROM streams WHERE id = ?", Number(c.params[0]));60  if (!s || !E.isProvider(s.url)) throw new HttpError(404, "Flux introuvable");61  return redirect(await E.resolveProvider(s.url).catch((e) => { throw new HttpError(503, (e as Error).message); }));62}, { public: true });63route("GET", "/provider/media/:id", async (c) => {64  allowed(c, `m:${c.params[0]}`);65  const m = get<{ url: string | null }>("SELECT url FROM media WHERE id = ?", Number(c.params[0]));66  if (!m || !E.isProvider(m.url)) throw new HttpError(404, "Média introuvable");67  return redirect(await E.resolveProvider(m.url, { hls: c.url.searchParams.get("hls") === "1" }).catch((e) => { throw new HttpError(503, (e as Error).message); }));68}, { public: true });69
Files main
Menu

Theme