49 lines
1.5 KiB
Python
49 lines
1.5 KiB
Python
"""Reicht den HLS-Stream von MediaMTX unter demselben Ursprung durch.
|
|
|
|
Ohne das läge der Player auf Port 8000 und der Stream auf 8890 — zwei
|
|
Ursprünge, also CORS und eine zweite Route nach außen. Produktiv ist ein
|
|
Reverse-Proxy davor die bessere Wahl: Traefik reicht die Segmente durch,
|
|
ohne dass Python jedes Byte anfasst.
|
|
"""
|
|
|
|
import httpx
|
|
from fastapi import HTTPException, Request
|
|
from fastapi.responses import Response, StreamingResponse
|
|
|
|
from .config import MEDIAMTX_URL
|
|
|
|
# Playlists ändern sich im Sekundentakt, Segmente nie
|
|
NICHT_ZWISCHENSPEICHERN = {"Cache-Control": "no-store"}
|
|
|
|
DURCHREICHEN = {
|
|
"content-type",
|
|
"content-length",
|
|
"cache-control",
|
|
"last-modified",
|
|
"etag",
|
|
}
|
|
|
|
|
|
async def weiterleiten(request: Request, pfad: str):
|
|
ziel = f"{MEDIAMTX_URL}/{pfad}"
|
|
frage = dict(request.query_params)
|
|
|
|
async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as http:
|
|
try:
|
|
antwort = await http.get(ziel, params=frage)
|
|
except httpx.HTTPError:
|
|
raise HTTPException(status_code=502, detail="Stream nicht erreichbar")
|
|
|
|
if antwort.status_code == 404:
|
|
raise HTTPException(status_code=404, detail="Kein Stream")
|
|
|
|
kopf = {k: v for k, v in antwort.headers.items() if k.lower() in DURCHREICHEN}
|
|
if pfad.endswith(".m3u8"):
|
|
kopf.update(NICHT_ZWISCHENSPEICHERN)
|
|
|
|
return Response(
|
|
content=antwort.content,
|
|
status_code=antwort.status_code,
|
|
headers=kopf,
|
|
)
|