Darietto17 commited on
Commit
7270a1b
·
verified ·
1 Parent(s): 0319ef4

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +609 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, Response
2
+ import requests
3
+ from urllib.parse import urlparse, urljoin, quote, unquote
4
+ import re
5
+ import traceback
6
+ import time
7
+ from threading import Lock
8
+ import gc
9
+ from collections import OrderedDict
10
+
11
+ import threading
12
+ import gzip
13
+ import xml.etree.ElementTree as ET
14
+ import json
15
+ import re
16
+
17
+ app = Flask(__name__)
18
+
19
+ # --- CONFIGURAZIONE CACHE OTTIMIZZATA ---
20
+ CACHE_TTL = 30 # Ridotto da 60 a 30 secondi
21
+ MAX_CACHE_SIZE = 50 # Limite massimo di elementi in cache
22
+ MAX_TS_SIZE = 5 * 1024 * 1024 # Massimo 5MB per segmento TS
23
+ MAX_TOTAL_CACHE_SIZE = 100 * 1024 * 1024 # Massimo 100MB totali in cache
24
+
25
+ # Cache LRU (Least Recently Used) ottimizzate
26
+ class LRUCache:
27
+ def __init__(self, max_size, max_item_size=None):
28
+ self.max_size = max_size
29
+ self.max_item_size = max_item_size
30
+ self.cache = OrderedDict()
31
+ self.lock = Lock()
32
+ self.current_size = 0 # Traccia la dimensione totale in byte
33
+
34
+ def get(self, key):
35
+ with self.lock:
36
+ if key in self.cache:
37
+ timestamp, value = self.cache[key]
38
+ if time.time() - timestamp < CACHE_TTL:
39
+ # Sposta alla fine (most recently used)
40
+ self.cache.move_to_end(key)
41
+ return value
42
+ else:
43
+ # Rimuovi elemento scaduto
44
+ self._remove_item(key)
45
+ return None
46
+
47
+ def put(self, key, value):
48
+ with self.lock:
49
+ # Controlla dimensione dell'elemento
50
+ value_size = len(value) if isinstance(value, (bytes, str)) else 0
51
+ if self.max_item_size and value_size > self.max_item_size:
52
+ return # Non cachare elementi troppo grandi
53
+
54
+ # Rimuovi elemento esistente se presente
55
+ if key in self.cache:
56
+ self._remove_item(key)
57
+
58
+ # Assicurati che ci sia spazio
59
+ while len(self.cache) >= self.max_size or self.current_size + value_size > MAX_TOTAL_CACHE_SIZE:
60
+ if not self.cache:
61
+ break
62
+ self._remove_oldest()
63
+
64
+ # Aggiungi nuovo elemento
65
+ self.cache[key] = (time.time(), value)
66
+ self.current_size += value_size
67
+
68
+ def _remove_item(self, key):
69
+ if key in self.cache:
70
+ _, value = self.cache[key]
71
+ value_size = len(value) if isinstance(value, (bytes, str)) else 0
72
+ self.current_size -= value_size
73
+ del self.cache[key]
74
+
75
+ def _remove_oldest(self):
76
+ if self.cache:
77
+ oldest_key = next(iter(self.cache))
78
+ self._remove_item(oldest_key)
79
+
80
+ def cleanup_expired(self):
81
+ """Rimuove elementi scaduti"""
82
+ with self.lock:
83
+ current_time = time.time()
84
+ expired_keys = [
85
+ key for key, (timestamp, _) in self.cache.items()
86
+ if current_time - timestamp >= CACHE_TTL
87
+ ]
88
+ for key in expired_keys:
89
+ self._remove_item(key)
90
+
91
+ def clear(self):
92
+ """Svuota completamente la cache"""
93
+ with self.lock:
94
+ self.cache.clear()
95
+ self.current_size = 0
96
+
97
+ # Inizializza cache ottimizzate
98
+ ts_cache = LRUCache(MAX_CACHE_SIZE, MAX_TS_SIZE)
99
+ key_cache = LRUCache(MAX_CACHE_SIZE // 2) # Cache più piccola per le chiavi
100
+
101
+ # Timer per pulizia periodica
102
+ last_cleanup = time.time()
103
+ CLEANUP_INTERVAL = 60 # Pulizia ogni 60 secondi
104
+
105
+ def periodic_cleanup():
106
+ """Pulizia periodica delle cache"""
107
+ global last_cleanup
108
+ current_time = time.time()
109
+ if current_time - last_cleanup > CLEANUP_INTERVAL:
110
+ ts_cache.cleanup_expired()
111
+ key_cache.cleanup_expired()
112
+ gc.collect() # Forza garbage collection
113
+ last_cleanup = current_time
114
+
115
+ def detect_m3u_type(content):
116
+ """Rileva se è un M3U (lista IPTV) o un M3U8 (flusso HLS)"""
117
+ if "#EXTM3U" in content and "#EXTINF" in content:
118
+ return "m3u8"
119
+ return "m3u"
120
+
121
+ def replace_key_uri(line, headers_query):
122
+ """Sostituisce l'URI della chiave AES-128 con il proxy"""
123
+ match = re.search(r'URI="([^"]+)"', line)
124
+ if match:
125
+ key_url = match.group(1)
126
+ proxied_key_url = f"/proxy/key?url={quote(key_url)}&{headers_query}"
127
+ return line.replace(key_url, proxied_key_url)
128
+ return line
129
+
130
+ def resolve_m3u8_link(url, headers=None):
131
+ """
132
+ Tenta di risolvere un URL M3U8.
133
+ Prova prima la logica specifica per iframe (tipo Daddylive), inclusa la lookup della server_key.
134
+ Se fallisce, verifica se l'URL iniziale era un M3U8 diretto e lo restituisce.
135
+ """
136
+ if not url:
137
+ print("Errore: URL non fornito.")
138
+ return {"resolved_url": None, "headers": {}}
139
+
140
+ print(f"Tentativo di risoluzione URL: {url}")
141
+ # Utilizza gli header forniti, altrimenti usa un User-Agent di default
142
+ 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'}
143
+
144
+ initial_response_text = None
145
+ final_url_after_redirects = None
146
+
147
+ try:
148
+ # Utilizza una sessione per gestire i cookie e i redirect
149
+ with requests.Session() as session:
150
+ # Imposta timeout più aggressivi per ridurre l'uso di memoria
151
+ session.timeout = 5
152
+
153
+ # Primo passo: Richiesta all'URL iniziale
154
+ print(f"Passo 1: Richiesta a {url}")
155
+ response = session.get(url, headers=current_headers, allow_redirects=True, timeout=5)
156
+ response.raise_for_status()
157
+ initial_response_text = response.text
158
+ final_url_after_redirects = response.url
159
+ print(f"Passo 1 completato. URL finale dopo redirect: {final_url_after_redirects}")
160
+
161
+ # Prova la logica dell'iframe
162
+ print("Tentativo con logica iframe...")
163
+ try:
164
+ # Secondo passo (Iframe): Trova l'iframe src nella risposta iniziale
165
+ iframes = re.findall(r'iframe src="([^"]+)', initial_response_text)
166
+ if not iframes:
167
+ raise ValueError("Nessun iframe src trovato.")
168
+
169
+ url2 = iframes[0]
170
+ print(f"Passo 2 (Iframe): Trovato iframe URL: {url2}")
171
+
172
+ # Terzo passo (Iframe): Richiesta all'URL dell'iframe
173
+ referer_raw = urlparse(url2).scheme + "://" + urlparse(url2).netloc + "/"
174
+ origin_raw = urlparse(url2).scheme + "://" + urlparse(url2).netloc
175
+ current_headers['Referer'] = referer_raw
176
+ current_headers['Origin'] = origin_raw
177
+ print(f"Passo 3 (Iframe): Richiesta a {url2}")
178
+ response = session.get(url2, headers=current_headers, timeout=5)
179
+ response.raise_for_status()
180
+ iframe_response_text = response.text
181
+ print("Passo 3 (Iframe) completato.")
182
+
183
+ # Quarto passo (Iframe): Estrai parametri dinamici dall'iframe response
184
+ channel_key_match = re.search(r'(?s) channelKey = \"([^"]*)', iframe_response_text)
185
+ auth_ts_match = re.search(r'(?s) authTs\s*= \"([^"]*)', iframe_response_text)
186
+ auth_rnd_match = re.search(r'(?s) authRnd\s*= \"([^"]*)', iframe_response_text)
187
+ auth_sig_match = re.search(r'(?s) authSig\s*= \"([^"]*)', iframe_response_text)
188
+ auth_host_match = re.search(r'\}\s*fetchWithRetry\(\s*\'([^\']*)', iframe_response_text)
189
+ server_lookup_match = re.search('n fetchWithRetry\(\s*\'([^\']*)', iframe_response_text)
190
+
191
+ if not all([channel_key_match, auth_ts_match, auth_rnd_match, auth_sig_match, auth_host_match, server_lookup_match]):
192
+ raise ValueError("Impossibile estrarre tutti i parametri dinamici dall'iframe response.")
193
+
194
+ channel_key = channel_key_match.group(1)
195
+ auth_ts = auth_ts_match.group(1)
196
+ auth_rnd = auth_rnd_match.group(1)
197
+ auth_sig = quote(auth_sig_match.group(1))
198
+ auth_host = auth_host_match.group(1)
199
+ server_lookup = server_lookup_match.group(1)
200
+
201
+ print("Passo 4 (Iframe): Parametri dinamici estratti.")
202
+
203
+ # Quinto passo (Iframe): Richiesta di autenticazione
204
+ auth_url = f'{auth_host}{channel_key}&ts={auth_ts}&rnd={auth_rnd}&sig={auth_sig}'
205
+ print(f"Passo 5 (Iframe): Richiesta di autenticazione a {auth_url}")
206
+ auth_response = session.get(auth_url, headers=current_headers, timeout=5)
207
+ auth_response.raise_for_status()
208
+ print("Passo 5 (Iframe) completato.")
209
+
210
+ # Sesto passo (Iframe): Richiesta di server lookup per ottenere la server_key
211
+ server_lookup_url = f"https://{urlparse(url2).netloc}{server_lookup}{channel_key}"
212
+ print(f"Passo 6 (Iframe): Richiesta server lookup a {server_lookup_url}")
213
+ server_lookup_response = session.get(server_lookup_url, headers=current_headers, timeout=5)
214
+ server_lookup_response.raise_for_status()
215
+ server_lookup_data = server_lookup_response.json()
216
+ print("Passo 6 (Iframe) completato.")
217
+
218
+ # Settimo passo (Iframe): Estrai server_key dalla risposta di server lookup
219
+ server_key = server_lookup_data.get('server_key')
220
+ if not server_key:
221
+ raise ValueError("'server_key' non trovato nella risposta di server lookup.")
222
+ print(f"Passo 7 (Iframe): Estratto server_key: {server_key}")
223
+
224
+ # Ottavo passo (Iframe): Costruisci il link finale
225
+ host_match = re.search('(?s)m3u8 =.*?:.*?:.*?".*?".*?"([^"]*)', iframe_response_text)
226
+ if not host_match:
227
+ raise ValueError("Impossibile trovare l'host finale per l'm3u8.")
228
+ host = host_match.group(1)
229
+ print(f"Passo 8 (Iframe): Trovato host finale per m3u8: {host}")
230
+
231
+ # Costruisci l'URL finale del flusso
232
+ final_stream_url = (
233
+ f'https://{server_key}{host}{server_key}/{channel_key}/mono.m3u8'
234
+ )
235
+
236
+ # Prepara gli header per lo streaming
237
+ stream_headers = {
238
+ 'User-Agent': current_headers.get('User-Agent', ''),
239
+ 'Referer': referer_raw,
240
+ 'Origin': origin_raw
241
+ }
242
+
243
+ return {
244
+ "resolved_url": final_stream_url,
245
+ "headers": stream_headers
246
+ }
247
+
248
+ except (ValueError, requests.exceptions.RequestException) as e:
249
+ print(f"Logica iframe fallita: {e}")
250
+ print("Tentativo fallback: verifica se l'URL iniziale era un M3U8 diretto...")
251
+
252
+ # Fallback: Verifica se la risposta iniziale era un file M3U8 diretto
253
+ if initial_response_text and initial_response_text.strip().startswith('#EXTM3U'):
254
+ print("Fallback riuscito: Trovato file M3U8 diretto.")
255
+ return {
256
+ "resolved_url": final_url_after_redirects,
257
+ "headers": current_headers
258
+ }
259
+ else:
260
+ print("Fallback fallito: La risposta iniziale non era un M3U8 diretto.")
261
+ return {
262
+ "resolved_url": url,
263
+ "headers": current_headers
264
+ }
265
+
266
+ except requests.exceptions.RequestException as e:
267
+ print(f"Errore durante la richiesta HTTP iniziale: {e}")
268
+ return {"resolved_url": url, "headers": current_headers}
269
+ except Exception as e:
270
+ print(f"Errore generico durante la risoluzione: {e}")
271
+ return {"resolved_url": url, "headers": current_headers}
272
+
273
+ @app.route('/proxy/m3u')
274
+ def proxy_m3u():
275
+ """Proxy per file M3U e M3U8 con supporto per redirezioni e header personalizzati"""
276
+ periodic_cleanup() # Pulizia periodica
277
+
278
+ m3u_url = request.args.get('url', '').strip()
279
+ if not m3u_url:
280
+ return "Errore: Parametro 'url' mancante", 400
281
+
282
+ default_headers = {
283
+ "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",
284
+ "Referer": "https://vavoo.to/",
285
+ "Origin": "https://vavoo.to"
286
+ }
287
+
288
+ # Estrai gli header dalla richiesta, sovrascrivendo i default
289
+ request_headers = {
290
+ unquote(key[2:]).replace("_", "-"): unquote(value).strip()
291
+ for key, value in request.args.items()
292
+ if key.lower().startswith("h_")
293
+ }
294
+ headers = {**default_headers, **request_headers}
295
+
296
+ # --- Logica per trasformare l'URL se necessario ---
297
+ processed_url = m3u_url
298
+ match_premium_m3u8 = re.search(r'/premium(\d+)/mono\.m3u8$', m3u_url)
299
+
300
+ if match_premium_m3u8:
301
+ channel_number = match_premium_m3u8.group(1)
302
+ transformed_url = f"https://daddylive.dad/embed/stream-{channel_number}.php"
303
+ print(f"URL {m3u_url} corrisponde al pattern premium. Trasformato in: {transformed_url}")
304
+ processed_url = transformed_url
305
+ else:
306
+ print(f"URL {m3u_url} non corrisponde al pattern premium/mono.m3u8. Utilizzo URL originale.")
307
+
308
+ try:
309
+ print(f"Chiamata a resolve_m3u8_link per URL processato: {processed_url}")
310
+ result = resolve_m3u8_link(processed_url, headers)
311
+
312
+ if not result["resolved_url"]:
313
+ return "Errore: Impossibile risolvere l'URL in un M3U8 valido.", 500
314
+
315
+ resolved_url = result["resolved_url"]
316
+ current_headers_for_proxy = result["headers"]
317
+
318
+ print(f"Risoluzione completata. URL M3U8 finale: {resolved_url}")
319
+
320
+ # Fetchare il contenuto M3U8 effettivo dall'URL risolto
321
+ print(f"Fetching M3U8 content from resolved URL: {resolved_url}")
322
+ m3u_response = requests.get(resolved_url, headers=current_headers_for_proxy, allow_redirects=True, timeout=5)
323
+ m3u_response.raise_for_status()
324
+ m3u_content = m3u_response.text
325
+ final_url = m3u_response.url
326
+
327
+ # Processa il contenuto M3U8
328
+ file_type = detect_m3u_type(m3u_content)
329
+
330
+ if file_type == "m3u":
331
+ return Response(m3u_content, content_type="application/vnd.apple.mpegurl")
332
+
333
+ # Processa contenuto M3U8
334
+ parsed_url = urlparse(final_url)
335
+ base_url = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path.rsplit('/', 1)[0]}/"
336
+
337
+ # Prepara la query degli header per segmenti/chiavi proxati
338
+ headers_query = "&".join([f"h_{quote(k)}={quote(v)}" for k, v in current_headers_for_proxy.items()])
339
+
340
+ modified_m3u8 = []
341
+ for line in m3u_content.splitlines():
342
+ line = line.strip()
343
+ if line.startswith("#EXT-X-KEY") and 'URI="' in line:
344
+ line = replace_key_uri(line, headers_query)
345
+ elif line and not line.startswith("#"):
346
+ segment_url = urljoin(base_url, line)
347
+ line = f"/proxy/ts?url={quote(segment_url)}&{headers_query}"
348
+ modified_m3u8.append(line)
349
+
350
+ modified_m3u8_content = "\n".join(modified_m3u8)
351
+ return Response(modified_m3u8_content, content_type="application/vnd.apple.mpegurl")
352
+
353
+ except requests.RequestException as e:
354
+ print(f"Errore durante il download o la risoluzione del file: {str(e)}")
355
+ return f"Errore durante il download o la risoluzione del file M3U/M3U8: {str(e)}", 500
356
+ except Exception as e:
357
+ print(f"Errore generico nella funzione proxy_m3u: {str(e)}")
358
+ return f"Errore generico durante l'elaborazione: {str(e)}", 500
359
+
360
+ @app.route('/proxy/resolve')
361
+ def proxy_resolve():
362
+ """Proxy per risolvere e restituire un URL M3U8"""
363
+ periodic_cleanup()
364
+
365
+ url = request.args.get('url', '').strip()
366
+ if not url:
367
+ return "Errore: Parametro 'url' mancante", 400
368
+
369
+ headers = {
370
+ unquote(key[2:]).replace("_", "-"): unquote(value).strip()
371
+ for key, value in request.args.items()
372
+ if key.lower().startswith("h_")
373
+ }
374
+
375
+ try:
376
+ result = resolve_m3u8_link(url, headers)
377
+
378
+ if not result["resolved_url"]:
379
+ return "Errore: Impossibile risolvere l'URL", 500
380
+
381
+ headers_query = "&".join([f"h_{quote(k)}={quote(v)}" for k, v in result["headers"].items()])
382
+
383
+ return Response(
384
+ f"#EXTM3U\n"
385
+ f"#EXTINF:-1,Canale Risolto\n"
386
+ f"/proxy/m3u?url={quote(result['resolved_url'])}&{headers_query}",
387
+ content_type="application/vnd.apple.mpegurl"
388
+ )
389
+
390
+ except Exception as e:
391
+ return f"Errore durante la risoluzione dell'URL: {str(e)}", 500
392
+
393
+ @app.route('/proxy/ts')
394
+ def proxy_ts():
395
+ """Proxy per segmenti .TS con headers personalizzati e caching ottimizzato"""
396
+ periodic_cleanup()
397
+
398
+ ts_url = request.args.get('url', '').strip()
399
+ if not ts_url:
400
+ return "Errore: Parametro 'url' mancante", 400
401
+
402
+ headers = {
403
+ unquote(key[2:]).replace("_", "-"): unquote(value).strip()
404
+ for key, value in request.args.items()
405
+ if key.lower().startswith("h_")
406
+ }
407
+
408
+ # Controlla cache
409
+ cached_data = ts_cache.get(ts_url)
410
+ if cached_data:
411
+ return Response(cached_data, content_type="video/mp2t")
412
+
413
+ try:
414
+ response = requests.get(ts_url, headers=headers, stream=True, allow_redirects=True, timeout=5)
415
+ response.raise_for_status()
416
+
417
+ # Leggi in chunks per evitare di caricare tutto in memoria
418
+ data = b''
419
+ for chunk in response.iter_content(chunk_size=8192):
420
+ data += chunk
421
+ # Limite di sicurezza per evitare segmenti troppo grandi
422
+ if len(data) > MAX_TS_SIZE:
423
+ break
424
+
425
+ # Carica in cache solo se non troppo grande
426
+ if len(data) <= MAX_TS_SIZE:
427
+ ts_cache.put(ts_url, data)
428
+
429
+ return Response(data, content_type="video/mp2t")
430
+
431
+ except requests.RequestException as e:
432
+ return f"Errore durante il download del segmento TS: {str(e)}", 500
433
+
434
+ @app.route('/proxy/key')
435
+ def proxy_key():
436
+ """Proxy per la chiave AES-128 con header personalizzati"""
437
+ key_url = request.args.get('url', '').strip()
438
+ if not key_url:
439
+ return "Errore: Parametro 'url' mancante per la chiave", 400
440
+
441
+ headers = {
442
+ unquote(key[2:]).replace("_", "-"): unquote(value).strip()
443
+ for key, value in request.args.items()
444
+ if key.lower().startswith("h_")
445
+ }
446
+
447
+ # Controlla cache per le chiavi
448
+ cached_key = key_cache.get(key_url)
449
+ if cached_key:
450
+ return Response(cached_key, content_type="application/octet-stream")
451
+
452
+ try:
453
+ response = requests.get(key_url, headers=headers, allow_redirects=True, timeout=5)
454
+ response.raise_for_status()
455
+
456
+ # Le chiavi sono piccole, cachale sempre
457
+ key_cache.put(key_url, response.content)
458
+
459
+ return Response(response.content, content_type="application/octet-stream")
460
+
461
+ except requests.RequestException as e:
462
+ return f"Errore durante il download della chiave AES-128: {str(e)}", 500
463
+
464
+ @app.route('/cache/stats')
465
+ def cache_stats():
466
+ """Endpoint per monitorare lo stato della cache"""
467
+ return {
468
+ "ts_cache_size": len(ts_cache.cache),
469
+ "ts_cache_bytes": ts_cache.current_size,
470
+ "key_cache_size": len(key_cache.cache),
471
+ "key_cache_bytes": key_cache.current_size,
472
+ "total_bytes": ts_cache.current_size + key_cache.current_size,
473
+ "max_total_bytes": MAX_TOTAL_CACHE_SIZE,
474
+ "cache_ttl": CACHE_TTL,
475
+ "max_ts_size": MAX_TS_SIZE
476
+ }
477
+
478
+ @app.route('/cache/clear')
479
+ def clear_cache():
480
+ """Endpoint per svuotare manualmente la cache"""
481
+ ts_cache.clear()
482
+ key_cache.clear()
483
+ gc.collect()
484
+ return "Cache svuotata con successo"
485
+
486
+ @app.route('/')
487
+ def index():
488
+ """Pagina principale che mostra un messaggio di benvenuto"""
489
+ return "Proxy started!"
490
+
491
+ # --- GESTIONE EPG E CANALI IN BACKGROUND ---
492
+ EPG_CACHE = []
493
+ APP_CHANNELS = [
494
+ {"id": "877", "name": "DAZN 1", "logo": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/DAZN_1_Logo.svg/774px-DAZN_1_Logo.svg.png"},
495
+ {"id": "878", "name": "EuroSport 1", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/spain/eurosport-1-es.png"},
496
+ {"id": "879", "name": "EuroSport 2", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/spain/eurosport-2-es.png"},
497
+ {"id": "854", "name": "Italia 1", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/italia1-it.png"},
498
+ {"id": "855", "name": "La7", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/la7-it.png"},
499
+ {"id": "856", "name": "LA7d", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/la7d-it.png"},
500
+ {"id": "850", "name": "Rai 1", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/rai-1-it.png"},
501
+ {"id": "851", "name": "Rai 2", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/rai-2-it.png"},
502
+ {"id": "852", "name": "Rai 3", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/rai-3-it.png"},
503
+ {"id": "853", "name": "Rai 4", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/rai-4-it.png"},
504
+ {"id": "882", "name": "Rai Sport", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/rai-sport-it.png"},
505
+ {"id": "858", "name": "Rai Premium", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/rai-premium-it.png"},
506
+ {"id": "574", "name": "Sky Sports Golf", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-sport-golf-it.png"},
507
+ {"id": "575", "name": "Sky Sport MotoGP", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-sport-motogp-it.png"},
508
+ {"id": "576", "name": "Sky Sport Tennis", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-sport-tennis-it.png"},
509
+ {"id": "577", "name": "Sky Sport F1", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-sport-f1-it.png"},
510
+ {"id": "460", "name": "Sky Sport MAX", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-sport-football-it.png"},
511
+ {"id": "461", "name": "Sky Sport UNO", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-sport-uno-it.png"},
512
+ {"id": "462", "name": "Sky Sport Arena", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-sport-arena-it.png"},
513
+ {"id": "881", "name": "Sky UNO", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-uno-it.png"},
514
+ {"id": "859", "name": "Sky Cinema Collection", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-cinema-collection-it.png"},
515
+ {"id": "860", "name": "Sky Cinema Uno", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-cinema-uno-it.png"},
516
+ {"id": "861", "name": "Sky Cinema Action", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-cinema-action-it.png"},
517
+ {"id": "862", "name": "Sky Cinema Comedy", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-cinema-comedy-it.png"},
518
+ {"id": "863", "name": "Sky Cinema Uno +24", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-cinema-uno-plus24-it.png"},
519
+ {"id": "864", "name": "Sky Cinema Romance", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-cinema-romance-it.png"},
520
+ {"id": "865", "name": "Sky Cinema Family", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-cinema-family-it.png"},
521
+ {"id": "867", "name": "Sky Cinema Drama", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-cinema-drama-it.png"},
522
+ {"id": "868", "name": "Sky Cinema Suspense", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-cinema-suspense-it.png"},
523
+ {"id": "869", "name": "Sky Sport 24", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-sport-24-it.png"},
524
+ {"id": "870", "name": "Sky Sport Calcio", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-sport-calcio-it.png"},
525
+ {"id": "871", "name": "Sky Calcio 1", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/germany/sky-select-1-alt-de.png"},
526
+ {"id": "872", "name": "Sky Calcio 2", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/germany/sky-select-2-alt-de.png"},
527
+ {"id": "873", "name": "Sky Calcio 3", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/germany/sky-select-3-alt-de.png"},
528
+ {"id": "874", "name": "Sky Calcio 4", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/germany/sky-select-4-alt-de.png"},
529
+ {"id": "875", "name": "Sky Sport Basket", "logo": "https://play-lh.googleusercontent.com/u7UNH06SU4KsMM4ZGWr7wghkJYN75PNCEMxnIYULpA__VPg8zfEOYMIAhUaIdmZnqw=w480-h960-rw"},
530
+ {"id": "880", "name": "Sky Serie", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/sky-serie-it.png"},
531
+ {"id": "857", "name": "20 Mediaset", "logo": "https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/italy/20-it.png"}
532
+ ]
533
+
534
+ def update_epg_background():
535
+ global EPG_CACHE
536
+ print("Inizio aggiornamento EPG in background...")
537
+ try:
538
+ r = requests.get('https://epgshare01.online/epgshare01/epg_ripper_IT1.xml.gz', timeout=20)
539
+ r.raise_for_status()
540
+ xml_data = gzip.decompress(r.content)
541
+ root = ET.fromstring(xml_data)
542
+
543
+ def normalize_name(name):
544
+ return re.sub(r'[^a-z0-9]', '', name.lower())
545
+
546
+ mapped_xml_ids = {}
547
+ for ch in root.findall('channel'):
548
+ xml_id = ch.attrib.get('id')
549
+ display_names = [dn.text for dn in ch.findall('display-name') if dn.text]
550
+ for app_ch in APP_CHANNELS:
551
+ norm_app = normalize_name(app_ch['name'])
552
+ for dn in display_names:
553
+ norm_dn = normalize_name(dn)
554
+ if norm_app == norm_dn or (norm_app in norm_dn and "hd" in norm_dn):
555
+ mapped_xml_ids[xml_id] = app_ch
556
+ break
557
+
558
+ epg_data = {ch['id']: {"channel_id": ch['id'], "channel_name": ch['name'], "programmes": []} for ch in APP_CHANNELS}
559
+
560
+ for prog in root.findall('programme'):
561
+ channel_id = prog.attrib.get('channel')
562
+ if channel_id in mapped_xml_ids:
563
+ app_ch = mapped_xml_ids[channel_id]
564
+ title_el = prog.find('title')
565
+ desc_el = prog.find('desc')
566
+ title = title_el.text if title_el is not None else "Programma sconosciuto"
567
+ desc = desc_el.text if desc_el is not None else ""
568
+ start = prog.attrib.get('start')
569
+ stop = prog.attrib.get('stop')
570
+
571
+ epg_data[app_ch['id']]['programmes'].append({
572
+ "start": start,
573
+ "stop": stop,
574
+ "title": title,
575
+ "desc": desc
576
+ })
577
+
578
+ for ch_id in epg_data:
579
+ epg_data[ch_id]['programmes'].sort(key=lambda x: x['start'])
580
+
581
+ final_epg = [v for k, v in epg_data.items() if len(v['programmes']) > 0]
582
+
583
+ from flask import jsonify
584
+ EPG_CACHE = final_epg
585
+ print(f"EPG aggiornato con successo! Trovati programmi per {len(final_epg)} canali.")
586
+ except Exception as e:
587
+ print("Errore durante l'aggiornamento EPG:", e)
588
+
589
+ # Ripeti ogni 12 ore
590
+ threading.Timer(12 * 3600, update_epg_background).start()
591
+
592
+ # Avvia l'aggiornamento EPG in background all'avvio del server
593
+ threading.Thread(target=update_epg_background, daemon=True).start()
594
+
595
+ from flask import jsonify
596
+
597
+ @app.route('/channels.json')
598
+ def get_channels():
599
+ """Restituisce la lista dinamica dei canali"""
600
+ return jsonify(APP_CHANNELS)
601
+
602
+ @app.route('/epg.json')
603
+ def get_epg():
604
+ """Restituisce l'EPG generata in background"""
605
+ return jsonify(EPG_CACHE)
606
+
607
+ if __name__ == '__main__':
608
+ print("Proxy started!")
609
+ app.run(host="0.0.0.0", port=7860, debug=False)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ flask==3.1.3
2
+ requests==2.33.1
3
+ blinker==1.9.0