Download api/video_proxy.py from QBANK/OFTQUEST: direct link, hf CLI and curl.
- Browser
- Download file 26.1 kB
-
https://huggingface.co/spaces/QBANK/OFTQUEST/resolve/main/api/video_proxy.py
- Command line
-
hf download hf://spaces/QBANK/OFTQUEST/api/video_proxy.py
-
curl -L -o video_proxy.py https://huggingface.co/spaces/QBANK/OFTQUEST/resolve/main/api/video_proxy.py
26.1 kB
| """ | |
| Video Proxy - Serves local video files with advanced DRM-like protection. | |
| Uses HMAC-signed tokens, session binding, rate limiting, anti-bot validation, | |
| chunked streaming with token rotation, and watermarked player pages. | |
| """ | |
| import os | |
| import time | |
| import json | |
| import hmac | |
| import hashlib | |
| import base64 | |
| import secrets | |
| import threading | |
| import mimetypes | |
| from collections import defaultdict | |
| from flask import Blueprint, request, jsonify, make_response, g, send_file, Response | |
| from auth.middleware import require_auth | |
| from auth.session_manager import validate_session | |
| from config import Config | |
| video_bp = Blueprint('video', __name__, url_prefix='/api') | |
| # ===== Configuration ===== | |
| TOKEN_EXPIRY = 600 # seconds (10 min — generous for slow connections / seeking) | |
| CHUNK_ROTATION_BYTES = 500 * 1024 * 1024 # 500MB — effectively disabled for normal videos | |
| RATE_LIMIT_TOKENS_PER_MIN = 15 # generous to allow multi-video pages + rotation | |
| MAX_CONCURRENT_STREAMS = 5 | |
| RATE_WINDOW = 60 # seconds | |
| # ===== In-memory stores ===== | |
| # {token_id: {payload, created, bytes_served, active_stream}} | |
| _video_tokens = {} | |
| # Rate limiting: {user_id: [timestamps]} | |
| _token_request_times = defaultdict(list) | |
| # Active streams: {user_id: set(token_ids)} | |
| _active_streams = defaultdict(set) | |
| # Lock for thread-safe access | |
| _lock = threading.Lock() | |
| def _get_secret_key(): | |
| """Get the signing key from config.""" | |
| return (Config.SECRET_KEY or 'change-me-in-production-use-secrets-token').encode('utf-8') | |
| def _hash_user_agent(ua): | |
| """Hash user agent to a short fingerprint.""" | |
| if not ua: | |
| return '' | |
| return hashlib.sha256(ua.encode('utf-8')).hexdigest()[:16] | |
| def _get_client_ip(): | |
| """Extract client IP from request.""" | |
| ip = request.headers.get('X-Forwarded-For', request.remote_addr) or '0.0.0.0' | |
| if ',' in ip: | |
| ip = ip.split(',')[0].strip() | |
| return ip | |
| def _sign_token(payload_dict): | |
| """Create an HMAC-signed token from a payload dict. | |
| Format: base64url(json_payload).base64url(hmac_signature) | |
| """ | |
| payload_json = json.dumps(payload_dict, separators=(',', ':'), sort_keys=True) | |
| payload_b64 = base64.urlsafe_b64encode(payload_json.encode('utf-8')).rstrip(b'=').decode('ascii') | |
| signature = hmac.new(_get_secret_key(), payload_b64.encode('utf-8'), hashlib.sha256).digest() | |
| sig_b64 = base64.urlsafe_b64encode(signature).rstrip(b'=').decode('ascii') | |
| return f"{payload_b64}.{sig_b64}" | |
| def _verify_token(token_str): | |
| """Verify an HMAC-signed token. Returns payload dict or None.""" | |
| if not token_str or '.' not in token_str: | |
| return None | |
| parts = token_str.rsplit('.', 1) | |
| if len(parts) != 2: | |
| return None | |
| payload_b64, sig_b64 = parts | |
| # Recompute signature | |
| expected_sig = hmac.new(_get_secret_key(), payload_b64.encode('utf-8'), hashlib.sha256).digest() | |
| expected_b64 = base64.urlsafe_b64encode(expected_sig).rstrip(b'=').decode('ascii') | |
| if not hmac.compare_digest(sig_b64, expected_b64): | |
| return None | |
| # Decode payload | |
| try: | |
| padding = 4 - len(payload_b64) % 4 | |
| if padding != 4: | |
| payload_b64 += '=' * padding | |
| payload_json = base64.urlsafe_b64decode(payload_b64.encode('utf-8')).decode('utf-8') | |
| return json.loads(payload_json) | |
| except Exception: | |
| return None | |
| def _cleanup_stores(): | |
| """Periodically clean up expired tokens and rate limit entries.""" | |
| now = time.time() | |
| with _lock: | |
| # Clean expired tokens | |
| expired = [k for k, v in _video_tokens.items() if now - v['created'] > TOKEN_EXPIRY * 3] | |
| for k in expired: | |
| entry = _video_tokens.pop(k, None) | |
| if entry: | |
| uid = entry.get('user_id') | |
| if uid and k in _active_streams.get(uid, set()): | |
| _active_streams[uid].discard(k) | |
| # Clean rate limit windows | |
| for uid in list(_token_request_times.keys()): | |
| _token_request_times[uid] = [t for t in _token_request_times[uid] if now - t < RATE_WINDOW] | |
| if not _token_request_times[uid]: | |
| del _token_request_times[uid] | |
| # Clean empty active stream sets | |
| for uid in list(_active_streams.keys()): | |
| # Remove token IDs no longer in _video_tokens | |
| _active_streams[uid] = {tid for tid in _active_streams[uid] if tid in _video_tokens} | |
| if not _active_streams[uid]: | |
| del _active_streams[uid] | |
| def _check_rate_limit(user_id): | |
| """Check if user has exceeded token request rate limit. Returns True if OK.""" | |
| now = time.time() | |
| with _lock: | |
| times = _token_request_times[user_id] | |
| times = [t for t in times if now - t < RATE_WINDOW] | |
| _token_request_times[user_id] = times | |
| if len(times) >= RATE_LIMIT_TOKENS_PER_MIN: | |
| return False | |
| _token_request_times[user_id].append(now) | |
| return True | |
| def _check_concurrent_streams(user_id): | |
| """Check if user has exceeded max concurrent streams. Returns True if OK.""" | |
| with _lock: | |
| active = _active_streams.get(user_id, set()) | |
| # Only count tokens that are still valid | |
| now = time.time() | |
| valid_active = set() | |
| for tid in active: | |
| entry = _video_tokens.get(tid) | |
| if entry and entry.get('active_stream') and now - entry['created'] < TOKEN_EXPIRY * 3: | |
| valid_active.add(tid) | |
| _active_streams[user_id] = valid_active | |
| return len(valid_active) < MAX_CONCURRENT_STREAMS | |
| def _register_stream(user_id, token_id): | |
| """Mark a stream as active.""" | |
| with _lock: | |
| _video_tokens[token_id]['active_stream'] = True | |
| _active_streams[user_id].add(token_id) | |
| def _unregister_stream(user_id, token_id): | |
| """Mark a stream as inactive.""" | |
| with _lock: | |
| entry = _video_tokens.get(token_id) | |
| if entry: | |
| entry['active_stream'] = False | |
| _active_streams.get(user_id, set()).discard(token_id) | |
| # ===== Routes ===== | |
| def create_video_token(): | |
| """Create an HMAC-signed, session-bound video token.""" | |
| data = request.get_json() | |
| if not data or 'filename' not in data: | |
| return jsonify({'error': 'Filename required'}), 400 | |
| filename = data['filename'] | |
| user = g.current_user | |
| session = g.current_session | |
| user_id = user.get('id', 0) if user else 0 | |
| _cleanup_stores() | |
| # --- Rate Limiting --- | |
| if not _check_rate_limit(user_id): | |
| return jsonify({'error': 'Muitas solicitacoes. Aguarde um momento.'}), 429 | |
| # --- Concurrent stream check --- | |
| if not _check_concurrent_streams(user_id): | |
| return jsonify({'error': 'Limite de streams simultaneos atingido.'}), 429 | |
| # --- Session validation (ensure session is still active) --- | |
| session_token = g.token | |
| session_user, session_obj = validate_session(session_token) | |
| if not session_user: | |
| return jsonify({'error': 'Sessao invalida. Faca login novamente.'}), 401 | |
| session_id = session.get('id', 0) | |
| # --- Build HMAC-signed token --- | |
| client_ip = _get_client_ip() | |
| ua_hash = _hash_user_agent(request.headers.get('User-Agent', '')) | |
| token_id = secrets.token_urlsafe(16) # unique ID for internal tracking | |
| payload = { | |
| 'tid': token_id, | |
| 'uid': user_id, | |
| 'email': user.get('email', '') if user else '', | |
| 'ip': client_ip, | |
| 'uah': ua_hash, | |
| 'ts': int(time.time()), | |
| 'fn': filename, | |
| 'sid': session_id, | |
| } | |
| signed_token = _sign_token(payload) | |
| # Store server-side state for stream tracking | |
| with _lock: | |
| _video_tokens[token_id] = { | |
| 'user_id': user_id, | |
| 'user_email': user.get('email', '') if user else '', | |
| 'user_name': user.get('display_name', '') if user else '', | |
| 'filename': filename, | |
| 'session_id': session_id, | |
| 'session_token': session_token, | |
| 'created': time.time(), | |
| 'bytes_served': 0, | |
| 'active_stream': False, | |
| 'rotation_required': False, | |
| } | |
| return jsonify({'token': signed_token, 'expires_in': TOKEN_EXPIRY}) | |
| def serve_video_player(token): | |
| """Serve an isolated HTML page with the video player, watermarks, and advanced protections.""" | |
| _cleanup_stores() | |
| # --- Verify HMAC signature --- | |
| payload = _verify_token(token) | |
| if not payload: | |
| return _error_page('Token invalido ou adulterado'), 403 | |
| # --- Check expiry --- | |
| token_age = int(time.time()) - payload.get('ts', 0) | |
| if token_age > TOKEN_EXPIRY: | |
| return _error_page('Token expirado'), 403 | |
| token_id = payload.get('tid', '') | |
| entry = _video_tokens.get(token_id) | |
| if not entry: | |
| return _error_page('Token nao encontrado'), 403 | |
| # --- Session validation --- | |
| session_token = entry.get('session_token', '') | |
| if session_token: | |
| session_user, session_obj = validate_session(session_token) | |
| if not session_user: | |
| with _lock: | |
| _video_tokens.pop(token_id, None) | |
| return _error_page('Sessao expirada. Faca login novamente.'), 403 | |
| filename = payload.get('fn', '') | |
| _user_email = entry.get('user_email', '') | |
| _user_name = entry.get('user_name', '') or (_user_email.split('@')[0] if _user_email else '---') | |
| _ip = _get_client_ip() | |
| wm_text = f"{_user_name} | {_user_email} | IP: {_ip}" | |
| # Generate a unique player session ID for anti-bot header | |
| player_session = secrets.token_urlsafe(24) | |
| # Build video URL pointing to our secure media endpoint | |
| video_url = f"/api/video-stream/{token}" | |
| # Origin for referer check | |
| origin = request.host_url.rstrip('/') | |
| html = f'''<!DOCTYPE html> | |
| <html><head> | |
| <meta charset="UTF-8"> | |
| <meta name="robots" content="noindex,nofollow"> | |
| <style> | |
| * {{ margin:0; padding:0; box-sizing:border-box; }} | |
| body {{ background:#000; overflow:hidden; }} | |
| .vp {{ position:relative; width:100vw; height:100vh; }} | |
| .vp video {{ width:100%; height:100%; object-fit:contain; }} | |
| [id*="IDM"],[id*="idm"],[class*="IDM"],[class*="idm"], | |
| [id*="EagleGet"],[class*="eagleget"],[id*="xdm"],[class*="xdm"] {{ | |
| display:none!important; visibility:hidden!important; | |
| width:0!important; height:0!important; | |
| }} | |
| .wm {{ position:fixed; pointer-events:none; z-index:9999; | |
| font: 700 14px sans-serif; color:rgba(255,255,255,0.22); | |
| transform:rotate(-25deg); white-space:nowrap; | |
| user-select:none; -webkit-user-select:none; }} | |
| #cv-overlay {{ position:fixed; top:0; left:0; width:100vw; height:100vh; | |
| pointer-events:none; z-index:9998; opacity:0.08; }} | |
| </style> | |
| </head><body> | |
| <div class="vp"> | |
| <video id="vplayer" controls controlslist="nodownload noplaybackrate" disablepictureinpicture | |
| oncontextmenu="return false;" preload="metadata"> | |
| </video> | |
| </div> | |
| <canvas id="cv-overlay"></canvas> | |
| <div class="wm" style="top:6%;left:3%">{wm_text}</div> | |
| <div class="wm" style="top:6%;left:55%">{wm_text}</div> | |
| <div class="wm" style="top:30%;left:20%">{wm_text}</div> | |
| <div class="wm" style="top:30%;left:70%">{wm_text}</div> | |
| <div class="wm" style="top:55%;left:5%">{wm_text}</div> | |
| <div class="wm" style="top:55%;left:50%">{wm_text}</div> | |
| <div class="wm" style="top:80%;left:15%">{wm_text}</div> | |
| <div class="wm" style="top:80%;left:65%">{wm_text}</div> | |
| <script> | |
| (function() {{ | |
| "use strict"; | |
| // ===== Configuration ===== | |
| var PLAYER_SESSION = "{player_session}"; | |
| var CURRENT_TOKEN = "{token}"; | |
| var FILENAME = "{filename}"; | |
| var SESSION_TOKEN = "{entry.get('session_token', '')}"; | |
| var ORIGIN = "{origin}"; | |
| var WM_TEXT = "{wm_text}"; | |
| // ===== Anti-download: block blob URL interception ===== | |
| var _origCreateObjectURL = URL.createObjectURL; | |
| URL.createObjectURL = function(obj) {{ | |
| if (obj instanceof Blob && obj.type && obj.type.startsWith('video/')) {{ | |
| console.warn('Blob URL creation blocked for video content'); | |
| return 'about:blank'; | |
| }} | |
| return _origCreateObjectURL.call(URL, obj); | |
| }}; | |
| // ===== Block video.src access from console ===== | |
| var vid = document.getElementById('vplayer'); | |
| var _realSrc = ''; | |
| function loadVideoWithToken(tkn) {{ | |
| _realSrc = "/api/video-stream/" + tkn; | |
| var currentTime = vid.currentTime || 0; | |
| var wasPlaying = !vid.paused; | |
| vid.innerHTML = ''; | |
| var src = document.createElement('source'); | |
| src.type = 'video/mp4'; | |
| src.src = _realSrc; | |
| vid.appendChild(src); | |
| vid.load(); | |
| // Restore playback position after token rotation | |
| if (currentTime > 1) {{ | |
| vid.addEventListener('loadedmetadata', function onMeta() {{ | |
| vid.removeEventListener('loadedmetadata', onMeta); | |
| vid.currentTime = currentTime; | |
| if (wasPlaying) vid.play().catch(function(){{}}); | |
| }}); | |
| }} | |
| }} | |
| // Override src getter to hide URL | |
| try {{ | |
| Object.defineProperty(vid, 'currentSrc', {{ | |
| get: function() {{ return ''; }}, | |
| configurable: false | |
| }}); | |
| }} catch(e) {{}} | |
| // ===== Token rotation every 4 minutes ===== | |
| var TOKEN_ROTATE_MS = 240000; | |
| function rotateToken() {{ | |
| fetch('/api/video-token', {{ | |
| method: 'POST', | |
| headers: {{ | |
| 'Content-Type': 'application/json', | |
| 'Authorization': 'Bearer ' + SESSION_TOKEN, | |
| 'X-Player-Session': PLAYER_SESSION | |
| }}, | |
| body: JSON.stringify({{ filename: FILENAME }}) | |
| }}) | |
| .then(function(r) {{ return r.json(); }}) | |
| .then(function(data) {{ | |
| if (data.token) {{ | |
| CURRENT_TOKEN = data.token; | |
| // Update the video source so seeking/buffering uses the fresh token | |
| loadVideoWithToken(CURRENT_TOKEN); | |
| }} | |
| }}) | |
| .catch(function(e) {{ /* silent */ }}); | |
| }} | |
| setInterval(rotateToken, TOKEN_ROTATE_MS); | |
| // ===== Handle video errors — retry with fresh token ===== | |
| vid.addEventListener('error', function() {{ | |
| console.warn('Video error, attempting token refresh...'); | |
| rotateToken(); | |
| }}); | |
| // ===== Canvas watermark overlay ===== | |
| var canvas = document.getElementById('cv-overlay'); | |
| var ctx = canvas.getContext('2d'); | |
| function drawWatermark() {{ | |
| canvas.width = window.innerWidth; | |
| canvas.height = window.innerHeight; | |
| ctx.clearRect(0, 0, canvas.width, canvas.height); | |
| ctx.save(); | |
| ctx.font = '14px sans-serif'; | |
| ctx.fillStyle = 'rgba(255,255,255,0.15)'; | |
| ctx.translate(canvas.width / 2, canvas.height / 2); | |
| ctx.rotate(-25 * Math.PI / 180); | |
| for (var y = -canvas.height; y < canvas.height; y += 120) {{ | |
| for (var x = -canvas.width; x < canvas.width; x += 400) {{ | |
| ctx.fillText(WM_TEXT, x, y); | |
| }} | |
| }} | |
| ctx.restore(); | |
| }} | |
| drawWatermark(); | |
| window.addEventListener('resize', drawWatermark); | |
| // Redraw periodically in case someone tries to clear the canvas | |
| setInterval(drawWatermark, 2000); | |
| // ===== Context menu / keyboard blocking ===== | |
| document.addEventListener('contextmenu', function(e) {{ e.preventDefault(); }}); | |
| document.addEventListener('keydown', function(e) {{ | |
| if (e.key === 'F12' || | |
| (e.ctrlKey && e.shiftKey && 'IJC'.includes(e.key.toUpperCase())) || | |
| (e.ctrlKey && e.key.toLowerCase() === 's') || | |
| (e.ctrlKey && e.key.toLowerCase() === 'u')) | |
| {{ e.preventDefault(); e.stopPropagation(); }} | |
| }}); | |
| // ===== IDM/download manager removal ===== | |
| setInterval(function() {{ | |
| document.querySelectorAll('[id*="IDM"],[id*="idm"],[class*="IDM"],[class*="idm"],[id*="EagleGet"],[class*="xdm"]') | |
| .forEach(function(el) {{ el.remove(); }}); | |
| }}, 300); | |
| // ===== Initialize video ===== | |
| loadVideoWithToken(CURRENT_TOKEN); | |
| }})(); | |
| </script> | |
| </body></html>''' | |
| response = make_response(html) | |
| response.headers['Content-Type'] = 'text/html; charset=utf-8' | |
| response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate' | |
| response.headers['X-Frame-Options'] = 'SAMEORIGIN' | |
| response.headers['X-Content-Type-Options'] = 'nosniff' | |
| response.headers['Referrer-Policy'] = 'same-origin' | |
| # Set the player session cookie for anti-bot validation | |
| response.set_cookie('_vps', player_session, httponly=True, samesite='Strict', max_age=TOKEN_EXPIRY * 3) | |
| return response | |
| def stream_video(token): | |
| """Stream the actual video file with advanced validation.""" | |
| _cleanup_stores() | |
| # --- Verify HMAC signature --- | |
| payload = _verify_token(token) | |
| if not payload: | |
| return jsonify({'error': 'Token invalido'}), 403 | |
| # --- Check expiry (use 3x for streaming to allow seeking) --- | |
| token_age = int(time.time()) - payload.get('ts', 0) | |
| if token_age > TOKEN_EXPIRY * 3: | |
| return jsonify({'error': 'Token expirado'}), 403 | |
| token_id = payload.get('tid', '') | |
| entry = _video_tokens.get(token_id) | |
| if not entry: | |
| return jsonify({'error': 'Token nao encontrado'}), 403 | |
| # --- IP check (relaxed — CDN/proxy can change IPs mid-session) --- | |
| # Only log mismatches; do NOT reject, as Cloudflare tunnels cause IP drift | |
| client_ip = _get_client_ip() | |
| if payload.get('ip') and payload['ip'] != client_ip: | |
| import logging | |
| logging.getLogger(__name__).debug( | |
| f"Video stream IP drift: token={payload['ip']} current={client_ip} user={payload.get('uid')}" | |
| ) | |
| # --- User-Agent hash check (relaxed — some browsers update UA between requests) --- | |
| # Only log; do NOT reject | |
| current_ua_hash = _hash_user_agent(request.headers.get('User-Agent', '')) | |
| if payload.get('uah') and payload['uah'] != current_ua_hash: | |
| import logging | |
| logging.getLogger(__name__).debug( | |
| f"Video stream UA drift: user={payload.get('uid')}" | |
| ) | |
| # --- Session validation --- | |
| session_token = entry.get('session_token', '') | |
| if session_token: | |
| session_user, session_obj = validate_session(session_token) | |
| if not session_user: | |
| with _lock: | |
| _video_tokens.pop(token_id, None) | |
| return jsonify({'error': 'Sessao expirada'}), 403 | |
| # --- Anti-bot: Referer check (relaxed for initial load) --- | |
| referer = request.headers.get('Referer', '') | |
| if referer: | |
| # If referer is present, it must be from our domain | |
| if not referer.startswith(request.host_url) and not referer.startswith('/'): | |
| return jsonify({'error': 'Acesso negado'}), 403 | |
| # --- Anti-bot: Cookie check --- | |
| player_session_cookie = request.cookies.get('_vps', '') | |
| # We allow the first request without cookie (initial video load sets it) | |
| # but if a cookie is present it should be non-empty | |
| # This is a soft check to not break the flow | |
| # --- Concurrent streams --- | |
| user_id = payload.get('uid', 0) | |
| if not entry.get('active_stream'): | |
| if not _check_concurrent_streams(user_id): | |
| return jsonify({'error': 'Limite de streams simultaneos atingido'}), 429 | |
| _register_stream(user_id, token_id) | |
| # --- Token rotation flag (informational only) --- | |
| # NOTE: Previously this returned 403 mid-stream, which broke playback because | |
| # the HTML5 video element cannot handle mid-stream auth failures gracefully. | |
| # Now we just log it and let the stream continue. | |
| filename = payload.get('fn', '') | |
| safe_name = os.path.basename(filename) | |
| # Try local file first | |
| video_path = os.path.join(Config.MEDIA_DIR, safe_name) | |
| if os.path.exists(video_path): | |
| return _stream_local_video(video_path, token_id, user_id) | |
| # Fallback: stream from Telegram | |
| return _stream_telegram_video(safe_name, token_id, user_id) | |
| def _stream_local_video(video_path, token_id, user_id): | |
| """Stream video from local filesystem with Range support and byte tracking.""" | |
| file_size = os.path.getsize(video_path) | |
| range_header = request.headers.get('Range') | |
| if range_header: | |
| byte_start = 0 | |
| byte_end = file_size - 1 | |
| match = range_header.replace('bytes=', '').split('-') | |
| byte_start = int(match[0]) if match[0] else 0 | |
| if match[1]: | |
| byte_end = int(match[1]) | |
| content_length = byte_end - byte_start + 1 | |
| def generate(): | |
| try: | |
| with open(video_path, 'rb') as f: | |
| f.seek(byte_start) | |
| remaining = content_length | |
| chunk_size = 1024 * 1024 | |
| total_sent = 0 | |
| while remaining > 0: | |
| read_size = min(chunk_size, remaining) | |
| data = f.read(read_size) | |
| if not data: | |
| break | |
| remaining -= len(data) | |
| total_sent += len(data) | |
| yield data | |
| # Track bytes served for rotation | |
| with _lock: | |
| entry = _video_tokens.get(token_id) | |
| if entry: | |
| entry['bytes_served'] = entry.get('bytes_served', 0) + len(data) | |
| if entry['bytes_served'] >= CHUNK_ROTATION_BYTES: | |
| entry['rotation_required'] = True | |
| finally: | |
| _unregister_stream(user_id, token_id) | |
| response = Response(generate(), status=206, mimetype='video/mp4') | |
| response.headers['Content-Range'] = f'bytes {byte_start}-{byte_end}/{file_size}' | |
| response.headers['Content-Length'] = content_length | |
| response.headers['Accept-Ranges'] = 'bytes' | |
| else: | |
| def generate_full(): | |
| try: | |
| with open(video_path, 'rb') as f: | |
| chunk_size = 1024 * 1024 | |
| while True: | |
| data = f.read(chunk_size) | |
| if not data: | |
| break | |
| yield data | |
| with _lock: | |
| entry = _video_tokens.get(token_id) | |
| if entry: | |
| entry['bytes_served'] = entry.get('bytes_served', 0) + len(data) | |
| if entry['bytes_served'] >= CHUNK_ROTATION_BYTES: | |
| entry['rotation_required'] = True | |
| finally: | |
| _unregister_stream(user_id, token_id) | |
| response = Response(generate_full(), status=200, mimetype='video/mp4') | |
| response.headers['Content-Length'] = file_size | |
| response.headers['Accept-Ranges'] = 'bytes' | |
| response.headers['Cache-Control'] = 'no-store' | |
| response.headers['Content-Disposition'] = 'inline' | |
| return response | |
| def _stream_telegram_video(filename, token_id, user_id): | |
| """Stream video from Telegram via media API.""" | |
| from models.database import get_db | |
| import re | |
| db = get_db() | |
| media = db.execute( | |
| "SELECT * FROM media_files WHERE filename = ?", (filename,) | |
| ).fetchone() | |
| if not media: | |
| _unregister_stream(user_id, token_id) | |
| return jsonify({'error': 'Video nao encontrado'}), 404 | |
| message_id = media['telegram_message_id'] | |
| size_bytes = media['size_bytes'] or 0 | |
| if not message_id: | |
| _unregister_stream(user_id, token_id) | |
| return jsonify({'error': 'Video nao disponivel para streaming'}), 404 | |
| try: | |
| from telegram_client import TelegramStreamer | |
| streamer = TelegramStreamer.get_instance() | |
| if not streamer or not streamer.is_ready(): | |
| _unregister_stream(user_id, token_id) | |
| return jsonify({'error': 'Telegram nao disponivel'}), 503 | |
| except ImportError: | |
| _unregister_stream(user_id, token_id) | |
| return jsonify({'error': 'Telegram nao configurado'}), 503 | |
| range_header = request.headers.get('Range') | |
| start = 0 | |
| end = size_bytes - 1 if size_bytes > 0 else 0 | |
| status = 200 | |
| if range_header and size_bytes > 0: | |
| range_match = re.match(r'bytes=(\d+)-(\d*)', range_header) | |
| if range_match: | |
| start = int(range_match.group(1)) | |
| end = min(int(range_match.group(2)), size_bytes - 1) if range_match.group(2) else size_bytes - 1 | |
| status = 206 | |
| content_length = end - start + 1 | |
| chunk_size = 1024 * 1024 | |
| def generate(): | |
| try: | |
| offset = start | |
| remaining = content_length | |
| while remaining > 0: | |
| read_size = min(chunk_size, remaining) | |
| chunk = streamer.get_file_chunk(message_id, offset=offset, limit=read_size) | |
| if not chunk: | |
| break | |
| yield chunk | |
| offset += len(chunk) | |
| remaining -= len(chunk) | |
| # Track bytes for rotation | |
| with _lock: | |
| entry = _video_tokens.get(token_id) | |
| if entry: | |
| entry['bytes_served'] = entry.get('bytes_served', 0) + len(chunk) | |
| if entry['bytes_served'] >= CHUNK_ROTATION_BYTES: | |
| entry['rotation_required'] = True | |
| if len(chunk) < read_size: | |
| break | |
| finally: | |
| _unregister_stream(user_id, token_id) | |
| response_headers = { | |
| 'Content-Type': 'video/mp4', | |
| 'Accept-Ranges': 'bytes', | |
| 'Content-Length': str(content_length), | |
| 'Cache-Control': 'no-store', | |
| 'Content-Disposition': 'inline', | |
| } | |
| if status == 206: | |
| response_headers['Content-Range'] = f'bytes {start}-{end}/{size_bytes}' | |
| from flask import stream_with_context | |
| return Response(stream_with_context(generate()), status=status, headers=response_headers) | |
| def _error_page(msg): | |
| html = f'''<!DOCTYPE html><html><body style="background:#000;color:#fff; | |
| display:flex;align-items:center;justify-content:center;height:100vh; | |
| font-family:sans-serif"><h2>{msg}</h2></body></html>''' | |
| resp = make_response(html) | |
| resp.headers['Content-Type'] = 'text/html' | |
| return resp | |