Update app.py
Browse files11 unmodified lines12131415161795 unmodified lines1131141151161171183 unmodified lines1221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511523 unmodified lines15615715815916016116211 unmodified linesimport cloudscraperfrom dotenv import load_dotenv# Setup logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)95 unmodified linesreturn {"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 linesif not hls_url:return {"error": "URL parameter is required"}timestamp = datetime.now().strftime('%Y%m%d%H%M%S')output_template = str(Path(global_download_dir) / f'%(title)s_{timestamp}.%(ext)s')ydl_opts = {'format': 'best','outtmpl': output_template,'quiet': True,'no_warnings': True,'noprogress': True,'merge_output_format': 'mp4'}try:await run_in_threadpool(lambda: yt_dlp.YoutubeDL(ydl_opts).download([hls_url]))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"}downloaded_file = downloaded_files[0]encoded_filename = urllib.parse.quote(downloaded_file.name)download_url = f"{BASE_URL}/file/{encoded_filename}"logger.info(f"Download successful: {download_url}")3 unmodified lineslogger.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."""11 unmodified lines1213141516171895 unmodified lines1141151161171181191203 unmodified lines1241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841853 unmodified lines18919019119219319411 unmodified linesimport cloudscraperfrom dotenv import load_dotenv# Setup logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)95 unmodified linesreturn {"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 linesif 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'hls_video_{timestamp}.%(ext)s')ydl_opts = {'format': 'best','outtmpl': output_template,'quiet': True,'no_warnings': True,'noprogress': True,# 优化点 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: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)}"}if not info:return {"error": "Could not extract video info"}# 优化点 4:精准获取最终生成的文件名,告别 glob 盲猜# 经过 postprocessor 转换后的最终文件路径通常在 requested_downloads 里filepath = Noneif '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])# 提取文件名并拼接 URLfilename = 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 lineslogger.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