File size: 4,289 Bytes
6e4b6a1 ff7a5f2 cdd2ff8 a108d08 7d46648 ff7a5f2 a108d08 40bd669 ff7a5f2 7d46648 ff7a5f2 40bd669 cdd2ff8 a108d08 cdd2ff8 bb24960 cdd2ff8 ff7a5f2 bb24960 ff7a5f2 bb24960 ff7a5f2 cdd2ff8 ff7a5f2 cdd2ff8 bb24960 cdd2ff8 7d46648 cdd2ff8 bb24960 a108d08 cdd2ff8 bb24960 cdd2ff8 7d46648 bb24960 7d46648 6e4b6a1 cdd2ff8 bb24960 cdd2ff8 7d46648 cdd2ff8 a108d08 363ed4f 0a1f269 363ed4f 6e4b6a1 a108d08 363ed4f 7d46648 a108d08 ff7a5f2 7d46648 ff7a5f2 cdd2ff8 ff7a5f2 cdd2ff8 bb24960 ff7a5f2 7d46648 ff7a5f2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
import shutil
from fastapi import FastAPI, HTTPException
from deezspot.deezloader import DeeLogin
import requests
import os
import logging
from typing import Optional
from fastapi.staticfiles import StaticFiles
from dotenv import load_dotenv
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI(title="Deezer API")
# Load environment variables
load_dotenv()
# Mount a static files directory to serve downloaded files
os.makedirs("downloads", exist_ok=True)
app.mount("/downloads", StaticFiles(directory="downloads"), name="downloads")
# Deezer API base URL
DEEZER_API_URL = "https://api.deezer.com"
# Deezer ARL token (required for deezspot downloads)
ARL_TOKEN = os.getenv('ARL')
dl = DeeLogin(arl=ARL_TOKEN)
@app.get("/")
def read_root():
return {"message": "running"}
# Helper function to get track info
def get_track_info(track_id: str):
try:
response = requests.get(f"{DEEZER_API_URL}/track/{track_id}")
if response.status_code != 200:
raise HTTPException(status_code=404, detail="Track not found")
return response.json()
except requests.exceptions.RequestException as e:
logger.error(f"Network error fetching track metadata: {e}")
raise HTTPException(status_code=500, detail=str(e))
except Exception as e:
logger.error(f"Error fetching track metadata: {e}")
raise HTTPException(status_code=500, detail=str(e))
# Fetch track metadata from Deezer API
@app.get("/track/{track_id}")
def get_track(track_id: str):
return get_track_info(track_id)
# Download a track and return a download URL
@app.post("/download/track/{track_id}")
def download_track(track_id: str, quality: str = "MP3_320"):
try:
# Fetch track info
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")
# Sanitize filename
track_title = track_info.get("title", "track")
artist_name = track_info.get("artist", {}).get("name", "unknown")
expected_filename = f"{artist_name} - {track_title}.mp3".replace("/", "_") # Sanitize filename
# 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))
# Download the track using deezspot
logger.info(f"Downloading track: {expected_filename}")
dl.download_trackdee(
link_track=track_link,
output_dir="downloads",
quality_download=quality,
recursive_quality=False,
recursive_download=False
)
# Recursively search for the MP3 file in the downloads directory
mp3_filepath = None
for root, dirs, files in os.walk("downloads"):
for file in files:
if file.endswith('.mp3'):
mp3_filepath = os.path.join(root, file)
break
if mp3_filepath:
break
if not mp3_filepath:
raise HTTPException(status_code=500, detail="MP3 file not found after download")
# Return the download URL
relative_path = os.path.relpath(mp3_filepath, "downloads")
download_url = f"/downloads/{relative_path}"
logger.info(f"Download successful: {download_url}")
return {"download_url": download_url}
except Exception as e:
logger.error(f"Error downloading track: {e}")
raise HTTPException(status_code=500, detail=str(e))
# Search tracks using Deezer API
@app.get("/search")
def search_tracks(query: str, limit: Optional[int] = 10):
try:
response = requests.get(f"{DEEZER_API_URL}/search", params={"q": query, "limit": limit})
return response.json()
except requests.exceptions.RequestException as e:
logger.error(f"Network error searching tracks: {e}")
raise HTTPException(status_code=500, detail=str(e))
except Exception as e:
logger.error(f"Error searching tracks: {e}")
raise HTTPException(status_code=500, detail=str(e)) |