Update app.py
Browse files11 unmodified lines1213141516171895 unmodified lines1141151161171181191203 unmodified lines1241251261251271281291301311271281321331341351361371381391351401411421431441451461471481491501511521531541391551561571581591441451461601611621481491631641651661671681691701711721731741751761771781791801811821831841853 unmodified lines18919019115919219319411 unmodified linesimport cloudscraperfrom dotenv import load_dotenv
# Setup logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)95 unmodified lines return {"error": f"Failed to process request: {str(e)}"}
@app.post("/hls")async def download_hls_video(request: Request): """Download HLS video and return download URL."""3 unmodified lines if not hls_url: return {"error": "URL parameter is required"}
timestamp = datetime.now().strftime('%Y%m%d%H%M%S') # 优化点 1:放弃 %(title)s,对于 m3u8,直接使用固定前缀+时间戳更稳妥 # 否则 %(title)s 解析出奇怪的路径符会导致报错 output_template = str(Path(global_download_dir) / f'%(title)s_{timestamp}.%(ext)s')
output_template = str(Path(global_download_dir) / f'hls_video_{timestamp}.%(ext)s') ydl_opts = { 'format': 'best', 'outtmpl': output_template, 'quiet': True, 'no_warnings': True, 'noprogress': True, 'merge_output_format': 'mp4' # 优化点 2:不要用 merge_output_format,改用后处理(postprocessors)强制转换格式 'postprocessors': [{ 'key': 'FFmpegVideoConvertor', 'preferedformat': 'mp4', }] } # 优化点 3:使用 extract_info 替代 download,这样能拿到确切的文件路径 def _download_task(): with yt_dlp.YoutubeDL(ydl_opts) as ydl: # download=True 会执行下载,并返回包含所有元数据的字典 return ydl.extract_info(hls_url, download=True) try: await run_in_threadpool(lambda: yt_dlp.YoutubeDL(ydl_opts).download([hls_url])) info = await run_in_threadpool(_download_task) except Exception as e: logger.error(f"yt-dlp download failed: {e}") return {"error": f"Download failed: {str(e)}"}
downloaded_files = list(Path(global_download_dir).glob(f"*_{timestamp}.mp4")) if not downloaded_files: return {"error": "Download failed - no files found"} if not info: return {"error": "Could not extract video info"}
downloaded_file = downloaded_files[0] encoded_filename = urllib.parse.quote(downloaded_file.name) # 优化点 4:精准获取最终生成的文件名,告别 glob 盲猜 # 经过 postprocessor 转换后的最终文件路径通常在 requested_downloads 里 filepath = None if 'requested_downloads' in info and len(info['requested_downloads']) > 0: filepath = info['requested_downloads'][0].get('filepath') # 兜底:如果没有触发后处理,拿原始文件名 if not filepath: filepath = info.get('_filename') if not filepath or not os.path.exists(filepath): # 最后的倔强兜底:如果不幸找不到,搜一下任意后缀 downloaded_files = list(Path(global_download_dir).glob(f"hls_video_{timestamp}.*")) if not downloaded_files: return {"error": "Download failed - no files generated"} filepath = str(downloaded_files[0])
# 提取文件名并拼接 URL filename = os.path.basename(filepath) encoded_filename = urllib.parse.quote(filename) download_url = f"{BASE_URL}/file/{encoded_filename}" logger.info(f"Download successful: {download_url}")3 unmodified lines logger.error(f"Error in download_hls_video: {e}") return {"error": f"Failed to process request: {str(e)}"}
@app.get("/health")async def health_check(): """Health check endpoint."""app.py+43-11