Add direct IPTV streams to the retroLabs guide
This commit is contained in:
@@ -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.
|
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.
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ from xml.etree import ElementTree as XML
|
|||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
from fastapi import FastAPI, HTTPException, Query, Request
|
from fastapi import FastAPI, HTTPException, Query, Request
|
||||||
|
from pydantic import BaseModel, Field, HttpUrl, TypeAdapter
|
||||||
from fastapi.responses import FileResponse, RedirectResponse, Response, StreamingResponse
|
from fastapi.responses import FileResponse, RedirectResponse, Response, StreamingResponse
|
||||||
from starlette.background import BackgroundTask
|
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")
|
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 = [
|
channels = [
|
||||||
{
|
{
|
||||||
"id": channel["id"],
|
"id": channel["id"],
|
||||||
@@ -47,6 +72,7 @@ def lineup(data):
|
|||||||
"id": WEATHER_ID, "number": number, "name": "retroLabs Weather",
|
"id": WEATHER_ID, "number": number, "name": "retroLabs Weather",
|
||||||
"type": "weather", "streamUrl": None,
|
"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"])
|
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]
|
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")
|
ip = os.getenv("RETROTV_LAN_IP", "127.0.0.1")
|
||||||
port = int(os.getenv("RETROTV_PORT", "4242"))
|
port = int(os.getenv("RETROTV_PORT", "4242"))
|
||||||
base_url = f"http://{ip}:{port}"
|
base_url = f"http://{ip}:{port}"
|
||||||
@@ -121,6 +147,7 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None):
|
|||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app):
|
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)
|
identity.parent.mkdir(parents=True, exist_ok=True)
|
||||||
if not identity.exists():
|
if not identity.exists():
|
||||||
temporary = identity.with_suffix(".tmp")
|
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")
|
@app.get("/api/v1/channels")
|
||||||
async def 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")
|
@app.get("/api/v1/guide")
|
||||||
async def 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),
|
"serverTime": utc_string(now),
|
||||||
"channels": [
|
"channels": [
|
||||||
{**channel, "programs": programs(schedules.get(channel["id"], {}), channel["name"])}
|
{**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)
|
stamp = utc_string(now)
|
||||||
if channel_id == WEATHER_ID:
|
if channel_id == WEATHER_ID:
|
||||||
return {"now": None, "next": None, "serverTime": stamp}
|
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(
|
channel_data, schedules = await asyncio.gather(
|
||||||
upstream_json("/api/channels"), guide_data(now, 24)
|
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:
|
if channel is None:
|
||||||
raise HTTPException(404, "Channel not found")
|
raise HTTPException(404, "Channel not found")
|
||||||
entries = programs(schedules.get(channel_id, {}), channel["name"])
|
entries = programs(schedules.get(channel_id, {}), channel["name"])
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ services:
|
|||||||
volumes:
|
volumes:
|
||||||
- bridge-data:/state
|
- bridge-data:/state
|
||||||
- ./data/weather:/app/data/weather:ro
|
- ./data/weather:/app/data/weather:ro
|
||||||
|
- ./data/iptv:/app/data/iptv:ro
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
tunarr-data:
|
tunarr-data:
|
||||||
|
|||||||
@@ -129,6 +129,7 @@ sub renderGuide()
|
|||||||
m.top.FindNode("guideChannel" + suffix).text = channelLabel(channel)
|
m.top.FindNode("guideChannel" + suffix).text = channelLabel(channel)
|
||||||
m.top.FindNode("guideNow" + suffix).text = programTitle(current)
|
m.top.FindNode("guideNow" + suffix).text = programTitle(current)
|
||||||
if channel.type = "weather" then m.top.FindNode("guideNow" + suffix).text = "Local weather"
|
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)
|
nextTitle = programTitle(upcoming)
|
||||||
if upcoming <> invalid then nextTitle = guideTime(parseUtc(upcoming.start)) + " " + nextTitle
|
if upcoming <> invalid then nextTitle = guideTime(parseUtc(upcoming.start)) + " " + nextTitle
|
||||||
m.top.FindNode("guideNext" + suffix).text = nextTitle
|
m.top.FindNode("guideNext" + suffix).text = nextTitle
|
||||||
|
|||||||
@@ -213,6 +213,7 @@ sub onSchedule(event as object)
|
|||||||
m.schedule = data
|
m.schedule = data
|
||||||
syncClock(data.serverTime)
|
syncClock(data.serverTime)
|
||||||
m.nowTitle.text = "NOW " + programTitle(data.now)
|
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)
|
m.nextTitle.text = "NEXT " + programTitle(data.next)
|
||||||
refreshClock()
|
refreshClock()
|
||||||
end sub
|
end sub
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ class BridgeTest(unittest.TestCase):
|
|||||||
self.app = create_app(
|
self.app = create_app(
|
||||||
tunarr_url="http://tunarr:8000", transport=httpx.MockTransport(self.upstream),
|
tunarr_url="http://tunarr:8000", transport=httpx.MockTransport(self.upstream),
|
||||||
discover=False, id_file=Path(temporary.name) / "server-id",
|
discover=False, id_file=Path(temporary.name) / "server-id",
|
||||||
|
iptv_file=Path(temporary.name) / "channels.json",
|
||||||
)
|
)
|
||||||
self.client = self.enterContext(TestClient(self.app))
|
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")
|
self.assertEqual(program_title(episode, "The Rookie"), "The Rookie S01E01")
|
||||||
episode["program"]["title"] = "The Rookie S01E01 Pilot"
|
episode["program"]["title"] = "The Rookie S01E01 Pilot"
|
||||||
self.assertEqual(program_title(episode, "The Rookie"), "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"])
|
||||||
|
|||||||
Reference in New Issue
Block a user