Run the retroLabs backend and add the Roku tuner

This commit is contained in:
Josh
2026-11-13 11:38:39 -05:00
parent a668681d2b
commit fceda10d90
21 changed files with 1447 additions and 0 deletions

282
bridge/app.py Normal file
View File

@@ -0,0 +1,282 @@
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 RedirectResponse, Response, StreamingResponse
from starlette.background import BackgroundTask
from .discovery import SERVICE, start_discovery
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"])
def programs(channel_guide):
result = []
for item in sorted(channel_guide.get("programs", []), key=lambda p: p["start"]):
title = item.get("title") or (item.get("program") or {}).get("title")
result.append({
"title": title or ("Off air" if item["type"] == "flex" else "Programming"),
"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")
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"], {}))}
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)
)
if not any(channel["id"] == channel_id for channel in lineup(channel_data)):
raise HTTPException(404, "Channel not found")
entries = programs(schedules.get(channel_id, {}))
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():
return {"status": "placeholder"}
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()

55
bridge/discovery.py Normal file
View File

@@ -0,0 +1,55 @@
import asyncio
import logging
import socket
SERVICE = "urn:retrolabs:service:retrotv:1"
GROUP = "239.255.255.250"
LOG = logging.getLogger(__name__)
class Discovery(asyncio.DatagramProtocol):
def __init__(self, server_id: str, base_url: str):
self.transport = None
self.reply = (
"HTTP/1.1 200 OK\r\n"
"CACHE-CONTROL: max-age=120\r\n"
"EXT:\r\n"
f"LOCATION: {base_url}/api/v1/device.xml\r\n"
"SERVER: Linux UPnP/1.1 retroLabs/0.1\r\n"
f"ST: {SERVICE}\r\n"
f"USN: uuid:{server_id}::{SERVICE}\r\n\r\n"
).encode("ascii")
def connection_made(self, transport):
self.transport = transport
def datagram_received(self, data, addr):
lines = data.decode("ascii", errors="ignore").splitlines()
if not lines or lines[0].strip().upper() != "M-SEARCH * HTTP/1.1":
return
headers = {}
for line in lines[1:]:
name, _, value = line.partition(":")
headers[name.strip().lower()] = value.strip().lower()
if headers.get("man") == '"ssdp:discover"' and headers.get("st") == SERVICE:
self.transport.sendto(self.reply, addr)
async def start_discovery(ip: str, server_id: str, base_url: str):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("", 1900))
sock.setsockopt(
socket.IPPROTO_IP,
socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(GROUP) + socket.inet_aton(ip),
)
transport, _ = await asyncio.get_running_loop().create_datagram_endpoint(
lambda: Discovery(server_id, base_url), sock=sock
)
return transport
except OSError:
sock.close()
LOG.exception("SSDP unavailable. The Roku can connect using manual server entry.")
return None

3
bridge/requirements.txt Normal file
View File

@@ -0,0 +1,3 @@
fastapi==0.115.14
httpx==0.28.1
uvicorn==0.34.3