From 66e24065824cf7966911eed115ace84ea74b347e Mon Sep 17 00:00:00 2001 From: Josh Date: Fri, 13 Nov 2026 16:16:17 -0500 Subject: [PATCH] Add direct IPTV streams to the retroLabs guide --- README.md | 6 ++++++ bridge/app.py | 39 +++++++++++++++++++++++++++++----- compose.yaml | 1 + roku/components/Guide.brs | 1 + roku/components/RetroScene.brs | 1 + tests/test_bridge.py | 19 +++++++++++++++++ 6 files changed, 62 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 9f81b5a..fb24333 100644 --- a/README.md +++ b/README.md @@ -61,3 +61,9 @@ python3 -m venv .venv ``` The tests exercise lineup and guide normalization, server ID persistence, Tunarr admin writes, and HLS manifest/segment forwarding. Physical Roku discovery, playback, live tuning, and reboot recovery are the remaining device acceptance checks. Pairing is deferred. + +## IPTV channels + +Add direct Roku-compatible HLS feeds to `data/iptv/channels.json`. Each entry has a stable lowercase `id`, a positive `number`, a `name`, and a `url`. The file stays local. Restart the bridge with `docker compose restart bridge` after changes, then refresh channels in the Roku app. Tunarr numbers take precedence when a number overlaps, and 99 is reserved for weather. + +The Roku plays the feed directly. These channels appear in the retroLabs guide with a live label. Program listings require a separate schedule feed. diff --git a/bridge/app.py b/bridge/app.py index 09361e3..ba3265a 100644 --- a/bridge/app.py +++ b/bridge/app.py @@ -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"]) diff --git a/compose.yaml b/compose.yaml index 736f6e0..98542f7 100644 --- a/compose.yaml +++ b/compose.yaml @@ -39,6 +39,7 @@ services: volumes: - bridge-data:/state - ./data/weather:/app/data/weather:ro + - ./data/iptv:/app/data/iptv:ro volumes: tunarr-data: diff --git a/roku/components/Guide.brs b/roku/components/Guide.brs index 72e7c99..967b3ef 100644 --- a/roku/components/Guide.brs +++ b/roku/components/Guide.brs @@ -129,6 +129,7 @@ sub renderGuide() m.top.FindNode("guideChannel" + suffix).text = channelLabel(channel) m.top.FindNode("guideNow" + suffix).text = programTitle(current) if channel.type = "weather" then m.top.FindNode("guideNow" + suffix).text = "Local weather" + if channel.type = "iptv" then m.top.FindNode("guideNow" + suffix).text = "Live stream" nextTitle = programTitle(upcoming) if upcoming <> invalid then nextTitle = guideTime(parseUtc(upcoming.start)) + " " + nextTitle m.top.FindNode("guideNext" + suffix).text = nextTitle diff --git a/roku/components/RetroScene.brs b/roku/components/RetroScene.brs index 65e50ae..b22c7cd 100644 --- a/roku/components/RetroScene.brs +++ b/roku/components/RetroScene.brs @@ -213,6 +213,7 @@ sub onSchedule(event as object) m.schedule = data syncClock(data.serverTime) m.nowTitle.text = "NOW " + programTitle(data.now) + if m.channels[m.channelIndex].type = "iptv" then m.nowTitle.text = "LIVE" m.nextTitle.text = "NEXT " + programTitle(data.next) refreshClock() end sub diff --git a/tests/test_bridge.py b/tests/test_bridge.py index 96aa3b4..00ea059 100644 --- a/tests/test_bridge.py +++ b/tests/test_bridge.py @@ -26,6 +26,7 @@ class BridgeTest(unittest.TestCase): self.app = create_app( tunarr_url="http://tunarr:8000", transport=httpx.MockTransport(self.upstream), discover=False, id_file=Path(temporary.name) / "server-id", + iptv_file=Path(temporary.name) / "channels.json", ) self.client = self.enterContext(TestClient(self.app)) @@ -105,3 +106,21 @@ class BridgeTest(unittest.TestCase): self.assertEqual(program_title(episode, "The Rookie"), "The Rookie S01E01") episode["program"]["title"] = "The Rookie S01E01 Pilot" self.assertEqual(program_title(episode, "The Rookie"), "The Rookie S01E01 ยท Pilot") + + def test_iptv_joins_lineup_without_tunarr_programming(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "channels.json" + path.write_text( + '[{"id":"sports","name":"Sports","number":12,' + '"url":"https://example.com/live.m3u8"}]' + ) + app = create_app( + transport=httpx.MockTransport(self.upstream), discover=False, + id_file=path.with_name("server-id"), iptv_file=path, + ) + with TestClient(app) as client: + channels = client.get("/api/v1/channels").json()["channels"] + self.assertEqual(channels[0]["streamUrl"], "https://example.com/live.m3u8") + self.assertEqual(channels[0]["type"], "iptv") + self.assertEqual(client.get("/api/v1/guide").json()["channels"][0]["programs"], []) + self.assertIsNone(client.get("/api/v1/channels/iptv-sports/now").json()["now"])