Update app.py
Browse files145 unmodified lines1461471481491501511523 unmodified lines156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239145 unmodified linesdef download_track(request: Request, download_request: DownloadRequest):try:user_ip = get_user_ip(request)if rate_limiter.is_rate_limited(user_ip):current_count = rate_limiter.get_current_count(user_ip)raise HTTPException(3 unmodified lines"help": "https://t.me/chrunoss"})if download_request.arl is None or download_request.arl.strip() == "":ARL = ARL_TOKENelse:ARL = download_request.arllogger.info(f'arl: {ARL}')url = download_request.urlif 'dzr.page' in url or 'deezer.page' in url or 'link.deezer' in url:url = convert_deezer_short_link_async(url)quality = download_request.qualitydl = DeeLogin(arl=ARL)logger.info(f'track_url: {url}')if quality not in ["MP3_320", "MP3_128", "FLAC"]:raise HTTPException(status_code=400, detail="Invalid quality specified")# 提取 track_id (假设 url 格式为 https://api.deezer.com/track/{track_id})track_id = url.split("/")[-1]# Fetch track infotrack_info = get_track_info(track_id)track_link = track_info.get("link")if not track_link:raise HTTPException(status_code=404, detail="Track link not found")# Sanitize filenametrack_title = track_info.get("title", "track")artist_name = track_info.get("artist", {}).get("name", "unknown")file_extension = "flac" if quality == "FLAC" else "mp3"expected_filename = f"{artist_name} - {track_title}.{file_extension}".replace("/", "_") # Sanitize filename# Clear the downloads directoryfor root, dirs, files in os.walk("downloads"):for file in files:os.remove(os.path.join(root, file))for dir in dirs:shutil.rmtree(os.path.join(root, dir))# Download the track using deezspottry:# 下载文件的代码dl.download_trackdee(link_track=track_link,output_dir="downloads",quality_download=quality,recursive_quality=False,recursive_download=False)except Exception as e:logger.error(f"Error downloading file: {e}")raise HTTPException(status_code=500, detail="File download failed")# Recursively search for the file in the downloads directoryfilepath = Nonefor root, dirs, files in os.walk("downloads"):for file in files:if file.endswith(f'.{file_extension}'):filepath = os.path.join(root, file)breakif filepath:breakif not filepath:raise HTTPException(status_code=500, detail=f"{file_extension} file not found after download")if filepath:file_size = os.path.getsize(filepath)logger.info(f"Downloaded file size: {file_size} bytes")# Return the download URLrelative_path = quote(str(os.path.relpath(filepath, "downloads")))# Remove spaces from the relative path# Auto-detect base URL from requestbase_url = str(request.base_url).rstrip('/')download_url = f"{base_url}/downloads/{relative_path}"logger.info(f"Download successful: {download_url}")gc.collect()return {"download_url": download_url, "requests_remaining": rate_limiter.max_requests - rate_limiter.get_current_count(user_ip)}except Exception as e:logger.error(f"Error downloading track: {e}")raise HTTPException(status_code=500, detail=str(e))145 unmodified lines1461471481491501513 unmodified lines155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275145 unmodified linesdef download_track(request: Request, download_request: DownloadRequest):try:user_ip = get_user_ip(request)if rate_limiter.is_rate_limited(user_ip):current_count = rate_limiter.get_current_count(user_ip)raise HTTPException(3 unmodified lines"help": "https://t.me/chrunoss"})if download_request.arl is None or download_request.arl.strip() == "":ARL = ARL_TOKENelse:ARL = download_request.arllogger.info(f'arl: {ARL}')url = download_request.urlif 'dzr.page' in url or 'deezer.page' in url or 'link.deezer' in url:url = convert_deezer_short_link_async(url)requested_quality = download_request.qualitydl = DeeLogin(arl=ARL)logger.info(f'track_url: {url}')# 1. 定义降级序列 (从高到低)QUALITY_HIERARCHY = ["FLAC", "MP3_320", "MP3_128"]if requested_quality not in QUALITY_HIERARCHY:raise HTTPException(status_code=400, detail="Invalid quality specified")# 确定需要尝试的音质列表(从用户指定的音质开始,截取列表后半段)start_index = QUALITY_HIERARCHY.index(requested_quality)qualities_to_try = QUALITY_HIERARCHY[start_index:]track_id = url.split("/")[-1]track_info = get_track_info(track_id)track_link = track_info.get("link")if not track_link:raise HTTPException(status_code=404, detail="Track link not found")track_title = track_info.get("title", "track")artist_name = track_info.get("artist", {}).get("name", "unknown")# Clear the downloads directory (保持原样,在下载前清空一次即可)for root, dirs, files in os.walk("downloads"):for file in files:os.remove(os.path.join(root, file))for dir in dirs:shutil.rmtree(os.path.join(root, dir))# 2. 循环尝试下载降级队列中的音质filepath = Noneactual_quality_downloaded = Noneactual_extension = Nonefor current_quality in qualities_to_try:try:logger.info(f"Attempting download with quality: {current_quality}")# 执行下载dl.download_trackdee(link_track=track_link,output_dir="downloads",quality_download=current_quality,recursive_quality=False,recursive_download=False)# 下载完成后,立即在目录下查找文件是否真的生成了temp_extension = "flac" if current_quality == "FLAC" else "mp3"found_path = Nonefor root, dirs, files in os.walk("downloads"):for file in files:if file.endswith(f'.{temp_extension}'):found_path = os.path.join(root, file)breakif found_path:break# 如果文件找到了,说明这一档的音质下载成功,跳出循环if found_path:filepath = found_pathactual_quality_downloaded = current_qualityactual_extension = temp_extensionlogger.info(f"Successfully downloaded in {current_quality}")breakelse:logger.warning(f"Download command executed but .{temp_extension} file not found for {current_quality}. Trying next lower quality...")except Exception as e:logger.warning(f"Error downloading {current_quality}: {e}. Falling back to next lower quality...")# 出现异常,继续循环体,尝试下一种音质# 如果循环结束 filepath 还是 None,说明所有音质都失败了if not filepath:logger.error(f"All download attempts failed for track: {track_link}")raise HTTPException(status_code=500, detail="File download failed for all available qualities")file_size = os.path.getsize(filepath)logger.info(f"Downloaded file size: {file_size} bytes")# Return the download URLrelative_path = quote(str(os.path.relpath(filepath, "downloads")))base_url = str(request.base_url).rstrip('/')download_url = f"{base_url}/downloads/{relative_path}"logger.info(f"Download successful: {download_url}")gc.collect()# 3. 建议在返回值中加上实际下载的音质,方便客户端/前端知道是否发生了降级return {"download_url": download_url,"requested_quality": requested_quality,"actual_quality": actual_quality_downloaded, # 告知客户端实际下到的音质"requests_remaining": rate_limiter.max_requests - rate_limiter.get_current_count(user_ip)}except HTTPException:# FastAPI 自带的 HTTPException 直接抛出,不经过下面的通用异常处理raiseexcept Exception as e:logger.error(f"Error processing track download: {e}")raise HTTPException(status_code=500, detail=str(e))
app.py+75-39