Download api/media.py from QBANK/OFTQUEST: direct link, hf CLI and curl.
- Browser
- Download file 18.6 kB
-
https://huggingface.co/spaces/QBANK/OFTQUEST/resolve/main/api/media.py
- Command line
-
hf download hf://spaces/QBANK/OFTQUEST/api/media.py
-
curl -L -o media.py https://huggingface.co/spaces/QBANK/OFTQUEST/resolve/main/api/media.py
18.6 kB
| """ | |
| Media API - Telegram Storage Integration | |
| Provides streaming proxy for files stored on Telegram, | |
| organized by categories. Supports MTProto streaming up to 2GB. | |
| Enhanced with anti-bot validation and canvas watermarks. | |
| """ | |
| import time | |
| import logging | |
| import re | |
| import secrets | |
| import threading | |
| from flask import Blueprint, request, jsonify, Response, make_response, g, stream_with_context | |
| from config import Config | |
| from models.database import get_db | |
| from auth.middleware import require_auth, require_admin | |
| try: | |
| import requests as http_requests | |
| except ImportError: | |
| http_requests = None | |
| try: | |
| from telegram_client import TelegramStreamer | |
| _streamer_available = True | |
| except ImportError: | |
| _streamer_available = False | |
| logger = logging.getLogger(__name__) | |
| def _get_streamer(): | |
| """Get the TelegramStreamer singleton if available and ready.""" | |
| if not _streamer_available: | |
| return None | |
| try: | |
| streamer = TelegramStreamer.get_instance() | |
| if streamer and streamer.is_ready(): | |
| return streamer | |
| except Exception as e: | |
| logger.debug(f"MTProto streamer not available: {e}") | |
| return None | |
| media_bp = Blueprint('media', __name__, url_prefix='/api/media') | |
| # Caches | |
| _file_path_cache = {} | |
| _CACHE_TTL = 1800 | |
| _chunk_cache = {} | |
| _CHUNK_CACHE_TTL = 600 | |
| _CHUNK_CACHE_MAX = 200 | |
| def _get_cached_chunk(streamer, message_id, offset, limit): | |
| now = time.time() | |
| cache_key = (message_id, offset, limit) | |
| cached = _chunk_cache.get(cache_key) | |
| if cached and (now - cached['cached_at']) < _CHUNK_CACHE_TTL: | |
| return cached['data'] | |
| if len(_chunk_cache) > _CHUNK_CACHE_MAX: | |
| expired = [k for k, v in _chunk_cache.items() if now - v['cached_at'] > _CHUNK_CACHE_TTL] | |
| for k in expired: | |
| del _chunk_cache[k] | |
| if len(_chunk_cache) > _CHUNK_CACHE_MAX: | |
| oldest = sorted(_chunk_cache.items(), key=lambda x: x[1]['cached_at']) | |
| for k, _ in oldest[:len(_chunk_cache) // 2]: | |
| del _chunk_cache[k] | |
| chunk = streamer.get_file_chunk(message_id, offset=offset, limit=limit) | |
| if chunk: | |
| _chunk_cache[cache_key] = {'data': chunk, 'cached_at': now} | |
| return chunk | |
| CONTENT_TYPES = { | |
| '.mp4': 'video/mp4', '.mkv': 'video/x-matroska', '.avi': 'video/x-msvideo', | |
| '.mov': 'video/quicktime', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', | |
| '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp', | |
| } | |
| STREAM_SIZE_LIMIT_BOT = 20 * 1024 * 1024 | |
| STREAM_SIZE_LIMIT_MTPROTO = 2 * 1024 * 1024 * 1024 | |
| def _get_telegram_file_path(file_id): | |
| now = time.time() | |
| cached = _file_path_cache.get(file_id) | |
| if cached and (now - cached['cached_at']) < _CACHE_TTL: | |
| return cached['file_path'] | |
| token = Config.TELEGRAM_BOT_TOKEN | |
| if not token or not http_requests: | |
| return None | |
| try: | |
| resp = http_requests.get( | |
| f'https://api.telegram.org/bot{token}/getFile', | |
| params={'file_id': file_id}, timeout=10 | |
| ) | |
| if resp.status_code != 200: | |
| return None | |
| data = resp.json() | |
| if not data.get('ok'): | |
| return None | |
| file_path = data['result'].get('file_path') | |
| if file_path: | |
| _file_path_cache[file_id] = {'file_path': file_path, 'cached_at': now} | |
| return file_path | |
| except Exception as e: | |
| logger.error(f"getFile exception: {e}") | |
| return None | |
| def _proxy_telegram_file(file_path, content_type, size_bytes=0): | |
| token = Config.TELEGRAM_BOT_TOKEN | |
| download_url = f'https://api.telegram.org/file/bot{token}/{file_path}' | |
| range_header = request.headers.get('Range') | |
| headers = {} | |
| if range_header: | |
| headers['Range'] = range_header | |
| try: | |
| upstream = http_requests.get(download_url, headers=headers, stream=True, timeout=30) | |
| except Exception as e: | |
| return jsonify({'error': 'Erro ao carregar arquivo'}), 502 | |
| status = 206 if upstream.status_code == 206 else 200 if upstream.status_code == 200 else None | |
| if status is None: | |
| return jsonify({'error': 'Arquivo indisponivel'}), 502 | |
| def generate(): | |
| try: | |
| for chunk in upstream.iter_content(chunk_size=64 * 1024): | |
| if chunk: | |
| yield chunk | |
| finally: | |
| upstream.close() | |
| response_headers = { | |
| 'Content-Type': content_type, | |
| 'Accept-Ranges': 'bytes', | |
| 'Cache-Control': 'private, max-age=1800', | |
| 'Content-Disposition': 'inline', | |
| } | |
| if 'Content-Length' in upstream.headers: | |
| response_headers['Content-Length'] = upstream.headers['Content-Length'] | |
| elif size_bytes and not range_header: | |
| response_headers['Content-Length'] = str(size_bytes) | |
| if 'Content-Range' in upstream.headers: | |
| response_headers['Content-Range'] = upstream.headers['Content-Range'] | |
| return Response(stream_with_context(generate()), status=status, headers=response_headers) | |
| def _stream_via_mtproto(streamer, message_id, content_type, total_size): | |
| range_header = request.headers.get('Range') | |
| start = 0 | |
| end = total_size - 1 if total_size > 0 else 0 | |
| status = 200 | |
| if range_header and total_size > 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)), total_size - 1) if range_match.group(2) else total_size - 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 = _get_cached_chunk(streamer, message_id, offset=offset, limit=read_size) | |
| if not chunk: | |
| break | |
| yield chunk | |
| offset += len(chunk) | |
| remaining -= len(chunk) | |
| if len(chunk) < read_size: | |
| break | |
| except Exception as e: | |
| logger.error(f"MTProto stream error for msg {message_id}: {e}") | |
| response_headers = { | |
| 'Content-Type': content_type, | |
| 'Accept-Ranges': 'bytes', | |
| 'Content-Length': str(content_length), | |
| 'Cache-Control': 'private, max-age=3600', | |
| 'Content-Disposition': 'inline', | |
| } | |
| if status == 206: | |
| response_headers['Content-Range'] = f'bytes {start}-{end}/{total_size}' | |
| return Response(stream_with_context(generate()), status=status, headers=response_headers) | |
| def _prefetch_video_moov(streamer, message_id, total_size): | |
| def _do_prefetch(): | |
| try: | |
| CHUNK = 1024 * 1024 | |
| if total_size <= CHUNK: | |
| _get_cached_chunk(streamer, message_id, offset=0, limit=total_size) | |
| else: | |
| moov_offset = total_size - CHUNK | |
| _get_cached_chunk(streamer, message_id, offset=moov_offset, limit=CHUNK) | |
| except Exception: | |
| pass | |
| t = threading.Thread(target=_do_prefetch, daemon=True) | |
| t.start() | |
| # ===== API Routes ===== | |
| def stream_file(media_id): | |
| """Stream a file from Telegram. Supports Range requests for seeking.""" | |
| db = get_db() | |
| media = db.execute("SELECT * FROM media_files WHERE id = ?", (media_id,)).fetchone() | |
| if not media: | |
| return jsonify({'error': 'Arquivo nao encontrado'}), 404 | |
| size_bytes = media['size_bytes'] or 0 | |
| message_id = media['telegram_message_id'] | |
| ext = '.' + media['filename'].rsplit('.', 1)[-1].lower() if '.' in media['filename'] else '' | |
| content_type = CONTENT_TYPES.get(ext, 'application/octet-stream') | |
| streamer = _get_streamer() | |
| if streamer and message_id: | |
| if size_bytes and size_bytes < 1024 * 1024: | |
| try: | |
| data = streamer.get_file_chunk(message_id, offset=0, limit=size_bytes + 4096) | |
| if data and len(data) > 0: | |
| resp = make_response(data) | |
| resp.headers['Content-Type'] = content_type | |
| resp.headers['Content-Length'] = str(len(data)) | |
| resp.headers['Cache-Control'] = 'private, max-age=3600' | |
| resp.headers['Content-Disposition'] = 'inline' | |
| return resp | |
| except Exception: | |
| pass | |
| else: | |
| try: | |
| return _stream_via_mtproto(streamer, message_id, content_type, size_bytes) | |
| except Exception as e: | |
| logger.error(f"MTProto streaming failed for media_id={media_id}: {e}") | |
| # Fallback to Bot API (20MB limit) | |
| if size_bytes > STREAM_SIZE_LIMIT_BOT: | |
| return jsonify({'error': 'MTProto nao disponivel e arquivo muito grande para Bot API'}), 413 | |
| file_path = _get_telegram_file_path(media['file_id']) | |
| if not file_path: | |
| return jsonify({'error': 'Arquivo indisponivel no Telegram'}), 502 | |
| return _proxy_telegram_file(file_path, content_type, size_bytes) | |
| def stream_by_filename(filename): | |
| """Stream a file by filename (used by video_proxy for question videos).""" | |
| db = get_db() | |
| media = db.execute( | |
| "SELECT * FROM media_files WHERE filename = ?", (filename,) | |
| ).fetchone() | |
| if not media: | |
| return jsonify({'error': 'Arquivo nao encontrado'}), 404 | |
| # Redirect to stream endpoint | |
| return stream_file.__wrapped__(media['id']) if hasattr(stream_file, '__wrapped__') else _stream_media(media) | |
| def _stream_media(media): | |
| """Internal: stream a media row.""" | |
| size_bytes = media['size_bytes'] or 0 | |
| message_id = media['telegram_message_id'] | |
| ext = '.' + media['filename'].rsplit('.', 1)[-1].lower() if '.' in media['filename'] else '' | |
| content_type = CONTENT_TYPES.get(ext, 'application/octet-stream') | |
| streamer = _get_streamer() | |
| if streamer and message_id: | |
| if size_bytes and size_bytes < 1024 * 1024: | |
| try: | |
| data = streamer.get_file_chunk(message_id, offset=0, limit=size_bytes + 4096) | |
| if data: | |
| resp = make_response(data) | |
| resp.headers['Content-Type'] = content_type | |
| resp.headers['Content-Length'] = str(len(data)) | |
| resp.headers['Cache-Control'] = 'private, max-age=3600' | |
| resp.headers['Content-Disposition'] = 'inline' | |
| return resp | |
| except Exception: | |
| pass | |
| try: | |
| return _stream_via_mtproto(streamer, message_id, content_type, size_bytes) | |
| except Exception as e: | |
| logger.error(f"MTProto error: {e}") | |
| if size_bytes > STREAM_SIZE_LIMIT_BOT: | |
| return jsonify({'error': 'Arquivo muito grande'}), 413 | |
| file_path = _get_telegram_file_path(media['file_id']) | |
| if not file_path: | |
| return jsonify({'error': 'Indisponivel'}), 502 | |
| return _proxy_telegram_file(file_path, content_type, size_bytes) | |
| def media_player(media_id): | |
| """Serve isolated HTML video player with watermarks.""" | |
| db = get_db() | |
| media = db.execute("SELECT * FROM media_files WHERE id = ?", (media_id,)).fetchone() | |
| if not media: | |
| return _error_page('Arquivo nao encontrado'), 404 | |
| # Pre-fetch moov atom for videos | |
| if media['file_type'] == 'video' and media['telegram_message_id'] and media['size_bytes']: | |
| streamer = _get_streamer() | |
| if streamer: | |
| _prefetch_video_moov(streamer, media['telegram_message_id'], media['size_bytes']) | |
| user = g.current_user | |
| token = g.token | |
| user_email = user.get('email', '') if user else '' | |
| user_name = user.get('display_name', '') or (user_email.split('@')[0] if user_email else '---') | |
| user_ip = request.headers.get('X-Forwarded-For', request.remote_addr) or '---' | |
| if user_ip and ',' in user_ip: | |
| user_ip = user_ip.split(',')[0].strip() | |
| wm_text = f"{user_name} | {user_email} | IP: {user_ip}" | |
| stream_url = f'/api/media/stream/{media_id}?token={token}' | |
| content_html = f''' | |
| <video id="vid" controls autoplay preload="auto" style="width:100%;height:100%;background:#000" | |
| controlsList="nodownload noremoteplayback"> | |
| <source src="{stream_url}" type="video/mp4"> | |
| Seu navegador nao suporta video HTML5. | |
| </video> | |
| <div id="loading" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%); | |
| color:#fff;font:16px sans-serif;text-align:center"> | |
| <div style="border:3px solid #333;border-top:3px solid #fff;border-radius:50%;width:40px;height:40px; | |
| animation:spin 1s linear infinite;margin:0 auto 10px"></div> | |
| Carregando video... | |
| </div> | |
| <style>@keyframes spin {{ from{{transform:rotate(0deg)}} to{{transform:rotate(360deg)}} }}</style> | |
| <script> | |
| var v=document.getElementById("vid"), ld=document.getElementById("loading"); | |
| v.addEventListener("canplay",function(){{ ld.style.display="none"; }}); | |
| v.addEventListener("playing",function(){{ ld.style.display="none"; }}); | |
| v.addEventListener("error",function(){{ | |
| ld.style.display="none"; | |
| var err=document.createElement("div"); | |
| err.style.cssText="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);color:#ff5252;font:16px sans-serif;text-align:center;background:rgba(0,0,0,.8);padding:20px;border-radius:8px"; | |
| err.textContent="Erro ao carregar video. Tente novamente."; | |
| document.body.appendChild(err); | |
| }}); | |
| </script> | |
| ''' | |
| player_session = secrets.token_urlsafe(24) | |
| 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; width:100vw; height:100vh; }} | |
| video {{ display:block; }} | |
| [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> | |
| {content_html} | |
| <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"; | |
| var WM_TEXT = "{wm_text}"; | |
| // Block blob URL creation for video content | |
| var _origCreateObjectURL = URL.createObjectURL; | |
| URL.createObjectURL = function(obj) {{ | |
| if (obj instanceof Blob && obj.type && obj.type.startsWith('video/')) {{ | |
| return 'about:blank'; | |
| }} | |
| return _origCreateObjectURL.call(URL, obj); | |
| }}; | |
| // Block video.src access from console | |
| var vid = document.getElementById('vid'); | |
| if (vid) {{ | |
| try {{ | |
| Object.defineProperty(vid, 'currentSrc', {{ | |
| get: function() {{ return ''; }}, | |
| configurable: false | |
| }}); | |
| }} catch(e) {{}} | |
| }} | |
| // 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); | |
| 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); | |
| }})(); | |
| </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['Referrer-Policy'] = 'no-referrer' | |
| return response | |
| def media_health(): | |
| """Health check for media streaming subsystem.""" | |
| streamer = _get_streamer() | |
| mtproto_ok = streamer is not None | |
| db = get_db() | |
| total_media = db.execute("SELECT COUNT(*) as c FROM media_files").fetchone() | |
| total_media = total_media['c'] if total_media else 0 | |
| return jsonify({ | |
| 'mtproto_ready': mtproto_ok, | |
| 'telethon_available': _streamer_available, | |
| 'bot_token_set': bool(Config.TELEGRAM_BOT_TOKEN), | |
| 'api_id_set': bool(Config.TELEGRAM_API_ID), | |
| 'total_media': total_media, | |
| }) | |
| 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 | |