depot / app.py
tecuts's picture
Update app.py
40bd669 verified
raw
history blame
4.01 kB
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.get_env('ARL')
dl = DeeLogin(arl=ARL_TOKEN)
@app.get("/")
def read_root():
return {"message": "running}"}
# Fetch track metadata from Deezer API
@app.get("/track/{track_id}")
def get_track(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 Exception as e:
logger.error(f"Error fetching track metadata: {e}")
raise HTTPException(status_code=500, detail=str(e))
# 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 link from Deezer API
track_info = requests.get(f"{DEEZER_API_URL}/track/{track_id}").json()
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")
filename = f"{artist_name} - {track_title}.mp3".replace("/", "_") # Sanitize filename
filepath = os.path.join("downloads", filename)
# Download the track using deezspot
logger.info(f"Downloading track: {filename}")
dl.download_trackdee(
link_track=track_link,
output_dir="downloads",
quality_download=quality,
recursive_quality=False,
recursive_download=False
)
# Check if the file exists
if not os.path.exists(filepath):
# If the file is not found, search for files in the downloads directory
logger.warning(f"File not found at expected path: {filepath}")
logger.warning("Searching for downloaded files in the downloads directory...")
downloaded_files = os.listdir("downloads")
logger.warning(f"Files in downloads directory: {downloaded_files}")
# Try to find the file with a similar name
for file in downloaded_files:
if track_title.lower() in file.lower() or artist_name.lower() in file.lower():
filepath = os.path.join("downloads", file)
logger.info(f"Found matching file: {filepath}")
break
else:
raise HTTPException(status_code=500, detail="File download failed")
# Return the download URL
download_url = f"/downloads/{os.path.basename(filepath)}"
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 Exception as e:
logger.error(f"Error searching tracks: {e}")
raise HTTPException(status_code=500, detail=str(e))