331 lines
13 KiB
Python
331 lines
13 KiB
Python
from flask import Flask, request, Response, send_from_directory, jsonify
|
|
import requests
|
|
from flask_cors import CORS
|
|
import urllib.parse
|
|
from requests.adapters import HTTPAdapter
|
|
from urllib3.util import Retry
|
|
import yt_dlp
|
|
import io
|
|
from urllib.parse import urljoin
|
|
|
|
# Serve frontend static files under `/static` to avoid colliding with API routes
|
|
app = Flask(__name__, static_folder='../frontend', static_url_path='/static')
|
|
app.url_map.strict_slashes = False
|
|
|
|
# Use flask-cors for API routes
|
|
CORS(app, resources={r"/api/*": {"origins": "*"}})
|
|
|
|
# Configure a requests session with retries
|
|
session = requests.Session()
|
|
retries = Retry(total=2, backoff_factor=0.2, status_forcelist=(500, 502, 503, 504))
|
|
adapter = HTTPAdapter(max_retries=retries)
|
|
session.mount('http://', adapter)
|
|
session.mount('https://', adapter)
|
|
|
|
@app.route('/api/status', methods=['POST', 'GET'])
|
|
def proxy_status():
|
|
if request.method == 'POST':
|
|
# Safely get the json body
|
|
client_data = request.get_json() or {}
|
|
target_server = client_data.get('server')
|
|
else:
|
|
target_server = request.args.get('server')
|
|
|
|
if not target_server:
|
|
return jsonify({"error": "No server provided"}), 400
|
|
if target_server.endswith('/'):
|
|
target_server = target_server[:-1]
|
|
target_server = f"{target_server.strip()}/api/status"
|
|
# Validate target URL
|
|
parsed = urllib.parse.urlparse(target_server)
|
|
if parsed.scheme not in ('http', 'https') or not parsed.netloc:
|
|
return jsonify({"error": "Invalid target URL"}), 400
|
|
|
|
try:
|
|
# Forward a small set of safe request headers
|
|
safe_request_headers = {}
|
|
for k in ('User-Agent', 'Accept', 'Accept-Encoding', 'Accept-Language', 'Range'):
|
|
if k in request.headers:
|
|
safe_request_headers[k] = request.headers[k]
|
|
|
|
# Remove hop-by-hop request headers per RFC
|
|
for hop in ('Connection', 'Keep-Alive', 'Proxy-Authenticate', 'Proxy-Authorization', 'TE', 'Trailers', 'Transfer-Encoding', 'Upgrade'):
|
|
safe_request_headers.pop(hop, None)
|
|
|
|
# Stream the GET via a session with small retry policy
|
|
resp = session.get(target_server, headers=safe_request_headers, timeout=5, stream=True)
|
|
|
|
hop_by_hop = {
|
|
'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
|
|
'te', 'trailers', 'transfer-encoding', 'upgrade'
|
|
}
|
|
|
|
forwarded_headers = []
|
|
for name, value in resp.headers.items():
|
|
if name.lower() in hop_by_hop:
|
|
continue
|
|
if name.lower() == 'content-length':
|
|
# Let Flask set Content-Length if needed for the assembled response
|
|
continue
|
|
forwarded_headers.append((name, value))
|
|
|
|
def generate():
|
|
try:
|
|
for chunk in resp.iter_content(1024 * 16):
|
|
if chunk:
|
|
yield chunk
|
|
finally:
|
|
resp.close()
|
|
|
|
return Response(generate(), status=resp.status_code, headers=forwarded_headers)
|
|
except Exception as e:
|
|
return jsonify({"error": str(e)}), 500
|
|
|
|
@app.route('/api/videos', methods=['POST'])
|
|
def videos_proxy():
|
|
client_data = request.get_json() or {}
|
|
target_server = client_data.get('server')
|
|
client_data.pop('server', None) # Remove server from payload
|
|
if not target_server:
|
|
return jsonify({"error": "No server provided"}), 400
|
|
if target_server.endswith('/'):
|
|
target_server = target_server[:-1]
|
|
target_server = f"{target_server.strip()}/api/videos"
|
|
# Validate target URL
|
|
parsed = urllib.parse.urlparse(target_server)
|
|
if parsed.scheme not in ('http', 'https') or not parsed.netloc:
|
|
return jsonify({"error": "Invalid target URL"}), 400
|
|
|
|
try:
|
|
resp = session.post(target_server, json=client_data,timeout=5)
|
|
return Response(resp.content, status=resp.status_code, content_type=resp.headers.get('Content-Type', 'application/json'))
|
|
except Exception as e:
|
|
return jsonify({"error": str(e)}), 500
|
|
|
|
@app.route('/')
|
|
def index():
|
|
return send_from_directory(app.static_folder, 'index.html')
|
|
|
|
@app.route('/favicon.ico')
|
|
def favicon():
|
|
return send_from_directory(app.static_folder, 'favicon.ico')
|
|
|
|
@app.route('/api/stream', methods=['POST', 'GET', 'HEAD'])
|
|
def stream_video():
|
|
# Note: <video> tags perform GET. To support your POST requirement,
|
|
# we handle the URL via JSON post or URL params.
|
|
video_url = ""
|
|
if request.method == 'POST':
|
|
video_url = request.json.get('url')
|
|
else:
|
|
video_url = request.args.get('url')
|
|
|
|
if not video_url:
|
|
return jsonify({"error": "No URL provided"}), 400
|
|
|
|
def is_hls(url):
|
|
return '.m3u8' in urllib.parse.urlparse(url).path
|
|
|
|
def is_dash(url):
|
|
return urllib.parse.urlparse(url).path.lower().endswith('.mpd')
|
|
|
|
def guess_content_type(url):
|
|
path = urllib.parse.urlparse(url).path.lower()
|
|
if path.endswith('.m3u8'):
|
|
return 'application/vnd.apple.mpegurl'
|
|
if path.endswith('.mpd'):
|
|
return 'application/dash+xml'
|
|
if path.endswith('.mp4') or path.endswith('.m4v') or path.endswith('.m4s'):
|
|
return 'video/mp4'
|
|
if path.endswith('.webm'):
|
|
return 'video/webm'
|
|
if path.endswith('.ts'):
|
|
return 'video/mp2t'
|
|
if path.endswith('.mov'):
|
|
return 'video/quicktime'
|
|
if path.endswith('.m4a'):
|
|
return 'audio/mp4'
|
|
if path.endswith('.mp3'):
|
|
return 'audio/mpeg'
|
|
if path.endswith('.ogg') or path.endswith('.oga'):
|
|
return 'audio/ogg'
|
|
return None
|
|
|
|
def is_direct_media(url):
|
|
path = urllib.parse.urlparse(url).path.lower()
|
|
return any(path.endswith(ext) for ext in ('.mp4', '.m4v', '.m4s', '.ts', '.webm', '.mov'))
|
|
|
|
def proxy_response(target_url, content_type_override=None):
|
|
# Extract the base domain to spoof the referer
|
|
referer_override = request.args.get('referer')
|
|
if referer_override:
|
|
referer = referer_override
|
|
else:
|
|
parsed_uri = urllib.parse.urlparse(target_url)
|
|
referer = f"{parsed_uri.scheme}://{parsed_uri.netloc}/"
|
|
|
|
safe_request_headers = {
|
|
'User-Agent': request.headers.get('User-Agent'),
|
|
'Referer': referer, # Vital for bypassing CDN blocks
|
|
'Origin': referer
|
|
}
|
|
|
|
# Pass through Range headers so the browser can 'sniff' the video
|
|
if 'Range' in request.headers:
|
|
safe_request_headers['Range'] = request.headers['Range']
|
|
|
|
resp = session.get(target_url, headers=safe_request_headers, stream=True, timeout=30, allow_redirects=True)
|
|
|
|
hop_by_hop = {
|
|
'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
|
|
'te', 'trailers', 'transfer-encoding', 'upgrade'
|
|
}
|
|
|
|
forwarded_headers = []
|
|
response_content_type = None
|
|
for name, value in resp.headers.items():
|
|
if name.lower() in hop_by_hop:
|
|
continue
|
|
if name.lower() == 'content-length':
|
|
forwarded_headers.append((name, value))
|
|
continue
|
|
if name.lower() == 'content-type':
|
|
response_content_type = value
|
|
if name.lower() == 'content-type' and content_type_override:
|
|
continue
|
|
forwarded_headers.append((name, value))
|
|
|
|
if not content_type_override:
|
|
if not response_content_type or 'application/octet-stream' in response_content_type:
|
|
content_type_override = guess_content_type(target_url)
|
|
|
|
if content_type_override:
|
|
forwarded_headers.append(('Content-Type', content_type_override))
|
|
|
|
if request.method == 'HEAD':
|
|
resp.close()
|
|
return Response("", status=resp.status_code, headers=forwarded_headers)
|
|
|
|
def generate():
|
|
try:
|
|
for chunk in resp.iter_content(chunk_size=1024 * 16):
|
|
if chunk:
|
|
yield chunk
|
|
finally:
|
|
resp.close()
|
|
|
|
return Response(generate(), status=resp.status_code, headers=forwarded_headers)
|
|
|
|
def proxy_hls_playlist(playlist_url, referer_hint=None):
|
|
headers = {
|
|
'User-Agent': request.headers.get('User-Agent', 'Mozilla/5.0'),
|
|
'Accept': request.headers.get('Accept', '*/*')
|
|
}
|
|
resp = session.get(playlist_url, headers=headers, timeout=30)
|
|
resp.raise_for_status()
|
|
base_url = resp.url
|
|
if referer_hint:
|
|
referer = referer_hint
|
|
else:
|
|
referer = f"{urllib.parse.urlparse(base_url).scheme}://{urllib.parse.urlparse(base_url).netloc}/"
|
|
|
|
def proxied_url(target):
|
|
absolute = urljoin(base_url, target)
|
|
return f"/api/stream?url={urllib.parse.quote(absolute, safe='')}&referer={urllib.parse.quote(referer, safe='')}"
|
|
|
|
lines = resp.text.splitlines()
|
|
rewritten = []
|
|
for line in lines:
|
|
stripped = line.strip()
|
|
if not stripped or stripped.startswith('#'):
|
|
# Rewrite URI attributes inside tags (keys/maps)
|
|
if 'URI="' in line:
|
|
def repl(match):
|
|
uri = match.group(1)
|
|
return f'URI="{proxied_url(uri)}"'
|
|
import re
|
|
line = re.sub(r'URI="([^"]+)"', repl, line)
|
|
rewritten.append(line)
|
|
continue
|
|
rewritten.append(proxied_url(stripped))
|
|
if request.method == 'HEAD':
|
|
return Response("", status=200, content_type='application/vnd.apple.mpegurl')
|
|
|
|
body = "\n".join(rewritten)
|
|
return Response(body, status=200, content_type='application/vnd.apple.mpegurl')
|
|
|
|
if is_hls(video_url):
|
|
try:
|
|
referer_hint = request.args.get('referer')
|
|
if not referer_hint:
|
|
parsed = urllib.parse.urlparse(video_url)
|
|
referer_hint = f"{parsed.scheme}://{parsed.netloc}/"
|
|
return proxy_hls_playlist(video_url, referer_hint)
|
|
except Exception as e:
|
|
return jsonify({"error": str(e)}), 500
|
|
|
|
if is_direct_media(video_url):
|
|
try:
|
|
return proxy_response(video_url)
|
|
except Exception as e:
|
|
return jsonify({"error": str(e)}), 500
|
|
|
|
try:
|
|
# Configure yt-dlp options
|
|
ydl_opts = {
|
|
# 'format': 'best[protocol*=m3u8]/best[ext=mp4]/best',
|
|
'format_sort': ['res', 'fps', 'vcodec:avc1', 'acodec:aac'],
|
|
'quiet': False,
|
|
'no_warnings': False,
|
|
'socket_timeout': 30,
|
|
'retries': 3,
|
|
'fragment_retries': 3,
|
|
'http_headers': {
|
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
|
},
|
|
'skip_unavailable_fragments': True
|
|
}
|
|
|
|
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
|
# Extract the info
|
|
info = ydl.extract_info(video_url, download=False)
|
|
|
|
# Try to get the URL from the info dict (works for progressive downloads)
|
|
stream_url = info.get('url')
|
|
protocol = info.get('protocol')
|
|
|
|
# If no direct URL, try to get it from formats
|
|
if not stream_url and 'formats' in info:
|
|
# Find the best format that has a URL
|
|
for fmt in info['formats']:
|
|
if fmt.get('url'):
|
|
stream_url = fmt.get('url')
|
|
break
|
|
|
|
if not stream_url:
|
|
return jsonify({"error": "Could not extract stream URL"}), 500
|
|
|
|
referer_hint = None
|
|
if isinstance(info.get('http_headers'), dict):
|
|
referer_hint = info['http_headers'].get('Referer') or info['http_headers'].get('referer')
|
|
if not referer_hint:
|
|
parsed = urllib.parse.urlparse(video_url)
|
|
referer_hint = f"{parsed.scheme}://{parsed.netloc}/"
|
|
|
|
if protocol and 'm3u8' in protocol:
|
|
return proxy_hls_playlist(stream_url, referer_hint)
|
|
|
|
if is_hls(stream_url):
|
|
return proxy_hls_playlist(stream_url, referer_hint)
|
|
|
|
if is_dash(stream_url):
|
|
return proxy_response(stream_url, content_type_override='application/dash+xml')
|
|
|
|
return proxy_response(stream_url)
|
|
except Exception as e:
|
|
return jsonify({"error": str(e)}), 500
|
|
|
|
if __name__ == '__main__':
|
|
# threaded=True allows multiple segments to be proxied at once
|
|
app.run(host='0.0.0.0', port=5000, threaded=True)
|