import spotipy from spotipy.oauth2 import SpotifyOAuth from fastapi import HTTPException from app.config import settings _oauth = SpotifyOAuth( client_id=settings.SPOTIFY_CLIENT_ID, client_secret=settings.SPOTIFY_CLIENT_SECRET, redirect_uri=settings.SPOTIFY_REDIRECT_URI, scope=settings.SPOTIFY_SCOPES, cache_path="data/.spotify_cache", open_browser=False, ) def get_auth_url() -> str: return _oauth.get_authorize_url() def exchange_code(code: str) -> dict: return _oauth.get_access_token(code, as_dict=True, check_cache=False) def get_client() -> spotipy.Spotify: token_info = _oauth.get_cached_token() if not token_info: raise HTTPException(status_code=401, detail="spotify_not_authenticated") if _oauth.is_token_expired(token_info): token_info = _oauth.refresh_access_token(token_info["refresh_token"]) return spotipy.Spotify(auth=token_info["access_token"]) def is_authenticated() -> bool: try: token_info = _oauth.get_cached_token() return token_info is not None except Exception: return False