Files
jacuzzi/backend/main.py
2026-02-09 16:28:01 +00:00

421 lines
16 KiB
Python

from flask import Flask, request, Response, send_from_directory, jsonify
import os
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('/api/image', methods=['GET', 'HEAD'])
def image_proxy():
image_url = request.args.get('url')
if not image_url:
return jsonify({"error": "No URL provided"}), 400
parsed = urllib.parse.urlparse(image_url)
if parsed.scheme not in ('http', 'https') or not parsed.netloc:
return jsonify({"error": "Invalid target URL"}), 400
try:
safe_request_headers = {}
for k in ('User-Agent', 'Accept', 'Accept-Encoding', 'Accept-Language'):
if k in request.headers:
safe_request_headers[k] = request.headers[k]
resp = session.get(image_url, headers=safe_request_headers, stream=True, timeout=15, allow_redirects=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
forwarded_headers.append((name, value))
if request.method == 'HEAD':
resp.close()
return Response("", status=resp.status_code, headers=forwarded_headers)
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('/')
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.
debug_param = os.getenv('STREAM_DEBUG', '').strip().lower()
debug_enabled = debug_param in ('1', 'true', 'yes', 'on')
cookie_param = os.getenv('STREAM_FORWARD_COOKIES', '').strip().lower()
forward_cookies = cookie_param in ('1', 'true', 'yes', 'on')
def dbg(message):
if debug_enabled:
app.logger.info("[stream_video] %s", message)
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
dbg(f"method={request.method} url={video_url}")
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 build_upstream_headers(referer):
headers = {
'User-Agent': request.headers.get('User-Agent'),
'Accept': request.headers.get('Accept'),
'Accept-Language': request.headers.get('Accept-Language'),
'Accept-Encoding': request.headers.get('Accept-Encoding'),
'Referer': referer,
'Origin': referer,
}
# Pass through fetch metadata and client hints when present
for key in (
'Sec-Fetch-Mode', 'Sec-Fetch-Site', 'Sec-Fetch-Dest', 'Sec-Fetch-User',
'Sec-CH-UA', 'Sec-CH-UA-Mobile', 'Sec-CH-UA-Platform', 'DNT'
):
if key in request.headers:
headers[key] = request.headers[key]
if forward_cookies and 'Cookie' in request.headers:
headers['Cookie'] = request.headers['Cookie']
dbg("forwarding cookies")
# Remove keys with None values
return {k: v for k, v in headers.items() if v}
def proxy_response(target_url, content_type_override=None, referer_override=None):
# Extract the base domain to spoof the referer
request_referer = request.args.get('referer')
if referer_override:
referer = referer_override
elif request_referer:
referer = request_referer
else:
parsed_uri = urllib.parse.urlparse(target_url)
referer = f"{parsed_uri.scheme}://{parsed_uri.netloc}/"
dbg(f"proxy_response target={target_url} referer={referer}")
safe_request_headers = build_upstream_headers(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)
if debug_enabled:
dbg(f"upstream status={resp.status_code} content_type={resp.headers.get('Content-Type')} content_length={resp.headers.get('Content-Length')}")
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))
dbg(f"content_type_override={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):
dbg(f"proxy_hls_playlist url={playlist_url} referer_hint={referer_hint}")
headers = build_upstream_headers(referer_hint or "")
if 'User-Agent' not in headers:
headers['User-Agent'] = 'Mozilla/5.0'
if 'Accept' not in headers:
headers['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:
dbg("detected input as hls")
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:
dbg("detected input as direct media")
return proxy_response(video_url)
except Exception as e:
return jsonify({"error": str(e)}), 500
try:
# Configure yt-dlp options
ydl_opts = {
# Prefer HLS when available to enable chunked streaming in the browser.
'format': 'best[protocol*=m3u8]/best[ext=mp4]/best',
'format_sort': ['res', 'fps', 'vcodec:avc1', 'acodec:aac'],
'quiet': False,
'no_warnings': False,
'http_headers': {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
},
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
# Extract the info
info = ydl.extract_info(video_url, download=False)
dbg(f"yt_dlp extractor={info.get('extractor')} protocol={info.get('protocol')}")
# 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}/"
dbg(f"resolved stream_url={stream_url} referer_hint={referer_hint}")
if protocol and 'm3u8' in protocol:
dbg("protocol indicates hls")
return proxy_hls_playlist(stream_url, referer_hint)
if is_hls(stream_url):
dbg("stream_url is hls")
return proxy_hls_playlist(stream_url, referer_hint)
if is_dash(stream_url):
dbg("stream_url is dash")
return proxy_response(stream_url, content_type_override='application/dash+xml', referer_override=referer_hint)
dbg("stream_url is direct media")
return proxy_response(stream_url, referer_override=referer_hint)
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)