Update app.py
Browse files1 unmodified line23456786 unmodified lines1516171819202122568 unmodified lines5915925935945955966 unmodified lines60360460560660760860961061161261361461561661761861962062162262316 unmodified lines64064164264364464564664764864965012 unmodified lines6636646656666676686691 unmodified lineimport loggingimport secretsfrom typing import Optional, Dict, Anyfrom fastapi import FastAPI, HTTPException, Requestimport requestsfrom bs4 import BeautifulSoupimport os6 unmodified linesimport urllib.parsefrom fastapi.responses import JSONResponseimport httpxfrom pydantic import BaseModelfrom urllib.parse import urlparse, parse_qs# Configure logginglogging.basicConfig(568 unmodified lines# --- 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 ---class InfoRequest(BaseModel):url: str # The Spotify URL or Song IDclass DownloadRequest(BaseModel):vid: str # The YouTube Video ID extracted from the /info endpoint# --- Endpoints ---@app.post("/info")async def get_info(request: InfoRequest):"""Extracts song metadata and returns the YouTube Video ID (vid)."""song_id = request.url.split("/")[-1]async with httpx.AsyncClient() as client:try:16 unmodified lines"metadata": metadata}except Exception as e:raise HTTPException(status_code=500, detail=str(e))@app.post("/download")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 Exception as e:raise HTTPException(status_code=500, detail=str(e))1 unmodified line23456786 unmodified lines151617181920212223242526568 unmodified lines5955965975985996006016026036046056 unmodified lines61261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267316 unmodified lines69069169269369469569669769869970070170212 unmodified lines7157167177187197207217227237247251 unmodified lineimport loggingimport secretsfrom typing import Optional, Dict, Anyfrom fastapi import FastAPI, HTTPException, Request, Dependsimport requestsfrom bs4 import BeautifulSoupimport os6 unmodified linesimport urllib.parsefrom fastapi.responses import JSONResponseimport httpxfrom 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"}# --- 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.hosttoday = date.today()# Reset count if it's a new day for this IPif ip_usage[client_ip]["date"] != today:ip_usage[client_ip] = {"date": today, "count": 0}# Check if limit is exceededif 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 usageip_usage[client_ip]["count"] += 1return client_ip# --- Request Models & Validation ---class InfoRequest(BaseModel):url: str@field_validator('url')@classmethoddef validate_spotify_id(cls, v: str) -> str:# Extract ID if a full Spotify URL is providedmatch = 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 cleanerclass DownloadRequest(BaseModel):vid: str@field_validator('vid')@classmethoddef 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", 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 # This is now guaranteed to be just the 22-char ID thanks to the validatorasync 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", 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