Add conection and remove proxy usage
This commit is contained in:
145
main.py
145
main.py
@@ -105,7 +105,7 @@ def get_video_metadata(
|
||||
|
||||
return info
|
||||
|
||||
info = execute_with_proxy_retry(ydl_opts, extract_metadata, retry_per_proxy=2)
|
||||
info = execute_with_proxy_retry(ydl_opts, extract_metadata, retry_per_proxy=1, max_proxies_to_try=3)
|
||||
|
||||
except ProxyError as e:
|
||||
error_msg = str(e).replace('\n', ' ').strip()
|
||||
@@ -175,16 +175,14 @@ def download_video(
|
||||
unique_id = str(uuid.uuid4())
|
||||
output_template = os.path.join(videos_dir, f"{unique_id}.%(ext)s")
|
||||
|
||||
ydl_opts = {
|
||||
"format": quality_map[qualidade],
|
||||
"outtmpl": output_template,
|
||||
# Opções base para extração de metadados (operação rápida com proxy)
|
||||
metadata_opts = {
|
||||
"quiet": True,
|
||||
"noplaylist": True,
|
||||
"merge_output_format": "mp4",
|
||||
"no_warnings": True,
|
||||
"skip_download": True,
|
||||
"nocheckcertificate": True,
|
||||
"socket_timeout": 60,
|
||||
"socket_timeout": 8,
|
||||
"retries": 0,
|
||||
"extractor_retries": 0,
|
||||
"force_ipv4": True,
|
||||
"geo_bypass": True,
|
||||
"extractor_args": {"youtube": {"player_client": ["android"], "player_skip": ["webpage"]}},
|
||||
@@ -194,44 +192,115 @@ def download_video(
|
||||
},
|
||||
}
|
||||
|
||||
# Opções para download (operação pesada - tentará com e sem proxy)
|
||||
download_opts = {
|
||||
"format": quality_map[qualidade],
|
||||
"outtmpl": output_template,
|
||||
"quiet": True,
|
||||
"noplaylist": True,
|
||||
"merge_output_format": "mp4",
|
||||
"nocheckcertificate": True,
|
||||
"socket_timeout": 45, # Timeout menor para detectar falha de proxy rapidamente
|
||||
"retries": 0,
|
||||
"extractor_retries": 0,
|
||||
"force_ipv4": True,
|
||||
"geo_bypass": True,
|
||||
"fragment_retries": 3,
|
||||
"file_access_retries": 3,
|
||||
"extractor_args": {"youtube": {"player_client": ["android"], "player_skip": ["webpage"]}},
|
||||
"http_headers": {
|
||||
"Accept-Language": "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||
"User-Agent": "com.google.android.youtube/19.17.36 (Linux; U; Android 13) gzip",
|
||||
},
|
||||
"http_chunk_size": 1048576, # 1MB chunks
|
||||
}
|
||||
|
||||
try:
|
||||
def download_operation(ydl):
|
||||
base = ydl.extract_info(target, download=False)
|
||||
title = base.get("title", unique_id)
|
||||
clean_title = sanitize_title(title)
|
||||
filename = f"{clean_title}_{qualidade}.mp4"
|
||||
final_path = os.path.join(videos_dir, filename)
|
||||
# ETAPA 1: Extrair metadados COM PROXY (operação rápida)
|
||||
def extract_metadata_operation(ydl):
|
||||
info = ydl.extract_info(target, download=False)
|
||||
if not info or 'title' not in info:
|
||||
raise Exception("Não foi possível extrair metadados do vídeo")
|
||||
return info
|
||||
|
||||
print('Info ok')
|
||||
# Tenta apenas 3 proxies para metadados antes de fallback
|
||||
metadata = execute_with_proxy_retry(
|
||||
metadata_opts,
|
||||
extract_metadata_operation,
|
||||
retry_per_proxy=1,
|
||||
max_proxies_to_try=3
|
||||
)
|
||||
|
||||
if os.path.exists(final_path):
|
||||
return {
|
||||
"videoId": video_id,
|
||||
"filename": filename,
|
||||
"cached": True
|
||||
}
|
||||
|
||||
print('Lets download')
|
||||
|
||||
result = ydl.extract_info(target, download=True)
|
||||
|
||||
if "requested_downloads" in result and len(result["requested_downloads"]) > 0:
|
||||
real_file_path = result["requested_downloads"][0]["filepath"]
|
||||
elif "filepath" in result:
|
||||
real_file_path = result["filepath"]
|
||||
else:
|
||||
real_file_path = output_template.replace("%(ext)s", "mp4")
|
||||
|
||||
os.rename(real_file_path, final_path)
|
||||
title = metadata.get("title", unique_id)
|
||||
clean_title = sanitize_title(title)
|
||||
filename = f"{clean_title}_{qualidade}.mp4"
|
||||
final_path = os.path.join(videos_dir, filename)
|
||||
|
||||
# Verifica cache
|
||||
if os.path.exists(final_path):
|
||||
return {
|
||||
"videoId": video_id,
|
||||
"filename": filename,
|
||||
"cached": False
|
||||
"cached": True
|
||||
}
|
||||
|
||||
return execute_with_proxy_retry(ydl_opts, download_operation, retry_per_proxy=3)
|
||||
# ETAPA 2: Download COM PROXY (tentativa rápida)
|
||||
def download_with_proxy(ydl):
|
||||
result = ydl.extract_info(target, download=True)
|
||||
return result
|
||||
|
||||
download_success = False
|
||||
result = None
|
||||
|
||||
try:
|
||||
# Tenta apenas 2 proxies para download antes de fallback
|
||||
result = execute_with_proxy_retry(
|
||||
download_opts,
|
||||
download_with_proxy,
|
||||
retry_per_proxy=1,
|
||||
max_proxies_to_try=2
|
||||
)
|
||||
download_success = True
|
||||
except ProxyError as proxy_err:
|
||||
# ETAPA 3: Download SEM PROXY (fallback)
|
||||
|
||||
# Aumenta timeout para download sem proxy
|
||||
download_opts_no_proxy = {**download_opts, "socket_timeout": 180}
|
||||
|
||||
try:
|
||||
with YoutubeDL(download_opts_no_proxy) as ydl:
|
||||
result = ydl.extract_info(target, download=True)
|
||||
download_success = True
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Falha no download com e sem proxy: {str(e)}"
|
||||
)
|
||||
|
||||
if not download_success or not result:
|
||||
raise HTTPException(status_code=500, detail="Erro desconhecido no download")
|
||||
|
||||
# Renomear arquivo para nome final
|
||||
if "requested_downloads" in result and len(result["requested_downloads"]) > 0:
|
||||
real_file_path = result["requested_downloads"][0]["filepath"]
|
||||
elif "filepath" in result:
|
||||
real_file_path = result["filepath"]
|
||||
else:
|
||||
real_file_path = output_template.replace("%(ext)s", "mp4")
|
||||
|
||||
if os.path.exists(real_file_path):
|
||||
os.rename(real_file_path, final_path)
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail="Arquivo de download não encontrado")
|
||||
|
||||
return {
|
||||
"videoId": video_id,
|
||||
"filename": filename,
|
||||
"cached": False
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except ProxyError as e:
|
||||
raise HTTPException(status_code=503, detail=f"Erro com proxies: {e}")
|
||||
except Exception as e:
|
||||
@@ -270,7 +339,7 @@ def search_youtube_yt_dlp(
|
||||
})
|
||||
return {"results": results}
|
||||
|
||||
return execute_with_proxy_retry(ydl_opts, search_operation, retry_per_proxy=2)
|
||||
return execute_with_proxy_retry(ydl_opts, search_operation, retry_per_proxy=1, max_proxies_to_try=3)
|
||||
|
||||
except ProxyError as e:
|
||||
raise HTTPException(status_code=503, detail=f"Erro com proxies: {e}")
|
||||
@@ -310,7 +379,7 @@ def list_formats(url: str):
|
||||
} for f in fmts]
|
||||
return {"total": len(brief), "formats": brief[:60]}
|
||||
|
||||
return execute_with_proxy_retry(opts, list_formats_operation, retry_per_proxy=2)
|
||||
return execute_with_proxy_retry(opts, list_formats_operation, retry_per_proxy=1, max_proxies_to_try=3)
|
||||
|
||||
except ProxyError as e:
|
||||
raise HTTPException(status_code=503, detail=f"Erro com proxies: {e}")
|
||||
|
||||
Reference in New Issue
Block a user