Relay IPTV streams over the Roku LAN connection
This commit is contained in:
@@ -66,4 +66,4 @@ The tests exercise lineup and guide normalization, server ID persistence, Tunarr
|
|||||||
|
|
||||||
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.
|
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.
|
The bridge relays HLS playlists and media over the LAN without transcoding. These channels appear in the retroLabs guide with a live label. Program listings require a separate schedule feed.
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ from starlette.background import BackgroundTask
|
|||||||
|
|
||||||
from .discovery import SERVICE, start_discovery
|
from .discovery import SERVICE, start_discovery
|
||||||
from .weather import NWSWeather
|
from .weather import NWSWeather
|
||||||
|
from .iptv import IPTVRelay
|
||||||
|
|
||||||
WEATHER_ID = "weather"
|
WEATHER_ID = "weather"
|
||||||
HOP_HEADERS = {
|
HOP_HEADERS = {
|
||||||
@@ -72,7 +73,10 @@ def lineup(data, iptv=()):
|
|||||||
"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)
|
channels.extend(
|
||||||
|
{**entry, "streamUrl": f'/iptv/{entry["id"]}/master.m3u8'}
|
||||||
|
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"])
|
||||||
|
|
||||||
|
|
||||||
@@ -148,6 +152,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")))
|
app.state.iptv = load_iptv(Path(iptv_file or os.getenv("RETROTV_IPTV_FILE", "data/iptv/channels.json")))
|
||||||
|
app.state.iptv_relay = IPTVRelay(app.state.iptv)
|
||||||
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")
|
||||||
@@ -161,7 +166,9 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None,
|
|||||||
timeout=httpx.Timeout(120, connect=5),
|
timeout=httpx.Timeout(120, connect=5),
|
||||||
) as client:
|
) as client:
|
||||||
app.state.tunarr = client
|
app.state.tunarr = client
|
||||||
yield
|
async with httpx.AsyncClient(timeout=12, trust_env=False) as iptv_client:
|
||||||
|
app.state.iptv_client = iptv_client
|
||||||
|
yield
|
||||||
finally:
|
finally:
|
||||||
if ssdp:
|
if ssdp:
|
||||||
ssdp.close()
|
ssdp.close()
|
||||||
@@ -323,6 +330,14 @@ def create_app(*, tunarr_url=None, transport=None, discover=True, id_file=None,
|
|||||||
result.raw_headers.append((key.lower().encode("latin-1"), value.encode("latin-1")))
|
result.raw_headers.append((key.lower().encode("latin-1"), value.encode("latin-1")))
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
@app.api_route("/iptv/{channel_id}/master.m3u8", methods=["GET", "HEAD"])
|
||||||
|
async def iptv_master(request: Request, channel_id: str):
|
||||||
|
return await app.state.iptv_relay.serve(app.state.iptv_client, request, channel_id)
|
||||||
|
|
||||||
|
@app.api_route("/iptv/{channel_id}/{resource}", methods=["GET", "HEAD"])
|
||||||
|
async def iptv_resource(request: Request, channel_id: str, resource: str):
|
||||||
|
return await app.state.iptv_relay.serve(app.state.iptv_client, request, channel_id, resource)
|
||||||
|
|
||||||
@app.api_route("/stream/{channel_id}/master.m3u8", methods=["GET", "HEAD"])
|
@app.api_route("/stream/{channel_id}/master.m3u8", methods=["GET", "HEAD"])
|
||||||
async def tune(request: Request, channel_id: UUID):
|
async def tune(request: Request, channel_id: UUID):
|
||||||
return await proxy(request, f"/stream/channels/{channel_id}.m3u8", playlist=True)
|
return await proxy(request, f"/stream/channels/{channel_id}.m3u8", playlist=True)
|
||||||
|
|||||||
93
bridge/iptv.py
Normal file
93
bridge/iptv.py
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
import re
|
||||||
|
from collections import OrderedDict
|
||||||
|
from hashlib import sha256
|
||||||
|
from pathlib import PurePosixPath
|
||||||
|
from urllib.parse import urljoin, urlsplit
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from fastapi import HTTPException, Request
|
||||||
|
from fastapi.responses import Response, StreamingResponse
|
||||||
|
from starlette.background import BackgroundTask
|
||||||
|
|
||||||
|
URI = re.compile(r'\bURI="([^"]+)"')
|
||||||
|
|
||||||
|
|
||||||
|
class IPTVRelay:
|
||||||
|
def __init__(self, channels):
|
||||||
|
self.sources = {channel["id"]: channel["streamUrl"] for channel in channels}
|
||||||
|
self.resources = OrderedDict()
|
||||||
|
|
||||||
|
def rewrite(self, channel_id, url, text):
|
||||||
|
def register(uri):
|
||||||
|
target = urljoin(str(url), uri)
|
||||||
|
if urlsplit(target).scheme not in {"http", "https"}:
|
||||||
|
return uri
|
||||||
|
key = sha256(target.encode()).hexdigest()[:32]
|
||||||
|
resource = (channel_id, key)
|
||||||
|
self.resources[resource] = target
|
||||||
|
self.resources.move_to_end(resource)
|
||||||
|
if len(self.resources) > 8192:
|
||||||
|
self.resources.popitem(last=False)
|
||||||
|
suffix = PurePosixPath(urlsplit(target).path).suffix.lower()
|
||||||
|
if suffix not in {".m3u8", ".ts", ".mp4", ".m4s", ".aac", ".vtt"}:
|
||||||
|
suffix = ""
|
||||||
|
return f"/iptv/{channel_id}/{key}{suffix}"
|
||||||
|
|
||||||
|
return "\n".join(
|
||||||
|
URI.sub(lambda match: f'URI="{register(match[1])}"', line)
|
||||||
|
if line.startswith("#") else register(line.strip()) if line.strip() else line
|
||||||
|
for line in text.splitlines()
|
||||||
|
) + "\n"
|
||||||
|
|
||||||
|
async def serve(self, client, request: Request, channel_id, resource=None):
|
||||||
|
url = (self.sources.get(channel_id) if resource is None
|
||||||
|
else self.resources.get((channel_id, resource.partition(".")[0])))
|
||||||
|
if url is None:
|
||||||
|
raise HTTPException(404, "IPTV stream or segment not found")
|
||||||
|
manifest = resource is None or resource.endswith(".m3u8")
|
||||||
|
headers = {"User-Agent": "retroLabs/0.1", "Accept-Encoding": "identity"}
|
||||||
|
if "range" in request.headers and not manifest:
|
||||||
|
headers["Range"] = request.headers["range"]
|
||||||
|
try:
|
||||||
|
upstream = await client.send(httpx.Request(request.method, url, headers=headers),
|
||||||
|
stream=True, follow_redirects=True)
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise HTTPException(502, "IPTV upstream unavailable") from exc
|
||||||
|
|
||||||
|
if not upstream.is_success:
|
||||||
|
await upstream.aclose()
|
||||||
|
if upstream.status_code in (404, 410, 416):
|
||||||
|
return Response(status_code=upstream.status_code)
|
||||||
|
raise HTTPException(502, f"IPTV upstream returned {upstream.status_code}")
|
||||||
|
|
||||||
|
content_type = upstream.headers.get("content-type", "").lower()
|
||||||
|
if request.method == "GET" and (manifest or "mpegurl" in content_type):
|
||||||
|
try:
|
||||||
|
await upstream.aread()
|
||||||
|
if not upstream.text.lstrip().startswith("#EXTM3U"):
|
||||||
|
raise HTTPException(502, "IPTV upstream did not return HLS")
|
||||||
|
playlist = self.rewrite(channel_id, upstream.url, upstream.text)
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
raise HTTPException(502, "IPTV playlist could not be read") from exc
|
||||||
|
finally:
|
||||||
|
await upstream.aclose()
|
||||||
|
return Response(playlist, media_type="application/vnd.apple.mpegurl",
|
||||||
|
headers={"Cache-Control": "no-store"})
|
||||||
|
|
||||||
|
response_headers = {
|
||||||
|
name: upstream.headers[name]
|
||||||
|
for name in ("content-type", "content-length", "content-range",
|
||||||
|
"accept-ranges", "content-encoding")
|
||||||
|
if name in upstream.headers
|
||||||
|
}
|
||||||
|
|
||||||
|
async def body():
|
||||||
|
try:
|
||||||
|
async for chunk in upstream.aiter_raw():
|
||||||
|
yield chunk
|
||||||
|
finally:
|
||||||
|
await upstream.aclose()
|
||||||
|
|
||||||
|
return StreamingResponse(body(), status_code=upstream.status_code,
|
||||||
|
headers=response_headers,
|
||||||
|
background=BackgroundTask(upstream.aclose))
|
||||||
@@ -120,7 +120,7 @@ class BridgeTest(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
with TestClient(app) as client:
|
with TestClient(app) as client:
|
||||||
channels = client.get("/api/v1/channels").json()["channels"]
|
channels = client.get("/api/v1/channels").json()["channels"]
|
||||||
self.assertEqual(channels[0]["streamUrl"], "https://example.com/live.m3u8")
|
self.assertEqual(channels[0]["streamUrl"], "/iptv/iptv-sports/master.m3u8")
|
||||||
self.assertEqual(channels[0]["type"], "iptv")
|
self.assertEqual(channels[0]["type"], "iptv")
|
||||||
self.assertEqual(client.get("/api/v1/guide").json()["channels"][0]["programs"], [])
|
self.assertEqual(client.get("/api/v1/guide").json()["channels"][0]["programs"], [])
|
||||||
self.assertIsNone(client.get("/api/v1/channels/iptv-sports/now").json()["now"])
|
self.assertIsNone(client.get("/api/v1/channels/iptv-sports/now").json()["now"])
|
||||||
|
|||||||
Reference in New Issue
Block a user