""" 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 ===== @media_bp.route('/stream/', methods=['GET']) @require_auth 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) @media_bp.route('/stream-by-filename/', methods=['GET']) @require_auth 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) @media_bp.route('/player/', methods=['GET']) @require_auth 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'''
Carregando video...
''' player_session = secrets.token_urlsafe(24) html = f''' {content_html}
{wm_text}
{wm_text}
{wm_text}
{wm_text}
{wm_text}
{wm_text}
{wm_text}
{wm_text}
''' 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 @media_bp.route('/health', methods=['GET']) 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'''

{msg}

''' resp = make_response(html) resp.headers['Content-Type'] = 'text/html' return resp