Upload 2 files
Browse files- app.py +392 -221
- requirements.txt +4 -3
app.py
CHANGED
|
@@ -1,248 +1,419 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
import
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
)
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
}
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
| 23 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
@app.get("/")
|
| 27 |
-
async def
|
| 28 |
-
return
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
|
| 41 |
-
|
| 42 |
-
<style>
|
| 43 |
-
html, body {
|
| 44 |
-
margin: 0;
|
| 45 |
-
width: 100%;
|
| 46 |
-
height: 100%;
|
| 47 |
-
background: #000;
|
| 48 |
-
}
|
| 49 |
-
|
| 50 |
-
video {
|
| 51 |
-
width: 100%;
|
| 52 |
-
height: 100%;
|
| 53 |
-
background: #000;
|
| 54 |
-
object-fit: contain;
|
| 55 |
-
}
|
| 56 |
-
|
| 57 |
-
#status {
|
| 58 |
-
position: fixed;
|
| 59 |
-
left: 10px;
|
| 60 |
-
bottom: 10px;
|
| 61 |
-
padding: 8px 12px;
|
| 62 |
-
background: rgba(0,0,0,.75);
|
| 63 |
-
color: white;
|
| 64 |
-
font-family: monospace;
|
| 65 |
-
font-size: 13px;
|
| 66 |
-
border-radius: 5px;
|
| 67 |
-
display: none;
|
| 68 |
-
}
|
| 69 |
-
</style>
|
| 70 |
-
</head>
|
| 71 |
-
|
| 72 |
-
<body>
|
| 73 |
-
|
| 74 |
-
<video
|
| 75 |
-
id="video"
|
| 76 |
-
controls
|
| 77 |
-
autoplay
|
| 78 |
-
muted
|
| 79 |
-
playsinline
|
| 80 |
-
></video>
|
| 81 |
-
|
| 82 |
-
<div id="status"></div>
|
| 83 |
-
|
| 84 |
-
<script>
|
| 85 |
-
const video = document.getElementById("video");
|
| 86 |
-
const status = document.getElementById("status");
|
| 87 |
-
|
| 88 |
-
const stream = "/hls/index.m3u8";
|
| 89 |
-
|
| 90 |
-
function showStatus(message) {
|
| 91 |
-
status.textContent = message;
|
| 92 |
-
status.style.display = "block";
|
| 93 |
-
}
|
| 94 |
-
|
| 95 |
-
function hideStatus() {
|
| 96 |
-
status.style.display = "none";
|
| 97 |
-
}
|
| 98 |
-
|
| 99 |
-
if (Hls.isSupported()) {
|
| 100 |
-
|
| 101 |
-
const hls = new Hls({
|
| 102 |
-
enableWorker: true,
|
| 103 |
-
lowLatencyMode: true,
|
| 104 |
-
liveSyncDurationCount: 3,
|
| 105 |
-
liveMaxLatencyDurationCount: 6
|
| 106 |
-
});
|
| 107 |
-
|
| 108 |
-
hls.loadSource(stream);
|
| 109 |
-
hls.attachMedia(video);
|
| 110 |
-
|
| 111 |
-
hls.on(Hls.Events.MANIFEST_PARSED, () => {
|
| 112 |
-
hideStatus();
|
| 113 |
-
|
| 114 |
-
video.play().catch(() => {
|
| 115 |
-
showStatus("Press play to start");
|
| 116 |
-
});
|
| 117 |
-
});
|
| 118 |
-
|
| 119 |
-
hls.on(Hls.Events.ERROR, (event, data) => {
|
| 120 |
-
|
| 121 |
-
console.error("HLS:", data);
|
| 122 |
-
|
| 123 |
-
if (!data.fatal)
|
| 124 |
-
return;
|
| 125 |
-
|
| 126 |
-
switch (data.type) {
|
| 127 |
-
|
| 128 |
-
case Hls.ErrorTypes.NETWORK_ERROR:
|
| 129 |
-
showStatus("Network error - reconnecting...");
|
| 130 |
-
hls.startLoad();
|
| 131 |
-
break;
|
| 132 |
-
|
| 133 |
-
case Hls.ErrorTypes.MEDIA_ERROR:
|
| 134 |
-
showStatus("Media error - recovering...");
|
| 135 |
-
hls.recoverMediaError();
|
| 136 |
-
break;
|
| 137 |
-
|
| 138 |
-
default:
|
| 139 |
-
showStatus("Fatal playback error");
|
| 140 |
-
hls.destroy();
|
| 141 |
-
break;
|
| 142 |
-
}
|
| 143 |
-
});
|
| 144 |
-
|
| 145 |
-
} else if (
|
| 146 |
-
video.canPlayType("application/vnd.apple.mpegurl")
|
| 147 |
-
) {
|
| 148 |
-
|
| 149 |
-
video.src = stream;
|
| 150 |
-
|
| 151 |
-
} else {
|
| 152 |
-
|
| 153 |
-
showStatus("HLS is not supported");
|
| 154 |
-
}
|
| 155 |
-
</script>
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
-
@app.get("/
|
| 163 |
-
async def
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
|
|
|
| 171 |
return Response(
|
| 172 |
-
|
| 173 |
-
|
|
|
|
| 174 |
)
|
| 175 |
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
"GET",
|
| 189 |
-
target,
|
| 190 |
-
headers=upstream_headers
|
| 191 |
-
)
|
| 192 |
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
|
|
|
| 196 |
)
|
| 197 |
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
return Response(
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
f"{location}"
|
| 213 |
-
),
|
| 214 |
-
status_code=502,
|
| 215 |
-
media_type="text/plain"
|
| 216 |
)
|
| 217 |
|
| 218 |
-
async def
|
| 219 |
try:
|
| 220 |
-
async for chunk in
|
| 221 |
yield chunk
|
| 222 |
finally:
|
| 223 |
-
await
|
|
|
|
| 224 |
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
"application/octet-stream"
|
|
|
|
| 228 |
)
|
| 229 |
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
)
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import hashlib
|
| 3 |
+
import hmac
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import secrets
|
| 8 |
+
import time
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, Optional
|
| 11 |
+
from urllib.parse import quote, urljoin, urlparse
|
| 12 |
|
| 13 |
+
import httpx
|
| 14 |
+
from fastapi import FastAPI, Header, HTTPException, Query, Request
|
| 15 |
+
from fastapi.responses import HTMLResponse, Response, StreamingResponse
|
| 16 |
+
from pydantic import BaseModel, Field
|
| 17 |
+
|
| 18 |
+
APP_NAME = "player2-hf-relay"
|
| 19 |
+
RELAY_TOKEN = os.getenv("RELAY_TOKEN", "").strip()
|
| 20 |
+
SIGNING_SECRET = os.getenv("SIGNING_SECRET", "").strip()
|
| 21 |
+
ALLOWED_UPSTREAM_SUFFIXES = [
|
| 22 |
+
x.strip().lower().lstrip(".")
|
| 23 |
+
for x in os.getenv(
|
| 24 |
+
"ALLOWED_UPSTREAM_SUFFIXES",
|
| 25 |
+
"fastly.live.brightcove.com,tvsimo.net",
|
| 26 |
+
).split(",")
|
| 27 |
+
if x.strip()
|
| 28 |
+
]
|
| 29 |
+
REGISTRY_PATH = Path(os.getenv("REGISTRY_PATH", "/tmp/player2_registry.json"))
|
| 30 |
+
KEY_RE = re.compile(r"^[A-Za-z0-9._-]{1,128}$")
|
| 31 |
+
ALLOWED_CAPTURED_HEADERS = {
|
| 32 |
+
"accept", "accept-language", "origin", "referer", "user-agent"
|
| 33 |
}
|
| 34 |
+
FORWARDED_RESPONSE_HEADERS = {
|
| 35 |
+
"accept-ranges", "content-length", "content-range", "content-type",
|
| 36 |
+
"etag", "last-modified"
|
| 37 |
+
}
|
| 38 |
+
PLAYLIST_CONTENT_TYPES = (
|
| 39 |
+
"application/vnd.apple.mpegurl", "application/x-mpegurl",
|
| 40 |
+
"audio/mpegurl", "audio/x-mpegurl"
|
| 41 |
)
|
| 42 |
+
REQUEST_TIMEOUT = httpx.Timeout(connect=10.0, read=30.0, write=15.0, pool=10.0)
|
| 43 |
+
MAX_REDIRECTS = 4
|
| 44 |
+
|
| 45 |
+
app = FastAPI(title=APP_NAME)
|
| 46 |
+
registry: Dict[str, dict] = {}
|
| 47 |
+
registry_lock = asyncio.Lock()
|
| 48 |
+
|
| 49 |
+
class RegisterRequest(BaseModel):
|
| 50 |
+
key: str = Field(min_length=1, max_length=128)
|
| 51 |
+
type: str
|
| 52 |
+
url: str = Field(min_length=1, max_length=8000)
|
| 53 |
+
headers: Dict[str, str] = Field(default_factory=dict)
|
| 54 |
+
|
| 55 |
+
def fail(status: int, message: str):
|
| 56 |
+
raise HTTPException(status_code=status, detail=message)
|
| 57 |
+
|
| 58 |
+
def validate_key(key: str) -> str:
|
| 59 |
+
key = key.strip()
|
| 60 |
+
if not KEY_RE.fullmatch(key):
|
| 61 |
+
fail(400, "Invalid key")
|
| 62 |
+
return key
|
| 63 |
+
|
| 64 |
+
def normalize_type(value: str) -> str:
|
| 65 |
+
value = value.strip().lower()
|
| 66 |
+
if value not in {"hls", "mp4"}:
|
| 67 |
+
fail(400, "type must be hls or mp4")
|
| 68 |
+
return value
|
| 69 |
+
|
| 70 |
+
def hostname_allowed(hostname: Optional[str]) -> bool:
|
| 71 |
+
if not hostname:
|
| 72 |
+
return False
|
| 73 |
+
host = hostname.rstrip(".").lower()
|
| 74 |
+
return any(host == s or host.endswith("." + s) for s in ALLOWED_UPSTREAM_SUFFIXES)
|
| 75 |
+
|
| 76 |
+
def validate_upstream_url(url: str) -> str:
|
| 77 |
+
p = urlparse(url)
|
| 78 |
+
if p.scheme != "https":
|
| 79 |
+
fail(400, "Only HTTPS upstream URLs are allowed")
|
| 80 |
+
if p.username or p.password:
|
| 81 |
+
fail(400, "Credentials in upstream URL are not allowed")
|
| 82 |
+
if not hostname_allowed(p.hostname):
|
| 83 |
+
fail(400, f"Upstream host is not allowed: {p.hostname or 'unknown'}")
|
| 84 |
+
return url
|
| 85 |
+
|
| 86 |
+
def clean_header_value(value: str) -> str:
|
| 87 |
+
return str(value).replace("\r", "").replace("\n", "").strip()[:2000]
|
| 88 |
+
|
| 89 |
+
def sanitize_headers(headers: Dict[str, str]) -> Dict[str, str]:
|
| 90 |
+
out = {}
|
| 91 |
+
for k, v in (headers or {}).items():
|
| 92 |
+
key = str(k).strip().lower()
|
| 93 |
+
if key in ALLOWED_CAPTURED_HEADERS:
|
| 94 |
+
value = clean_header_value(v)
|
| 95 |
+
if value:
|
| 96 |
+
out[key] = value
|
| 97 |
+
out.setdefault("accept", "*/*")
|
| 98 |
+
out.setdefault(
|
| 99 |
+
"user-agent",
|
| 100 |
+
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
|
| 101 |
+
"(KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36",
|
| 102 |
+
)
|
| 103 |
+
return out
|
| 104 |
+
|
| 105 |
+
def save_registry():
|
| 106 |
+
try:
|
| 107 |
+
REGISTRY_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 108 |
+
tmp = REGISTRY_PATH.with_suffix(".tmp")
|
| 109 |
+
tmp.write_text(json.dumps(registry, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 110 |
+
tmp.replace(REGISTRY_PATH)
|
| 111 |
+
except Exception as exc:
|
| 112 |
+
print(f"[registry] save warning: {exc}")
|
| 113 |
+
|
| 114 |
+
def load_registry():
|
| 115 |
+
global registry
|
| 116 |
+
try:
|
| 117 |
+
if not REGISTRY_PATH.exists():
|
| 118 |
+
return
|
| 119 |
+
raw = json.loads(REGISTRY_PATH.read_text(encoding="utf-8"))
|
| 120 |
+
good = {}
|
| 121 |
+
if isinstance(raw, dict):
|
| 122 |
+
for key, item in raw.items():
|
| 123 |
+
try:
|
| 124 |
+
key = validate_key(str(key))
|
| 125 |
+
good[key] = {
|
| 126 |
+
"type": normalize_type(str(item.get("type", ""))),
|
| 127 |
+
"url": validate_upstream_url(str(item.get("url", ""))),
|
| 128 |
+
"headers": sanitize_headers(item.get("headers", {})),
|
| 129 |
+
"updated_at": item.get("updated_at"),
|
| 130 |
+
}
|
| 131 |
+
except HTTPException:
|
| 132 |
+
pass
|
| 133 |
+
registry = good
|
| 134 |
+
except Exception as exc:
|
| 135 |
+
print(f"[registry] load warning: {exc}")
|
| 136 |
+
|
| 137 |
+
def get_stream(key: str) -> dict:
|
| 138 |
+
key = validate_key(key)
|
| 139 |
+
item = registry.get(key)
|
| 140 |
+
if not item:
|
| 141 |
+
fail(404, "Unknown stream key")
|
| 142 |
+
return item
|
| 143 |
+
|
| 144 |
+
def authorize(authorization: Optional[str]):
|
| 145 |
+
if not RELAY_TOKEN:
|
| 146 |
+
fail(503, "RELAY_TOKEN is not configured")
|
| 147 |
+
if not authorization or not authorization.startswith("Bearer "):
|
| 148 |
+
fail(401, "Unauthorized")
|
| 149 |
+
supplied = authorization[7:].strip()
|
| 150 |
+
if not secrets.compare_digest(supplied, RELAY_TOKEN):
|
| 151 |
+
fail(401, "Unauthorized")
|
| 152 |
+
|
| 153 |
+
def sign(key: str, url: str, exp: int) -> str:
|
| 154 |
+
if not SIGNING_SECRET:
|
| 155 |
+
fail(503, "SIGNING_SECRET is not configured")
|
| 156 |
+
msg = f"{key}\n{exp}\n{url}".encode()
|
| 157 |
+
return hmac.new(SIGNING_SECRET.encode(), msg, hashlib.sha256).hexdigest()
|
| 158 |
+
|
| 159 |
+
def signed_fetch_url(key: str, url: str, ttl: int = 900) -> str:
|
| 160 |
+
exp = int(time.time()) + ttl
|
| 161 |
+
sig = sign(key, url, exp)
|
| 162 |
+
return (
|
| 163 |
+
f"/hls/{quote(key, safe='')}/fetch?url={quote(url, safe='')}"
|
| 164 |
+
f"&exp={exp}&sig={sig}"
|
| 165 |
+
)
|
| 166 |
|
| 167 |
+
def verify_signature(key: str, url: str, exp: int, sig: str):
|
| 168 |
+
now = int(time.time())
|
| 169 |
+
if exp < now or exp > now + 3600:
|
| 170 |
+
fail(403, "Signed media URL expired or invalid")
|
| 171 |
+
expected = sign(key, url, exp)
|
| 172 |
+
if not secrets.compare_digest(expected, sig):
|
| 173 |
+
fail(403, "Invalid media signature")
|
| 174 |
+
|
| 175 |
+
URI_ATTR_RE = re.compile(r'URI="([^"]+)"')
|
| 176 |
+
|
| 177 |
+
def rewrite_playlist(body: bytes, base_url: str, key: str) -> bytes:
|
| 178 |
+
text = body.decode("utf-8", errors="replace")
|
| 179 |
+
out = []
|
| 180 |
+
for raw in text.splitlines():
|
| 181 |
+
line = raw.strip()
|
| 182 |
+
if not line:
|
| 183 |
+
out.append(raw)
|
| 184 |
+
continue
|
| 185 |
+
if line.startswith("#"):
|
| 186 |
+
def repl(m):
|
| 187 |
+
absolute = validate_upstream_url(urljoin(base_url, m.group(1)))
|
| 188 |
+
return f'URI="{signed_fetch_url(key, absolute)}"'
|
| 189 |
+
out.append(URI_ATTR_RE.sub(repl, raw))
|
| 190 |
+
else:
|
| 191 |
+
absolute = validate_upstream_url(urljoin(base_url, line))
|
| 192 |
+
out.append(signed_fetch_url(key, absolute))
|
| 193 |
+
return ("\n".join(out) + ("\n" if text.endswith("\n") else "")).encode()
|
| 194 |
+
|
| 195 |
+
def is_playlist(url: str, content_type: str, body: bytes) -> bool:
|
| 196 |
+
if urlparse(url).path.lower().endswith(".m3u8"):
|
| 197 |
+
return True
|
| 198 |
+
ctype = (content_type or "").lower()
|
| 199 |
+
if any(x in ctype for x in PLAYLIST_CONTENT_TYPES):
|
| 200 |
+
return True
|
| 201 |
+
return body.lstrip().startswith(b"#EXTM3U")
|
| 202 |
+
|
| 203 |
+
async def fetch_bytes(url: str, headers: Dict[str, str]):
|
| 204 |
+
current = validate_upstream_url(url)
|
| 205 |
+
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT, follow_redirects=False) as client:
|
| 206 |
+
for _ in range(MAX_REDIRECTS + 1):
|
| 207 |
+
r = await client.get(current, headers=headers)
|
| 208 |
+
if r.status_code in {301, 302, 303, 307, 308}:
|
| 209 |
+
location = r.headers.get("location")
|
| 210 |
+
if not location:
|
| 211 |
+
return r, r.content, current
|
| 212 |
+
current = validate_upstream_url(urljoin(current, location))
|
| 213 |
+
continue
|
| 214 |
+
return r, r.content, current
|
| 215 |
+
fail(502, "Too many upstream redirects")
|
| 216 |
+
|
| 217 |
+
async def open_stream(url: str, headers: Dict[str, str]):
|
| 218 |
+
current = validate_upstream_url(url)
|
| 219 |
+
client = httpx.AsyncClient(timeout=REQUEST_TIMEOUT, follow_redirects=False)
|
| 220 |
+
try:
|
| 221 |
+
for _ in range(MAX_REDIRECTS + 1):
|
| 222 |
+
req = client.build_request("GET", current, headers=headers)
|
| 223 |
+
r = await client.send(req, stream=True)
|
| 224 |
+
if r.status_code in {301, 302, 303, 307, 308}:
|
| 225 |
+
location = r.headers.get("location")
|
| 226 |
+
await r.aclose()
|
| 227 |
+
if not location:
|
| 228 |
+
return client, r, current
|
| 229 |
+
current = validate_upstream_url(urljoin(current, location))
|
| 230 |
+
continue
|
| 231 |
+
return client, r, current
|
| 232 |
+
await client.aclose()
|
| 233 |
+
fail(502, "Too many upstream redirects")
|
| 234 |
+
except Exception:
|
| 235 |
+
await client.aclose()
|
| 236 |
+
raise
|
| 237 |
+
|
| 238 |
+
def passthrough_headers(r: httpx.Response) -> Dict[str, str]:
|
| 239 |
+
out = {}
|
| 240 |
+
for k, v in r.headers.items():
|
| 241 |
+
if k.lower() in FORWARDED_RESPONSE_HEADERS:
|
| 242 |
+
out[k.lower()] = v
|
| 243 |
+
out["cache-control"] = "no-store"
|
| 244 |
+
return out
|
| 245 |
+
|
| 246 |
+
@app.on_event("startup")
|
| 247 |
+
async def startup():
|
| 248 |
+
load_registry()
|
| 249 |
+
print("[startup] allowed:", ", ".join(ALLOWED_UPSTREAM_SUFFIXES))
|
| 250 |
|
| 251 |
@app.get("/")
|
| 252 |
+
async def root():
|
| 253 |
+
return {"ok": True, "service": APP_NAME, "streams": len(registry)}
|
| 254 |
+
|
| 255 |
+
@app.get("/health")
|
| 256 |
+
async def health():
|
| 257 |
+
return {
|
| 258 |
+
"ok": True,
|
| 259 |
+
"service": APP_NAME,
|
| 260 |
+
"streams": len(registry),
|
| 261 |
+
"relay_token_configured": bool(RELAY_TOKEN),
|
| 262 |
+
"signing_secret_configured": bool(SIGNING_SECRET),
|
| 263 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
+
@app.post("/api/register")
|
| 266 |
+
async def register(payload: RegisterRequest, request: Request, authorization: Optional[str] = Header(default=None)):
|
| 267 |
+
authorize(authorization)
|
| 268 |
+
key = validate_key(payload.key)
|
| 269 |
+
record = {
|
| 270 |
+
"type": normalize_type(payload.type),
|
| 271 |
+
"url": validate_upstream_url(payload.url),
|
| 272 |
+
"headers": sanitize_headers(payload.headers),
|
| 273 |
+
"updated_at": int(time.time()),
|
| 274 |
+
}
|
| 275 |
+
async with registry_lock:
|
| 276 |
+
registry[key] = record
|
| 277 |
+
save_registry()
|
| 278 |
+
base = str(request.base_url).rstrip("/")
|
| 279 |
+
return {
|
| 280 |
+
"success": True,
|
| 281 |
+
"key": key,
|
| 282 |
+
"type": record["type"],
|
| 283 |
+
"player_url": f"{base}/player/{key}",
|
| 284 |
+
"media_url": f"{base}/media/{key}",
|
| 285 |
+
}
|
| 286 |
|
| 287 |
+
@app.get("/api/status/{key}")
|
| 288 |
+
async def status(key: str):
|
| 289 |
+
item = get_stream(key)
|
| 290 |
+
return {
|
| 291 |
+
"success": True,
|
| 292 |
+
"key": key,
|
| 293 |
+
"type": item["type"],
|
| 294 |
+
"updated_at": item.get("updated_at"),
|
| 295 |
+
"player_url": f"/player/{key}",
|
| 296 |
+
}
|
| 297 |
|
| 298 |
+
@app.get("/media/{key}")
|
| 299 |
+
async def media(key: str, request: Request):
|
| 300 |
+
item = get_stream(key)
|
| 301 |
+
headers = dict(item["headers"])
|
| 302 |
+
if request.headers.get("range"):
|
| 303 |
+
headers["range"] = request.headers["range"]
|
| 304 |
|
| 305 |
+
if item["type"] == "hls":
|
| 306 |
+
try:
|
| 307 |
+
r, body, final_url = await fetch_bytes(item["url"], headers)
|
| 308 |
+
except httpx.RequestError as exc:
|
| 309 |
+
fail(502, f"Upstream HLS request failed: {exc}")
|
| 310 |
+
if r.status_code >= 400:
|
| 311 |
+
return Response(body, status_code=r.status_code, media_type=r.headers.get("content-type", "text/plain"))
|
| 312 |
return Response(
|
| 313 |
+
rewrite_playlist(body, final_url, key),
|
| 314 |
+
media_type="application/vnd.apple.mpegurl",
|
| 315 |
+
headers={"cache-control": "no-store"},
|
| 316 |
)
|
| 317 |
|
| 318 |
+
try:
|
| 319 |
+
client, r, _ = await open_stream(item["url"], headers)
|
| 320 |
+
except httpx.RequestError as exc:
|
| 321 |
+
fail(502, f"Upstream MP4 request failed: {exc}")
|
| 322 |
|
| 323 |
+
async def iterator():
|
| 324 |
+
try:
|
| 325 |
+
async for chunk in r.aiter_bytes():
|
| 326 |
+
yield chunk
|
| 327 |
+
finally:
|
| 328 |
+
await r.aclose()
|
| 329 |
+
await client.aclose()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
|
| 331 |
+
return StreamingResponse(
|
| 332 |
+
iterator(), status_code=r.status_code,
|
| 333 |
+
media_type=r.headers.get("content-type", "video/mp4"),
|
| 334 |
+
headers=passthrough_headers(r)
|
| 335 |
)
|
| 336 |
|
| 337 |
+
@app.get("/hls/{key}/fetch")
|
| 338 |
+
async def hls_fetch(
|
| 339 |
+
key: str,
|
| 340 |
+
request: Request,
|
| 341 |
+
url: str = Query(..., min_length=1, max_length=8000),
|
| 342 |
+
exp: int = Query(...),
|
| 343 |
+
sig: str = Query(..., min_length=64, max_length=128),
|
| 344 |
+
):
|
| 345 |
+
item = get_stream(key)
|
| 346 |
+
if item["type"] != "hls":
|
| 347 |
+
fail(400, "Stream is not HLS")
|
| 348 |
+
validate_upstream_url(url)
|
| 349 |
+
verify_signature(key, url, exp, sig)
|
| 350 |
+
|
| 351 |
+
headers = dict(item["headers"])
|
| 352 |
+
if request.headers.get("range"):
|
| 353 |
+
headers["range"] = request.headers["range"]
|
| 354 |
|
| 355 |
+
if urlparse(url).path.lower().endswith(".m3u8"):
|
| 356 |
+
try:
|
| 357 |
+
r, body, final_url = await fetch_bytes(url, headers)
|
| 358 |
+
except httpx.RequestError as exc:
|
| 359 |
+
fail(502, f"Upstream HLS request failed: {exc}")
|
| 360 |
+
if r.status_code >= 400:
|
| 361 |
+
return Response(body, status_code=r.status_code, media_type=r.headers.get("content-type", "text/plain"))
|
| 362 |
+
if is_playlist(final_url, r.headers.get("content-type", ""), body):
|
| 363 |
+
return Response(
|
| 364 |
+
rewrite_playlist(body, final_url, key),
|
| 365 |
+
media_type="application/vnd.apple.mpegurl",
|
| 366 |
+
headers={"cache-control": "no-store"},
|
| 367 |
+
)
|
| 368 |
+
return Response(body, status_code=r.status_code, media_type=r.headers.get("content-type", "application/octet-stream"))
|
| 369 |
+
|
| 370 |
+
try:
|
| 371 |
+
client, r, final_url = await open_stream(url, headers)
|
| 372 |
+
except httpx.RequestError as exc:
|
| 373 |
+
fail(502, f"Upstream media request failed: {exc}")
|
| 374 |
+
|
| 375 |
+
ctype = r.headers.get("content-type", "")
|
| 376 |
+
if any(x in ctype.lower() for x in PLAYLIST_CONTENT_TYPES):
|
| 377 |
+
try:
|
| 378 |
+
body = await r.aread()
|
| 379 |
+
finally:
|
| 380 |
+
await r.aclose()
|
| 381 |
+
await client.aclose()
|
| 382 |
return Response(
|
| 383 |
+
rewrite_playlist(body, final_url, key),
|
| 384 |
+
media_type="application/vnd.apple.mpegurl",
|
| 385 |
+
headers={"cache-control": "no-store"},
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
)
|
| 387 |
|
| 388 |
+
async def iterator():
|
| 389 |
try:
|
| 390 |
+
async for chunk in r.aiter_bytes():
|
| 391 |
yield chunk
|
| 392 |
finally:
|
| 393 |
+
await r.aclose()
|
| 394 |
+
await client.aclose()
|
| 395 |
|
| 396 |
+
return StreamingResponse(
|
| 397 |
+
iterator(), status_code=r.status_code,
|
| 398 |
+
media_type=ctype or "application/octet-stream",
|
| 399 |
+
headers=passthrough_headers(r)
|
| 400 |
)
|
| 401 |
|
| 402 |
+
@app.get("/player/{key}", response_class=HTMLResponse)
|
| 403 |
+
async def player(key: str):
|
| 404 |
+
item = get_stream(key)
|
| 405 |
+
media_type = json.dumps(item["type"])
|
| 406 |
+
media_url = json.dumps(f"/media/{key}")
|
| 407 |
+
page = f'''<!doctype html>
|
| 408 |
+
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name="referrer" content="no-referrer"><title>Live Player</title>
|
| 409 |
+
<style>html,body{{margin:0;width:100%;height:100%;background:#000;overflow:hidden}}video{{width:100%;height:100%;background:#000;object-fit:contain}}#m{{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:#fff;background:#000;font:15px system-ui}}#m.hide{{display:none}}</style></head>
|
| 410 |
+
<body><video id="v" controls autoplay playsinline preload="auto"></video><div id="m">Loading stream…</div>
|
| 411 |
+
<script src="https://cdn.jsdelivr.net/npm/hls.js@1/dist/hls.min.js"></script>
|
| 412 |
+
<script>(()=>{{const t={media_type},s={media_url},v=document.getElementById('v'),m=document.getElementById('m');const hide=()=>m.classList.add('hide');const show=()=>{{m.textContent='Stream temporarily unavailable.';m.classList.remove('hide')}};v.addEventListener('playing',hide);v.addEventListener('canplay',hide);v.addEventListener('error',show);if(t==='mp4'){{v.src=s;v.play().catch(()=>{{}});return}}if(v.canPlayType('application/vnd.apple.mpegurl')){{v.src=s;v.play().catch(()=>{{}});return}}if(window.Hls&&Hls.isSupported()){{const h=new Hls({{enableWorker:true,lowLatencyMode:true,backBufferLength:60}});h.loadSource(s);h.attachMedia(v);h.on(Hls.Events.MANIFEST_PARSED,()=>{{hide();v.play().catch(()=>{{}})}});h.on(Hls.Events.ERROR,(_e,d)=>{{if(!d||!d.fatal)return;if(d.type===Hls.ErrorTypes.NETWORK_ERROR){{h.startLoad();return}}if(d.type===Hls.ErrorTypes.MEDIA_ERROR){{h.recoverMediaError();return}}show();h.destroy()}});return}}show()}})();</script></body></html>'''
|
| 413 |
+
return HTMLResponse(
|
| 414 |
+
page,
|
| 415 |
+
headers={
|
| 416 |
+
"cache-control": "no-store",
|
| 417 |
+
"content-security-policy": "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline'; media-src 'self' blob:; connect-src 'self'; object-src 'none'; base-uri 'none'",
|
| 418 |
+
},
|
| 419 |
+
)
|
|
|
requirements.txt
CHANGED
|
@@ -1,3 +1,4 @@
|
|
| 1 |
-
fastapi
|
| 2 |
-
uvicorn[standard]
|
| 3 |
-
httpx
|
|
|
|
|
|
| 1 |
+
fastapi>=0.115,<1
|
| 2 |
+
uvicorn[standard]>=0.30,<1
|
| 3 |
+
httpx>=0.27,<1
|
| 4 |
+
pydantic>=2.8,<3
|