Update app.py
Browse files513 unmodified lines514515516517517518518519520521522523524525520526527528529530531532533534535536537538539523524540541542543544545546547548549550551552553554555556557558527559560561562563564565566567568569570571530531532533534535536572573574575576577578579580581582513 unmodified lines
@app.get("/fetch")async def generate_mock_session_token():@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 mock_token = secrets.token_hex(16) # 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 function token = get_spotify_token() # 3. Fetch Track Info from the official Spotify API headers = {"Authorization": f"Bearer {token}"} spotify_api_url = f"https://api.spotify.com/v1/tracks/{track_id}" expire_in_seconds = 3600 expires_timestamp_ms = int((time.time() + expire_in_seconds) * 1000) 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 filename track_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 characters safe_track_name = track_name.replace("/", "_").replace("\\", "_") safe_artist_name = artist_name.replace("/", "_").replace("\\", "_") filename = f"{safe_track_name} - {safe_artist_name}" response_data = { # 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 = 3600 expires_timestamp_ms = int((time.time() + expire_in_seconds) * 1000)
# 6. Return the combined JSON payload return JSONResponse(content={ "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) "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