Exemple #1
0
    def test_prompt_for_user_token(self):
        cred = MagicMock()
        input_ = MagicMock(return_value='http://example.com?code=1&state=s')
        state = MagicMock(return_value='s')
        util_mod = 'tekore._auth.util'
        with patch('tekore._auth.refreshing.Credentials', cred), \
                patch(util_mod + '.webbrowser', MagicMock()), \
                patch(util_mod + '.input', input_), \
                patch(util_mod + '.print', MagicMock()), \
                patch(util_mod + '.gen_state', state):
            prompt_for_user_token('', '', '')

        input_.assert_called_once()
Exemple #2
0
def exportPlaylist(request):
    list_id = request.POST["playlilstid"]
    playlisttoexport = Playlist.objects.get(id=list_id)
    tracks = playlisttoexport.tracks.all()
    uris = []
    for t in tracks:
        uri = "spotify:track:" + t.spotify_id
        uris.append(uri)
    app_token = tk.request_client_token(client_id, client_secret)
    spotify = tk.Spotify(app_token)
    user_token = tk.prompt_for_user_token(client_id,
                                          client_secret,
                                          redirect_uri,
                                          scope=tk.scope.every)
    spotify.token = user_token
    user = spotify.current_user()
    playlist = spotify.playlist_create(
        user.id,
        playlisttoexport.name,
        public=False,
        description='Generated By Ewan\'s Spotify Playlist Assist')
    spotify.playlist_add(playlist.id, uris=uris)

    #THIS IS WHERE ONE AVIODS COPYING PASTING INTO COSNOLE, COULDN'T QUITE WORK IT, FOR THE PURPOSES OF THIS PROJECT I DECIDED TO NOT WASTE MORE TIME ON IT

    #code = request.GET.get('', '')
    #token = cred.request_user_token(code)
    #with spotify.token_as(token):
    #    info = spotify.current_user()
    #    session['user'] = info.id
    #    users[info.id] = token

    return HttpResponseRedirect(reverse("playlistlist"))
Exemple #3
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)
Exemple #4
0
 def setup_spotify_client(self, client_id, client_secret, username):
     scope = "user-modify-playback-state user-read-playback-state playlist-modify-private playlist-read-private"
     token = tekore.prompt_for_user_token(
         scope=scope,
         client_id=client_id,
         client_secret=client_secret,
         redirect_uri="http://localhost:/callback",
     )
     return tekore.Spotify(token=token)
Exemple #5
0
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
Exemple #6
0
def play_anti_flag():
    app_key = tools.get_setting("app_key", "settings.npy")
    secret_key = tools.get_setting("secret_key", "settings.npy")
    conf = (app_key, secret_key, "https://example.com/callback")
    token = tk.prompt_for_user_token(*conf, scope=tk.scope.every)
    #print(tools.get_setting("app_key"))
    spotify = tk.Spotify(token)
    tracks1 = spotify.album_tracks("3thDALJX9mvXyJVNSqHwd7")
    #tracks = spotify.current_user_top_tracks(limit=10)
    spotify.playback_start_tracks([t.id for t in tracks1.items])
def setting_spotify_Object(client_id, client_secret, redirect_uri):
    user_token = tk.prompt_for_user_token(
        client_id=client_id,
        client_secret=client_secret,
        redirect_uri=redirect_uri,
        scope=tk.scope.every
    )

    spotify = tk.Spotify(user_token)
    print(spotify.playback_currently_playing())
    return spotify
Exemple #8
0
    def inicialization(self):
        try:
            user_token = tk.prompt_for_user_token(self.client_id,
                                                  self.client_secret,
                                                  self.redirect_uri,
                                                  scope=tk.scope.every)

            self.spotify.token = user_token
            self.inicialize = True
            return 'Inicializado com sucesso!'
        except:
            return 'Erro ao conectar com spotify'
Exemple #9
0
def main():
    # Function that starts all.

    # Authorizing APIs.
    try:
        # Trying to auth.

        # Global APIs.
        global API_Spotify, API_VKontakte

        # Spotify auth.
        API_Spotify = tekore.Spotify(
            tekore.prompt_for_user_token(__AUTH_SPOTIFY_CLIENT_ID,
                                         __AUTH_SPOTIFY_CLIENT_SECRET,
                                         __AUTH_SPOTIFY_REDIRECT_URI,
                                         tekore.scope.every))

        # Vkontakte auth.
        API_VKontakte = vk_api.VkApi(token=__AUTH_VKONTAKTE_TOKEN)

        if __genius_enabled:
            # If genius is enabled.

            # Global API.
            global API_Genius

            # Genius auth.
            API_Genius = lyricsgenius.Genius(__AUTH_GENIUS_TOKEN)
    except Exception as Error:
        # If there exception.

        # Error message.
        if __loguru_enabled:
            logger.error(
                f"Error when authorizing the APIs! Error information: {Error}")
        else:
            print(
                f"Error when authorizing the APIs! Error information: {Error}")

        # Raising error.
        raise AuthError

    # Launching threads.
    threading.Thread(target=vk_status_updater, args=()).start()
    threading.Thread(target=vk_process_messages, args=()).start()

    # Success message.
    if __loguru_enabled:
        logger.success("Launched main() function!")
    else:
        print("Launched main() function!")
Exemple #10
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])
Exemple #11
0
def get_user_token():
    config = get_config()
    token_path = pathlib.Path.home().joinpath('.spotify.token.pkl')

    if not token_path.exists():
        user_token = tk.prompt_for_user_token(*config, scope=tk.scope.every)
        with open(token_path.as_posix(), 'wb') as f:
            pickle.dump({'refresh': user_token.refresh_token}, f)
    else:
        with open(token_path.as_posix(), 'rb') as f:
            d = pickle.load(f)
            refresh_token = d['refresh']
        refresher = tk.RefreshingCredentials(*config)
        user_token = refresher.refresh_user_token(refresh_token)
    return user_token
Exemple #12
0
def spotify_callback(request):
    """
    Note - you need to manually copy the full URL with ?code= and paste it into runserver terminal where prompted.
    This is due to running it only on localhost (production would need a hosted domain)
    """
    # this is the way we will auth on Localhost
    client_id = settings.SPOTIFY_CLIENT_ID
    client_secret = settings.SPOTIFY_SECRET
    redirect_uri = settings.SPOTIFY_REDIRECT_URL
    conf = (client_id, client_secret, redirect_uri)
    file = settings.SPOTIFY_LOCAL_FILE
    # save file so we can read credentials in future calls
    token = tk.prompt_for_user_token(*conf, scope=tk.scope.every)
    tk.config_to_file(file, conf + (token.refresh_token, ))
    return JsonResponse({'response': 'spotify login successful'})
Exemple #13
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
Exemple #14
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")
Exemple #15
0
import tekore as tk

st.set_page_config(
    page_title='Spotify Viz',
    page_icon=
    "https://raw.githubusercontent.com/Githubaments/Images/main/favicon.ico")

px.defaults.template = "simple_white"
client_id = (os.environ.get('client_id'))
client_secret = (os.environ.get('client_secret'))
#scope = 'playlist-modify-private,playlist-modify-public,playlist-modify-public,user-top-read,user-read-recently-played,user-library-read'
redirect_uri = 'http://localhost:5000/callback'

conf = (client_id, client_secret, redirect_uri)
scope = tk.scope.user_top_read + tk.scope.playlist_modify_private
token = tk.prompt_for_user_token(*conf, scope=scope)

spotify = tk.Spotify(token)
top_tracks = spotify.current_user_top_tracks(limit=5).items

st.write(top_tracks)


def cache_on_button_press(label, **cache_kwargs):
    """Function decorator to memoize function executions.
    Parameters
    ----------
    label : str
        The label for the button to display prior to running the cached funnction.
    cache_kwargs : Dict[Any, Any]
        Additional parameters (such as show_spinner) to pass into the underlying @st.cache decorator.
Exemple #16
0
import tekore as tk

client_id = ''
client_secret = ''
redirect_uri = '' 
conf = (client_id, client_secret, redirect_uri)
file = 'tekore.cfg'

token = tk.prompt_for_user_token(*conf, scope=tk.scope.every)
tk.config_to_file(file, conf + (token.refresh_token,))
Exemple #17
0
 def __init__(self, client_id, client_secret, redirect_url, user_id):
     conf = (client_id, client_secret, redirect_url)
     token = tk.prompt_for_user_token(*conf, scope=tk.scope.every)
     self.sp = tk.Spotify(token)
     self.user_id = user_id
Exemple #18
0
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'
]
import tekore as tk

## Authorization
# set client ID and secret
client_id = '330de5fda11346ed8fe1c9e683471877'
client_secret = '616969349565471587934d59077bce2f'
redirect_uri = 'http://localhost' #TODO figure out uri....
#
app_token = tk.request_client_token(client_id, client_secret)
spotify = tk.Spotify(app_token)

user_token = tk.prompt_for_user_token(
    client_id,
    client_secret,
    redirect_uri,
    scope=tk.scope.every
)

            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(
    f"\nYou have a total of {ct.prGreen}{albums_number}{ct.endc} saved albums. Now selecting one randomly")
Exemple #21
0
    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
sys.stdout = old_stdout

for playlist in s.all_items(s.followed_playlists()):
    if playlist.name in EXCLUDED_PLAYLISTS:
        continue

    print(playlist.name)

    for item in s.all_items(s.playlist_items(playlist.id)):