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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
COPY app.py .
|
| 7 |
+
|
| 8 |
+
RUN pip install --upgrade pip
|
| 9 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 10 |
+
|
| 11 |
+
RUN pip install gunicorn
|
| 12 |
+
|
| 13 |
+
EXPOSE 7860
|
| 14 |
+
|
| 15 |
+
CMD ["gunicorn", "app:app", \
|
| 16 |
+
"-w", "4", \
|
| 17 |
+
"--worker-class", "gevent", \
|
| 18 |
+
"--worker-connections", "100", \
|
| 19 |
+
"-b", "0.0.0.0:7860", \
|
| 20 |
+
"--timeout", "120", \
|
| 21 |
+
"--keep-alive", "5", \
|
| 22 |
+
"--max-requests", "1000", \
|
| 23 |
+
"--max-requests-jitter", "100"]
|
| 24 |
+
|
| 25 |
+
app.py dosyası oluşturun
|
| 26 |
+
|
| 27 |
+
from flask import Flask, request, Response
|
| 28 |
+
import requests
|
| 29 |
+
from urllib.parse import urlparse, urljoin, quote, unquote
|
| 30 |
+
import re
|
| 31 |
+
import traceback
|
| 32 |
+
import os
|
| 33 |
+
|
| 34 |
+
app = Flask(__name__)
|
| 35 |
+
|
| 36 |
+
def detect_m3u_type(content):
|
| 37 |
+
"""Rileva se è un M3U (lista IPTV) o un M3U8 (flusso HLS)"""
|
| 38 |
+
if "#EXTM3U" in content and "#EXTINF" in content:
|
| 39 |
+
return "m3u8"
|
| 40 |
+
return "m3u"
|
| 41 |
+
|
| 42 |
+
def replace_key_uri(line, headers_query):
|
| 43 |
+
"""Sostituisce l'URI della chiave AES-128 con il proxy"""
|
| 44 |
+
match = re.search(r'URI="([^"]+)"', line)
|
| 45 |
+
if match:
|
| 46 |
+
key_url = match.group(1)
|
| 47 |
+
proxied_key_url = f"/proxy/key?url={quote(key_url)}&{headers_query}"
|
| 48 |
+
return line.replace(key_url, proxied_key_url)
|
| 49 |
+
return line
|
| 50 |
+
|
| 51 |
+
def resolve_m3u8_link(url, headers=None):
|
| 52 |
+
"""
|
| 53 |
+
Tenta di risolvere un URL M3U8.
|
| 54 |
+
Prova prima la logica specifica per iframe (tipo Daddylive), inclusa la lookup della server_key.
|
| 55 |
+
Se fallisce, verifica se l'URL iniziale era un M3U8 diretto e lo restituisce.
|
| 56 |
+
"""
|
| 57 |
+
if not url:
|
| 58 |
+
print("Errore: URL non fornito.")
|
| 59 |
+
return {"resolved_url": None, "headers": {}}
|
| 60 |
+
|
| 61 |
+
print(f"Tentativo di risoluzione URL: {url}")
|
| 62 |
+
# Utilizza gli header forniti, altrimenti usa un User-Agent di default
|
| 63 |
+
current_headers = headers if headers else {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0+Safari/537.36'}
|
| 64 |
+
|
| 65 |
+
initial_response_text = None
|
| 66 |
+
final_url_after_redirects = None
|
| 67 |
+
|
| 68 |
+
# Verifica se è un URL di vavoo.to
|
| 69 |
+
is_vavoo = "vavoo.to" in url.lower()
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
with requests.Session() as session:
|
| 73 |
+
print(f"Passo 1: Richiesta a {url}")
|
| 74 |
+
response = session.get(url, headers=current_headers, allow_redirects=True, timeout=(5, 15))
|
| 75 |
+
response.raise_for_status()
|
| 76 |
+
initial_response_text = response.text
|
| 77 |
+
final_url_after_redirects = response.url
|
| 78 |
+
print(f"Passo 1 completato. URL finale dopo redirect: {final_url_after_redirects}")
|
| 79 |
+
|
| 80 |
+
# Se è un URL di vavoo.to, salta la logica dell'iframe
|
| 81 |
+
if is_vavoo:
|
| 82 |
+
if initial_response_text and initial_response_text.strip().startswith('#EXTM3U'):
|
| 83 |
+
return {
|
| 84 |
+
"resolved_url": final_url_after_redirects,
|
| 85 |
+
"headers": current_headers
|
| 86 |
+
}
|
| 87 |
+
else:
|
| 88 |
+
# Se non è un M3U8 diretto, restituisci l'URL originale per vavoo
|
| 89 |
+
print(f"URL vavoo.to non è un M3U8 diretto: {url}")
|
| 90 |
+
return {
|
| 91 |
+
"resolved_url": url,
|
| 92 |
+
"headers": current_headers
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
# Prova la logica dell'iframe per gli altri URL
|
| 96 |
+
print("Tentativo con logica iframe...")
|
| 97 |
+
try:
|
| 98 |
+
# Secondo passo (Iframe): Trova l'iframe src nella risposta iniziale
|
| 99 |
+
iframes = re.findall(r'iframe src="([^"]+)"', initial_response_text)
|
| 100 |
+
if not iframes:
|
| 101 |
+
raise ValueError("Nessun iframe src trovato.")
|
| 102 |
+
|
| 103 |
+
url2 = iframes[0]
|
| 104 |
+
print(f"Passo 2 (Iframe): Trovato iframe URL: {url2}")
|
| 105 |
+
|
| 106 |
+
# Terzo passo (Iframe): Richiesta all'URL dell'iframe
|
| 107 |
+
referer_raw = urlparse(url2).scheme + "://" + urlparse(url2).netloc + "/"
|
| 108 |
+
origin_raw = urlparse(url2).scheme + "://" + urlparse(url2).netloc
|
| 109 |
+
current_headers['Referer'] = referer_raw
|
| 110 |
+
current_headers['Origin'] = origin_raw
|
| 111 |
+
print(f"Passo 3 (Iframe): Richiesta a {url2}")
|
| 112 |
+
response = session.get(url2, headers=current_headers, timeout=(5, 15))
|
| 113 |
+
response.raise_for_status()
|
| 114 |
+
iframe_response_text = response.text
|
| 115 |
+
print("Passo 3 (Iframe) completato.")
|
| 116 |
+
|
| 117 |
+
# Quarto passo (Iframe): Estrai parametri dinamici dall'iframe response
|
| 118 |
+
channel_key_match = re.search(r'(?s) channelKey = \"([^\"]*)"', iframe_response_text)
|
| 119 |
+
auth_ts_match = re.search(r'(?s) authTs\s*= \"([^\"]*)"', iframe_response_text)
|
| 120 |
+
auth_rnd_match = re.search(r'(?s) authRnd\s*= \"([^\"]*)"', iframe_response_text)
|
| 121 |
+
auth_sig_match = re.search(r'(?s) authSig\s*= \"([^\"]*)"', iframe_response_text)
|
| 122 |
+
auth_host_match = re.search(r'\}\s*fetchWithRetry\(\s*\'([^\']*)\'', iframe_response_text)
|
| 123 |
+
server_lookup_match = re.search(r'n fetchWithRetry\(\s*\'([^\']*)\'', iframe_response_text)
|
| 124 |
+
|
| 125 |
+
if not all([channel_key_match, auth_ts_match, auth_rnd_match, auth_sig_match, auth_host_match, server_lookup_match]):
|
| 126 |
+
raise ValueError("Impossibile estrarre tutti i parametri dinamici dall'iframe response.")
|
| 127 |
+
|
| 128 |
+
channel_key = channel_key_match.group(1)
|
| 129 |
+
auth_ts = auth_ts_match.group(1)
|
| 130 |
+
auth_rnd = auth_rnd_match.group(1)
|
| 131 |
+
auth_sig = quote(auth_sig_match.group(1))
|
| 132 |
+
auth_host = auth_host_match.group(1)
|
| 133 |
+
server_lookup = server_lookup_match.group(1)
|
| 134 |
+
|
| 135 |
+
print("Passo 4 (Iframe): Parametri dinamici estratti.")
|
| 136 |
+
|
| 137 |
+
# Quinto passo (Iframe): Richiesta di autenticazione
|
| 138 |
+
auth_url = f'{auth_host}{channel_key}&ts={auth_ts}&rnd={auth_rnd}&sig={auth_sig}'
|
| 139 |
+
print(f"Passo 5 (Iframe): Richiesta di autenticazione a {auth_url}")
|
| 140 |
+
auth_response = session.get(auth_url, headers=current_headers, timeout=(5, 15))
|
| 141 |
+
auth_response.raise_for_status()
|
| 142 |
+
print("Passo 5 (Iframe) completato.")
|
| 143 |
+
|
| 144 |
+
# Sesto passo (Iframe): Richiesta di server lookup per ottenere la server_key
|
| 145 |
+
server_lookup_url = f"https://{urlparse(url2).netloc}{server_lookup}{channel_key}"
|
| 146 |
+
print(f"Passo 6 (Iframe): Richiesta server lookup a {server_lookup_url}")
|
| 147 |
+
server_lookup_response = session.get(server_lookup_url, headers=current_headers, timeout=(5, 15))
|
| 148 |
+
server_lookup_response.raise_for_status()
|
| 149 |
+
server_lookup_data = server_lookup_response.json()
|
| 150 |
+
print("Passo 6 (Iframe) completato.")
|
| 151 |
+
|
| 152 |
+
# Settimo passo (Iframe): Estrai server_key dalla risposta di server lookup
|
| 153 |
+
server_key = server_lookup_data.get('server_key')
|
| 154 |
+
if not server_key:
|
| 155 |
+
raise ValueError("'server_key' non trovato nella risposta di server lookup.")
|
| 156 |
+
print(f"Passo 7 (Iframe): Estratto server_key: {server_key}")
|
| 157 |
+
|
| 158 |
+
# Ottavo passo (Iframe): Costruisci il link finale
|
| 159 |
+
host_match = re.search('(?s)m3u8 =.*?:.*?:.*?".*?".*?"([^"]*)"', iframe_response_text)
|
| 160 |
+
if not host_match:
|
| 161 |
+
raise ValueError("Impossibile trovare l'host finale per l'm3u8.")
|
| 162 |
+
host = host_match.group(1)
|
| 163 |
+
print(f"Passo 8 (Iframe): Trovato host finale per m3u8: {host}")
|
| 164 |
+
|
| 165 |
+
# Costruisci l'URL finale del flusso
|
| 166 |
+
final_stream_url = (
|
| 167 |
+
f'https://{server_key}{host}{server_key}/{channel_key}/mono.m3u8'
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
# Prepara gli header per lo streaming
|
| 171 |
+
stream_headers = {
|
| 172 |
+
'User-Agent': current_headers.get('User-Agent', ''),
|
| 173 |
+
'Referer': referer_raw,
|
| 174 |
+
'Origin': origin_raw
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
return {
|
| 178 |
+
"resolved_url": final_stream_url,
|
| 179 |
+
"headers": stream_headers
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
except (ValueError, requests.exceptions.RequestException) as e:
|
| 183 |
+
print(f"Logica iframe fallita: {e}")
|
| 184 |
+
print("Tentativo fallback: verifica se l'URL iniziale era un M3U8 diretto...")
|
| 185 |
+
|
| 186 |
+
# Fallback: Verifica se la risposta iniziale era un file M3U8 diretto
|
| 187 |
+
if initial_response_text and initial_response_text.strip().startswith('#EXTM3U'):
|
| 188 |
+
print("Fallback riuscito: Trovato file M3U8 diretto.")
|
| 189 |
+
return {
|
| 190 |
+
"resolved_url": final_url_after_redirects,
|
| 191 |
+
"headers": current_headers
|
| 192 |
+
}
|
| 193 |
+
else:
|
| 194 |
+
print("Fallback fallito: La risposta iniziale non era un M3U8 diretto.")
|
| 195 |
+
return {
|
| 196 |
+
"resolved_url": url,
|
| 197 |
+
"headers": current_headers
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
except requests.exceptions.RequestException as e:
|
| 201 |
+
print(f"Errore durante la richiesta HTTP iniziale: {e}")
|
| 202 |
+
return {"resolved_url": url, "headers": current_headers}
|
| 203 |
+
except Exception as e:
|
| 204 |
+
print(f"Errore generico durante la risoluzione: {e}")
|
| 205 |
+
return {"resolved_url": url, "headers": current_headers}
|
| 206 |
+
|
| 207 |
+
@app.route('/proxy')
|
| 208 |
+
def proxy():
|
| 209 |
+
"""Proxy per liste M3U che aggiunge automaticamente /proxy/m3u?url= con IP prima dei link"""
|
| 210 |
+
m3u_url = request.args.get('url', '').strip()
|
| 211 |
+
if not m3u_url:
|
| 212 |
+
return "Errore: Parametro 'url' mancante", 400
|
| 213 |
+
|
| 214 |
+
try:
|
| 215 |
+
# Ottieni l'IP del server
|
| 216 |
+
server_ip = request.host
|
| 217 |
+
|
| 218 |
+
# Scarica la lista M3U originale
|
| 219 |
+
response = requests.get(m3u_url, timeout=(10, 30)) # Timeout connessione 10s, lettura 30s
|
| 220 |
+
response.raise_for_status()
|
| 221 |
+
m3u_content = response.text
|
| 222 |
+
|
| 223 |
+
# Modifica solo le righe che contengono URL (non iniziano con #)
|
| 224 |
+
modified_lines = []
|
| 225 |
+
for line in m3u_content.splitlines():
|
| 226 |
+
line = line.strip()
|
| 227 |
+
if line and not line.startswith('#'):
|
| 228 |
+
# Per tutti i link, usa il proxy normale
|
| 229 |
+
modified_line = f"http://{server_ip}/proxy/m3u?url={line}"
|
| 230 |
+
modified_lines.append(modified_line)
|
| 231 |
+
else:
|
| 232 |
+
# Mantieni invariate le righe di metadati
|
| 233 |
+
modified_lines.append(line)
|
| 234 |
+
|
| 235 |
+
modified_content = '\n'.join(modified_lines)
|
| 236 |
+
|
| 237 |
+
# Estrai il nome del file dall'URL originale
|
| 238 |
+
parsed_m3u_url = urlparse(m3u_url)
|
| 239 |
+
original_filename = os.path.basename(parsed_m3u_url.path)
|
| 240 |
+
|
| 241 |
+
return Response(modified_content, content_type="application/vnd.apple.mpegurl", headers={'Content-Disposition': f'attachment; filename="{original_filename}"'})
|
| 242 |
+
|
| 243 |
+
except requests.RequestException as e:
|
| 244 |
+
return f"Errore durante il download della lista M3U: {str(e)}", 500
|
| 245 |
+
except Exception as e:
|
| 246 |
+
return f"Errore generico: {str(e)}", 500
|
| 247 |
+
|
| 248 |
+
@app.route('/proxy/m3u')
|
| 249 |
+
def proxy_m3u():
|
| 250 |
+
"""Proxy per file M3U e M3U8 con supporto per redirezioni e header personalizzati"""
|
| 251 |
+
m3u_url = request.args.get('url', '').strip()
|
| 252 |
+
if not m3u_url:
|
| 253 |
+
return "Errore: Parametro 'url' mancante", 400
|
| 254 |
+
|
| 255 |
+
default_headers = {
|
| 256 |
+
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/33.0 Mobile/15E148 Safari/605.1.15",
|
| 257 |
+
"Referer": "https://vavoo.to/",
|
| 258 |
+
"Origin": "https://vavoo.to"
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
# Estrai gli header dalla richiesta, sovrascrivendo i default
|
| 262 |
+
request_headers = {
|
| 263 |
+
unquote(key[2:]).replace("_", "-"): unquote(value).strip()
|
| 264 |
+
for key, value in request.args.items()
|
| 265 |
+
if key.lower().startswith("h_")
|
| 266 |
+
}
|
| 267 |
+
headers = {**default_headers, **request_headers}
|
| 268 |
+
|
| 269 |
+
# --- Logica per trasformare l'URL se necessario ---
|
| 270 |
+
processed_url = m3u_url
|
| 271 |
+
|
| 272 |
+
# Trasforma /stream/ in /embed/ per Daddylive
|
| 273 |
+
if '/stream/stream-' in m3u_url and 'daddylive.dad' in m3u_url:
|
| 274 |
+
processed_url = m3u_url.replace('/stream/stream-', '/embed/stream-')
|
| 275 |
+
print(f"URL {m3u_url} trasformato da /stream/ a /embed/: {processed_url}")
|
| 276 |
+
|
| 277 |
+
match_premium_m3u8 = re.search(r'/premium(\d+)/mono\.m3u8$', m3u_url)
|
| 278 |
+
|
| 279 |
+
if match_premium_m3u8:
|
| 280 |
+
channel_number = match_premium_m3u8.group(1)
|
| 281 |
+
transformed_url = f"https://daddylive.dad/embed/stream-{channel_number}.php"
|
| 282 |
+
print(f"URL {m3u_url} corrisponde al pattern premium. Trasformato in: {transformed_url}")
|
| 283 |
+
processed_url = transformed_url
|
| 284 |
+
else:
|
| 285 |
+
print(f"URL {processed_url} processato per la risoluzione.")
|
| 286 |
+
|
| 287 |
+
try:
|
| 288 |
+
print(f"Chiamata a resolve_m3u8_link per URL processato: {processed_url}")
|
| 289 |
+
result = resolve_m3u8_link(processed_url, headers)
|
| 290 |
+
|
| 291 |
+
if not result["resolved_url"]:
|
| 292 |
+
return "Errore: Impossibile risolvere l'URL in un M3U8 valido.", 500
|
| 293 |
+
|
| 294 |
+
resolved_url = result["resolved_url"]
|
| 295 |
+
current_headers_for_proxy = result["headers"]
|
| 296 |
+
|
| 297 |
+
print(f"Risoluzione completata. URL M3U8 finale: {resolved_url}")
|
| 298 |
+
|
| 299 |
+
# Fetchare il contenuto M3U8 effettivo dall'URL risolto
|
| 300 |
+
print(f"Fetching M3U8 content from resolved URL: {resolved_url}")
|
| 301 |
+
m3u_response = requests.get(resolved_url, headers=current_headers_for_proxy, allow_redirects=True, timeout=(10, 20)) # Timeout connessione 10s, lettura 20s
|
| 302 |
+
m3u_response.raise_for_status()
|
| 303 |
+
m3u_content = m3u_response.text
|
| 304 |
+
final_url = m3u_response.url
|
| 305 |
+
|
| 306 |
+
# Processa il contenuto M3U8
|
| 307 |
+
file_type = detect_m3u_type(m3u_content)
|
| 308 |
+
|
| 309 |
+
if file_type == "m3u":
|
| 310 |
+
return Response(m3u_content, content_type="application/vnd.apple.mpegurl")
|
| 311 |
+
|
| 312 |
+
# Processa contenuto M3U8
|
| 313 |
+
parsed_url = urlparse(final_url)
|
| 314 |
+
base_url = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path.rsplit('/', 1)[0]}/"
|
| 315 |
+
|
| 316 |
+
# Prepara la query degli header per segmenti/chiavi proxati
|
| 317 |
+
headers_query = "&".join([f"h_{quote(k)}={quote(v)}" for k, v in current_headers_for_proxy.items()])
|
| 318 |
+
|
| 319 |
+
modified_m3u8 = []
|
| 320 |
+
for line in m3u_content.splitlines():
|
| 321 |
+
line = line.strip()
|
| 322 |
+
if line.startswith("#EXT-X-KEY") and 'URI="' in line:
|
| 323 |
+
line = replace_key_uri(line, headers_query)
|
| 324 |
+
elif line and not line.startswith("#"):
|
| 325 |
+
segment_url = urljoin(base_url, line)
|
| 326 |
+
line = f"/proxy/ts?url={quote(segment_url)}&{headers_query}"
|
| 327 |
+
modified_m3u8.append(line)
|
| 328 |
+
|
| 329 |
+
modified_m3u8_content = "\n".join(modified_m3u8)
|
| 330 |
+
return Response(modified_m3u8_content, content_type="application/vnd.apple.mpegurl")
|
| 331 |
+
|
| 332 |
+
except requests.RequestException as e:
|
| 333 |
+
print(f"Errore durante il download o la risoluzione del file: {str(e)}")
|
| 334 |
+
return f"Errore durante il download o la risoluzione del file M3U/M3U8: {str(e)}", 500
|
| 335 |
+
except Exception as e:
|
| 336 |
+
print(f"Errore generico nella funzione proxy_m3u: {str(e)}")
|
| 337 |
+
return f"Errore generico durante l'elaborazione: {str(e)}", 500
|
| 338 |
+
|
| 339 |
+
@app.route('/proxy/resolve')
|
| 340 |
+
def proxy_resolve():
|
| 341 |
+
"""Proxy per risolvere e restituire un URL M3U8"""
|
| 342 |
+
url = request.args.get('url', '').strip()
|
| 343 |
+
if not url:
|
| 344 |
+
return "Errore: Parametro 'url' mancante", 400
|
| 345 |
+
|
| 346 |
+
headers = {
|
| 347 |
+
unquote(key[2:]).replace("_", "-"): unquote(value).strip()
|
| 348 |
+
for key, value in request.args.items()
|
| 349 |
+
if key.lower().startswith("h_")
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
try:
|
| 353 |
+
result = resolve_m3u8_link(url, headers)
|
| 354 |
+
|
| 355 |
+
if not result["resolved_url"]:
|
| 356 |
+
return "Errore: Impossibile risolvere l'URL", 500
|
| 357 |
+
|
| 358 |
+
headers_query = "&".join([f"h_{quote(k)}={quote(v)}" for k, v in result["headers"].items()])
|
| 359 |
+
|
| 360 |
+
return Response(
|
| 361 |
+
f"#EXTM3U\n"
|
| 362 |
+
f"#EXTINF:-1,Canale Risolto\n"
|
| 363 |
+
f"/proxy/m3u?url={quote(result['resolved_url'])}&{headers_query}",
|
| 364 |
+
content_type="application/vnd.apple.mpegurl"
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
except Exception as e:
|
| 368 |
+
return f"Errore durante la risoluzione dell'URL: {str(e)}", 500
|
| 369 |
+
|
| 370 |
+
@app.route('/proxy/ts')
|
| 371 |
+
def proxy_ts():
|
| 372 |
+
"""Proxy per segmenti .TS con headers personalizzati - SENZA CACHE"""
|
| 373 |
+
ts_url = request.args.get('url', '').strip()
|
| 374 |
+
if not ts_url:
|
| 375 |
+
return "Errore: Parametro 'url' mancante", 400
|
| 376 |
+
|
| 377 |
+
headers = {
|
| 378 |
+
unquote(key[2:]).replace("_", "-"): unquote(value).strip()
|
| 379 |
+
for key, value in request.args.items()
|
| 380 |
+
if key.lower().startswith("h_")
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
try:
|
| 384 |
+
# Stream diretto senza cache per evitare freezing
|
| 385 |
+
response = requests.get(ts_url, headers=headers, stream=True, allow_redirects=True, timeout=(10, 30)) # Timeout di connessione 10s, lettura 30s
|
| 386 |
+
response.raise_for_status()
|
| 387 |
+
|
| 388 |
+
def generate():
|
| 389 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 390 |
+
if chunk:
|
| 391 |
+
yield chunk
|
| 392 |
+
|
| 393 |
+
return Response(generate(), content_type="video/mp2t")
|
| 394 |
+
|
| 395 |
+
except requests.RequestException as e:
|
| 396 |
+
return f"Errore durante il download del segmento TS: {str(e)}", 500
|
| 397 |
+
|
| 398 |
+
@app.route('/proxy/key')
|
| 399 |
+
def proxy_key():
|
| 400 |
+
"""Proxy per la chiave AES-128 con header personalizzati"""
|
| 401 |
+
key_url = request.args.get('url', '').strip()
|
| 402 |
+
if not key_url:
|
| 403 |
+
return "Errore: Parametro 'url' mancante per la chiave", 400
|
| 404 |
+
|
| 405 |
+
headers = {
|
| 406 |
+
unquote(key[2:]).replace("_", "-"): unquote(value).strip()
|
| 407 |
+
for key, value in request.args.items()
|
| 408 |
+
if key.lower().startswith("h_")
|
| 409 |
+
}
|
| 410 |
+
|
| 411 |
+
try:
|
| 412 |
+
response = requests.get(key_url, headers=headers, allow_redirects=True, timeout=(5, 15)) # Timeout connessione 5s, lettura 15s
|
| 413 |
+
response.raise_for_status()
|
| 414 |
+
|
| 415 |
+
return Response(response.content, content_type="application/octet-stream")
|
| 416 |
+
|
| 417 |
+
except requests.RequestException as e:
|
| 418 |
+
return f"Errore durante il download della chiave AES-128: {str(e)}", 500
|
| 419 |
+
|
| 420 |
+
@app.route('/')
|
| 421 |
+
def index():
|
| 422 |
+
"""Pagina principale che mostra un messaggio di benvenuto"""
|
| 423 |
+
return "Proxy started!"
|
| 424 |
+
|
| 425 |
+
if __name__ == '__main__':
|
| 426 |
+
print("Proxy started!")
|
| 427 |
+
app.run(host="0.0.0.0", port=7860, debug=False)
|