Beispiel #1
0
def user_token(app_env, user_refresh):
    """
    Provides a user token based on the environment.
    """
    cred = tk.Credentials(*app_env)

    try:
        return cred.refresh_user_token(user_refresh)
    except tk.HTTPError as error:
        skip_or_fail(tk.HTTPError, 'Error in retrieving user token!', error)
Beispiel #2
0
 def __init__(self):
     self.client_id = '04b4767cc75549d7a19f70985c837dcb'
     self.client_secret = 'cfbd881c349a409ab4794b2547889ce1'
     self.redirect_uri = 'http://localhost/teste/spotifyTeste.php'
     self.cred = tk.Credentials(self.client_id, self.client_secret,
                                self.redirect_uri)
     self.app_token = tk.request_client_token(self.client_id,
                                              self.client_secret)
     self.spotify = tk.Spotify(self.app_token)
     self.inicialize = False
Beispiel #3
0
def app_token(app_env):
    """
    Provides an application token based on the environment.
    """
    cred = tk.Credentials(*app_env)

    try:
        return cred.request_client_token()
    except tk.HTTPError as error:
        skip_or_fail(tk.HTTPError, 'Error in retrieving application token!',
                     error)
def queue_song(db: Session, song_url: str, spotify_username: str):
    if spotify_username:
        conf = tk.config_from_environment()
        cred = tk.Credentials(*conf)
        spotify = tk.Spotify()
        spotify_data = crud.spotify.get(db_session=db, id=spotify_username)
        token = cred.refresh_user_token(spotify_data.refresh_token)
        with spotify.token_as(token):
            uri = "spotify:track:" + song_url.split("/").pop(-1)
            spotify.playback_queue_add(uri)
    else:
        print("ERROR: NO USERNAME - " + str(spotify_username))
Beispiel #5
0
def get_spotify_auth() -> UserAuth:
    """get a User auth object
    Returns:
        auth
    """
    conf = (current_app.config['SPOTIFY_CLIENT_ID'],
            current_app.config['SPOTIFY_CLIENT_SECRET'],
            current_app.config['SPOTIFY_REDIRECT_URI'])
    cred = tk.Credentials(*conf)
    # scopes allow client to read user's name, id, avatar & user's top artists/tracks
    scope = tk.Scope(tk.scope.user_top_read, tk.scope.user_read_private)
    auth = tk.UserAuth(cred, scope)
    return auth
def get_left_playtime(db: Session, spotify_username: str) -> int:
    if spotify_username:
        conf = tk.config_from_environment()
        cred = tk.Credentials(*conf)
        spotify = tk.Spotify()
        spotify_data = crud.spotify.get(db_session=db, id=spotify_username)
        token = cred.refresh_user_token(spotify_data.refresh_token)
        with spotify.token_as(token):
            current = spotify.playback_currently_playing()
            if current:
                return current.item.duration_ms - current.progress_ms
            else:
                return 0
    else:
        return 0
Beispiel #7
0
 def get_user(self):
     """
     Get a tekore.Spotify object representing a user using the refresh token.
     :return: None if the refresh token is invalid.
     """
     refresh_token = self.get_refresh_token()
     if refresh_token:
         creds = tk.Credentials(client_id=self.client_id)
         try:
             new_token = creds.refresh_pkce_token(refresh_token)
             self.set_refresh_token(new_token.refresh_token)
             return tk.Spotify(new_token)
         except tk.BadRequest:
             self.remove_refresh_token()
     return None
    def __init__(self):
        """Read the "SPOTIFY" section from the given config path and configure the Credentials object.

        Parameters
        ----------
        config_path: str
            Path to the configuration file.
        """
        client_id = config.SPOTIFY_CLIENT_ID
        client_secret = config.SPOTIFY_CLIENT_SECRET
        redirect_uri = config.SPOTIFY_REDIRECT_URI
        logging.info(redirect_uri)
        self.Credentials = tk.Credentials(client_id,
                                          client_secret,
                                          redirect_uri,
                                          asynchronous=True)
Beispiel #9
0
def get_spotify_client():
    token_dict = current_token_dict()
    if token_dict:
        # If token has expired, refresh it
        if int(time.time()) > token_dict['expires_at']:
            app.server.logger.debug('Spotify tokens expired, refreshing...')
            new_token = tk.Credentials(
                client_id=client_id,
                client_secret=client_secret,
                redirect_uri=redirect_uri).refresh_user_token(
                    token_dict['refresh_token'])
            # Save to DB
            save_spotify_token(new_token)
            # Query the new tokens into a dict
            token_dict = current_token_dict()

        client = tk.Spotify(token_dict['access_token'])
    else:
        client = tk.Spotify()

    return client
Beispiel #10
0
def check_spotify_login() -> Optional[tuple]:
    """checks if the person's logged in the token's not expired
    refreshes token if present

    Returns:
        (user, token)
    """
    user = session.get('user', None)
    token = session.get('token', None)
    if token:
        token = pickle.loads(session.get('token', None))

    if user is None or token is None:
        print('either user or token is None')
        session.pop('user', None)
        session.pop('token', None)
        return None, None

    if token.is_expiring:
        # get new access token
        print('token is expiring')
        conf = (current_app.config['SPOTIFY_CLIENT_ID'],
                current_app.config['SPOTIFY_CLIENT_SECRET'],
                current_app.config['SPOTIFY_REDIRECT_URI'])
        print(user)
        cred = tk.Credentials(*conf)
        user_entry = User.query.filter_by(spotify_id=user).first()
        print(f"user entry: {user_entry}")
        if user_entry:
            print(f'user found: {user}')
            # get user's refresh token from db
            refresh_token = user_entry.spotify_token
            print(f'refresh_token: {refresh_token}')
            if refresh_token:
                # get new token via refresh token
                token = cred.refresh_user_token(refresh_token)
                session['token'] = pickle.dumps(token)

    return user, token
Beispiel #11
0
import tekore as tk

from flask import Flask, request, redirect, session, render_template, jsonify, make_response
from pprint import pprint

from lyricscraper import search_lyrics
from config import *

conf = (CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)
cred = tk.Credentials(*conf)
spotify = tk.Spotify()

users = {}
auths = {}

app = Flask(__name__)
app.config['SECRET_KEY'] = 'chicken'
playbackdata = {}


def get_user_data():
    user = spotify.current_user()
    if not len(user.images):
        pfp = 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png'
    else:
        pfp = user.images[0].url
    data = {
        'pfp':
        pfp,
        'name':
        user.display_name,
Beispiel #12
0
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
import tekore as tk
from dotenv import load_dotenv
import os

app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# initialize Spotify cursor
load_dotenv()
CLIENT_ID = os.getenv('CLIENT_ID')
CLIENT_SECRET = os.getenv('CLIENT_SECRET')
cred = tk.Credentials(CLIENT_ID, CLIENT_SECRET)
access_token = cred.request_client_token()
spotify = tk.Spotify(access_token)


@app.route('/')
def root():
    return "You don't want to look at this page"


@app.route('/request')
def request():
    tracks, = spotify.search('5 best songs', types=('track', ), limit=5)
    result = ''
    for track in tracks.items:
        result = result + track.name + '\n'  #' by ' + track.artists.name +
    return result
Beispiel #13
0
EXCLUDED_PLAYLISTS = [
    'Discover Weekly',
    'New Releases',
]
CLIENT_ID = "[REMOVED]"
CLIENT_SECRET = "[REMOVED]"
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=[
Beispiel #14
0
import tekore as tk
import os
from flask import Flask, Response, session, jsonify
from functools import wraps

spotify_conf = tk.config_from_environment()
spotfy_cred = tk.Credentials(*spotify_conf)
spotify = tk.Spotify()

user_to_token = {}
app = Flask(__name__)


# Decorate to ensure user is logged in to spotify
def spotify_user_logged_in(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        user = session.get('spotify_user', None)
        if user is None:
            # There is no logged in user --> Send to login page
            return jsonify({
                'redirect':
                spotfy_cred.user_authorisation_url(
                    scope=tk.scope.playlist_read_private)
            })
        else:
            user_token: tk.Token = user_to_token.get(user, None)
            if user_token.is_expiring:
                user_token = user_token.refresh_token(user_token)
                user_to_token[user] = user_token
            return f(*args, **kwargs)