Exemple #1
0
def async_spotify_user_auth():
    spotify = AsyncSpotify()
    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 __init__(
        self,
        access_token=None,
        refresh_token=None,
    ):
        scopes = [
            "user-read-recently-played",
            "user-read-playback-state",
            "user-modify-playback-state",
        ]

        user_creds = None

        if access_token and refresh_token:
            user_creds = UserCreds(access_token=access_token,
                                   refresh_token=refresh_token)

        super().__init__(
            client_creds=ClientCreds(
                client_id=os.getenv("SPOTIFY_CLIENT_ID"),
                client_secret=os.getenv("SPOTIFY_CLIENT_SECRET"),
                redirect_uri=os.getenv("SPOTIFY_CLIENT_REDIRECT"),
                scopes=scopes,
            ),
            user_creds=user_creds,
        )
Exemple #3
0
def test_initdata(client):
    cl = ClientCreds()
    spot = spotty_search.api.User(Spotify())

    client.get('/auth/')

    spot.initdata()
Exemple #4
0
    def __init__(
        self,
        access_token=None,
        refresh_token=None,
    ):
        scopes = [
            "user-read-recently-played",
            "user-read-playback-state",
        ]

        user_creds = None

        if access_token and refresh_token:
            user_creds = UserCreds(access_token=access_token,
                                   refresh_token=refresh_token)

        super().__init__(
            client_creds=ClientCreds(
                client_id=SPT_CLIENT_ID,
                client_secret=SPT_CLIENT_SECRET,
                redirect_uri=APP_URL + "acutebot/webserver",
                scopes=scopes,
            ),
            user_creds=user_creds,
        )
Exemple #5
0
    def __init__(
        self,
        access_token=None,
        refresh_token=None,
        # modify_playback_state=False
    ):
        scopes = [
            "user-read-recently-played",
            "user-read-playback-state",
            "user-modify-playback-state",
        ]

        """
        if modify_playback_state:
            scopes.append("user-modify-playback-state")
        """

        user_creds = None

        if access_token and refresh_token:
            user_creds = UserCreds(
                access_token=access_token, refresh_token=refresh_token
            )

        super().__init__(
            client_creds=ClientCreds(
                client_id=config["spotify"]["client_id"],
                client_secret=config["spotify"]["client_secret"],
                redirect_uri=config["spotify"]["client_redirect"],
                scopes=scopes,
            ),
            user_creds=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)
Exemple #7
0
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
Exemple #8
0
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 (
Exemple #9
0
def async_spotify_client_auth():
    spotify = AsyncSpotify()
    client_creds = ClientCreds()
    client_creds.load_from_env()
    spotify.client_creds = client_creds
    yield spotify
Exemple #10
0
def client_creds_from_env():
    client = ClientCreds()
    client.load_from_env()
    client.show_dialog = "true"
    yield client
Exemple #11
0
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)
from pyfy import Spotify, ClientCreds, UserCreds
from dotenv import load_dotenv

load_dotenv()

# Init pyfy
spotify = Spotify()
client_creds = ClientCreds(
    client_id=os.getenv("SPOTIFY_CLIENT_ID"),
    client_secret=os.getenv("SPOTIFY_CLIENT_SECRET"),
    redirect_uri=os.getenv("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)
    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 download_tracks(self, spotify_credentials, force=False):
        '''
        Download top tracks features of every artist in self._artists

        :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 tracks')

        existing_depth = -1
        artists = None
        if not force:
            name = self._name.replace(' ', '')
            for i in range(0, self._depth + 1):
                p = pathlib.Path(self.tracks_path % (name, i))
                if p.exists():
                    existing_depth = i

            self.load_artists(self.depth)

            if existing_depth > -1:
                if existing_depth == self._depth:
                    print("Data already exists - loading data")
                    self.load_tracks(existing_depth)
                    return
                elif existing_depth < self.depth:
                    self.load_tracks(existing_depth)
                    print(f'Loaded data: l_{existing_depth}')
            else:
                print("No track data downloaded")

            if self.tracks is not None:
                artists = {
                    key: item
                    for key, item in self.artists.items()
                    if item['depth'] > existing_depth
                }
                # artist_tracks = set(self.tracks[self.tracks['artist'] not in artists]['artist'])
            else:
                artists = self.artists
        else:
            artists = self.artists

        tracks = []
        try:
            for artist in artists:
                name = artists[artist]['name']
                print(f'Downloading top tracks info for {name}')
                artist_tracks = self._client.artist_top_tracks(artist,
                                                               country='US')
                # Check if there are any tracks available for current artist
                if artist_tracks['tracks']:
                    tracks_features = self._client.tracks_audio_features(
                        [t['id'] for t in artist_tracks['tracks']])
                    if tracks_features:
                        # Check if there are multiple tracks
                        if 'audio_features' in tracks_features:
                            tracks_features = tracks_features['audio_features']
                        # Add to each track features an id of current artist
                        if isinstance(tracks_features, list):
                            for i in range(len(tracks_features)):
                                if tracks_features[i]:
                                    tracks_features[i]['artist'] = artist
                                else:
                                    tracks_features[i] = {'artist': artist}
                        elif isinstance(tracks_features, dict):
                            tracks_features['artist'] = artist
                            tracks_features = [tracks_features]
                else:
                    tracks_features = [{'artist': artist}]
                tracks.extend(tracks_features)
                sleep(0.2)
        except excs.ApiError as e:
            print('Error')
            print(e.msg)

        df = pd.DataFrame(tracks)
        df = df.drop(['analysis_url', 'track_href', 'type', 'uri'],
                     axis='columns')
        if self.tracks is not None:
            df = df.append(self.tracks)
        self._tracks = df
        if set(self.tracks['artist']) == set(self.artists):
            print("Download successful")
        else:
            diff = set(self.tracks['artist']) - set(self.artists)
            print(f'Missing top tracks for {diff}')
            raise ValueError(
                'Top track features not downloaded for all artists')
Exemple #15
0
def client_creds_from_env_session():
    client = ClientCreds()
    client.load_from_env()
    client.show_dialog = 'true'
    yield client
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)
Exemple #17
0
from pyfy import Spotify, AuthError, ClientCreds
import pytest

## This must test authentication without having a client credentials model loaded to the client.
## Only User model loaded from developer console or by any other means

empty_client_creds = ClientCreds()


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 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,
        )
#!/usr/bin/python3.7
from flask import Flask, request, jsonify
from pyfy import ClientCreds as ClientCreds, Spotify
import requests, os, time, json, pprint

client = ClientCreds(client_id='634a89ab0e2e4ec2b59dff7bfcbfca3d',
                     client_secret='541bf8cfdced4f01896b3d4f7551ece9')
spt = Spotify(client_creds=client)
spt.authorize_client_creds()
pp = pprint.PrettyPrinter(indent=4)

app = Flask(__name__)


@app.route('/api/v1/convert', methods=['POST'])
def convert_csv():
    playlist_id = str(request.data).split(":", 2)[2].strip("'")
    #print(playlist_id)

    results = []
    num_offset = 1
    response = spt.playlist_tracks(
        playlist_id,
        fields='items(track(name,artists(name),total))',
        offset=num_offset)
    pp.pprint(response)

    #while "\"next\" : null" not in response.values():
    #pp.pprint(response)
    #num_offset = num_offset + 100
    #response = spt.playlist_tracks(playlist_id, fields='items(track(name,artists(name)))', offset=num_offset)