mcfc commited on
Commit
a3b661e
·
verified ·
1 Parent(s): cd4226f

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +23 -0
  2. app.py +632 -0
  3. requirements.txt +3 -0
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"]
app.py ADDED
@@ -0,0 +1,632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, Response
2
+ import requests
3
+ from urllib.parse import urlparse, urljoin, quote, unquote
4
+ import re
5
+ import json
6
+ import os
7
+
8
+ app = Flask(__name__)
9
+
10
+ def detect_m3u_type(content):
11
+ """Rileva se è un M3U (lista IPTV) o un M3U8 (flusso HLS)"""
12
+ if "#EXTM3U" in content and "#EXTINF" in content:
13
+ return "m3u8"
14
+ return "m3u"
15
+
16
+ def replace_key_uri(line, headers_query):
17
+ """Sostituisce l'URI della chiave AES-128 con il proxy"""
18
+ match = re.search(r'URI="([^"]+)"', line)
19
+ if match:
20
+ key_url = match.group(1)
21
+ proxied_key_url = f"/proxy/key?url={quote(key_url)}&{headers_query}"
22
+ return line.replace(key_url, proxied_key_url)
23
+ return line
24
+
25
+ def resolve_m3u8_link(url, headers=None):
26
+ """
27
+ Tenta di risolvere un URL M3U8 supportando sia URL puliti che URL con header concatenati.
28
+ Gestisce automaticamente l'estrazione degli header dai parametri dell'URL.
29
+ """
30
+ if not url:
31
+ print("Errore: URL non fornito.")
32
+ return {"resolved_url": None, "headers": {}}
33
+
34
+ print(f"Tentativo di risoluzione URL: {url}")
35
+
36
+ # Inizializza gli header di default
37
+ current_headers = headers if headers else {
38
+ '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'
39
+ }
40
+
41
+ # **SUPPORTO PER ENTRAMBE LE VERSIONI**
42
+ clean_url = url
43
+ extracted_headers = {}
44
+
45
+ # Verifica se l'URL contiene parametri header concatenati
46
+ if '&h_' in url or '%26h_' in url:
47
+ print("Rilevati parametri header nell'URL - Estrazione in corso...")
48
+
49
+ # Gestisci sia il formato normale che quello URL-encoded
50
+ if '%26h_' in url:
51
+ # Per vavoo.to, sostituisci solo %26 con & senza doppia decodifica
52
+ if 'vavoo.to' in url.lower():
53
+ url = url.replace('%26', '&')
54
+ print(f"URL vavoo.to processato: {url}")
55
+ else:
56
+ # Per altri URL, applica la doppia decodifica completa
57
+ url = unquote(unquote(url))
58
+ print(f"URL con doppia decodifica: {url}")
59
+
60
+ # Separa l'URL base dai parametri degli header
61
+ url_parts = url.split('&h_', 1)
62
+ clean_url = url_parts[0]
63
+ header_params = '&h_' + url_parts[1]
64
+
65
+ # Estrai gli header dai parametri
66
+ for param in header_params.split('&'):
67
+ if param.startswith('h_'):
68
+ try:
69
+ key_value = param[2:].split('=', 1)
70
+ if len(key_value) == 2:
71
+ key = unquote(key_value[0]).replace('_', '-')
72
+ value = unquote(key_value[1])
73
+ extracted_headers[key] = value
74
+ print(f"Header estratto: {key} = {value}")
75
+ except Exception as e:
76
+ print(f"Errore nell'estrazione dell'header {param}: {e}")
77
+
78
+ # Combina gli header estratti con quelli esistenti
79
+ current_headers.update(extracted_headers)
80
+ print(f"URL pulito: {clean_url}")
81
+ print(f"Header finali: {current_headers}")
82
+ else:
83
+ print("URL pulito rilevato - Nessuna estrazione header necessaria")
84
+
85
+ initial_response_text = None
86
+ final_url_after_redirects = None
87
+
88
+ # Verifica se è un URL di vavoo.to
89
+ is_vavoo = "vavoo.to" in clean_url.lower()
90
+
91
+ try:
92
+ with requests.Session() as session:
93
+ print(f"Passo 1: Richiesta a {clean_url}")
94
+ response = session.get(clean_url, headers=current_headers, allow_redirects=True, timeout=(5, 15))
95
+ response.raise_for_status()
96
+ initial_response_text = response.text
97
+ final_url_after_redirects = response.url
98
+ print(f"Passo 1 completato. URL finale dopo redirect: {final_url_after_redirects}")
99
+
100
+ # Se è un URL di vavoo.to, salta la logica dell'iframe
101
+ if is_vavoo:
102
+ if initial_response_text and initial_response_text.strip().startswith('#EXTM3U'):
103
+ return {
104
+ "resolved_url": final_url_after_redirects,
105
+ "headers": current_headers
106
+ }
107
+ else:
108
+ # Se non è un M3U8 diretto, restituisci l'URL originale per vavoo
109
+ print(f"URL vavoo.to non è un M3U8 diretto: {clean_url}")
110
+ return {
111
+ "resolved_url": clean_url,
112
+ "headers": current_headers
113
+ }
114
+
115
+ # Prova la logica dell'iframe per gli altri URL
116
+ print("Tentativo con logica iframe...")
117
+ try:
118
+ # Secondo passo (Iframe): Trova l'iframe src nella risposta iniziale
119
+ iframes = re.findall(r'iframe src="([^"]+)"', initial_response_text)
120
+ if not iframes:
121
+ raise ValueError("Nessun iframe src trovato.")
122
+
123
+ url2 = iframes[0]
124
+ print(f"Passo 2 (Iframe): Trovato iframe URL: {url2}")
125
+
126
+ # Terzo passo (Iframe): Richiesta all'URL dell'iframe
127
+ referer_raw = urlparse(url2).scheme + "://" + urlparse(url2).netloc + "/"
128
+ origin_raw = urlparse(url2).scheme + "://" + urlparse(url2).netloc
129
+ current_headers['Referer'] = referer_raw
130
+ current_headers['Origin'] = origin_raw
131
+ print(f"Passo 3 (Iframe): Richiesta a {url2}")
132
+ response = session.get(url2, headers=current_headers, timeout=(5, 15))
133
+ response.raise_for_status()
134
+ # Applica la codifica corretta
135
+ response.encoding = response.apparent_encoding or 'utf-8'
136
+ iframe_response_text = response.text
137
+ print("Passo 3 (Iframe) completato.")
138
+
139
+ # ... resto del codice iframe rimane uguale ...
140
+ # Quarto passo (Iframe): Estrai parametri dinamici dall'iframe response
141
+ channel_key_match = re.search(r'(?s) channelKey = \"([^\"]*)"', iframe_response_text)
142
+ auth_ts_match = re.search(r'(?s) authTs\s*= \"([^\"]*)"', iframe_response_text)
143
+ auth_rnd_match = re.search(r'(?s) authRnd\s*= \"([^\"]*)"', iframe_response_text)
144
+ auth_sig_match = re.search(r'(?s) authSig\s*= \"([^\"]*)"', iframe_response_text)
145
+ auth_host_match = re.search(r'\}\s*fetchWithRetry\(\s*\'([^\']*)\'', iframe_response_text)
146
+ server_lookup_match = re.search(r'n fetchWithRetry\(\s*\'([^\']*)\'', iframe_response_text)
147
+
148
+ if not all([channel_key_match, auth_ts_match, auth_rnd_match, auth_sig_match, auth_host_match, server_lookup_match]):
149
+ raise ValueError("Impossibile estrarre tutti i parametri dinamici dall'iframe response.")
150
+
151
+ channel_key = channel_key_match.group(1)
152
+ auth_ts = auth_ts_match.group(1)
153
+ auth_rnd = auth_rnd_match.group(1)
154
+ auth_sig = quote(auth_sig_match.group(1))
155
+ auth_host = auth_host_match.group(1)
156
+ server_lookup = server_lookup_match.group(1)
157
+
158
+ print("Passo 4 (Iframe): Parametri dinamici estratti.")
159
+
160
+ # Quinto passo (Iframe): Richiesta di autenticazione
161
+ auth_url = f'{auth_host}{channel_key}&ts={auth_ts}&rnd={auth_rnd}&sig={auth_sig}'
162
+ print(f"Passo 5 (Iframe): Richiesta di autenticazione a {auth_url}")
163
+ auth_response = session.get(auth_url, headers=current_headers, timeout=(5, 15))
164
+ auth_response.raise_for_status()
165
+ print("Passo 5 (Iframe) completato.")
166
+
167
+ # Sesto passo (Iframe): Richiesta di server lookup per ottenere la server_key
168
+ server_lookup_url = f"https://{urlparse(url2).netloc}{server_lookup}{channel_key}"
169
+ print(f"Passo 6 (Iframe): Richiesta server lookup a {server_lookup_url}")
170
+ server_lookup_response = session.get(server_lookup_url, headers=current_headers, timeout=(5, 15))
171
+ server_lookup_response.raise_for_status()
172
+ server_lookup_data = server_lookup_response.json()
173
+ print("Passo 6 (Iframe) completato.")
174
+
175
+ # Settimo passo (Iframe): Estrai server_key dalla risposta di server lookup
176
+ server_key = server_lookup_data.get('server_key')
177
+ if not server_key:
178
+ raise ValueError("'server_key' non trovato nella risposta di server lookup.")
179
+ print(f"Passo 7 (Iframe): Estratto server_key: {server_key}")
180
+
181
+ # Ottavo passo (Iframe): Costruisci il link finale
182
+ host_match = re.search('(?s)m3u8 =.*?:.*?:.*?".*?".*?"([^"]*)"', iframe_response_text)
183
+ if not host_match:
184
+ raise ValueError("Impossibile trovare l'host finale per l'm3u8.")
185
+ host = host_match.group(1)
186
+ print(f"Passo 8 (Iframe): Trovato host finale per m3u8: {host}")
187
+
188
+ # Costruisci l'URL finale del flusso
189
+ final_stream_url = (
190
+ f'https://{server_key}{host}{server_key}/{channel_key}/mono.m3u8'
191
+ )
192
+
193
+ # Prepara gli header per lo streaming
194
+ stream_headers = {
195
+ 'User-Agent': current_headers.get('User-Agent', ''),
196
+ 'Referer': referer_raw,
197
+ 'Origin': origin_raw
198
+ }
199
+
200
+ return {
201
+ "resolved_url": final_stream_url,
202
+ "headers": stream_headers
203
+ }
204
+
205
+ except (ValueError, requests.exceptions.RequestException) as e:
206
+ print(f"Logica iframe fallita: {e}")
207
+ print("Tentativo fallback: verifica se l'URL iniziale era un M3U8 diretto...")
208
+
209
+ # Fallback: Verifica se la risposta iniziale era un file M3U8 diretto
210
+ if initial_response_text and initial_response_text.strip().startswith('#EXTM3U'):
211
+ print("Fallback riuscito: Trovato file M3U8 diretto.")
212
+ return {
213
+ "resolved_url": final_url_after_redirects,
214
+ "headers": current_headers
215
+ }
216
+ else:
217
+ print("Fallback fallito: La risposta iniziale non era un M3U8 diretto.")
218
+ return {
219
+ "resolved_url": clean_url,
220
+ "headers": current_headers
221
+ }
222
+
223
+ except requests.exceptions.RequestException as e:
224
+ print(f"Errore durante la richiesta HTTP iniziale: {e}")
225
+ return {"resolved_url": clean_url, "headers": current_headers}
226
+ except Exception as e:
227
+ print(f"Errore generico durante la risoluzione: {e}")
228
+ return {"resolved_url": clean_url, "headers": current_headers}
229
+
230
+ @app.route('/proxy')
231
+ def proxy():
232
+ """Proxy per liste M3U che aggiunge automaticamente /proxy/m3u?url= con IP prima dei link"""
233
+ m3u_url = request.args.get('url', '').strip()
234
+ if not m3u_url:
235
+ return "Errore: Parametro 'url' mancante", 400
236
+
237
+ try:
238
+ # Ottieni l'IP del server
239
+ server_ip = request.host
240
+
241
+ # Scarica la lista M3U originale
242
+ response = requests.get(m3u_url, timeout=(10, 30)) # Timeout connessione 10s, lettura 30s
243
+ response.raise_for_status()
244
+ m3u_content = response.text
245
+
246
+ modified_lines = []
247
+ exthttp_headers_query_params = "" # Stringa per conservare gli header da #EXTHTTP
248
+
249
+ for line in m3u_content.splitlines():
250
+ line = line.strip()
251
+ if line.startswith('#EXTHTTP:'):
252
+ try:
253
+ # Estrai la parte JSON dalla riga #EXTHTTP:
254
+ json_str = line.split(':', 1)[1].strip()
255
+ headers_dict = json.loads(json_str)
256
+
257
+ # Costruisci la stringa dei parametri di query per gli header con doppia codifica
258
+ temp_params = []
259
+ for key, value in headers_dict.items():
260
+ # Doppia codifica: prima codifica normale, poi codifica di nuovo
261
+ encoded_key = quote(quote(key))
262
+ encoded_value = quote(quote(str(value)))
263
+ temp_params.append(f"h_{encoded_key}={encoded_value}")
264
+
265
+ if temp_params:
266
+ # Usa %26 invece di & come separatore per gli header
267
+ exthttp_headers_query_params = "%26" + "%26".join(temp_params)
268
+ else:
269
+ exthttp_headers_query_params = ""
270
+ except Exception as e:
271
+ print(f"Errore nel parsing di #EXTHTTP '{line}': {e}")
272
+ exthttp_headers_query_params = "" # Resetta in caso di errore
273
+ modified_lines.append(line) # Mantieni la riga #EXTHTTP originale
274
+ elif line and not line.startswith('#'):
275
+ # Questa è una riga di URL del flusso
276
+ # Verifica se è un URL di Pluto.tv e saltalo
277
+ if 'pluto.tv' in line.lower():
278
+ modified_lines.append(line) # Mantieni l'URL originale senza proxy
279
+ exthttp_headers_query_params = "" # Resetta gli header
280
+ else:
281
+ # Applica gli header #EXTHTTP se presenti e poi resettali
282
+ # Assicurati che l'URL sia completamente codificato, inclusi gli slash
283
+ encoded_line = quote(line, safe='')
284
+ modified_line = f"http://{server_ip}/proxy/m3u?url={encoded_line}{exthttp_headers_query_params}"
285
+ modified_lines.append(modified_line)
286
+ exthttp_headers_query_params = "" # Resetta gli header dopo averli usati
287
+ else:
288
+ # Mantieni invariate le altre righe di metadati o righe vuote
289
+ modified_lines.append(line)
290
+
291
+ modified_content = '\n'.join(modified_lines)
292
+
293
+ # Estrai il nome del file dall'URL originale
294
+ parsed_m3u_url = urlparse(m3u_url)
295
+ original_filename = os.path.basename(parsed_m3u_url.path)
296
+
297
+ return Response(modified_content, content_type="application/vnd.apple.mpegurl", headers={'Content-Disposition': f'attachment; filename="{original_filename}"'})
298
+
299
+ except requests.RequestException as e:
300
+ return f"Errore durante il download della lista M3U: {str(e)}", 500
301
+ except Exception as e:
302
+ return f"Errore generico: {str(e)}", 500
303
+
304
+ @app.route('/proxy/m3u')
305
+ def proxy_m3u():
306
+ """Proxy per file M3U e M3U8 con supporto per entrambe le versioni di URL"""
307
+ m3u_url = request.args.get('url', '').strip()
308
+ if not m3u_url:
309
+ return "Errore: Parametro 'url' mancante", 400
310
+
311
+ default_headers = {
312
+ "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",
313
+ "Referer": "https://vavoo.to/",
314
+ "Origin": "https://vavoo.to"
315
+ }
316
+
317
+ # Estrai gli header dalla richiesta (versione parametri query)
318
+ request_headers = {
319
+ unquote(key[2:]).replace("_", "-"): unquote(value).strip()
320
+ for key, value in request.args.items()
321
+ if key.lower().startswith("h_")
322
+ }
323
+
324
+ # Combina header di default con quelli della richiesta
325
+ headers = {**default_headers, **request_headers}
326
+
327
+ # --- Logica per trasformare l'URL se necessario ---
328
+ processed_url = m3u_url
329
+
330
+ # Trasforma /stream/ in /embed/ per Daddylive
331
+ if '/stream/stream-' in m3u_url and 'thedaddy.click' in m3u_url:
332
+ processed_url = m3u_url.replace('/cast/stream-', '/embed/stream-')
333
+ print(f"URL {m3u_url} trasformato da /cast/ a /embed/: {processed_url}")
334
+
335
+ match_premium_m3u8 = re.search(r'/premium(\d+)/mono\.m3u8$', m3u_url)
336
+
337
+ if match_premium_m3u8:
338
+ channel_number = match_premium_m3u8.group(1)
339
+ transformed_url = f"https://thedaddy.click/embed/stream-{channel_number}.php"
340
+ print(f"URL {m3u_url} corrisponde al pattern premium. Trasformato in: {transformed_url}")
341
+ processed_url = transformed_url
342
+ else:
343
+ print(f"URL {processed_url} processato per la risoluzione.")
344
+
345
+ try:
346
+ print(f"Chiamata a resolve_m3u8_link per URL processato: {processed_url}")
347
+ result = resolve_m3u8_link(processed_url, headers)
348
+
349
+ if not result["resolved_url"]:
350
+ return "Errore: Impossibile risolvere l'URL in un M3U8 valido.", 500
351
+
352
+ resolved_url = result["resolved_url"]
353
+ current_headers_for_proxy = result["headers"]
354
+
355
+ print(f"Risoluzione completata. URL M3U8 finale: {resolved_url}")
356
+
357
+ # Fetchare il contenuto M3U8 effettivo dall'URL risolto
358
+ print(f"Fetching M3U8 content from resolved URL: {resolved_url}")
359
+ m3u_response = requests.get(resolved_url, headers=current_headers_for_proxy, allow_redirects=True, timeout=(10, 20)) # Timeout connessione 10s, lettura 20s
360
+ m3u_response.raise_for_status()
361
+ # Applica la codifica corretta
362
+ m3u_response.encoding = m3u_response.apparent_encoding or 'utf-8'
363
+ m3u_content = m3u_response.text
364
+ final_url = m3u_response.url
365
+
366
+ # Processa il contenuto M3U8
367
+ file_type = detect_m3u_type(m3u_content)
368
+
369
+ if file_type == "m3u":
370
+ return Response(m3u_content, content_type="application/vnd.apple.mpegurl; charset=utf-8")
371
+
372
+ # Processa contenuto M3U8
373
+ parsed_url = urlparse(final_url)
374
+ base_url = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path.rsplit('/', 1)[0]}/"
375
+
376
+ # Prepara la query degli header per segmenti/chiavi proxati
377
+ headers_query = "&".join([f"h_{quote(k)}={quote(v)}" for k, v in current_headers_for_proxy.items()])
378
+
379
+ modified_m3u8 = []
380
+ for line in m3u_content.splitlines():
381
+ line = line.strip()
382
+ if line.startswith("#EXT-X-KEY") and 'URI="' in line:
383
+ line = replace_key_uri(line, headers_query)
384
+ elif line and not line.startswith("#"):
385
+ segment_url = urljoin(base_url, line)
386
+ line = f"/proxy/ts?url={quote(segment_url)}&{headers_query}"
387
+ modified_m3u8.append(line)
388
+
389
+ modified_m3u8_content = "\n".join(modified_m3u8)
390
+ return Response(modified_m3u8_content, content_type="application/vnd.apple.mpegurl; charset=utf-8")
391
+
392
+ except requests.RequestException as e:
393
+ print(f"Errore durante il download o la risoluzione del file: {str(e)}")
394
+ return f"Errore durante il download o la risoluzione del file M3U/M3U8: {str(e)}", 500
395
+ except Exception as e:
396
+ print(f"Errore generico nella funzione proxy_m3u: {str(e)}")
397
+ return f"Errore generico durante l'elaborazione: {str(e)}", 500
398
+
399
+ @app.route('/proxy/resolve')
400
+ def proxy_resolve():
401
+ """Proxy per risolvere e restituire un URL M3U8"""
402
+ url = request.args.get('url', '').strip()
403
+ if not url:
404
+ return "Errore: Parametro 'url' mancante", 400
405
+
406
+ headers = {
407
+ unquote(key[2:]).replace("_", "-"): unquote(value).strip()
408
+ for key, value in request.args.items()
409
+ if key.lower().startswith("h_")
410
+ }
411
+
412
+ try:
413
+ result = resolve_m3u8_link(url, headers)
414
+
415
+ if not result["resolved_url"]:
416
+ return "Errore: Impossibile risolvere l'URL", 500
417
+
418
+ headers_query = "&".join([f"h_{quote(k)}={quote(v)}" for k, v in result["headers"].items()])
419
+
420
+ return Response(
421
+ f"#EXTM3U\n"
422
+ f"#EXTINF:-1,Canale Risolto\n"
423
+ f"/proxy/m3u?url={quote(result['resolved_url'])}&{headers_query}",
424
+ content_type="application/vnd.apple.mpegurl; charset=utf-8"
425
+ )
426
+
427
+ except Exception as e:
428
+ return f"Errore durante la risoluzione dell'URL: {str(e)}", 500
429
+
430
+ @app.route('/proxy/ts')
431
+ def proxy_ts():
432
+ """Proxy per segmenti .TS con headers personalizzati - SENZA CACHE"""
433
+ ts_url = request.args.get('url', '').strip()
434
+ if not ts_url:
435
+ return "Errore: Parametro 'url' mancante", 400
436
+
437
+ headers = {
438
+ unquote(key[2:]).replace("_", "-"): unquote(value).strip()
439
+ for key, value in request.args.items()
440
+ if key.lower().startswith("h_")
441
+ }
442
+
443
+ try:
444
+ # Stream diretto senza cache per evitare freezing
445
+ response = requests.get(ts_url, headers=headers, stream=True, allow_redirects=True, timeout=(10, 30)) # Timeout di connessione 10s, lettura 30s
446
+ response.raise_for_status()
447
+
448
+ def generate():
449
+ for chunk in response.iter_content(chunk_size=8192):
450
+ if chunk:
451
+ yield chunk
452
+
453
+ return Response(generate(), content_type="video/mp2t")
454
+
455
+ except requests.RequestException as e:
456
+ return f"Errore durante il download del segmento TS: {str(e)}", 500
457
+
458
+ @app.route('/proxy/key')
459
+ def proxy_key():
460
+ """Proxy per la chiave AES-128 con header personalizzati"""
461
+ key_url = request.args.get('url', '').strip()
462
+ if not key_url:
463
+ return "Errore: Parametro 'url' mancante per la chiave", 400
464
+
465
+ headers = {
466
+ unquote(key[2:]).replace("_", "-"): unquote(value).strip()
467
+ for key, value in request.args.items()
468
+ if key.lower().startswith("h_")
469
+ }
470
+
471
+ try:
472
+ response = requests.get(key_url, headers=headers, allow_redirects=True, timeout=(5, 15)) # Timeout connessione 5s, lettura 15s
473
+ response.raise_for_status()
474
+
475
+ return Response(response.content, content_type="application/octet-stream")
476
+
477
+ except requests.RequestException as e:
478
+ return f"Errore durante il download della chiave AES-128: {str(e)}", 500
479
+
480
+ @app.route('/playlist/channels.m3u8')
481
+ def playlist_channels():
482
+ """Gibt eine modifizierte Playlist mit Proxy-Links zurück"""
483
+ playlist_url = "https://raw.githubusercontent.com/MarkMCFC/NewDadProxy/refs/heads/main/channel.m3u8"
484
+
485
+ try:
486
+ host_url = request.host_url.rstrip('/')
487
+ response = requests.get(playlist_url, timeout=10)
488
+ response.raise_for_status()
489
+ playlist_content = response.text
490
+
491
+ modified_lines = []
492
+ for line in playlist_content.splitlines():
493
+ stripped_line = line.strip()
494
+ if stripped_line and not stripped_line.startswith('#'):
495
+ proxy_line = f"{host_url}/proxy/m3u?url={quote(stripped_line)}"
496
+ modified_lines.append(proxy_line)
497
+ else:
498
+ modified_lines.append(line)
499
+
500
+ modified_content = '\n'.join(modified_lines)
501
+ return Response(modified_content, content_type="application/vnd.apple.mpegurl")
502
+
503
+ except requests.RequestException as e:
504
+ return f"Fehler beim Laden der Playlist: {str(e)}", 500
505
+ except Exception as e:
506
+ return f"Allgemeiner Fehler: {str(e)}", 500
507
+
508
+
509
+ @app.route('/playlist/events.m3u8')
510
+ def playlist_events():
511
+ """Generiert die Events-Playlist mit Proxy-Links bei jedem Aufruf"""
512
+ try:
513
+ # Hole die aktuelle Host-URL
514
+ host_url = request.host_url.rstrip('/')
515
+
516
+ # Lade die Sendeplandaten
517
+ schedule_data = fetch_schedule_data()
518
+ if not schedule_data:
519
+ return "Fehler beim Abrufen der Sendeplandaten", 500
520
+
521
+ # Konvertiere JSON in M3U mit Proxy-Links
522
+ m3u_content = json_to_m3u(schedule_data, host_url)
523
+ if not m3u_content:
524
+ return "Fehler beim Generieren der Playlist", 500
525
+
526
+ return Response(m3u_content, content_type="application/vnd.apple.mpegurl")
527
+
528
+ except Exception as e:
529
+ print(f"Fehler in /playlist/events: {str(e)}")
530
+ return f"Interner Serverfehler: {str(e)}", 500
531
+
532
+ def fetch_schedule_data():
533
+ """Holt die aktuellen Sendeplandaten von der Website"""
534
+ url = "https://daddylive.dad/schedule/schedule-generated.php"
535
+ headers = {
536
+ "authority": "daddylive.dad",
537
+ "accept": "*/*",
538
+ "accept-encoding": "gzip, deflate, br, zstd",
539
+ "accept-language": "de-DE,de;q=0.9",
540
+ "priority": "u=1, i",
541
+ "referer": "https://daddylive.dad/",
542
+ "sec-ch-ua": '"Brave";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
543
+ "sec-ch-ua-mobile": "?0",
544
+ "sec-ch-ua-platform": '"Windows"',
545
+ "sec-fetch-dest": "empty",
546
+ "sec-fetch-mode": "cors",
547
+ "sec-fetch-site": "same-origin",
548
+ "sec-gpc": "1",
549
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
550
+ }
551
+
552
+ try:
553
+ response = requests.get(url, headers=headers, timeout=30)
554
+ if response.status_code == 200:
555
+ return response.json()
556
+ else:
557
+ print(f"Fehler beim Abrufen der Daten: Status-Code {response.status_code}")
558
+ return None
559
+ except Exception as e:
560
+ print(f"Fehler beim Abrufen der Daten: {e}")
561
+ return None
562
+
563
+ def json_to_m3u(data, host_url):
564
+ """Konvertiert JSON-Daten in M3U-Format mit Proxy-Links im gewünschten Format"""
565
+ if not data:
566
+ return None
567
+
568
+ m3u_content = '#EXTM3U\n\n'
569
+
570
+ try:
571
+ main_key = list(data.keys())[0]
572
+ categories = data[main_key]
573
+ except Exception as e:
574
+ print(f"Fehler beim Verarbeiten der JSON-Daten: {e}")
575
+ return None
576
+
577
+ for category_name, events in categories.items():
578
+ if not isinstance(events, list):
579
+ continue
580
+
581
+ for event in events:
582
+ if not isinstance(event, dict):
583
+ continue
584
+
585
+ group_title = event.get("event", "Unknown Event")
586
+ channels_list = []
587
+
588
+ for channel_key in ["channels", "channels2"]:
589
+ channels = event.get(channel_key, [])
590
+ if isinstance(channels, dict):
591
+ channels_list.extend(channels.values())
592
+ elif isinstance(channels, list):
593
+ channels_list.extend(channels)
594
+
595
+ for channel in channels_list:
596
+ if not isinstance(channel, dict):
597
+ continue
598
+
599
+ channel_name = channel.get("channel_name", "Unknown Channel")
600
+ channel_id = channel.get("channel_id", "0")
601
+
602
+ # Generiere die Stream-URL basierend auf der ID
603
+ try:
604
+ channel_id_int = int(channel_id)
605
+ if channel_id_int > 999:
606
+ stream_url = f"https://thedaddy.click/stream/bet.php?id=bet{channel_id}"
607
+ else:
608
+ stream_url = f"https://thedaddy.click/stream/stream-{channel_id}.php"
609
+ except (ValueError, TypeError):
610
+ stream_url = f"https://thedaddy.click/stream/stream-{channel_id}.php"
611
+
612
+ # Generiere den Proxy-Link im gewünschten Format
613
+ proxy_url = f"{host_url}/proxy/m3u?url={stream_url}"
614
+
615
+ m3u_content += (
616
+ f'#EXTINF:-1 tvg-id="{channel_name}" group-title="{group_title}",{channel_name}\n'
617
+ '#EXTVLCOPT:http-referrer=https://forcedtoplay.xyz/\n'
618
+ '#EXTVLCOPT:http-origin=https://forcedtoplay.xyz\n'
619
+ '#EXTVLCOPT:http-user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 17_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1\n'
620
+ f'{proxy_url}\n\n'
621
+ )
622
+
623
+ return m3u_content
624
+
625
+ @app.route('/')
626
+ def index():
627
+ """Pagina principale che mostra un messaggio di benvenuto"""
628
+ return "Proxy started!"
629
+
630
+ if __name__ == '__main__':
631
+ print("And Your In!")
632
+ app.run(host="0.0.0.0", port=7860, debug=False)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ flask
2
+ requests
3
+ gunicorn[gevent]