async def test_user_is_active(user_creds_from_env, client_creds_from_env): ''' This will also work if you provide an empty client creds model. But when the access token eventually expires you'll need valid client creds to refresh it ''' spt = Spotify(client_creds=client_creds_from_env, user_creds=user_creds_from_env) assert await spt.is_active is True
def test_and_get_me_attr_attr_exists(): spt = Spotify() spt.user_creds = UserCreds() spt.user_creds.id = "id1234" assert _set_and_get_me_attr_sync(spt, "id") == "id1234"
def test_populate_user_creds(me_stub): spt = Spotify(populate_user_creds=False) # Offline test user = UserCreds() spt.user_creds = user spt._populate_user_creds(me_stub) assert getattr(spt.user_creds, "type", None) is None assert spt.user_creds.product == "premium"
def test_and_get_me_attr_attr_exists(): spt = Spotify() spt.user_creds = UserCreds() spt.user_creds.id = 'id1234' assert _set_and_get_me_attr_sync(spt, 'id') == 'id1234'
def test_user_is_rejected_with_bad_access_token(user_creds_from_env, client_creds_from_env): user_creds_from_env.access_token = 'BAD_ACCESS_TOKEN' with pytest.raises(AuthError): Spotify(client_creds=client_creds_from_env, user_creds=user_creds_from_env, ensure_user_auth=True)
def test_initdata(client): cl = ClientCreds() spot = spotty_search.api.User(Spotify()) client.get('/auth/') spot.initdata()
def test_user_playlists(user_creds_from_env, client_creds_from_env): c = Spotify( client_creds=client_creds_from_env, user_creds=user_creds_from_env, ensure_user_auth=True, ) c.user_creds.user_id = None assert c.user_playlists()
async def test_user_is_rejected_with_bad_access_token(user_creds_from_env, client_creds_from_env): user_creds_from_env.access_token = 'BAD_ACCESS_TOKEN' spt = Spotify(client_creds=client_creds_from_env, user_creds=user_creds_from_env) assert spt._caller == spt.user_creds with pytest.raises(AuthError): await spt._check_authorization()
def test_authenticated_user_is_authorized(user_creds_from_env, client_creds_from_env): spotify = Spotify( client_creds=client_creds_from_env, user_creds=user_creds_from_env, ensure_user_auth=True, ) assert spotify.me()
async def test_user_is_authenticated_by_access_token(user_creds_from_env, client_creds_from_env): ''' This will also work if you provide an empty client creds model. But when the access token eventually expires you'll need valid client creds to refresh it ''' spt = Spotify(client_creds=client_creds_from_env, user_creds=user_creds_from_env) await spt.populate_user_creds()
def get_spotify_client(hostname) -> Spotify: client = ClientCreds( client_id=os.getenv("SPOTIFY_CLIENT_KEY"), client_secret=os.getenv("SPOTIFY_CLIENT_SECRET"), scopes=["user-read-currently-playing", "user-read-recently-played"], redirect_uri=f"http://{hostname}:4444", ) return Spotify(client_creds=client)
def test_client_instantiates_with_user_creds(): u = UserCreds() u.load_from_env() spt = Spotify(user_creds=u, ensure_user_auth=False, populate_user_creds=False) assert spt.user_creds.access_token is not None assert spt._caller == spt.user_creds
def test_user_is_authenticated_by_access_token(user_creds_from_env, client_creds_from_env): """ This will also work if you provide an empty client creds model. But when the access token eventually expires you'll need valid client creds to refresh it """ Spotify( client_creds=client_creds_from_env, user_creds=user_creds_from_env, ensure_user_auth=True, )
def spotify_user_auth(): spotify = Spotify() user_creds = UserCreds() client_creds = ClientCreds() client_creds.load_from_env() user_creds.load_from_env() spotify.client_creds = client_creds spotify.user_creds = user_creds spotify._caller = spotify.user_creds yield spotify
def test_client_instantiates_with_access_token(): u = UserCreds() u.load_from_env() access_token = u.access_token spt = Spotify(access_token=access_token, ensure_user_auth=False, populate_user_creds=False) assert spt.user_creds.access_token is not None assert spt.user_creds.refresh_token is None assert spt._caller == spt.user_creds assert not hasattr(spt, "access_token")
def test_oauth_uri_raises_deprecation_warning(): creds = ClientCreds(client_id='asdasdasdasdads', client_secret='asdasdasdasdasd', scopes=['asdasd', 'asdasd'], redirect_uri='asdasdasdasd') sync = Spotify(client_creds=creds) async_ = AsyncSpotify(client_creds=creds) with pytest.warns(DeprecationWarning): sync.oauth_uri with pytest.warns(DeprecationWarning): async_.oauth_uri
from pyfy import Spotify, ClientCreds, UserCreds from utils import config # Init pyfy spotify = Spotify() client_creds = ClientCreds( client_id=config["spotify"]["client_id"], client_secret=config["spotify"]["client_secret"], redirect_uri=config["spotify"]["client_redirect"], scopes=["user-read-recently-played", "user-read-playback-state"], ) spotify.client_creds = client_creds def get_credentials(user): return UserCreds(access_token=user.spotify_access_token, refresh_token=user.spotify_refresh_token)
za.start() blob_listener = BlobListener() za.register_listener(blob_listener) while True: sleep(1) if blob_listener.blob is not None: break za.stop() login = blob_listener.blob.create_login() connection = Connection() session = Session().connect(connection) session.authenticate(login) manager = MercuryManager(connection) client_id = '<YOUR_CLIENT_ID>' authToken = AuthToken(manager, client_id) manager.terminate() token = authToken.accessToken print("AuthToken: ", token) spt = Spotify(token) devices = spt.devices() print(devices) last_10_played = spt.recently_played_tracks(10) print(last_10_played)
import json from flask import Flask, request, redirect, g, render_template, make_response, session, abort, jsonify, url_for, Response import requests from pyfy import Spotify, ClientCreds, UserCreds, AuthError, ApiError import os import webbrowser from spt_keys import KEYS from main import mood import datetime import database import display import io spt = Spotify() client = ClientCreds() state = "123" app = Flask(__name__) @app.route("/authorize") def authorize(): export_keys() client.load_from_env() spt.client_creds = client if spt.is_oauth_ready: return redirect( 'https://accounts.spotify.com/authorize?redirect_uri=http://127.0.0.1:5000/callback/q&client_id=&response_type=code&scope=user-read-recently-played&show_dialog=false&state=123' ) else: return (
def spotify(): yield Spotify()
def spotify_client_auth(): spotify = Spotify() client_creds = ClientCreds() client_creds.load_from_env() spotify.client_creds = client_creds yield spotify
async def test_authenticated_user_is_authorized(user_creds_from_env, client_creds_from_env): spotify = Spotify(client_creds=client_creds_from_env, user_creds=user_creds_from_env) assert await spotify.me()
from pyfy import Spotify import time spt = Spotify('your-code') """ Add_tracks_Archived -checks to see if an archived playlist exists for the selected playlist -If no playlist (pl) exists then create a new one -Once pl situation is solved removed all songs from selected playlist and add them to archived """ def add_tracks_archived(archivedTrackList, selectedPL_ID, selectedPL_Name): #check to see if an archived playlist exists foundPlaylist = False users_playlists = spt.user_playlists() archived_PL_ID = 0 for playlists in users_playlists['items']: if selectedPL_Name + str("_archived") == playlists['name']: archived_PL_ID = playlists['id'] print("playlist exists") foundPlaylist = True break if foundPlaylist == False: print("Creating Playlist") archived_PL_ID = spt.create_playlist( selectedPL_Name + str("_archived"))['id'] #creates the new playlist and grabs the id
def test_client_raises_error_if_both_access_token_and_model(): u = UserCreds() u.load_from_env() with pytest.raises(ValueError): Spotify(user_creds=u, access_token=u.access_token)
def test_sync_client_instantiates_empty(): Spotify()
async def test_user_playlists(user_creds_from_env, client_creds_from_env): c = Spotify(client_creds=client_creds_from_env, user_creds=user_creds_from_env) c.user_creds.user_id = None assert await c.user_playlists()
def download_data(self, spotify_credentials, force=False): ''' Download artist with specified name. If depth > 0 downloads related artists to given artist in iterations. :param spotify_credentials: tuple with id and key to Spotify Web API :type spotify_credentials: tuple of strings :param force: should data be re-downloaded if it already exists in default directory :type force: boolean ''' creds = ClientCreds(client_id=spotify_credentials[0], client_secret=spotify_credentials[1]) self._client = Spotify(client_creds=creds) self._client.authorize_client_creds() print('Downloading artists') result = self._client.search(q=self._name, types='artist', limit=1) if len(result['artists']['items']) == 0: raise NameError(f'No artist with name: {self._name}.') self._root = Artist(result['artists']['items'][0], depth=0) self._adjacency[self._root.id] = [] self._artists[self._root.id] = self._root.get_dict() if self._depth < 0: raise ValueError('Depth must be positive integer') if self._depth == 0: print('0 nearest neighbors') return if self._root is None: raise NameError(f'No data retrieved for {self._name}.') existing_depth = -1 if not force: name = self._name.replace(' ', '') for i in range(0, self._depth + 1): p1 = pathlib.Path(self.artist_path % (name, i)) p2 = pathlib.Path(self.adjacency_path % (name, i)) if p1.exists() and p2.exists(): existing_depth = i if existing_depth > -1: if existing_depth == self._depth: print("Data already exists") return elif existing_depth < self.depth: self.load_artists(existing_depth) self.load_adjacency(existing_depth) print(f'Loaded data: l_{existing_depth}') else: print("No artist, adjacency data downloaded") if self.adjacency is None or self.artists is None: existing_depth = 0 for i in range(existing_depth + 1, self._depth + 1): print(f'{i} nearest neighbors') for id in list(self._artists): self.add_related(id, i) for key in self.adjacency.keys(): self._adjacency[key] = list(set(self.adjacency[key]))
def test_caller_defaults_to_user(): u = UserCreds(access_token="asdasdasd") c = Spotify(user_creds=u, populate_user_creds=False) assert c._caller == c.user_creds
from pyfy import Spotify from pyfy import ClientCreds, Spotify # client_id ="2c0d0c49b20c4a2cbe346f42bb6dab74" client_secret ="811e8611fafc4683b415caae2814d98b" redirect_uri = 'http://localhost/' username = "******" scope = 'user-read-playback-state user-library-modify' client = ClientCreds(client_id=client_id, client_secret=client_secret) spt = Spotify(client_creds=client) print(spt.auth_uri(client_id=client_id,scopes=scope.split(" "),redirect_uri=redirect_uri,show_dialog=True)) authcode=input().strip() spt.build_user_creds(grant=authcode)
async def test_user_refresh_token(user_creds_from_env, client_creds_from_env): spotify = Spotify(client_creds=client_creds_from_env, user_creds=user_creds_from_env) await spotify.populate_user_creds() await spotify._refresh_token()