Files
retroLabs/bridge/iptv.py

94 lines
4.0 KiB
Python

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))