From 564a2a4b9aa49af5f4cee426fc53b9ea79ea23de Mon Sep 17 00:00:00 2001 From: AnouarElKihal Date: Sat, 2 Aug 2025 05:04:53 +0200 Subject: [PATCH] creazione primi endpoint --- backend/auth/session.py | 4 ++++ backend/endpoints/spotify_api.py | 32 ++++++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/backend/auth/session.py b/backend/auth/session.py index 812f207..d35b021 100644 --- a/backend/auth/session.py +++ b/backend/auth/session.py @@ -49,9 +49,13 @@ class SessionData(): except requests.exceptions.RequestException as e: print(f"Errore durante il refresh del token: {e}") + raise e @property def access_tokens(self): + if self.nearly_expired(): + self.refresh() + return self.__access_token diff --git a/backend/endpoints/spotify_api.py b/backend/endpoints/spotify_api.py index 8f7c2cd..2507e91 100644 --- a/backend/endpoints/spotify_api.py +++ b/backend/endpoints/spotify_api.py @@ -11,7 +11,7 @@ SPOTIFY_CLIENT_SECRET = os.getenv("SPOTIFY_CLIENT_SECRET") SPOTIFY_REDIRECT_URI = os.getenv("HOST") + "/music/callback" SPOTIFY_AUTH_URL = "https://accounts.spotify.com/authorize" SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token" -SPOTIFY_PLAY_URL = "https://api.spotify.com/v1/me/player/play" +SPOTIFY_PLAY_URL = "https://api.spotify.com/v1/" # Step 1: Redirect user to Spotify login @music_router.get("/login") @@ -48,4 +48,32 @@ def callback(code: str): @music_router.get("/search") def search(query: str): - pass + try: + url = SPOTIFY_PLAY_URL + f"search?q={query}&type={["track"]}" + header = { + "Authorization": "Bearer " + SessionManager.instance().get_current_session().access_tokens, + "Content-Type": "application/json" + } + return requests.get(url, headers=header) + except Exception as e: + print(e) + +@music_router.get("/play") +def play(song_id: str): + url = SPOTIFY_PLAY_URL + "me/player/play" + body = { "uris": [f"spotify:track:{song_id}"] } + header = { + "Authorization": "Bearer " + SessionManager.instance().get_current_session().access_tokens, + "Content-Type": "application/json" + } + requests.put(url, data=body, headers=header) + +@music_router.get("/current-song") +def current_song(): + url = SPOTIFY_PLAY_URL + f"me/player/currently-playing?marketing=IT" + header = { + "Authorization": "Bearer " + SessionManager.instance().get_current_session().access_tokens, + "Content-Type": "application/json" + } + return requests.get(url, headers=header) +