Update app.py
Browse files1 unmodified line234556786 unmodified lines15161718181920212223242526568 unmodified lines5955965975985996006016026036046056 unmodified lines61261361460661561661761861962062162262362462562662762862963063163263363463563660863763863964064164264364464564664764864965065165261165365465565665765865966066166266366461566566666766866962067067167267316 unmodified lines69069169269369469569669769864769970070170212 unmodified lines7157167177187197207217227237247251 unmodified lineimport loggingimport secretsfrom typing import Optional, Dict, Anyfrom fastapi import FastAPI, HTTPException, Requestfrom fastapi import FastAPI, HTTPException, Request, Dependsimport requestsfrom bs4 import BeautifulSoupimport os6 unmodified linesimport urllib.parsefrom fastapi.responses import JSONResponseimport httpxfrom pydantic import BaseModelfrom urllib.parse import urlparse, parse_qsimport refrom datetime import datefrom collections import defaultdictfrom pydantic import BaseModel, field_validator
# Configure logginglogging.basicConfig(568 unmodified lines
# --- Configuration ---DAILY_IP_LIMIT = 16 # Set your desired daily limit per IP here
# --- Headers required by the source API ---HEADERS = { "referer": "https://spotubedl.com/",6 unmodified lines "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36"}
# --- Request Models ---# --- Rate Limiting Logic ---# In-memory store for IP tracking. Note: This resets if the server restarts.ip_usage = defaultdict(lambda: {"date": date.today(), "count": 0})
def check_rate_limit(request: Request): client_ip = request.client.host today = date.today() # Reset count if it's a new day for this IP if ip_usage[client_ip]["date"] != today: ip_usage[client_ip] = {"date": today, "count": 0} # Check if limit is exceeded if ip_usage[client_ip]["count"] >= DAILY_IP_LIMIT: raise HTTPException(status_code=429, detail=f"Daily request limit ({DAILY_IP_LIMIT}) exceeded for IP: {client_ip}") # Increment usage ip_usage[client_ip]["count"] += 1 return client_ip
# --- Request Models & Validation ---class InfoRequest(BaseModel): url: str # The Spotify URL or Song ID url: str
@field_validator('url') @classmethod def validate_spotify_id(cls, v: str) -> str: # Extract ID if a full Spotify URL is provided match = re.search(r"track/([a-zA-Z0-9]{22})", v) song_id = match.group(1) if match else v.split("/")[-1] # Validate that the resulting ID is exactly 22 alphanumeric characters (Standard Spotify ID format) if not re.match(r"^[a-zA-Z0-9]{22}$", song_id): raise ValueError("Invalid input: Must be a valid Spotify Track URL or a 22-character Spotify ID.") return song_id # We return just the ID to make the endpoint logic cleaner
class DownloadRequest(BaseModel): vid: str # The YouTube Video ID extracted from the /info endpoint vid: str
@field_validator('vid') @classmethod def validate_youtube_vid(cls, v: str) -> str: # Validate that the YouTube ID is exactly 11 characters (base64url format) if not re.match(r"^[a-zA-Z0-9_-]{11}$", v): raise ValueError("Invalid input: Must be a valid 11-character YouTube Video ID.") return v
# --- Endpoints ---
@app.post("/info")@app.post("/info", dependencies=[Depends(check_rate_limit)])async def get_info(request: InfoRequest): """ Extracts song metadata and returns the YouTube Video ID (vid). """ song_id = request.url.split("/")[-1] song_id = request.url # This is now guaranteed to be just the 22-char ID thanks to the validator async with httpx.AsyncClient() as client: try:16 unmodified lines "metadata": metadata } except httpx.HTTPStatusError as e: raise HTTPException(status_code=e.response.status_code, detail="Failed to fetch data from upstream API.") except Exception as e: raise HTTPException(status_code=500, detail=str(e))
@app.post("/download")@app.post("/download", dependencies=[Depends(check_rate_limit)])async def get_download_link(request: DownloadRequest): """ Fetches the actual MP3 download URL using the provided YouTube Video ID (vid).12 unmodified lines "raw_response": dl_data }
except httpx.HTTPStatusError as e: raise HTTPException(status_code=e.response.status_code, detail="Failed to fetch download link from upstream API.") except Exception as e: raise HTTPException(status_code=500, detail=str(e))
app.py+64-8