Skip to content

Commit

Permalink
Tested some Spotify authentifaction workflows + added some functions …
Browse files Browse the repository at this point in the history
…for Spotify & Deezer
  • Loading branch information
SebRil committed Jul 5, 2024
1 parent 0afd5f0 commit e9efd3c
Show file tree
Hide file tree
Showing 4 changed files with 157 additions and 21 deletions.
10 changes: 9 additions & 1 deletion DeezerHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,12 @@ def get_loved_tracks_as_dir(self, private_user):
result.append([track.title, track.artist.name, track.album.title])
i+=25
output_dict['Coups de coeur'] = result
return output_dict
return output_dict

def get_public_playlist(self, playlist_id):
playlist = None
try:
playlist = self.client.get_playlist(playlist_id)
except Exception as e:
print('Couldn\'t retrieve playlist with id: ' + playlist_id)
return playlist
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,11 @@
Launch the "testUI.py" file to run the main UI.

## Create a Spotify API Application
- Go to https://developer.spotify.com/documentation/web-api
- Go to https://developer.spotify.com/dashboard
- Create an app:
- Provide an app name & description
- Set the redirect URI to http://localhost
- Tick the usage of the Web API
- Go to the app's settings
- Copy the Client ID and the Client Secret into a notepad (or anywhere, just don't save it!)

64 changes: 63 additions & 1 deletion SpotifyHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,61 @@
from spotipy.oauth2 import SpotifyClientCredentials, SpotifyOAuth
import os
from math import ceil
import base64
import datetime
from urllib.parse import urlencode
import requests
import spotipy.util as util



class SpotifyHandler:

def __init__(self, client_id, client_secret, redirect_uri):
print('Creation d\'un client spotify')
os.environ['SPOTIPY_CLIENT_ID'] = client_id
os.environ['SPOTIPY_CLIENT_SECRET'] = client_secret
os.environ['SPOTIPY_REDIRECT_URI'] = redirect_uri

scope = "user-library-read playlist-modify-private playlist-modify-public"
self.sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

#print('test')
#token = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
#cache_token = token.get_access_token()
#print(cache_token)
#self.sp = spotipy.Spotify(cache_token)

#self.sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(),scope=scope)

#username = 'serilba@laposte.net'
#scope = "user-library-read playlist-modify-private playlist-modify-public"
#token = util.prompt_for_user_token(username, scope)
#self.sp = spotipy.Spotify(auth=token)
#results = sp.current_user_saved_tracks()

#access_token = None
#token_url = "https://accounts.spotify.com/api/token"
#if client_secret == None or client_id == None:
#raise Exception("You must set client_id and client_secret")
#client_creds = f"{client_id}:{client_secret}"
#client_creds_b64 = base64.b64encode(client_creds.encode())
#print(client_creds)
#print(client_creds_b64)
#token_headers = {"Authorization": f"Basic {client_creds_b64}"}
#token_data = {"grant_type": "client_credentials"}
#r = requests.post(token_url, data=token_data, headers=token_headers)
#print(r)
#print(r.status_code)
#if r.status_code not in range(200, 299):
#print("Could not authenticate client")
#print('yolo')
#data = r.json()
#print(data)
#access_token = data['access_token']
#print(access_token)
#self.sp = spotipy.Spotify(auth=access_token)

try :
self.user_id = self.sp.current_user()['id']
except :
Expand Down Expand Up @@ -109,4 +154,21 @@ def add_tracks_to_playlist(self, playlist_id, tracks_list):
self.sp.playlist_add_items(playlist_id, tracks_list[j:(j + API_limit)])
j += API_limit
if last_packet_length > 0:
self.sp.playlist_add_items(playlist_id, tracks_list[j:(j + last_packet_length)])
self.sp.playlist_add_items(playlist_id, tracks_list[j:(j + last_packet_length)])

# Récupère les playlists
def get_playlists(self):
playlists = self.sp.current_user_playlists()
playlists_dict = {}
for playlist in playlists['items']:
playlists_dict[playlist['name']] = {}
playlists_dict[playlist['name']]['id'] = playlist['id']
playlists_dict[playlist['name']]['tracks'] = ['TODO']
# TODO: add list of tracks in this playlist!
return playlists_dict

# Récupère les morceaux d'une playlist
def get_playlist_tracks(self,playlist_id):
tracks = self.sp.playlist(playlist_id,additional_types=('track'))
print('##########################')
print(tracks['items'])
95 changes: 77 additions & 18 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,39 +7,71 @@
# - Playlist ID
# - User ID (public playlists)
# - User application (private playlists)
# TODO: ask user app_id, app_secret, access_token infos
deezer_handler = dh.DeezerHandler()

# Left menu
# Deezer elements
st.sidebar.text('Deezer')
deezer_element_choice = st.sidebar.selectbox(
'What element would you like to retrieve from Deezer?',
('One public playlist', 'A user\'s public playlists', 'All playlists from a user')
)
playlist_id = ''
user_id = ''
app_id,app_secret,access_token='','',''
dzr_playlist_id = ''
dzr_user_id = ''
dzr_app_id,dzr_app_secret,dzr_access_token='','',''
default_value = 'example: 12345678'
if deezer_element_choice == 'One public playlist':
playlist_id = st.sidebar.text_input("Playlist ID", default_value)
dzr_playlist_id = st.sidebar.text_input("Playlist ID", default_value)
elif deezer_element_choice == 'A user\'s public playlists':
user_id = st.sidebar.text_input("Deezer user ID", default_value)
dzr_user_id = st.sidebar.text_input("Deezer user ID", default_value)
elif deezer_element_choice == 'All playlists from a user':
app_id = st.sidebar.text_input("Application ID", "")
app_secret = st.sidebar.text_input("Application Secret", "")
access_token = st.sidebar.text_input("Access Token", "")
dzr_app_id = st.sidebar.text_input("Application ID", "")
dzr_app_secret = st.sidebar.text_input("Application Secret", "")
dzr_access_token = st.sidebar.text_input("Redirect URI", "")

if playlist_id != '' and playlist_id != default_value:
#TODO
pass
if user_id != '' and user_id != default_value:
# Spotify elements
st.sidebar.text('Spotify')
spfy_app_id = st.sidebar.text_input("Application ID", "")
spfy_app_secret = st.sidebar.text_input("Application Secret", "")
spfy_access_token = st.sidebar.text_input("Redirect URI", "")


# Methods
def handle_deezer_input_playlist(playlist_id):
try:
deezer_handler = dh.DeezerHandler()
playlist = deezer_handler.get_public_playlist(playlist_id)
st.write("The playlist title is", playlist.title)
except Exception as e:
st.sidebar.write("Wrong playlist ID 🫣")
playlist = None

if playlist is not None:
tracks = {}
tracks = deezer_handler.get_playlist_as_dir([playlist],tracks)
print(tracks)
#df = pd.DataFrame([tracks[0]], columns=["Title", "Author", "Album"])
df = pd.DataFrame.from_dict(tracks)#, columns=["Title", "Author", "Album"])
#df_spotify = pd.DataFrame([["Test1", "Test1", "Test1"],["Test2", "Test2", "Test2"]],columns=["Title", "Author", "Album"])
#edited_df = st.data_editor(df)
edited_df = st.table(df)
#col1, col2 = st.columns(2)
#col1.data_editor(df)
#col2.data_editor(df_spotify)
#tabs
#tab1, tab2 = st.tabs(["Data", "Chart"])
#with tab1:
# st.table(df)

def handle_deezer_input_user(dzr_user_id):
try:
st.sidebar.write("The user is", deezer_handler.get_user_name(user_id))
deezer_handler = dh.DeezerHandler()
st.sidebar.write("The user is", deezer_handler.get_user_name(dzr_user_id))
except Exception as e:
st.sidebar.write("Wrong user ID 🫣")
user_id = None
dzr_user_id = None

if user_id is not None:
deezer_playlists = deezer_handler.get_playlists_from_user(user_id)
if dzr_user_id is not None:
deezer_playlists = deezer_handler.get_playlists_from_user(dzr_user_id)

selected_playlists = st.multiselect(
"Select playlists you want to migrate",
Expand All @@ -60,3 +92,30 @@
#with tab1:
# st.table(df)

def handle_deezer_input_app(app_id, app_secret, app_token):
pass

if dzr_playlist_id != '' and dzr_playlist_id != default_value:
handle_deezer_input_playlist(dzr_playlist_id)
if dzr_user_id != '' and dzr_user_id != default_value:
handle_deezer_input_user(dzr_user_id)

if spfy_app_id != '' and spfy_app_secret != '' and spfy_access_token != '':
try:
spotify_handler = sh.SpotifyHandler(spfy_app_id,spfy_app_secret,spfy_access_token)
st.sidebar.write("Successfully connected to Spotify! 😊")
except Exception as e:
st.sidebar.write("Couldn't connect to this Spotify App 🫣")
spotify_handler = None

if spotify_handler is not None:
spotify_playlists = spotify_handler.get_playlists()

selected_playlists = st.multiselect(
"Select playlists you want to browse",
list(spotify_playlists.keys()),
[])

for selected_playlist in selected_playlists :
print('Getting tracks from playlist ' + selected_playlist + ' id (' + spotify_playlists[selected_playlist]['id'] + ')')
spotify_handler.get_playlist_tracks(spotify_playlists[selected_playlist]['id'])

0 comments on commit e9efd3c

Please sign in to comment.