basic functionality running

This commit is contained in:
Simon
2026-01-30 11:24:19 +00:00
parent 6762fb9513
commit 273e7c61f3
8 changed files with 293 additions and 125 deletions

View File

@@ -1,13 +0,0 @@
FROM python:3.9-slim
# Install yt-dlp and dependencies
RUN apt-get update && apt-get install -y ffmpeg curl && \
curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/local/bin/yt-dlp && \
chmod a+rx /usr/local/bin/yt-dlp
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "main.py"]

View File

@@ -1,10 +1,26 @@
from flask import Flask, request, Response, send_from_directory, jsonify
import subprocess
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
app = Flask(__name__, static_folder='../frontend', static_url_path='')
# 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':
@@ -16,15 +32,74 @@ def proxy_status():
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:
# Use the data gathered above
response = requests.post(target_server, json=client_data if request.method == 'POST' else {}, timeout=5)
return (response.content, response.status_code, response.headers.items())
# 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():
@@ -39,24 +114,64 @@ def stream_video():
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 generate():
# yt-dlp command to get the stream and pipe to stdout
cmd = [
'yt-dlp',
'-o', '-', # output to stdout
'-f', 'best[ext=mp4]/best',
video_url
]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
try:
while True:
chunk = process.stdout.read(1024 * 16)
if not chunk:
break
yield chunk
finally:
process.kill()
# Configure yt-dlp options
ydl_opts = {
'format': 'best[ext=mp4]/best[vcodec^=avc1]/best[vcodec^=vp]/best',
'quiet': True,
'no_warnings': True,
'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')
format_id = info.get('format_id')
# 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:
yield b"Error: Could not extract stream URL"
return
# Prepare headers for the stream request
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
# Add any cookies or authentication headers from yt-dlp
if 'http_headers' in info:
headers.update(info['http_headers'])
# Stream the video from the extracted URL
resp = session.get(stream_url, headers=headers, stream=True, timeout=30, allow_redirects=True)
resp.raise_for_status()
for chunk in resp.iter_content(chunk_size=1024 * 16):
if chunk:
yield chunk
except Exception as e:
yield f"Error: {str(e)}".encode()
return Response(generate(), mimetype='video/mp4')

View File

@@ -3,6 +3,7 @@ certifi==2026.1.4
charset-normalizer==3.4.4
click==8.3.1
Flask==3.1.2
Flask-Cors==4.0.0
idna==3.11
itsdangerous==2.2.0
Jinja2==3.1.6
@@ -11,3 +12,4 @@ MarkupSafe==3.0.3
requests==2.32.5
urllib3==2.6.3
Werkzeug==3.1.5
yt-dlp==2026.1.29