Update app.py
Browse files513 unmodified lines514515516517518519520521522523524525526527528529530531532533534535536513 unmodified lines@app.get("/fetch")async def generate_mock_session_token():mock_token = secrets.token_hex(16)expire_in_seconds = 3600expires_timestamp_ms = int((time.time() + expire_in_seconds) * 1000)response_data = {"token": mock_token,"expires": expires_timestamp_ms,"user_id": "user_999","status": "success","session": "https://spotdown.org/api/get-session-token","download": "https://spotdown.org/api/download"}return JSONResponse(content=response_data)513 unmodified lines514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582513 unmodified lines@app.post("/fetch")async def fetch_track_info(request_data: TrackDlRequest):"""Accepts a Spotify track URL, fetches track metadata from Spotify,and returns it alongside a newly generated session token."""url = request_data.spotify_url# 1. Extract the Track ID from the Spotify URL# Example URL: https://open.spotify.com/track/4cOdK2wGLETKBW3PvgPWqT?si=...try:track_id = url.split("track/")[1].split("?")[0]except IndexError:raise HTTPException(status_code=400, detail="Invalid Spotify track URL format")# 2. Get a valid Spotify access token using your existing functiontoken = get_spotify_token()# 3. Fetch Track Info from the official Spotify APIheaders = {"Authorization": f"Bearer {token}"}spotify_api_url = f"https://api.spotify.com/v1/tracks/{track_id}"try:response = requests.get(spotify_api_url, headers=headers, timeout=10)response.raise_for_status()track_data = response.json()except requests.exceptions.RequestException as e:logger.error(f"Failed to fetch track info from Spotify API: {e}")raise HTTPException(status_code=500, detail="Failed to fetch track information from Spotify")# 4. Extract track name and primary artist to format the filenametrack_name = track_data.get("name", "Unknown Track")artists = track_data.get("artists", [])artist_name = artists[0].get("name", "Unknown Artist") if artists else "Unknown Artist"# Sanitize the filename to prevent path traversal or invalid characterssafe_track_name = track_name.replace("/", "_").replace("\\", "_")safe_artist_name = artist_name.replace("/", "_").replace("\\", "_")filename = f"{safe_track_name} - {safe_artist_name}"# Extract album cover (using the highest resolution image available)album_images = track_data.get("album", {}).get("images", [])album_cover_url = album_images[0]["url"] if album_images else None# 5. Generate the Mock Session Data (from the previous setup)mock_token = secrets.token_hex(16)expire_in_seconds = 3600expires_timestamp_ms = int((time.time() + expire_in_seconds) * 1000)# 6. Return the combined JSON payloadreturn JSONResponse(content={"token": mock_token,"expires": expires_timestamp_ms,"filename": filename,"track_info": {"id": track_id,"name": track_name,"artist": artist_name,"duration_ms": track_data.get("duration_ms"),"album_cover": album_cover_url,"spotify_uri": track_data.get("uri")},"status": "success"})
app.py+59-13