Repository Public
1import { z } from "zod";2import { all, get, getSetting, now } from "../db";3import { clientIp, HttpError, route } from "./core";4import * as A from "../relay/access";5import * as C from "../relay/config";6import { recentEvents } from "../relay/events";7import * as R from "../relay/relays";8import * as S from "../relay/sessions";9import { listSources } from "../relay/sources";10import fs from "node:fs";1112const wrap = async <T>(fn: () => T | Promise<T>): Promise<T> => { try { return await fn(); } catch (e) { if (e instanceof A.RelayRefused) throw new HttpError(e.status, e.message); throw e; } };1314/** Opens a playback session on the relay of a stream, starting nothing yet: MediaMTX starts the ingest at the first request. */15export async function openRelay(streamId: number, auth: string, meta: { ip: string; userAgent: string | null }) {16 const row = A.streamRow(streamId); if (!row) throw new A.RelayRefused("Flux introuvable", 404);17 const ok = A.eligibility(row); if (!ok.ok) throw new A.RelayRefused(ok.reason, 403);18 const engine = JSON.parse(getSetting("relay_engine") ?? "{}") as { at?: number; up?: boolean };19 if (engine.at && now() - engine.at < 30_000 && engine.up === false) throw new A.RelayRefused("Le moteur de relais ne répond pas", 503);20 const relay = await R.ensure(row, ok.policy, auth);21 const s = S.open(relay, row, auth, meta);22 const l = C.limits();23 return { url: `/relay/${s.token}/index.m3u8`, token: s.token, mode: relay.mode, shared: !!relay.shared, bufferSec: l.bufferSec,24 timeshift: relay.record ? { base: `/relay/${s.token}/timeshift`, windowSec: l.timeshiftMin * 60 } : null };25}2627route("POST", "/relay/open", async (c) => {28 const b = await c.body(z.object({ streamId: z.number().int().positive() }));29 return wrap(() => openRelay(b.streamId, `s:${c.session!.id}`, { ip: clientIp(c.req), userAgent: c.req.headers.get("user-agent") }));30});31route("POST", "/relay/close", async (c) => {32 const b = await c.body(z.object({ token: z.string().regex(A.TOKEN) }));33 const s = S.lookup(b.token);34 if (s && s.auth === `s:${c.session!.id}`) S.close(s.id, "fermé par le lecteur");35});3637route("GET", "/admin/relay", () => {38 S.flush();39 const t = now(); const l = C.limits();40 const engine = JSON.parse(getSetting("relay_engine") ?? "{}") as { at?: number; up?: boolean; version?: string | null };41 const name = new Map<string, string>();42 const chan = (id: string) => { if (!name.has(id)) name.set(id, get<{ name: string }>("SELECT name FROM channels WHERE id = ?", id)?.name ?? id); return name.get(id)!; };43 const srcName = new Map(all<{ id: number; name: string }>("SELECT id, name FROM sources").map((s) => [s.id, s.name]));44 const last = (id: string) => get<{ at: number; cpu: number; rss_mb: number; in_kbps: number; out_kbps: number; clients: number }>("SELECT * FROM relay_samples WHERE relay_id = ? AND at > ? ORDER BY at DESC LIMIT 1", id, t - 20_000);45 const rows = all<R.Relay>(`SELECT * FROM relays WHERE state IN ${R.ACTIVE} OR stopped_at > ? ORDER BY (state IN ${R.ACTIVE}) DESC, COALESCE(stopped_at, started_at) DESC LIMIT 40`, t - 24 * 3600_000);46 const relays = rows.map((r) => { const s = R.isActive(r) ? last(r.id) : undefined; return {47 id: r.id, channel: chan(r.channel_id), source: srcName.get(r.source_id) ?? "—", state: r.state, mode: r.mode, shared: !!r.shared, record: !!r.record, video: r.vcodec, audio: r.acodec, height: r.height,48 startedAt: r.started_at, readyAt: r.ready_at, stoppedAt: r.stopped_at, restarts: r.restarts, error: r.last_error, clients: R.isActive(r) ? r.clients : 0, bytesIn: r.bytes_in, bytesOut: r.bytes_out,49 inKbps: s?.in_kbps ?? 0, outKbps: s?.out_kbps ?? 0, cpu: s?.cpu ?? 0, rssMb: s?.rss_mb ?? 0, ffmpeg: R.isActive(r) && !!r.ffmpeg_pid }; });50 const sessions = S.openSessions().map((s) => ({ id: s.id.slice(0, 10), relay: s.relay_id, channel: chan(s.channel_id), ip: s.ip, userAgent: s.user_agent, via: s.auth.startsWith("p:") ? "playlist" : "session", since: s.created_at, lastSeen: s.last_seen_at, bytes: s.bytes_out, playSec: Math.round((s.last_seen_at - s.created_at) / 1000) }));51 const day = get<{ n: number; sec: number; bytes: number }>("SELECT COUNT(*) n, COALESCE(SUM(last_seen_at - created_at), 0) / 1000 sec, COALESCE(SUM(bytes_out), 0) bytes FROM relay_sessions WHERE created_at > ?", t - 24 * 3600_000)!;52 const tot = last("*");53 const active = relays.filter((r) => R.isActive(r));54 return {55 engine: { enabled: C.enabled(), up: !!engine.up && !!engine.at && t - engine.at < 30_000, checkedAt: engine.at ?? null, version: engine.version ?? null, installed: fs.existsSync(C.configPath()) },56 limits: l,57 totals: { relays: active.length, transcodes: active.filter((r) => r.mode === "transcode").length, ffmpeg: active.filter((r) => r.ffmpeg).length, clients: sessions.length, inKbps: tot?.in_kbps ?? 0, outKbps: tot?.out_kbps ?? 0, cpu: tot?.cpu ?? 0, rssMb: tot?.rss_mb ?? 0,58 errors24h: get<{ n: number }>("SELECT COUNT(*) n FROM relay_events WHERE level = 'error' AND at > ?", t - 24 * 3600_000)!.n, sessions24h: day.n, playSec24h: Math.round(day.sec), bytes24h: day.bytes },59 relays, sessions,60 history: all<{ at: number; cpu: number; rss_mb: number; in_kbps: number; out_kbps: number; clients: number }>("SELECT at, cpu, rss_mb, in_kbps, out_kbps, clients FROM relay_samples WHERE relay_id = '*' AND at > ? ORDER BY at", t - 30 * 60_000),61 events: recentEvents(80), sources: listSources(),62 };63});6465route("PUT", "/admin/relay/sources/:id", async (c) => {66 const b = await c.body(z.object({ allowed: z.boolean(), basis: z.string().max(400).optional(), share: z.boolean().optional(), record: z.boolean().optional(), maxConnections: z.number().int().min(0).max(50).nullable().optional(), declaration: z.boolean().optional() }));67 const policy = await wrap(() => A.setPolicy(Number(c.params[0]), b));68 // Withdrawing the authorisation ends what is running for that source.69 if (!policy.allowed) for (const r of R.activeRelays().filter((x) => x.source_id === Number(c.params[0]))) R.stop(r.id, "autorisation retirée");70 const { bumpCatalog } = await import("../db"); bumpCatalog();71 return { policy };72});73route("POST", "/admin/relay/relays/:id/stop", (c) => { if (!C.RELAY_ID.test(c.params[0]) || !R.stop(c.params[0], "arrêt manuel")) throw new HttpError(404, "Relais introuvable"); });74