mcfc commited on
Commit
5bb7a8f
·
verified ·
1 Parent(s): 3b21961

Upload 4 files

Browse files
Files changed (4) hide show
  1. Dockerfile +32 -0
  2. README.md +162 -7
  3. app.py +486 -0
  4. requirements.txt +3 -0
Dockerfile ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Usa l'immagine base di Python
2
+ FROM python:3.12-slim
3
+
4
+ # Installa git e certificati SSL
5
+ RUN apt-get update && apt-get install -y \
6
+ git \
7
+ ca-certificates \
8
+ && rm -rf /var/lib/apt/lists/*
9
+
10
+ # Imposta la directory di lavoro
11
+ WORKDIR /app
12
+
13
+ # Clona il repository GitHub
14
+ RUN git clone https://github.com/nzo66/tvproxy .
15
+
16
+ # Installa le dipendenze
17
+ RUN pip install --upgrade pip
18
+ RUN pip install --no-cache-dir -r requirements.txt
19
+
20
+ # Espone la porta 7860 per Flask/Gunicorn
21
+ EXPOSE 7860
22
+
23
+ # Comando ottimizzato per avviare il server
24
+ CMD ["gunicorn", "app:app", \
25
+ "-w", "4", \
26
+ "--worker-class", "gevent", \
27
+ "--worker-connections", "100", \
28
+ "-b", "0.0.0.0:7860", \
29
+ "--timeout", "120", \
30
+ "--keep-alive", "5", \
31
+ "--max-requests", "1000", \
32
+ "--max-requests-jitter", "100"]
README.md CHANGED
@@ -1,10 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
- title: Newnewnew
3
- emoji: 🐠
4
- colorFrom: yellow
5
- colorTo: yellow
6
- sdk: docker
7
- pinned: false
 
 
 
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 📺 tvproxy
2
+
3
+ ## 🚀 M3U8 Proxy Dockerizzato
4
+
5
+ Un server proxy leggero basato su **Flask** e **Requests**, progettato per:
6
+
7
+ - 📥 Scaricare e modificare flussi **.m3u / .m3u8**
8
+ - 🔁 Proxare i segmenti `.ts`, mantenendo header personalizzati
9
+ - 🚫 Superare restrizioni come **Referer**, **User-Agent**, ecc.
10
+ - 🐳 Essere facilmente **dockerizzabile** su qualsiasi macchina o server
11
+
12
+ ---
13
+
14
+ ## ☁️ Deploy su Render
15
+
16
+ 1. Vai su **Projects → Deploy a Web Service → Public Git Repo**
17
+ 2. Inserisci il repo: `https://github.com/nzo66/tvproxy` → **Connect**
18
+ 3. Dai un nome a piacere
19
+ 4. Imposta **Instance Type** su `Free`
20
+ 5. Clicca su **Deploy Web Service**
21
+
22
  ---
23
+
24
+ ## 🤗 Deploy su HuggingFace
25
+
26
+ `ricora di fare factory rebuild per aggiornare il proxy se ci sono aggiornamenti!`
27
+
28
+ 1. Crea un nuovo **Space**
29
+ 2. Scegli un nome qualsiasi e imposta **Docker** come tipo
30
+ 3. Lascia **Public** e crea lo Space
31
+ 4. Vai in alto a destra → `⋮` → **Files** → carica **DockerfileHF** rinominandolo **Dockerfile**
32
+ 5. Infine vai su `⋮` → **Embed this Space** per ottenere il **Direct URL**
33
+
34
  ---
35
 
36
+ ## 🐳 Docker (Locale o Server)
37
+
38
+ ### ✅ Costruzione e Avvio
39
+
40
+ ```bash
41
+ git clone https://github.com/nzo66/tvproxy.git
42
+ cd tvproxy
43
+ docker build -t tvproxy .
44
+ docker run -d -p 7860:7860 --name tvproxy tvproxy
45
+ ```
46
+
47
+ ---
48
+
49
+ ## 🐧 Termux (Dispositivi Android)
50
+
51
+ ### ✅ Costruzione e Avvio
52
+
53
+ ```bash
54
+ pkg install git python -y
55
+ git clone https://github.com/nzo66/tvproxy.git
56
+ cd tvproxy
57
+ pip install -r requirements.txt'
58
+ gunicorn app:app -w 4 --worker-class gevent --worker-connections 100 -b 0.0.0.0:7860 --timeout 120 --keep-alive 5 --max-requests 1000 --max-requests-jitter 100
59
+ ```
60
+
61
+ ---
62
+
63
+ ## 🐍 Avvio con Python (Locale)
64
+
65
+ ### ✅ Setup e Avvio
66
+
67
+ ```bash
68
+ # Clona il repository
69
+ git clone https://github.com/nzo66/tvproxy.git
70
+ cd tvproxy
71
+
72
+ # Installa le dipendenze
73
+ pip install -r requirements.txt
74
+
75
+ # Avvia il server
76
+ gunicorn app:app -w 4 --worker-class gevent --worker-connections 100 -b 0.0.0.0:7860 --timeout 120 --keep-alive 5 --max-requests 1000 --max-requests-jitter 100
77
+ ```
78
+
79
+ ---
80
+
81
+ ## 🛠️ Gestione Docker
82
+
83
+ - 📄 Logs: `docker logs -f tvproxy`
84
+ - ⛔ Stop: `docker stop tvproxy`
85
+ - 🔄 Start: `docker start tvproxy`
86
+ - 🧹 Rimozione: `docker rm -f tvproxy`
87
+
88
+ ---
89
+
90
+ ## 🛠️ Come Utilizzare
91
+
92
+ Assicurati di sostituire i placeholder come `<server-ip>` con l'indirizzo IP o l'hostname effettivo del tuo server e `<URL_...>` con gli URL specifici.
93
+
94
+ ---
95
+
96
+ ### 1. Proxy per Liste M3U Complete 📡
97
+
98
+ Questo endpoint è progettato per proxare l'intera lista M3U. È particolarmente utile per garantire compatibilità e stabilità, con supporto menzionato per formati come Vavoo e Daddylive.
99
+
100
+ **Formato URL:**
101
+ ```text
102
+ http://<server-ip>:7860/proxy?url=<URL_LISTA_M3U>
103
+ ```
104
+
105
+ **Dove:**
106
+ - `<server-ip>`: L'indirizzo IP o hostname del tuo server proxy.
107
+ - `<URL_LISTA_M3U>`: L'URL completo della lista M3U che vuoi proxare.
108
+
109
+ > 📝 **Nota:** Questo endpoint è ideale per gestire l'intera collezione di flussi contenuta in un file M3U.
110
+
111
+ ---
112
+
113
+ ### 2. Proxy per Singoli Flussi M3U8 (con Headers Personalizzati) 📺✨
114
+
115
+ Questo endpoint è specifico per proxare singoli flussi video `.m3u8`. La sua caratteristica distintiva è la capacità di inoltrare headers HTTP personalizzati, essenziale per scenari che richiedono autenticazione specifica o per simulare richieste da client particolari.
116
+
117
+ **Formato URL Base:**
118
+ ```text
119
+ http://<server-ip>:7860/proxy/m3u?url=<URL_FLUSSO_M3U8>
120
+ ```
121
+
122
+ **Esempio:**
123
+ ```text
124
+ http://<server-ip>:7860/proxy/m3u?url=https://example.com/stream.m3u8
125
+ ```
126
+
127
+ **Dove:**
128
+ - `<server-ip>`: L'indirizzo IP o hostname del tuo server proxy.
129
+ - `<URL_FLUSSO_M3U8>`: L'URL completo del singolo flusso M3U8.
130
+
131
+ #### 🎯 Aggiungere Headers HTTP Personalizzati (Opzionale)
132
+
133
+ Per includere headers personalizzati nella richiesta al flusso M3U8, accodali all'URL del proxy. Ogni header deve essere prefissato da `&h_`, seguito dal nome dell'header, un segno di uguale (`=`), e il valore dell'header.
134
+
135
+ **Formato per gli Headers:**
136
+ ```text
137
+ &h_<NOME_HEADER>=<VALORE_HEADER>
138
+ ```
139
+
140
+ **Esempio con Headers Personalizzati:**
141
+ ```text
142
+ http://<server-ip>:7860/proxy/m3u?url=https://example.com/stream.m3u8&h_user-agent=Mozilla/5.0...&h_referer=https://ilovetoplay.xyz/&h_origin=https://ilovetoplay.xyz
143
+ ```
144
+
145
+ > ⚠️ **Attenzione:**
146
+ > - Ricorda di sostituire `Mozilla/5.0...` con lo User-Agent completo che intendi utilizzare.
147
+ > - Se i valori degli header contengono caratteri speciali (es. spazi, due punti), assicurati che siano correttamente URL-encoded per evitare errori.
148
+
149
+ ---
150
+
151
+ ## ✅ Caratteristiche
152
+
153
+ - 📁 Supporta **.m3u** e **.m3u8** automaticamente
154
+ - 🧾 Inoltra gli **HTTP Headers** necessari (Auth, Referer, etc.)
155
+ - 🔓 Supera restrizioni geografiche o di accesso
156
+ - ��️ Compatibile con **qualsiasi player IPTV**
157
+ - 🐳 Totalmente dockerizzato, pronto per il deploy
158
+ - 🐍 Avviabile anche direttamente con **Python**
159
+
160
+ ---
161
+
162
+ ## 🎉 Fine!
163
+
164
+ > Ora puoi guardare flussi M3U8 ovunque, senza restrizioni!
165
+ > Enjoy the Stream 🚀
app.py ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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('/stream/stream-', '/embed/stream-')
333
+ print(f"URL {m3u_url} trasformato da /stream/ 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: {str(e)}", 500
479
+
480
+ @app.route('/')
481
+ def index():
482
+ """Pagina principale che mostra un messaggio di benvenuto"""
483
+ return "Proxy started!"
484
+
485
+ if __name__ == '__main__':
486
+ 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]