mcfc commited on
Commit
2072924
·
verified ·
1 Parent(s): 21c5d70

Upload 3 files

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