Пример #1
0
 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)
Пример #2
0
def get_token(refresh_token: Optional[str], client_id: Optional[str],
              client_secret: Optional[str]) -> Optional[RefreshingToken]:
    """
    Tries to generate a self-refreshing token from the parameters. The
    authentication token itself isn't even saved in the config because it
    expires in an hour. Instead, the refresh token is used to generate a new
    token whenever the app is launched.

    `refresh_token` is a special token used to refresh or generate a token.
    It's useful to create a RefreshingToken rather than a regular Token so
    that it automatically refreshes itself when it's expired.
    """

    # Trying to use the environment variables
    if client_id is None:
        client_id = os.getenv('SPOTIFY_CLIENT_ID')
    if client_secret is None:
        client_secret = os.getenv('SPOTIFY_CLIENT_SECRET')

    # Checking that the credentials are valid. The refresh token isn't really
    # needed because tekore.refresh_user_token already obtains it from the
    # refresh token.
    for c in (refresh_token, client_id, client_secret):
        if c in (None, ''):
            logging.info("Rejecting the token because one of the credentials"
                         " provided is empty.")
            return None

    # Generating a RefreshingToken with the parameters
    return refresh_user_token(client_id, client_secret, refresh_token)
Пример #3
0
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)
Пример #4
0
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)
Пример #5
0
 def load_token(self):
     if self.tauon.prefs.spotify_token:
         try:
             self.token = tk.refresh_user_token(self.tauon.prefs.spot_client, self.tauon.prefs.spot_secret, self.tauon.prefs.spotify_token)
         except:
             print("ERROR LOADING TOKEN")
             self.tauon.prefs.spotify_token = ""
Пример #6
0
    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])
Пример #7
0
def validate_credentials(filename='config.ini'):
    """
    Check the config file for valid credentials, or prompt login window to obtain token
    """

    config = _load_config(filename)
    client_id, client_secret, redirect_uri, refresh_token = config

    if refresh_token:
        token = tk.refresh_user_token(*config[:2], refresh_token)
    else:
        scope = tk.scope.every
        token = tk.prompt_for_user_token(client_id, client_secret,
                                         redirect_uri, scope)
    refresh_token = token.refresh_token
    tk.config_to_file(filename,
                      (client_id, client_secret, redirect_uri, refresh_token))
    return token
Пример #8
0
def get_access_token():
    """
    Returns an access token for interfacing with Spotify Web API. Refreshes it if needed.
    :return: String access token
    """
    ddb_token_item_key = {'spotify': 'prod'}
    ddb_credentials_item_key = {'spotify': 'Soundprint'}

    access_token_ddb_key = 'accessToken'
    expires_at_ddb_key = 'expiresAt'

    client_id_ddb_key = 'clientId'
    client_secret_ddb_key = 'clientSecret'
    refresh_token_ddb_key = 'refreshToken'

    ddb_table = boto3.resource('dynamodb').Table('SpotifyTokenState')

    # Get currently stored access token
    current_token_item = ddb_table.get_item(Key=ddb_token_item_key)['Item']

    if current_token_item[expires_at_ddb_key] > datetime.now().timestamp():
        # If current token has not expired yet, return it
        return current_token_item[access_token_ddb_key]
    else:
        # If current token has expired, refresh it and update token store,
        # then attempt getting stored token again
        credentials_item = ddb_table.get_item(
            Key=ddb_credentials_item_key)['Item']
        client_id = credentials_item[client_id_ddb_key]
        client_secret = credentials_item[client_secret_ddb_key]
        refresh_token = credentials_item[refresh_token_ddb_key]

        refreshing_token = tk.refresh_user_token(client_id, client_secret,
                                                 refresh_token)

        new_token_item = {
            access_token_ddb_key: refreshing_token.access_token,
            expires_at_ddb_key: int(datetime.now().timestamp()) + 3200
        }
        new_token_item.update(ddb_token_item_key)

        ddb_table.put_item(Item=new_token_item)
        return get_access_token()
Пример #9
0
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")
Пример #10
0
def run_program():

    config_file = "/home/kip/.config/polybar/spotify-status/config.cfg"

    config = configparser.ConfigParser()
    config.read(config_file)

    tail = False
    tail_delay = 0
    cutoff = -1
    vibe = True
    config_vibe = True

    if "settings" in config:
        if "tail" in config["settings"]:
            tail = True if config["settings"]["tail"] == "True" else tail
        if "tail_delay" in config["settings"]:
            tail_delay = float(config["settings"]["tail_delay"])
        if "active" in config["settings"]:
            if config["settings"]["active"] == "False":
                return
        if "cutoff" in config["settings"]:
            cutoff = int(config["settings"]["cutoff"])

    try:
        warnings.simplefilter('error')

        try:
            conf = tk.config_from_file(config_file, return_refresh=True)
        except tk.MissingConfigurationWarning:
            print("fuckfuck config")
            return
            config_vibe = False
            raise Exception("")

        warnings.simplefilter('ignore')

        user_token = tk.refresh_user_token(*conf[:2], conf[3])

        spotify = tk.Spotify(user_token)

    except:
        vibe = False
#TODO: Make this relevant again

    play = ""
    pause = ""
    previous = ""
    next = ""
    saved = ""
    notsaved = ""

    # Only update the creds file when showing the track to avoid duplicates or something
    #	if len(argv) > 1:
    #		if argv[1] == "track":
    #			tk.config_to_file(config_file, (conf[0], conf[1], conf[2], user_token.refresh_token))

    while True:
        if len(argv) > 1:
            try:
                track = spotify.playback_currently_playing()
            except:
                track = 0
                vibe = False

            if argv[1] == "track":
                try:
                    if not vibe:
                        raise Exception("WE NOT GOOD FAM")

                    if isinstance(track, tk.model.CurrentlyPlaying):
                        track_name = track.item.name
                        track_artists = track.item.artists
                        track_artist_names = track_artists[0].name

                        # Cuz non-western characters dont exactly render properly
                        if track_name == "佐賀事変" and track_artist_names == "フランシュシュ":
                            track_name = "Sagajihen"
                            track_artist_names = "Franchouchou"

                        for i in range(1, len(track_artists)):
                            track_artist_names += ", " + track_artists[i].name

                        toPrint = track_name + " - " + track_artist_names

                        if cutoff > 0 and len(toPrint) > cutoff:
                            toPrint = toPrint[:cutoff - 3]
                            toPrint += "..."

                        print(toPrint, flush=True)
                    else:
                        print(" - ", flush=True)

                except:
                    if config_vibe:
                        print(" - ", flush=True)
                    else:
                        print("Missing config, login again manually")

            elif argv[1] == "playpause_dry":
                try:
                    if isinstance(track, tk.model.CurrentlyPlaying):
                        print(pause if track.is_playing else play, flush=True)
                    else:
                        print(play, flush=True)

                except:
                    print(play)

            elif argv[1] == "play":
                spotify.playback_resume()
                break
            elif argv[1] == "pause":
                spotify.playback_pause()
                break

            elif argv[1] == "playpause":
                try:
                    if isinstance(track, tk.model.CurrentlyPlaying):
                        if track.is_playing:
                            spotify.playback_pause()
                            print(play)
                        else:
                            spotify.playback_resume()
                            print(pause)
                    else:
                        print(play)
                except:
                    print(play)
                break


#TODO: something when there isnt a track playing (might work now tho)
            elif argv[1] == "saved":
                try:
                    if isinstance(track, tk.model.CurrentlyPlaying):
                        print(saved if spotify.saved_tracks_contains(
                            [track.item.uri.split(':')[-1]])[0] else notsaved,
                              flush=True)
                    else:
                        print(notsaved, flush=True)
                except:
                    print(notsaved, flush=True)

            elif argv[1] == "save":
                try:
                    id = track.item.uri.split(':')[-1]

                    if spotify.saved_tracks_contains([id])[0]:
                        spotify.saved_tracks_delete([id])
                        print(notsaved)
                    else:
                        spotify.saved_tracks_add([id])
                        print(saved)

                except:
                    print(notsaved)
                break

            elif argv[1] == "random_queue":
                all_uris = []
                for i in range(0, (spotify.saved_tracks()).total, 50):
                    page = (spotify.saved_tracks(limit=50, offset=i)).items
                    for j in range(0, len(page)):
                        all_uris.append(page[j].track.uri)
                random.shuffle(all_uris)
                for i in range(0, len(all_uris)):
                    spotify.playback_queue_add(all_uris[i])
                break

            elif argv[1] == "previous_dry":
                print(previous)
                break

            elif argv[1] == "next_dry":
                print(next)
                break

            elif argv[1] == "previous":
                try:
                    spotify.playback_previous()
                except:
                    pass
                print(previous)
                break

            elif argv[1] == "next":
                try:
                    spotify.playback_next()
                except:
                    pass
                print(next)
                break

            else:
                print("Unknown argument")
                break

        else:
            break

        if not tail:
            break

        vibe = True
        sleep(tail_delay)
Пример #11
0
    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)
Пример #12
0
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'
}
Пример #13
0
def save_edited_playlist():
    """Update db for an edited playlist and save to Spotify"""

    user_id = session.get('user_id')
    user = crud.get_user(user_id) if user_id else None
    if not user:
        raise 'TODO Unautborized Exception'

    data = request.get_json()
    playlist_track_ids = data["playlist_tracks"]
    playlist_title = data["playlist_title"]
    playlist_id = data["playlist_id"]
    save_to_spotify = data["save_to_spotify"]

    playlist = crud.get_playlist_by_id(playlist_id)
    spotify_playlist_id = playlist.spotify_playlist_id

    if save_to_spotify == True:

        token = tk.refresh_user_token(client_id, client_secret,
                                      user.refresh_token)

        uris = []
        # TODO: tracks = crud.get_tracks_by_ids(playlist_track_ids)
        for track_id in playlist_track_ids:
            track = crud.get_track_by_track_id(track_id)
            uris.append("spotify:track:" + track.uid)

        name = data["playlist_title"]

        if spotify_playlist_id != None:

            with spotify.token_as(token):
                spotify.playlist_replace(playlist_id=spotify_playlist_id,
                                         uris=uris)
                spotify.playlist_change_details(
                    playlist_id=spotify_playlist_id,
                    name=name,
                    public=False,
                    collaborative=None,
                    description=None)
        else:
            with spotify.token_as(token):
                playlist_spot = spotify.playlist_create(user.spotify_id,
                                                        name=name,
                                                        public=False,
                                                        description=None)

                response = spotify.playlist_add(playlist_id=playlist_spot.id,
                                                uris=uris,
                                                position=None)

                spotify_playlist_id = playlist_spot.id

    playlist = crud.update_edited_playlist(
        playlist_id=playlist_id,
        playlist_track_ids=playlist_track_ids,
        playlist_title=playlist_title,
        spotify_playlist_id=spotify_playlist_id)

    return jsonify({"playlist_id": playlist_id})
Пример #14
0
 def test_expiring_user_token_refreshed(self, app_env, user_refresh):
     token = refresh_user_token(app_env[0], app_env[1], user_refresh)
     old_token = str(token)
     token._token._expires_at -= token._token.expires_in - 30
     assert old_token != str(token)
Пример #15
0
 def test_request_refreshed_token_returns_refreshing_token(
         self, app_env, user_refresh):
     token = refresh_user_token(app_env[0], app_env[1], user_refresh)
     assert isinstance(token, RefreshingToken)
Пример #16
0
            os.chdir(path_cred)
        except:
            ('failed to create directory, do you have write access?')
            exit()

    #dir = os.getcwd()

    if(path.exists(file_auth)):
        try:
            #fourth element is the refresh token
            #try to create new session based on this token
            spot_token = tekore.config_from_file(file_auth, return_refresh=True)
            client_id = spot_token[0]
            client_key = spot_token[1]
            user_re_token = spot_token[3] 
            spot_token = tekore.refresh_user_token(client_id, client_key, user_re_token)
            #spot_token = pickle.load(open(file_auth, 'rb'))
            ##skip directly to authentication portion
        except:
            print('cannot read auth.spoticli')
            print('attempting to delete auth.spoticli')
            if(fsop.fsop.delete_conf('')):
                print('auth.spoticli deleted')
                print('please restart spoticli')
                exit()
            print('unable to delete auth.spoticli')
            print('do you have read/write access to directory?')
            print('please attempt manually deleting the file and restarting spoticli')
            print('file is located in .config/spoticli/ directory')
            exit()
Пример #17
0
REDIRECT_URI = "http://localhost:8888/callback/"
REFRESH_TOKEN = "[REMOVED]"

# Temporary redirection to stderr for script usability
old_stdout = sys.stdout
sys.stdout = sys.stderr

creds = tk.Credentials(
    client_id=CLIENT_ID,
    client_secret=CLIENT_SECRET,
    redirect_uri=REDIRECT_URI,
)

cached_token = tk.refresh_user_token(
    creds.client_id,
    creds.client_secret,
    REFRESH_TOKEN
)

# If the token is invalid, prompt the user.
user_token = cached_token or tk.prompt_for_user_token(
    creds.client_id,
    creds.client_secret,
    creds.redirect_uri,
    scope=[
        tk.scope.playlist_read_private
    ]
)
s = tk.Spotify(user_token, max_limits_on=True, chunked_on=True)

# Restoring stdout
Пример #18
0
def get_token():
    global spotify
    file = 'tekore.cfg'
    conf = tk.config_from_file(file, return_refresh=True)
    token = tk.refresh_user_token(*conf[:2], conf[3])
    spotify = tk.Spotify(token)