def get_spotify_user_tracks(request): # read credentials from the saved file from callback file = settings.SPOTIFY_LOCAL_FILE conf = tk.config_from_file(file, return_refresh=True) token = tk.refresh_user_token(*conf[:2], conf[3]) spotify = tk.Spotify(token) spotify_tracks = spotify.saved_tracks() tracks = [] for saved_track in spotify_tracks.items: track = saved_track.track album = track.album images = list(album.images) image = images[0].url spotify_link = tk.to_url('track', track.id) _artists = album.artists artists = [] for artist in _artists: artists.append(artist.name) t = { 'title': track.name, 'artists': artists, 'image': image, 'url': spotify_link, 'preview_url': track.preview_url, } tracks.append(t) save_spotify_track(track, artists, spotify_link) return JsonResponse(tracks, safe=False)
def get_spotify_object(tekore_cfg_file, scope=None): token = None if os.path.exists(tekore_cfg_file): conf = tekore.config_from_file(tekore_cfg_file, return_refresh=True) token = tekore.refresh_user_token(*conf[:2], conf[3]) if not scope: scope = tekore.Scope() elif not isinstance(scope, tekore.Scope): scope = tekore.Scope(scope) if not (scope <= token.scope): missing_scopes = scope - token.scope print("Existing token lacks scope(s): " + ", ".join(missing_scopes)) token = None if token is None: token = tekore.prompt_for_user_token(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI, scope=scope) if not token: print("Couldn't get Spotify API token") exit(1) tekore.config_to_file(tekore_cfg_file, (CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, token.refresh_token)) return tekore.Spotify(token)
def __init__(self): self.sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) file = 'tekore.cfg' conf = tk.config_from_file(file, return_refresh=True) token = tk.refresh_user_token(*conf[:2], conf[3]) self.tk = tk.Spotify(token)
def test_config_written_with_dict(self, conf_path): import tekore as tk written = {tk.client_secret_var: 'secret'} config_to_file(conf_path, written) with handle_warnings('ignore'): loaded = config_from_file(conf_path) assert (None, 'secret', None) == loaded
def test_config_tuple_nones_not_written(self, conf_path): original = ('id', 'secret', 'uri') config_to_file(conf_path, original) written = (None, 'another', None) config_to_file(conf_path, written) loaded = config_from_file(conf_path) assert ('id', 'another', 'uri') == loaded
def setup_config(scope): """ Configure setup for library-read step, return the spotify object which will interact with the Spotify API. """ conf = tk.config_from_file('credentials.ini') token = tk.prompt_for_user_token(*conf, scope=scope) spotify = tk.Spotify(token, chunked_on=True) return spotify
def authorize(): try: conf = tk.config_from_file(config_file, return_refresh=True) token = tk.refresh_pkce_token(conf[0], conf[3]) tk.config_to_file(config_file, conf[:3] + (token.refresh_token, )) except: client_secret = 'your_client_secret' redirect_uri = 'https://example.com/callback' # Or your redirect uri conf = (client_id, client_secret, redirect_uri) token = tk.prompt_for_pkce_token(client_id, redirect_uri, scope=tk.scope.every) tk.config_to_file(config_file, conf + (token.refresh_token, )) return tk.Spotify(token)
def authenticate(self): credentials = (self.CLIENT_ID, self.CLIENT_SECRET, self.REDIRECT_URI) if not os.path.isfile(self.CONFIG_NAME): token = tekore.prompt_for_user_token(*credentials, self.SCOPES) tekore.config_to_file( self.CONFIG_NAME, credentials + (token.refresh_token,) ) return token else: config = tekore.config_from_file(self.CONFIG_NAME, return_refresh=True) return tekore.refresh_user_token(config[0], config[1], config[3])
def spotify(): client_id = "<spotifyClientId>" client_secret = "<spotifyClientSecret>" redirect_uri = "http://localhost" conf = (client_id, client_secret, redirect_uri) file = 'tekore.cfg' try: conf = tk.config_from_file(file, return_refresh=True) token = tk.refresh_user_token(*conf[:2], conf[3]) except FileNotFoundError: token = tk.prompt_for_user_token(*conf, scope=tk.scope.every) tk.config_to_file(file, conf + (token.refresh_token, )) spot = tk.Spotify(token) current_track = spot.playback_currently_playing() if current_track and current_track.is_playing: name = current_track.item.name artist = " + ".join([a.name for a in current_track.item.artists]) display_message = f"{name} - {artist}" print(display_message) send_message(message=display_message, style=2, repeat=2) else: print("Nothing Playing")
import tekore as tk # Initialising Tekore tk_config_file_location = input("Provide Tekore config file location: ") config = tk.config_from_file(tk_config_file_location) user_token = tk.prompt_for_user_token(*config, scope=[ tk.scope.playlist_read_private, tk.scope.playlist_read_collaborative, tk.scope.playlist_modify_public, tk.scope.playlist_modify_private ]) spotify = tk.Spotify(user_token) # Exclusion lists exclusions = [ 'karaoke', 'the style of', 'tribute', 'originally performed by', 'includes hidden track', 'bluegrass rendition', 'Live From The Royal Albert Hall', 'Ghostface UK Version', 'Spotify', 'Djlilruben', 'djlilruben', 'Made Famous by', 'Bimbo Jones Radio Mix', 'Live Lounge' ] blacklisted_artists = [ 'Karaoke', "Pickin' On Series", 'Midifine Systems', 'Studio Allstars', 'Grandes Canciones - Versiones Acústicas', 'Lucky Voice Karaoke', 'The Karaoke Channel', 'Ameritz', 'Poptastik Karaoke', "Singer's Edge Karaoke", 'Brazillian Bossa Nova', 'Nursery Rhymes 123', 'DJ Top Gun', 'Dj lil Ruben', 'Extreme DJs & Remixers' ]
def _load_config(filename): try: return tk.config_from_file(filename, return_refresh=True) except: print("invallid config.ini file")
import tekore as tk conf = tk.config_from_file("conf.txt") token = tk.prompt_for_user_token(*conf, scope=tk.scope.every) spotify = tk.Spotify(token) spotify.playlist_follow(playlist_id="4eGUqz708EdfM4bkNaYsL6") playlist = spotify.followed_playlists(limit=1).items[0] track = spotify.playlist_items(playlist.id, limit=1).items[0].track name = f'"{track.name}" from {playlist.name}' if track.episode: print(f'Cannot analyse episodes!\nGot {name}.') elif track.track and track.is_local: print(f'Cannot analyse local tracks!\nGot {name}.') else: print(f'Analysing {name}...\n') analysis = spotify.track_audio_features(track.id) print(repr(analysis))
def __init__(self): client_id, client_secret, _ = tk.config_from_file( "/bot/server/conf.ini", section='SPOTIFY') app_token = tk.request_client_token(client_id, client_secret) self.spotify = tk.Spotify(app_token)
def test_file_pathlib_path_accepted(self, conf_path): from pathlib import Path path = Path(conf_path) conf = config_from_file(path) assert conf == ('df_id', 'df_secret', 'df_uri')
# Playing the selected album spotify.playback_start_context( tk.to_uri('album', selected_album.id)) exit() elif answer == "n": print(f"\n{ct.prLightPurple}Selecting another album...{ct.endc}") break elif answer == "quit": exit() else: print( f"\n{ct.prRed}I didn't understood that. Please try again{ct.endc}") # Authorization conf = tk.config_from_file('conf.txt') token = tk.prompt_for_user_token( *conf, scope=tk.scope.user_library_read + tk.scope.user_modify_playback_state) spotify = tk.Spotify(token) # Getting the number of all saved albums albums_number = spotify.saved_albums(limit=1).total albums = {} # Checking if the user has any saved albums if albums_number == 0: print(f"\n{ct.prRed}You don't have any saved albums. Aborting!{ct.endc}") sleep(2) exit() print(
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) server = app.server project_path = '/home/ubuntu/offbeat/src/' index_filename = 'index.bin' # initiate hnswlib index num_elements = 2000000 dim = 180 index = hnswlib.Index(space = 'cosine', dim = dim) index.load_index(os.path.join(project_path, index_filename), max_elements = num_elements) index.set_ef(50) # initiate spotify token_file = 'tekore.cfg' conf = tk.config_from_file(os.path.join(project_path, token_file), return_refresh=True) token = tk.refresh_user_token(*conf[:2], conf[3]) spotify = tk.Spotify(token) conn = connect() num_neighbors = 20 num_initial_rows = 100 initial_query = "SELECT si.name, si.artist, si.popularity, si.url FROM song_info as si LIMIT {}".format(num_initial_rows) default_df = pd.read_sql_query(initial_query, conn) default_df['rank'] = np.arange(1, num_initial_rows + 1) default_df['distance'] = np.zeros(num_initial_rows) default_df = default_df[['rank', 'distance', 'name', 'artist', 'popularity', 'url']] colors = { 'background': '#111111', 'text': '#D63BEE'
def get_config(): conf_path = pathlib.Path.home().joinpath('.spotify.cnf') return tk.config_from_file(conf_path.as_posix())
def test_file_another_section_is_case_sensitive(self, conf_path): config_names_set('client_id', 'client_secret', 'redirect_uri', '_') with handle_warnings('ignore'): conf = config_from_file(conf_path) assert conf == (None, None, None)
from app import app from flask import render_template, flash, redirect, request, session from app.forms import Input, LoginForm from spot import Spot import tekore as tk from tekore import model """ export SPOTIFY_CLIENT_ID="" export SPOTIFY_CLIENT_SECRET="" export SPOTIFY_REDIRECT_URI="http://*****:*****@app.route('/') def main(): user = session.get('user', None) song = None in_link = '<a href="/login">login</a>' out_link = '<a href="/logout">logout</a>' if user is None: page = f'User ID: {user}<br>You can {in_link} or {out_link}.'
def test_config_written_with_tuple_refresh_token(self, conf_path): written = ('id', 'secret', 'uri', 'refresh') config_to_file(conf_path, written) loaded = config_from_file(conf_path, return_refresh=True) assert written == loaded
def test_config_write_to_section(self, conf_path): written = ('id', 'secret', 'uri') config_to_file(conf_path, written, section='SEC') loaded = config_from_file(conf_path, section='SEC') assert written == loaded
def test_file_nonexistent_file_raises(self): with pytest.raises(FileNotFoundError): config_from_file('not_file.ini')
def test_config_written_with_tuple(self, conf_path): written = ('id', 'secret', 'uri') config_to_file(conf_path, written) loaded = config_from_file(conf_path) assert written == loaded
def test_missing_variables_warned(self, conf_path): config_names_set('CLIENT_ID', 'CLIENT_SECRET', 'REDIRECT_URI', '_') with handle_warnings('error'): with pytest.raises(MissingConfigurationWarning): config_from_file(conf_path, 'MISSING')
def test_file_refresh_returned(self, conf_path): conf = config_from_file(conf_path, return_refresh=True) assert conf == ('df_id', 'df_secret', 'df_uri', 'df_refresh')
def test_file_another_section(self, conf_path): config_names_set('CLIENT_ID', 'CLIENT_SECRET', 'REDIRECT_URI', '_') conf = config_from_file(conf_path, 'ANOTHER') assert conf == ('an_id', 'an_secret', 'an_uri')
def __init__(self): file = 'tekore.cfg' conf = tk.config_from_file(file, return_refresh=True) token = tk.refresh_user_token(*conf[:2], conf[3]) self.tk = tk.Spotify(token)
def test_file_missing_variables_returns_none(self, conf_path): config_names_set('CLIENT_ID', 'CLIENT_SECRET', 'REDIRECT_URI', '_') with handle_warnings('ignore'): conf = config_from_file(conf_path, 'MISSING') assert conf == (None, None, None)
def test_file_default_section(self, conf_path): conf = config_from_file(conf_path) assert conf == ('df_id', 'df_secret', 'df_uri')
def test_file_nonexistent_section_raises(self, conf_path): with pytest.raises(KeyError): config_from_file(conf_path, 'NOTSECTION')