diff --git a/main.py b/main.py index b4a04bb..9f4ed52 100644 --- a/main.py +++ b/main.py @@ -72,31 +72,65 @@ def get_video_metadata( 'quiet': True, 'no_warnings': True, 'skip_download': True, - 'extract_flat': True, - 'force_generic_extractor': True, - 'format': 'best', 'nocheckcertificate': True, 'ignoreerrors': True, 'no_color': True, 'extract_flat': 'in_playlist', 'force_generic_extractor': True, + 'format': 'best[ext=mp4]/best[ext=webm]/best', + 'allow_unplayable_formats': True, } try: with YoutubeDL(ydl_opts) as ydl: - # Primeiro tenta extrair as informações básicas info = ydl.extract_info(target, download=False, process=False) - # Se for um vídeo, tenta obter mais detalhes - if info.get('_type') == 'url' or 'entries' not in info: + if not info or 'title' not in info: info = ydl.extract_info(target, download=False) - # Se ainda assim não tiver as informações básicas, retorna erro + if not info or 'title' not in info: + simple_ydl_opts = { + 'quiet': True, + 'skip_download': True, + 'extract_flat': True, + 'force_generic_extractor': True, + } + with YoutubeDL(simple_ydl_opts) as simple_ydl: + info = simple_ydl.extract_info(target, download=False) + if not info: raise Exception("Não foi possível extrair as informações do vídeo") + if isinstance(info, dict): + if 'title' not in info and 'url' in info: + with YoutubeDL(ydl_opts) as ydl_redirect: + info = ydl_redirect.extract_info(info['url'], download=False) + + if 'title' not in info: + info['title'] = f"Vídeo {videoId or 'desconhecido'}" + except Exception as e: error_msg = str(e).replace('\n', ' ').strip() + try: + import requests + from bs4 import BeautifulSoup + + video_id = videoId or (url.split('v=')[-1].split('&')[0] if 'v=' in url else '') + if video_id: + response = requests.get(f'https://www.youtube.com/watch?v={video_id}', timeout=10) + soup = BeautifulSoup(response.text, 'html.parser') + title = soup.find('title').text.replace(' - YouTube', '').strip() + if title and title != 'YouTube': + return { + 'id': video_id, + 'title': title, + 'url': f'https://www.youtube.com/watch?v={video_id}', + 'thumbnail': f'https://img.youtube.com/vi/{video_id}/hqdefault.jpg', + 'error': f'Informações limitadas: {error_msg}' + } + except Exception as fallback_error: + pass + raise HTTPException( status_code=500, detail=f"Erro ao processar o vídeo: {error_msg}"