SPB Git

Repository Public

admin.ts 7.7 KB 102 lines typescript

1import { z } from "zod";2import { all, bumpCatalog, DEFAULT_SETTINGS, get, getSetting, log, now, run, setSetting } from "../db";3import { enqueue, recentJobs } from "../jobs";4import { assertPublicUrl, UrlRejected } from "../ssrf";5import { HttpError, route } from "./core";67function publicUrl(raw: string): string {8  try { return assertPublicUrl(raw.trim()).toString(); } catch (e) { throw new HttpError(400, e instanceof UrlRejected ? e.message : "URL invalide"); }9}1011route("GET", "/admin/overview", () => {12  const n = (sql: string, ...p: (string | number)[]) => get<{ n: number }>(sql, ...p)!.n;13  const settings: Record<string, string> = {};14  for (const k of Object.keys(DEFAULT_SETTINGS)) settings[k] = getSetting(k)!;15  const hb = Number(getSetting("worker_heartbeat") ?? 0);16  return {17    stats: {18      channels: n("SELECT COUNT(*) n FROM channels WHERE active = 1"), streams: n("SELECT COUNT(*) n FROM streams"),19      up: n("SELECT COUNT(*) n FROM streams WHERE status = 'up'"), down: n("SELECT COUNT(*) n FROM streams WHERE status = 'down'"), unknown: n("SELECT COUNT(*) n FROM streams WHERE status = 'unknown'"),20      insecure: n("SELECT COUNT(*) n FROM streams WHERE url LIKE 'http:%'"), needsHeaders: n("SELECT COUNT(*) n FROM streams WHERE referrer IS NOT NULL OR user_agent IS NOT NULL"),21      corsOk: n("SELECT COUNT(*) n FROM streams WHERE status = 'up' AND cors = 1"),22      countries: n("SELECT COUNT(DISTINCT country) n FROM channels WHERE active = 1"), withGuide: n("SELECT COUNT(*) n FROM channels WHERE active = 1 AND has_guide = 1"),23      epgChannels: n("SELECT COUNT(DISTINCT channel_id) n FROM programs WHERE stop > ?", now()), programmes: n("SELECT COUNT(*) n FROM programs WHERE stop > ?", now()),24      favorites: n("SELECT COUNT(DISTINCT channel_id) n FROM list_items"), hidden: n("SELECT COUNT(*) n FROM hidden"),25      oldestCheck: get<{ t: number | null }>("SELECT MIN(checked_at) t FROM streams WHERE checked_at IS NOT NULL")?.t ?? null,26    },27    worker: { heartbeat: hb || null, alive: now() - hb < 90_000, lastBatch: JSON.parse(getSetting("last_check_batch") ?? "null") },28    lastSyncAt: Number(getSetting("last_sync_at") ?? 0) || null, lastEpgAt: Number(getSetting("last_epg_at") ?? 0) || null,29    sources: all("SELECT id, kind, name, url, country, enabled, builtin, last_sync_at, last_status, last_error, stream_count FROM sources ORDER BY builtin DESC, id"),30    epgSources: all("SELECT id, name, url, enabled, last_sync_at, last_status, last_error, program_count FROM epg_sources ORDER BY id"),31    jobs: recentJobs(20).map((j) => ({ ...j, result: j.result ? JSON.parse(j.result) : null })),32    settings,33  };34});3536route("POST", "/admin/jobs", async (c) => {37  const b = await c.body(z.object({ type: z.enum(["sync", "epg", "vod", "library", "sources"]) }));38  const hb = Number(getSetting("worker_heartbeat") ?? 0);39  if (now() - hb > 90_000) throw new HttpError(503, "Le worker ne répond pas : la tâche ne peut pas être exécutée (voir DEPLOYMENT.md → Dépannage)");40  return { id: enqueue(b.type, "manual") };41});4243route("POST", "/admin/sources", async (c) => {44  const b = await c.body(z.object({ name: z.string().trim().min(1).max(80), url: z.string().max(2000), country: z.string().regex(/^[A-Za-z]{2}$/).optional().or(z.literal("")), authorized: z.literal(true, "Confirmez que vous êtes autorisé à utiliser cette source") }));45  const url = publicUrl(b.url);46  if (get("SELECT 1 FROM sources WHERE url = ?", url)) throw new HttpError(409, "Cette source existe déjà");47  const id = Number(run("INSERT INTO sources(kind, name, url, country, created_at) VALUES('m3u', ?, ?, ?, ?)", b.name, url, b.country ? b.country.toUpperCase() : null, now()).lastInsertRowid);48  log("info", "admin", `Source ajoutée : ${b.name}`, { url });49  return { id };50});51route("PATCH", "/admin/sources/:id", async (c) => {52  const b = await c.body(z.object({ enabled: z.boolean() }));53  run("UPDATE sources SET enabled = ? WHERE id = ?", Number(b.enabled), Number(c.params[0]));54});55route("DELETE", "/admin/sources/:id", (c) => {56  const s = get<{ builtin: number; name: string }>("SELECT builtin, name FROM sources WHERE id = ?", Number(c.params[0]));57  if (!s) throw new HttpError(404, "Source introuvable");58  if (s.builtin) throw new HttpError(400, "Les sources IPTV-org intégrées peuvent être désactivées, pas supprimées");59  run("DELETE FROM sources WHERE id = ?", Number(c.params[0])); // streams follow (ON DELETE CASCADE)60  run("UPDATE channels SET active = EXISTS(SELECT 1 FROM streams s WHERE s.channel_id = channels.id)");61  bumpCatalog();62  log("info", "admin", `Source supprimée : ${s.name}`);63});6465route("POST", "/admin/epg-sources", async (c) => {66  const b = await c.body(z.object({ name: z.string().trim().min(1).max(80), url: z.string().max(2000) }));67  const url = publicUrl(b.url);68  if (get("SELECT 1 FROM epg_sources WHERE url = ?", url)) throw new HttpError(409, "Cette source existe déjà");69  return { id: Number(run("INSERT INTO epg_sources(name, url, created_at) VALUES(?,?,?)", b.name, url, now()).lastInsertRowid) };70});71route("DELETE", "/admin/epg-sources/:id", (c) => {72  run("DELETE FROM programs WHERE origin = ?", `xmltv:${Number(c.params[0])}`);73  run("DELETE FROM epg_sources WHERE id = ?", Number(c.params[0]));74});7576const int = (min: number, max: number) => z.coerce.number().int().min(min).max(max).transform(String);77const flag = z.union([z.boolean(), z.enum(["0", "1"])]).transform((v) => (v === true || v === "1" ? "1" : "0"));78const SettingsSchema = z.object({79  sync_interval_hours: int(1, 168), check_enabled: flag, check_concurrency: int(1, 12), check_host_delay_ms: int(500, 60_000), check_timeout_ms: int(3000, 30_000),80  check_recheck_hours: int(6, 720), check_priority_hours: int(1, 168), epg_enabled: flag, epg_interval_hours: int(3, 168),81  epg_countries: z.string().max(200).transform((s) => s.toUpperCase().split(/[\s,;]+/).filter((x) => /^[A-Z]{2}$/.test(x)).join(",")),82  epg_max_channels: int(0, 600), epg_days: int(1, 3), session_days: int(1, 365), auto_resume: flag, premium_filter: flag, vod_interval_hours: int(24, 2160), library_interval_minutes: int(5, 1440), transcode_cache_gb: int(1, 500), sources_interval_hours: int(6, 720),83  relay_enabled: flag, relay_max_relays: int(1, 24), relay_max_transcodes: int(0, 8), relay_max_sessions: int(1, 60), relay_buffer_sec: int(4, 60), relay_idle_sec: int(10, 600),84  relay_out_kbps: int(0, 100_000), relay_video_kbps: int(500, 20_000), relay_timeshift_min: int(5, 720), relay_reconnect_max: int(0, 30),85}).partial();86route("PUT", "/admin/settings", async (c) => {87  const b = await c.body(SettingsSchema);88  for (const [k, v] of Object.entries(b)) if (v !== undefined) setSetting(k, v);89  // The relay engine reads its buffer and inactivity delays from its own file, which it reloads when it changes.90  if (Object.keys(b).some((k) => k.startsWith("relay_"))) { try { const { writeConfig } = await import("../relay/config"); writeConfig(); } catch (e) { log("warn", "relay", "Configuration du relais non réécrite", { error: (e as Error).message }); } }91  log("info", "admin", "Paramètres modifiés", b);92});9394route("GET", "/admin/logs", (c) => {95  const p = c.url.searchParams;96  const level = p.get("level"), scope = p.get("scope"), before = Number(p.get("before")) || Number.MAX_SAFE_INTEGER;97  const where = ["id < ?"]; const args: (string | number)[] = [before];98  if (level === "warn") where.push("level IN ('warn','error')"); else if (level === "error") where.push("level = 'error'");99  if (scope) { where.push("scope = ?"); args.push(scope); }100  return { logs: all(`SELECT id, at, level, scope, message, meta FROM logs WHERE ${where.join(" AND ")} ORDER BY id DESC LIMIT 100`, ...args), scopes: all<{ scope: string }>("SELECT DISTINCT scope FROM logs").map((r) => r.scope) };101});102
Files main
Menu

Theme