317 lines
13 KiB
Python
317 lines
13 KiB
Python
import asyncio
|
|
import os
|
|
import re
|
|
from contextlib import asynccontextmanager
|
|
from datetime import UTC, datetime, timedelta
|
|
from pathlib import Path
|
|
from urllib.parse import urljoin, urlsplit
|
|
from uuid import UUID, uuid4
|
|
from xml.etree import ElementTree as XML
|
|
|
|
import httpx
|
|
from fastapi import FastAPI, HTTPException, Query, Request
|
|
from fastapi.responses import FileResponse, RedirectResponse, Response, StreamingResponse
|
|
from starlette.background import BackgroundTask
|
|
|
|
from .discovery import SERVICE, start_discovery
|
|
from .weather import NWSWeather
|
|
|
|
WEATHER_ID = "weather"
|
|
HOP_HEADERS = {
|
|
"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
|
|
"te", "trailer", "transfer-encoding", "upgrade",
|
|
}
|
|
URI_ATTRIBUTE = re.compile(r'\bURI="([^"]+)"')
|
|
|
|
|
|
def utc_string(value: datetime):
|
|
return value.astimezone(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
|
|
|
|
def lineup(data):
|
|
channels = [
|
|
{
|
|
"id": channel["id"],
|
|
"number": channel["number"],
|
|
"name": channel["name"],
|
|
"type": "linear",
|
|
"streamUrl": f'/stream/{channel["id"]}/master.m3u8',
|
|
}
|
|
for channel in data if not channel.get("stealth")
|
|
]
|
|
used = {channel["number"] for channel in channels}
|
|
number = 99
|
|
while number in used:
|
|
number += 1
|
|
channels.append({
|
|
"id": WEATHER_ID, "number": number, "name": "retroLabs Weather",
|
|
"type": "weather", "streamUrl": None,
|
|
})
|
|
return sorted(channels, key=lambda channel: channel["number"])
|
|
|
|
|
|
EPISODE_CODE = re.compile(r"\bS(\d{1,2})E(\d{1,3})\b", re.IGNORECASE)
|
|
RELEASE_SUFFIX = re.compile(
|
|
r"\b(?:\d{3,4}p|WEB(?:[ ._-]?(?:DL|Rip))?|BluRay|BRRip|HDTV|[xh][ .]?26[45]|HEVC)\b",
|
|
re.IGNORECASE,
|
|
)
|
|
|
|
|
|
def program_title(item, channel_name):
|
|
program = item.get("program") or {}
|
|
title = item.get("title") or program.get("title")
|
|
if not title:
|
|
return "Off air" if item["type"] == "flex" else "Programming"
|
|
if program.get("type") != "episode":
|
|
return title
|
|
words = re.sub(r"(?<=\w)\.(?=\w)", " ", title)
|
|
match = EPISODE_CODE.search(words)
|
|
if not match:
|
|
return words
|
|
season, episode = map(int, match.groups())
|
|
label = f"{channel_name} S{season:02d}E{episode:02d}"
|
|
detail = RELEASE_SUFFIX.split(words[match.end():], maxsplit=1)[0].strip(" ._-")
|
|
return f"{label} · {detail}" if detail else label
|
|
|
|
|
|
def programs(channel_guide, channel_name):
|
|
result = []
|
|
for item in sorted(channel_guide.get("programs", []), key=lambda p: p["start"]):
|
|
result.append({
|
|
"title": program_title(item, channel_name),
|
|
"start": utc_string(datetime.fromtimestamp(item["start"] / 1000, UTC)),
|
|
"stop": utc_string(datetime.fromtimestamp(item["stop"] / 1000, UTC)),
|
|
})
|
|
return result
|
|
|
|
|
|
def rewrite_playlist(body, upstream_url):
|
|
def rewrite(uri):
|
|
target = urlsplit(urljoin(str(upstream_url), uri))
|
|
if target.netloc != urlsplit(str(upstream_url)).netloc:
|
|
return uri
|
|
return target.path + (f"?{target.query}" if target.query else "")
|
|
|
|
lines = []
|
|
for line in body.splitlines():
|
|
if line.startswith("#"):
|
|
line = URI_ATTRIBUTE.sub(lambda match: f'URI="{rewrite(match[1])}"', line)
|
|
elif line.strip():
|
|
line = rewrite(line.strip())
|
|
lines.append(line)
|
|
return "\n".join(lines) + "\n"
|
|
|
|
|
|
def forwarded_headers(headers, excluded):
|
|
connection = set(headers.get("connection", "").lower().replace(" ", "").split(","))
|
|
blocked = HOP_HEADERS | excluded | connection
|
|
return [(key.decode("latin-1"), value.decode("latin-1"))
|
|
for key, value in headers.raw if key.decode("latin-1").lower() not in blocked]
|
|
|
|
|
|
def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None):
|
|
ip = os.getenv("RETROTV_LAN_IP", "127.0.0.1")
|
|
port = int(os.getenv("RETROTV_PORT", "4242"))
|
|
base_url = f"http://{ip}:{port}"
|
|
name = os.getenv("RETROTV_NAME", "retroLabs")
|
|
weather_provider = NWSWeather()
|
|
weather_music = Path(os.getenv("RETROTV_WEATHER_MUSIC", "data/weather/forecast.mp3"))
|
|
upstream = tunarr_url or os.getenv("RETROTV_TUNARR_URL", "http://127.0.0.1:14242")
|
|
identity = Path(id_file or os.getenv("RETROTV_ID_FILE", "data/server-id"))
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app):
|
|
identity.parent.mkdir(parents=True, exist_ok=True)
|
|
if not identity.exists():
|
|
temporary = identity.with_suffix(".tmp")
|
|
temporary.write_text(f"{uuid4()}\n")
|
|
temporary.replace(identity)
|
|
app.state.server_id = str(UUID(identity.read_text().strip()))
|
|
ssdp = await start_discovery(ip, app.state.server_id, base_url) if discover else None
|
|
try:
|
|
async with httpx.AsyncClient(
|
|
base_url=upstream, transport=transport, trust_env=False,
|
|
timeout=httpx.Timeout(120, connect=5),
|
|
) as client:
|
|
app.state.tunarr = client
|
|
yield
|
|
finally:
|
|
if ssdp:
|
|
ssdp.close()
|
|
|
|
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
|
|
|
async def upstream_json(path, **params):
|
|
try:
|
|
response = await app.state.tunarr.get(path, params=params, timeout=10)
|
|
response.raise_for_status()
|
|
return response.json()
|
|
except (httpx.HTTPError, ValueError) as exc:
|
|
raise HTTPException(502, "Tunarr did not return usable data") from exc
|
|
|
|
async def guide_data(start, hours):
|
|
return await upstream_json(
|
|
"/api/guide/channels", dateFrom=utc_string(start),
|
|
dateTo=utc_string(start + timedelta(hours=hours)),
|
|
)
|
|
|
|
@app.get("/api/v1/health")
|
|
async def health():
|
|
return {"status": "ok"}
|
|
|
|
@app.get("/api/v1/server")
|
|
async def server():
|
|
return {"id": app.state.server_id, "name": name, "baseUrl": base_url}
|
|
|
|
@app.get("/api/v1/device.xml")
|
|
async def device():
|
|
root = XML.Element("root", xmlns="urn:schemas-upnp-org:device-1-0")
|
|
spec = XML.SubElement(root, "specVersion")
|
|
XML.SubElement(spec, "major").text = "1"
|
|
XML.SubElement(spec, "minor").text = "0"
|
|
node = XML.SubElement(root, "device")
|
|
XML.SubElement(node, "deviceType").text = "urn:retrolabs:device:retrotv:1"
|
|
XML.SubElement(node, "friendlyName").text = name
|
|
XML.SubElement(node, "UDN").text = f"uuid:{app.state.server_id}"
|
|
services = XML.SubElement(node, "serviceList")
|
|
service = XML.SubElement(services, "service")
|
|
XML.SubElement(service, "serviceType").text = SERVICE
|
|
return Response(XML.tostring(root, encoding="utf-8", xml_declaration=True),
|
|
media_type="application/xml")
|
|
|
|
@app.get("/api/v1/channels")
|
|
async def channels():
|
|
return {"channels": lineup(await upstream_json("/api/channels"))}
|
|
|
|
@app.get("/api/v1/guide")
|
|
async def guide(
|
|
start: datetime | None = Query(None, alias="from"),
|
|
hours: int = Query(3, ge=1, le=24),
|
|
):
|
|
now = datetime.now(UTC)
|
|
if start is not None and start.utcoffset() is None:
|
|
raise HTTPException(422, "Guide start must include a timezone")
|
|
channel_data, schedules = await asyncio.gather(
|
|
upstream_json("/api/channels"), guide_data(start or now, hours)
|
|
)
|
|
return {
|
|
"serverTime": utc_string(now),
|
|
"channels": [
|
|
{**channel, "programs": programs(schedules.get(channel["id"], {}), channel["name"])}
|
|
for channel in lineup(channel_data)
|
|
],
|
|
}
|
|
|
|
@app.get("/api/v1/channels/{channel_id}/now")
|
|
async def now_next(channel_id: str):
|
|
now = datetime.now(UTC)
|
|
stamp = utc_string(now)
|
|
if channel_id == WEATHER_ID:
|
|
return {"now": None, "next": None, "serverTime": stamp}
|
|
channel_data, schedules = await asyncio.gather(
|
|
upstream_json("/api/channels"), guide_data(now, 24)
|
|
)
|
|
channel = next((entry for entry in lineup(channel_data) if entry["id"] == channel_id), None)
|
|
if channel is None:
|
|
raise HTTPException(404, "Channel not found")
|
|
entries = programs(schedules.get(channel_id, {}), channel["name"])
|
|
return {
|
|
"now": next((p for p in entries if p["start"] <= stamp < p["stop"]), None),
|
|
"next": next((p for p in entries if p["start"] > stamp), None),
|
|
"serverTime": stamp,
|
|
}
|
|
|
|
@app.get("/api/v1/weather")
|
|
async def weather():
|
|
data = await weather_provider.read()
|
|
return {**data, "musicUrl": "/api/v1/weather/music.mp3" if weather_music.is_file() else None}
|
|
|
|
@app.api_route("/api/v1/weather/music.mp3", methods=["GET", "HEAD"])
|
|
async def weather_audio():
|
|
if not weather_music.is_file():
|
|
raise HTTPException(404, "Weather music is not configured")
|
|
return FileResponse(weather_music, media_type="audio/mpeg")
|
|
|
|
async def proxy(request, path, *, playlist=False, params=None):
|
|
client = app.state.tunarr
|
|
headers = forwarded_headers(
|
|
request.headers, {"host", "content-length", "x-forwarded-for",
|
|
"x-forwarded-host", "x-forwarded-proto"}
|
|
)
|
|
if request.client:
|
|
headers.append(("x-forwarded-for", request.client.host))
|
|
headers.extend([
|
|
("x-forwarded-host", request.url.netloc),
|
|
("x-forwarded-proto", request.url.scheme),
|
|
])
|
|
has_body = "content-length" in request.headers or "transfer-encoding" in request.headers
|
|
raw_path = request.scope["raw_path"] if path == request.url.path else path.encode("ascii")
|
|
target = httpx.Request(
|
|
request.method, client.base_url.copy_with(raw_path=raw_path),
|
|
params=params if params is not None else request.url.query,
|
|
headers=headers, content=request.stream() if has_body else None,
|
|
)
|
|
try:
|
|
response = await client.send(target, stream=True)
|
|
client.cookies.clear()
|
|
except httpx.HTTPError as exc:
|
|
raise HTTPException(502, "Tunarr is unavailable") from exc
|
|
is_playlist = playlist and request.method == "GET" and response.is_success
|
|
excluded = {"date", "server"}
|
|
if is_playlist:
|
|
excluded.update({"content-length", "content-encoding", "etag"})
|
|
response_headers = forwarded_headers(response.headers, excluded)
|
|
if is_playlist:
|
|
try:
|
|
await response.aread()
|
|
body = rewrite_playlist(response.text, response.url)
|
|
except httpx.HTTPError as exc:
|
|
raise HTTPException(502, "Tunarr playlist could not be read") from exc
|
|
finally:
|
|
await response.aclose()
|
|
result = Response(body.encode("utf-8"), status_code=response.status_code)
|
|
response_headers = [(k, v) for k, v in response_headers if k.lower() != "content-type"]
|
|
response_headers.append(("content-type", "application/vnd.apple.mpegurl"))
|
|
else:
|
|
async def body_stream():
|
|
try:
|
|
async for chunk in response.aiter_raw():
|
|
yield chunk
|
|
finally:
|
|
await response.aclose()
|
|
|
|
result = StreamingResponse(body_stream(), status_code=response.status_code,
|
|
background=BackgroundTask(response.aclose))
|
|
for key, value in response_headers:
|
|
if key.lower() == "location":
|
|
location = urlsplit(value)
|
|
if location.netloc == client.base_url.netloc.decode():
|
|
value = location.path or "/"
|
|
if location.query:
|
|
value += "?" + location.query
|
|
if location.fragment:
|
|
value += "#" + location.fragment
|
|
result.raw_headers.append((key.lower().encode("latin-1"), value.encode("latin-1")))
|
|
return result
|
|
|
|
@app.api_route("/stream/{channel_id}/master.m3u8", methods=["GET", "HEAD"])
|
|
async def tune(request: Request, channel_id: UUID):
|
|
return await proxy(request, f"/stream/channels/{channel_id}.m3u8", playlist=True)
|
|
|
|
@app.get("/admin", include_in_schema=False)
|
|
@app.get("/admin/", include_in_schema=False)
|
|
async def admin():
|
|
return RedirectResponse("/")
|
|
|
|
@app.api_route("/{path:path}", methods=["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"])
|
|
async def tunarr_admin_and_assets(request: Request, path: str):
|
|
if path == "api/v1" or path.startswith("api/v1/"):
|
|
raise HTTPException(404, "Unknown retroLabs endpoint")
|
|
return await proxy(request, f"/{path}",
|
|
playlist=path.startswith("stream/") and path.endswith(".m3u8"))
|
|
|
|
return app
|
|
|
|
|
|
app = create_app()
|