Add direct IPTV streams to the retroLabs guide

This commit is contained in:
Josh
2026-11-13 16:16:17 -05:00
parent 41f863b0f8
commit 66e2406582
6 changed files with 62 additions and 5 deletions

View File

@@ -10,6 +10,7 @@ from xml.etree import ElementTree as XML
import httpx
from fastapi import FastAPI, HTTPException, Query, Request
from pydantic import BaseModel, Field, HttpUrl, TypeAdapter
from fastapi.responses import FileResponse, RedirectResponse, Response, StreamingResponse
from starlette.background import BackgroundTask
@@ -28,7 +29,31 @@ def utc_string(value: datetime):
return value.astimezone(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
def lineup(data):
class IPTVChannel(BaseModel):
id: str = Field(pattern=r"^[a-z0-9-]+$")
number: int = Field(gt=0)
name: str = Field(min_length=1)
url: HttpUrl
def load_iptv(path):
if not path.is_file():
return []
entries = TypeAdapter(list[IPTVChannel]).validate_json(path.read_text())
if len({entry.id for entry in entries}) != len(entries):
raise ValueError("IPTV channel IDs must be unique")
if len({entry.number for entry in entries}) != len(entries):
raise ValueError("IPTV channel numbers must be unique")
if any(entry.number == 99 for entry in entries):
raise ValueError("IPTV channel 99 is reserved for weather")
return [
{"id": f"iptv-{entry.id}", "number": entry.number, "name": entry.name,
"type": "iptv", "streamUrl": str(entry.url)}
for entry in entries
]
def lineup(data, iptv=()):
channels = [
{
"id": channel["id"],
@@ -47,6 +72,7 @@ def lineup(data):
"id": WEATHER_ID, "number": number, "name": "retroLabs Weather",
"type": "weather", "streamUrl": None,
})
channels.extend(entry for entry in iptv if entry["number"] not in used and entry["number"] != number)
return sorted(channels, key=lambda channel: channel["number"])
@@ -109,7 +135,7 @@ def forwarded_headers(headers, excluded):
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):
def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None, iptv_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}"
@@ -121,6 +147,7 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None):
@asynccontextmanager
async def lifespan(app):
app.state.iptv = load_iptv(Path(iptv_file or os.getenv("RETROTV_IPTV_FILE", "data/iptv/channels.json")))
identity.parent.mkdir(parents=True, exist_ok=True)
if not identity.exists():
temporary = identity.with_suffix(".tmp")
@@ -181,7 +208,7 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None):
@app.get("/api/v1/channels")
async def channels():
return {"channels": lineup(await upstream_json("/api/channels"))}
return {"channels": lineup(await upstream_json("/api/channels"), app.state.iptv)}
@app.get("/api/v1/guide")
async def guide(
@@ -198,7 +225,7 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None):
"serverTime": utc_string(now),
"channels": [
{**channel, "programs": programs(schedules.get(channel["id"], {}), channel["name"])}
for channel in lineup(channel_data)
for channel in lineup(channel_data, app.state.iptv)
],
}
@@ -208,10 +235,12 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None):
stamp = utc_string(now)
if channel_id == WEATHER_ID:
return {"now": None, "next": None, "serverTime": stamp}
if any(entry["id"] == channel_id for entry in app.state.iptv):
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)
channel = next((entry for entry in lineup(channel_data, app.state.iptv) if entry["id"] == channel_id), None)
if channel is None:
raise HTTPException(404, "Channel not found")
entries = programs(schedules.get(channel_id, {}), channel["name"])