Beispiel #1
0
import spotipy
from sklearn.neighbors import NearestNeighbors

CLIENT_ID = 'bb101bf3987840f79cdc0c11a819b8c5'
CLIENT_SECRET = '2acb736cc399427382570f1e47996c48'
redirect_uri = 'http://localhost:8000/home'
scope = 'user-top-read'
TOKEN = {}
DATA = {}

mg_client = pymongo.MongoClient('localhost', 27017)
mongo_db = mg_client['db']
collection = mongo_db['collection']

sp_oauth = oauth2.SpotifyOAuth(CLIENT_ID,
                               CLIENT_SECRET,
                               redirect_uri,
                               scope=scope)


def login(request):
    return render(request, 'hack/login.html')


def save_info():
    sp = spotipy.Spotify(auth=TOKEN['access_token'])
    results = sp.current_user_top_artists(42)
    aux = pd.DataFrame()

    for r in results['items']:
        aux = pd.concat(
            [aux, pd.DataFrame(r['genres'], columns=['genero'])],
Beispiel #2
0
from flask import (Blueprint, flash, redirect, render_template, request,
                   url_for, session)
import spotipy
from spotipy import oauth2

bp = Blueprint('spotify', __name__)

SCOPE = 'user-top-read user-read-currently-playing user-modify-playback-state user-read-playback-state'
CACHE = '.spotifycache'
# Reads client id and client secret from environment variables
sp_oauth = oauth2.SpotifyOAuth(scope=SCOPE, cache_path=CACHE)


@bp.route('/', methods=['GET'])
def login():
    # If auth token is already cached and not expired, use that else redirect
    # user to login or refresh token
    token_info = sp_oauth.get_cached_token()
    if token_info and not sp_oauth.is_token_expired(token_info):
        access_token = token_info['access_token']
        session['access_token'] = access_token
        return redirect(url_for('spotify.top_tracks'))
    else:
        login_url = sp_oauth.get_authorize_url()
        return redirect(login_url)


# After generating code, Spotify redirects to this endpoint
@bp.route('/oauth/callback', methods=['GET'])
def set_token():
    code = request.args['code']
Beispiel #3
0
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import UpdateModelMixin

import random
import csv

SPOTIPY_CLIENT_ID = 'c42e107d3ae641e4af9e08e7d7a55b9b'
SPOTIPY_CLIENT_SECRET = 'cd1e4e0aa3684e34ae12b313ebea1074'
SPOTIPY_REDIRECT_URI = 'http://localhost:3000/spotifyresult/'
SCOPE = 'user-top-read user-read-currently-playing user-read-playback-state user-library-read'
CACHE = '.spotipyoauthcache'



sp_oauth = oauth2.SpotifyOAuth( SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET,SPOTIPY_REDIRECT_URI,scope=SCOPE,cache_path=CACHE )



class question(APIView):
    @csrf_exempt
    def get(self, request):
        print ("Found cached token!")
        user = get_object_or_404(CustomUser, id = request.user.id)
        user_id = user.id
        token_info = sp_oauth.get_cached_token(user_id)
        access_token = token_info['access_token']
        dict = {}
        q = []
        if access_token:
                    print ("Access token available! Wating for find question...")
Beispiel #4
0
app = Flask(__name__)
CORS(app)

clf = joblib.load('src/model.pkl')

appname = 'Partify'

client_id = os.environ['SPOTIPY_CLIENT_ID']
client_secret = os.environ['SPOTIFY_CLIENT_SECRET']
redirect_uri = 'http://127.0.0.1:5000/admin/callback'
scope = 'user-read-private user-top-read playlist-modify-private user-modify-playback-state'

sp_oauth = oauth2.SpotifyOAuth(client_id,
                               client_secret,
                               redirect_uri,
                               scope=scope,
                               cache_path=None)

### Database (lol)
# party_id -> [tokens]
# [(str, [int])]
database = {}
# [(str, [str])]
# party_id -> [track_ids]
playlists = {}

db = {}

### Spotify helper functions
Beispiel #5
0
    redirect_uri = "http://localhost:8080"
else:
    CLIENT_ID, CLIENT_SECRET, redirect_uri, USERNAME, = [
        os.environ[item] for item in [
            "SPOTIPY_CLIENT_ID", "SPOTIPY_CLIENT_SECRET",
            "SPOTIPY_REDIRECT_URI", "USERNAME"
        ]
    ]
app = QApplication([])
app.setQuitOnLastWindowClosed(False)
scope = "streaming user-library-read user-modify-playback-state user-read-playback-state user-library-modify " \
        "playlist-read-private playlist-read-private"

sp_oauth = oauth2.SpotifyOAuth(client_id=CLIENT_ID,
                               client_secret=CLIENT_SECRET,
                               redirect_uri=redirect_uri,
                               scope=scope,
                               username=USERNAME)

token_info = sp_oauth.get_access_token(as_dict=True)
token = token_info["access_token"]

try:
    sp = Spotify(auth=token)
except:
    print("User token could not be created")
    exit()


def exit_app():
    app.quit()
Beispiel #6
0
import os
import spotipy
import spotipy.util as util
import spotipy.oauth2 as oauth2
import spotipyExtension

USERNAME = str(os.environ.get('SPOTIFY_USER_NAME'))
CLIENT_ID = str(os.environ.get('SPOTIFY_CLIENT_ID'))
CLIENT_SECRET = str(os.environ.get('SPOTIFY_CLIENT_SECRET'))
REDIRECT_URL = 'http://localhost/'

SCOPE = 'user-read-recently-played user-library-modify playlist-read-private user-read-email playlist-modify-public playlist-modify-private user-library-read playlist-read-collaborative user-read-birthdate user-read-playback-state user-read-private app-remote-control user-modify-playback-state user-follow-read user-top-read user-read-currently-playing user-follow-modify streaming'


sp_oauth = oauth2.SpotifyOAuth(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL, scope=SCOPE, cache_path=".cache-" + USERNAME)
token_info = sp_oauth.get_cached_token()
if not token_info:
	code = os.environ.get('SPOTIFY_AUTHORIZATION_CODE')
	token_info = sp_oauth.get_access_token(code)
token = token_info['access_token']

sp = spotipy.Spotify(token)


def fetchPlaylist(name):
	print('[LOG] fetchPlaylist() was called.')
	id = ''
	results = sp.current_user_playlists()
	for item in results['items']:
		if item['name'] == name:
			id = item['id']
Beispiel #7
0
from flask import Flask, request, render_template, redirect, session, url_for, g, jsonify, abort
from flask_session import Session

from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, HiddenField
from wtforms.validators import DataRequired, NumberRange

import spotipy
from spotipy import oauth2

app = Flask(__name__)
app.config.from_pyfile('config.py')
Session(app)

sp_oauth = oauth2.SpotifyOAuth(client_id=app.config.get('SPOTIPY_CLIENT_ID'),
                               client_secret=app.config.get('SPOTIPY_CLIENT_SECRET'),
                               redirect_uri=app.config.get('SPOTIPY_REDIRECT_URI'),
                               scope='playlist-modify-public')


def is_valid_raw_data(message: str='request is not valid'):
    def _is_valid_raw_data(form, field):
        if field.raw_data is None or not all(field.raw_data):
            raise ValueError(message)
    return _is_valid_raw_data


class ArtistForm(FlaskForm):
    artist_id = HiddenField(validators=[is_valid_raw_data()])
    track_count = IntegerField(NumberRange(min=1, max=10), validators=[is_valid_raw_data()])

Beispiel #8
0
def prompt_for_user_token(username,
                          scope=None,
                          client_id=None,
                          client_secret=None,
                          redirect_uri=None):
    ''' prompts the user to login if necessary and returns
        the user token suitable for use with the spotipy.Spotify
        constructor

        Parameters:

         - username - the Spotify username
         - scope - the desired scope of the request
         - client_id - the client id of your app
         - client_secret - the client secret of your app
         - redirect_uri - the redirect URI of your app

    '''

    if not client_id:
        client_id = os.getenv('SPOTIPY_CLIENT_ID')

    if not client_secret:
        client_secret = os.getenv('SPOTIPY_CLIENT_SECRET')

    if not redirect_uri:
        redirect_uri = os.getenv('SPOTIPY_REDIRECT_URI')

    if not client_id:
        print('''
            You need to set your Spotify API credentials. You can do this by
            setting environment variables like so:

            export SPOTIPY_CLIENT_ID='your-spotify-client-id'
            export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
            export SPOTIPY_REDIRECT_URI='your-app-redirect-url'

            Get your credentials at
                https://developer.spotify.com/my-applications
        ''')
        raise spotipy.SpotifyException(550, -1, 'no credentials set')

    sp_oauth = oauth2.SpotifyOAuth(client_id,
                                   client_secret,
                                   redirect_uri,
                                   scope=scope,
                                   cache_path=".cache-" + username)

    # try to get a valid token for this user, from the cache,
    # if not in the cache, the create a new (this will send
    # the user to a web page where they can authorize this app)

    token_info = sp_oauth.get_cached_token()

    if not token_info:
        print('''

            User authentication requires interaction with your
            web browser. Once you enter your credentials and
            give authorization, you will be redirected to
            a url.  Paste that url you were directed to to
            complete the authorization.

        ''')
        auth_url = sp_oauth.get_authorize_url()
        try:
            subprocess.call(["open", auth_url])
            print("Opening %s in your browser" % auth_url)
        except:
            print("Please navigate here: %s" % auth_url)

        print()
        print()
        response = input("Enter the URL you were redirected to: ")
        print()
        print()

        code = sp_oauth.parse_response_code(response)
        token_info = sp_oauth.get_access_token(code)
    # Auth'ed API request
    if token_info:
        return token_info['access_token']
    else:
        return None
Beispiel #9
0
from spotipy import oauth2
import pprint
import operator
import os

app = Flask(__name__)
app.secret_key = ""

CLIENT_ID = ''
CLIENT_SECRET = ''
REDIRECT_URI = "http://*****:*****@app.route("/", methods=['GET'])
def render_welcome():
    return render_template('welcome.html')

@app.route('/signout', methods=['GET'])
def signout():
    os.remove('.spotipyoauthcache')
    return render_template('welcome.html', msg="Successfully signed out.")

#Below is authorization logic when a user first visits the app
@app.route("/home", methods=['GET'])
def authorize():
    global sp
    global current_user
    access_token = ""
def spotlogin(request):
    ''' prompts the user to login if necessary and returns
        the user token suitable for use with the spotipy.Spotify
        constructor
        Parameters:
         - username - the Spotify username
         - scope - the desired scope of the request
         - client_id - the client id of your app
         - client_secret - the client secret of your app    
         - redirect_uri - the redirect URI of your app
         - cache_path - path to location to save tokens
    '''
    client_id = '327541285c7343afbf4822dc9d30ef7f'
    client_secret = '713dbe89b2ea4bd382fb0a7b366a63bb'
    redirect_uri = 'http://smalldata411.web.illinois.edu/redirect'
    cache_path = None
    username = '******'  #hardcoded now...change for later
    scope = 'user-library-read'
    if not client_id:
        client_id = os.getenv('SPOTIPY_CLIENT_ID')

    if not client_secret:
        client_secret = os.getenv('SPOTIPY_CLIENT_SECRET')

    if not redirect_uri:
        redirect_uri = os.getenv('SPOTIPY_REDIRECT_URI')

    if not client_id:
        print('''
            You need to set your Spotify API credentials. You can do this by
            setting environment variables like so:
            export SPOTIPY_CLIENT_ID='your-spotify-client-id'
            export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
            export SPOTIPY_REDIRECT_URI='your-app-redirect-url'
            Get your credentials at
                https://developer.spotify.com/my-applications
        ''')
        raise spotipy.SpotifyException(550, -1, 'no credentials set')

    cache_path = cache_path or ".cache-" + username
    sp_oauth = oauth2.SpotifyOAuth(client_id,
                                   client_secret,
                                   redirect_uri,
                                   scope=scope,
                                   cache_path=cache_path)

    # try to get a valid token for this user, from the cache,
    # if not in the cache, the create a new (this will send
    # the user to a web page where they can authorize this app)

    token_info = sp_oauth.get_cached_token()

    if not token_info:
        print('''
            User authentication requires interaction with your
            web browser. Once you enter your credentials and
            give authorization, you will be redirected to
            a url.  Paste that url you were directed to to
            complete the authorization.
        ''')

        auth_url = sp_oauth.get_authorize_url()
        #attempt to open the authorize url. This will redirect to our redirect page upon login
        try:
            # import webbrowser
            # webbrowser.open_new_tab(auth_url)
            #return HttpResponse("OPENED: " + str(auth_url))
            return HttpResponseRedirect(str(auth_url))

        except:
            return HttpResponse("FAILED")
def finish_spot_auth(request):
    c = connections['default'].cursor()
    client_id = '327541285c7343afbf4822dc9d30ef7f'
    client_secret = '713dbe89b2ea4bd382fb0a7b366a63bb'
    redirect_uri = 'http://smalldata411.web.illinois.edu/redirect'
    cache_path = None
    username = '******'  #hardcoded now...change for later
    scope = 'user-library-read'
    sp_oauth = oauth2.SpotifyOAuth(client_id,
                                   client_secret,
                                   redirect_uri,
                                   scope=scope,
                                   cache_path=cache_path)
    response = str(request.build_absolute_uri())
    code = sp_oauth.parse_response_code(response)
    token_info = sp_oauth.get_access_token(code)
    token = token_info['access_token']
    # # Auth'ed API request
    client_credentials_manager = SpotifyClientCredentials(
        client_id=client_id, client_secret=client_secret)

    if token:
        sp = spotipy.Spotify(
            auth=token, client_credentials_manager=client_credentials_manager)
        results = sp.current_user_saved_tracks(
            limit=50
        )  #max limit is fifty songs...use paging to scroll through results
        tracks = results['items']
        while results['next']:
            results = sp.next(results)
            tracks.extend(results['items'])  #tracks is a list
        values = list()
        songID = 0
        for track in tracks:
            song = track['track']
            name = song['name']
            #quote in name braks errything
            artist = song['artists'][0]['name']
            if "'" in name or "'" in artist:
                continue
            #check if song, artist, and service combination already exist in the DB
            command = "SELECT UniqueSongID FROM TopSongsMeta WHERE artist = \"" + str(
                artist) + "\" and title = \"" + str(name) + "\""
            c.execute(command, [])
            rows = c.fetchall()
            if (len(rows) == 0):
                continue
            tuple = "("
            tuple += "1, "
            tuple += "'Spotify', "
            tuple += "'" + str(artist) + "', "
            tuple += "'" + str(name) + "', "
            tuple += str(songID)
            tuple += ")"
            values.append(tuple)
            songID = songID + 1
        insert_a_lot('TopSongsMeta',
                     '(UserID, Service, Artist, Title, UniqueSongID)', values)
        return HttpResponseRedirect("http://smalldata411/web/illinois.edu")
    else:
        return HttpResponse("ERROR")
Beispiel #12
0
scopes = [
    'playlist-modify-public', 'playlist-modify-private',
    'playlist-read-private', 'playlist-read-collaborative'
]

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('username')
    parser.add_argument('--force', action='store_true')

    args = parser.parse_args()

    credentials = Credentials()
    sp_oauth = oauth2.SpotifyOAuth(credentials.spotify_id,
                                   credentials.spotify_secret,
                                   "http://localhost/",
                                   scope=' '.join(scopes),
                                   cache_path=".cache-" + args.username)
    token_info = sp_oauth.get_cached_token()

    if not token_info or args.force:
        auth_url = sp_oauth.get_authorize_url()
        print("Please navigate here: {}".format(auth_url))
        print()
        response = raw_input("Enter the URL you were redirected to: ")
        print()
        code = sp_oauth.parse_response_code(response)
        token_info = sp_oauth.get_access_token(code)

    if token_info:
        print('Your token is:')
Beispiel #13
0
import requests
import json
from dotenv import load_dotenv

dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
load_dotenv(dotenv_path)

SCOPE = 'playlist-modify-public playlist-read-private playlist-modify-private'

CLIENT_ID = os.environ['MERGIFY_CLIENT_ID']
CLIENT_SECRET = os.environ['MERGIFY_CLIENT_SECRET']
REDIRECT_URI = os.environ['MERGIFY_REDIRECT_URI']

SPOTIFY_TOKEN_ENDPOINT = 'https://accounts.spotify.com/api/token'

spoauth = oauth2.SpotifyOAuth(client_id=CLIENT_ID, client_secret=CLIENT_SECRET,
                              redirect_uri=REDIRECT_URI, scope=SCOPE)


def get_oauth_url():
    return spoauth.get_authorize_url()


# { access_token: "", refresh_token: "" }
def get_token_info_from_code(auth_code):
    body = {
        "grant_type": 'authorization_code',
        "code": str(auth_code),
        "redirect_uri": REDIRECT_URI,
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET
    }
# getting credentials
username = settings["spotify_user_id"]
scope = 'playlist-read-private,' \
  ' playlist-read-collaborative,' \
  ' user-read-playback-state,' \
  ' user-modify-playback-state,' \
  ' user-read-currently-playing'
client_id = settings["spotify_client_id"]
client_secret = settings["spotify_client_secret"]
redirect_uri = settings["spotify_redirect_uri"]

# creating spotify credentials manager
spotify_auth = oauth.SpotifyOAuth(client_id=client_id,
                                  client_secret=client_secret,
                                  redirect_uri=redirect_uri,
                                  scope=scope,
                                  cache_path=f".cache-{username}")


# 'logging in' to spotify
def spotify_log_in(username):
    try:
        # if cache file exists, then we have a chached token
        if os.path.isfile(f".cache-{username}"):
            cached_token = spotify_auth.get_cached_token()
            token = cached_token["access_token"]
        # if not then we need to create the cache file
        else:
            token = util.prompt_for_user_token(username, scope, client_id,
                                               client_secret, redirect_uri)
Beispiel #15
0
from flask import Blueprint, redirect, request, url_for, render_template, flash
from flask_login import login_required, current_user
import spotipy, json
from . import db
from .models import Room
from spotipy import oauth2

SPOTIPY_CLIENT_ID = '62067c3296db41bda75539a1749da1cb'
SPOTIPY_CLIENT_SECRET = '287d8a2554d14871bfda2f2b2577026c'
SPOTIPY_REDIRECT_URI = 'http://127.0.0.1:5000/spotifyauth'  # prolly needs to change
SCOPE = 'user-read-private user-read-playback-state user-modify-playback-state streaming'

spotify = Blueprint('spotify', __name__)

spotify_oauth = oauth2.SpotifyOAuth(SPOTIPY_CLIENT_ID,
                                    SPOTIPY_CLIENT_SECRET,
                                    SPOTIPY_REDIRECT_URI,
                                    scope=SCOPE)


def song_in_queue(song, queue):
    for s in queue:
        if s['id'] == song['id']:
            s['votes'] += 1
            return True
    return False


def add_dict_to_queue(dict, queueStr):
    queue = json.loads(queueStr)
    if not song_in_queue(dict, queue):
        queue.append(dict)
Beispiel #16
0
from flask_restful import Api
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from app.config import Config
import spotipy
import spotipy.util as util
from spotipy import oauth2

app = Flask(__name__, static_folder='static', template_folder='templates')
app.config.from_object(Config)
CORS(app, supports_credentials=True)

api_bp = Blueprint('api', __name__)
api = Api(api_bp)
db = SQLAlchemy(app)
ma = Marshmallow(app)
migrate = Migrate(app, db)
jwt = JWTManager(app)

SCOPE = 'user-library-read user-follow-read'
CACHE = '.spotipyoauthcache'
sp_oauth = oauth2.SpotifyOAuth(app.config["SPOTIFY_CLIENT_ID"],
                               app.config["SPOTIFY_CLIENT_SECRET"],
                               app.config["SPOTIFY_REDIRECT_URI"],
                               scope=SCOPE,
                               cache_path=CACHE)

from app import models, routes

# Register blueprints
app.register_blueprint(api_bp)
Beispiel #17
0
 def __init__(self):
     super(SpotifySignIn, self).__init__('spotify')
     self.oauth = spoauth.SpotifyOAuth(self.consumer_id,self.consumer_secret,SP_REDIRECT,scope='user-read-private playlist-modify-public user-read-email user-library-read playlist-modify-private user-top-read',cache_path='spotify.json')
     self.spotify = spotipy
Beispiel #18
0
def main():

    while pygameanticrasher():
        os.environ["SPOTIPY_CLIENT_ID"] = "221e9a5fac5c4f40bb2de9c33ce7a863"
        print(os.environ["SPOTIPY_CLIENT_ID"])
        os.environ[
            "SPOTIPY_CLIENT_SECRET"] = "8c5e85b7165840bbb605b43924952889"
        print(os.environ["SPOTIPY_CLIENT_SECRET"])
        os.environ["SPOTIPY_REDIRECT_URI"] = "http://google.com/"
        print(os.environ["SPOTIPY_REDIRECT_URI"])
        print("x")
        smslist = []
        heb = 'אבגדהוזחטיכלמנסעפצקרשתץףך'
        address = '192.168.1.11'
        port = 8000
        bsize = 1024
        scope = 'playlist-modify-public streaming user-modify-playback-state user-read-playback-state user-read-currently-playing user-read-recently-played'
        screen = pg.display.set_mode((640, 480))
        pg.display.set_caption('SPOTISHARE by Rom Gvili')
        gameIcon = pg.image.load('icon.png')
        pg.display.set_icon(gameIcon)
        startscreen = pg.image.load("start.png")
        font = pg.font.Font(None, 32)
        clock = pg.time.Clock()
        input_box = pg.Rect(224, 150, 140, 32)
        color_inactive = pg.Color('lightskyblue3')
        color_active = pg.Color('dodgerblue2')
        color = color_inactive
        active = False
        text = 'enter username'
        done = False
        b = False
        while not done:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    pg.quit()
                if event.type == pg.MOUSEBUTTONDOWN:
                    # If the user clicked on the input_box rect.
                    if input_box.collidepoint(event.pos):
                        # Toggle the active variable.
                        active = not active
                    else:
                        active = False
                    # Change the current color of the input box.
                    color = color_active if active else color_inactive
                if event.type == pg.KEYDOWN:
                    if active:
                        if event.key == pg.K_RETURN:
                            b = True
                        elif event.key == pg.K_BACKSPACE:
                            text = text[:-1]
                        elif event.key == pg.K_v and pg.key.get_mods(
                        ) & pg.KMOD_CTRL:
                            win32clipboard.OpenClipboard()
                            text += win32clipboard.GetClipboardData()

                        else:
                            text += event.unicode
            if b == True:
                break

            screen.blit(startscreen, (0, 0))
            # Render the current text.
            txt_surface = font.render(text, True, color)
            # Resize the box if the text is too long.
            width = max(200, txt_surface.get_width() + 10)
            input_box.w = width
            # Blit the text.
            screen.blit(txt_surface, (input_box.x + 5, input_box.y + 5))
            # Blit the input_box rect.
            pg.draw.rect(screen, color, input_box, 2)

            pg.display.flip()
            clock.tick(30)
        name = text
        pg.display.quit()

        token = util.prompt_for_user_token(name, scope,
                                           '221e9a5fac5c4f40bb2de9c33ce7a863',
                                           '8c5e85b7165840bbb605b43924952889',
                                           'http://google.com/')
        sp_oauth = oauth2.SpotifyOAuth(
            os.getenv('221e9a5fac5c4f40bb2de9c33ce7a863'),
            os.getenv('8c5e85b7165840bbb605b43924952889'),
            os.getenv('http://google.com/'),
            scope=scope,
            cache_path='.cache-' + name)
        token_info = sp_oauth.get_cached_token()
        print(token_info)
        spoyifyObj = spotipy.Spotify(auth=token_info['access_token'])

        user = spoyifyObj.current_user()
        pg.init()
        screen = pg.display.set_mode((640, 480))
        pg.display.set_caption('SPOTISHARE by Rom Gvili')
        devicesimg = pg.image.load("devices.png")
        font = pg.font.SysFont(None, 34)
        font2 = pg.font.SysFont(None, 20)
        fontheb = pg.font.SysFont('arial.ttf', 15)
        clock = pg.time.Clock()
        input_box = pg.Rect(224, 150, 140, 32)
        color_inactive = pg.Color('lightskyblue3')
        color_active = pg.Color('dodgerblue2')
        color = color_inactive
        active = False
        text = 'enter device'
        done = False
        global device
        devices = spoyifyObj.devices()
        devices = devices['devices']
        lis = "your devices: "
        for device in devices:
            lis += device['name'] + ", "
        LENG = len(devices)
        text = "enter the desired device"
        text2 = font2.render(lis, True, (0, 255, 0), (0, 0, 128))
        textRect2 = text2.get_rect()
        textRect2.center = (640 // 2, 480 // 2)
        screen.blit(text2, textRect2)
        b = False
        while not done:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    pg.quit()
                if event.type == pg.MOUSEBUTTONDOWN:
                    # If the user clicked on the input_box rect.
                    if input_box.collidepoint(event.pos):
                        # Toggle the active variable.
                        active = not active
                    else:
                        active = False
                    # Change the current color of the input box.
                    color = color_active if active else color_inactive
                if event.type == pg.KEYDOWN:
                    if active:
                        if event.key == pg.K_RETURN:
                            b = True
                        elif event.key == pg.K_BACKSPACE:
                            text = text[:-1]
                        elif event.key == pg.K_v and pg.key.get_mods(
                        ) & pg.KMOD_CTRL:
                            win32clipboard.OpenClipboard()
                            text += win32clipboard.GetClipboardData()
                        else:
                            text += event.unicode
            if b == True:
                break
            devices = spoyifyObj.devices()['devices']
            if len(devices) != LENG:
                lis = "your devices: "
                for device in devices:
                    lis += device['name'] + ", "
                LENG = len(devices)
            screen.blit(devicesimg, (0, 0))
            # Render the current text.
            txt_surface = font.render(text, True, color)
            for c in text:
                if c not in heb:
                    txt_surface = font.render(text, True, color)
                else:
                    txt_surface = fontheb.render(text[::-1], True, color)
                    break
            # Resize the box if the text is too long.
            width = max(200, txt_surface.get_width() + 10)
            input_box.w = width
            # Blit the text.
            screen.blit(txt_surface, (input_box.x + 5, input_box.y + 5))
            # Blit the input_box rect.
            pg.draw.rect(screen, color, input_box, 2)
            text2 = font2.render(lis, True, (0, 255, 0), (0, 0, 128))
            textRect2 = text2.get_rect()
            textRect2.center = (640 // 2, 480 // 2)
            screen.blit(text2, textRect2)
            pg.display.flip()
            clock.tick(30)
        for d in devices:
            print(d['name'])
            if text == d['name']:
                device = d
                break
        displayName = user['display_name']
        Followers = user['followers']['total']
        bg = pg.image.load("playing.png")
        screen.blit(bg, (0, 0))
        text2 = font2.render("welcome to SpotiShare " + displayName + "!",
                             True, (0, 255, 0), (0, 0, 128))
        textRect2 = text2.get_rect()
        textRect2.center = (640 // 2, 480 // 2)
        screen.blit(text2, textRect2)
        text3 = font2.render("you have " + str(Followers) + "followers!", True,
                             (0, 255, 0), (0, 0, 128))
        textRect3 = text3.get_rect()
        textRect3.center = (640 // 2, (480 // 2) + 20)
        screen.blit(text3, textRect3)
        pg.display.flip()
        pg.time.wait(2000)
        clientSocket = socket.socket()
        clientSocket.connect((address, port))
        clientSocket.settimeout(2)
        while True:
            try:
                print(clientSocket.recv(22).decode('UTF8'))
                break
            except:
                pass
        while True:
            try:
                x = clientSocket.recv(34).decode('UTF8')
                break
            except:
                pass

        def play():
            if "T" in x:
                try:
                    spoyifyObj.start_playback(device['id'], None, [track],
                                              None, pos)
                except:
                    print(
                        "plase check you're connected to the internet and spotify is open on the device"
                    )
                    pg.time.wait(5000)
                    play()
            else:
                try:
                    spoyifyObj.start_playback(device['id'], None, trackurl)
                except:
                    print(
                        "plase check you're connected to the internet and spotify is open on the device"
                    )
                    pg.time.wait(5000)
                    play()

        def isPlaying():
            try:
                if spoyifyObj.currently_playing()["is_playing"]:
                    return True
                return False
            except:
                return False

        if "T" in x:
            yo = pg.image.load("welcome.png")
            screen.blit(yo, (0, 0))
            pg.display.flip()
            while True:
                try:
                    track = clientSocket.recv(69).decode('UTF8')
                    break
                except:
                    pass
            while True:
                try:
                    pos = clientSocket.recv(bsize).decode('UTF8')
                    break
                except:
                    pass
            play()
            while (isPlaying() == False):
                pass
        else:
            yo = pg.image.load("first.png")
            screen.blit(yo, (0, 0))
            pg.display.flip()
            recently = "start" + spoyifyObj.current_user_recently_played(
                1)['items'][0]['track']['id']
            clientSocket.send(recently.encode())
            trackurl = []
            while True:
                try:
                    trackurl.append(clientSocket.recv(bsize).decode('UTF8'))
                    break
                except:
                    pass
            print(trackurl)
            play()
            while (isPlaying() == False):
                pass
        pg.time.wait(5000)
        yo = pg.image.load("last.png")
        screen.blit(yo, (0, 0))
        addbutton = pg.Rect(500, 40, 100, 100)
        nextbutton = pg.Rect(500, 200, 100, 100)
        textbutton = pg.Rect(500, 360, 100, 100)
        nextbuttontext = font2.render("play next song", True, (0, 255, 0),
                                      (0, 0, 128))
        nextbuttonRect = nextbuttontext.get_rect()
        nextbuttonRect.center = (550, 250)
        screen.blit(nextbuttontext, nextbuttonRect)
        addbuttontext = font2.render("add a song", True, (0, 255, 0),
                                     (0, 0, 128))
        addbuttonRect = addbuttontext.get_rect()
        addbuttonRect.center = (550, 90)
        screen.blit(addbuttontext, addbuttonRect)
        smsbuttontext = font2.render("send a message", True, (0, 255, 0),
                                     (0, 0, 128))
        smsbuttonRect = smsbuttontext.get_rect()
        smsbuttonRect.center = (550, 410)
        screen.blit(smsbuttontext, smsbuttonRect)

        def sendsms():
            color = color_inactive
            screen.blit(bg, (0, 0))
            text = "enter a message to send"
            txt_surface = font.render(text, True, color)
            width = max(200, txt_surface.get_width() + 10)
            input_box.w = width
            screen.blit(txt_surface, (input_box.x + 5, input_box.y + 5))
            pg.draw.rect(screen, color, input_box, 2)
            b = False
            active = False
            while not done:
                for event in pg.event.get():
                    if event.type == pg.QUIT:
                        pg.quit()
                    if event.type == pg.MOUSEBUTTONDOWN:
                        # If the user clicked on the input_box rect.
                        if input_box.collidepoint(event.pos):
                            # Toggle the active variable.
                            active = not active
                        else:
                            active = False
                        # Change the current color of the input box.
                        color = color_active if active else color_inactive
                    if event.type == pg.KEYDOWN:
                        if active:
                            if event.key == pg.K_RETURN:
                                b = True
                            elif event.key == pg.K_BACKSPACE:
                                text = text[:-1]
                            elif event.key == pg.K_v and pg.key.get_mods(
                            ) & pg.KMOD_CTRL:
                                win32clipboard.OpenClipboard()
                                text += win32clipboard.GetClipboardData()
                            else:
                                text += event.unicode
                screen.blit(bg, (0, 0))
                txt_surface = font.render(text, True, color)
                for c in text:
                    if c not in heb:
                        txt_surface = font.render(text, True, color)
                    else:
                        txt_surface = fontheb.render(text[::-1], True, color)
                        break
                width = max(200, txt_surface.get_width() + 10)
                input_box.w = width
                screen.blit(txt_surface, (input_box.x + 5, input_box.y + 5))
                pg.draw.rect(screen, color, input_box, 2)
                pg.display.flip()
                if b == True:
                    break
            clientSocket.send(("sms " + name + ": " + text).encode())
            screen.blit(yo, (0, 0))
            return

        def nextsongpressed():
            clientSocket.send("play next song".encode())
            while True:
                try:
                    res = clientSocket.recv(bsize).decode()
                    break
                except:
                    pass
            if res != "gotch":
                print(spoyifyObj.recommendations(
                    None,
                    None,
                    [res[17:]],
                    1,
                ))
                clientSocket.send(
                    spoyifyObj.recommendations(None, None, [res[17:]],
                                               1)['tracks'][0]['id'].encode())

        def addsongpressed():
            color = color_inactive
            screen.blit(bg, (0, 0))
            text = "enter artist name"
            txt_surface = font.render(text, True, color)
            width = max(200, txt_surface.get_width() + 10)
            input_box.w = width
            screen.blit(txt_surface, (input_box.x + 5, input_box.y + 5))
            pg.draw.rect(screen, color, input_box, 2)
            b = False
            active = False
            while not done:
                for event in pg.event.get():
                    if event.type == pg.QUIT:
                        pg.quit()
                    if event.type == pg.MOUSEBUTTONDOWN:
                        # If the user clicked on the input_box rect.
                        if input_box.collidepoint(event.pos):
                            # Toggle the active variable.
                            active = not active
                        else:
                            active = False
                        # Change the current color of the input box.
                        color = color_active if active else color_inactive
                    if event.type == pg.KEYDOWN:
                        if active:
                            if event.key == pg.K_RETURN:
                                b = True
                            elif event.key == pg.K_BACKSPACE:
                                text = text[:-1]
                            elif event.key == pg.K_v and pg.key.get_mods(
                            ) & pg.KMOD_CTRL:
                                win32clipboard.OpenClipboard()
                                text += win32clipboard.GetClipboardData()
                            else:
                                text += event.unicode
                screen.blit(bg, (0, 0))
                txt_surface = font.render(text, True, color)
                for c in text:
                    if c not in heb:
                        txt_surface = font.render(text, True, color)
                    else:
                        txt_surface = fontheb.render(text[::-1], True, color)
                        break
                width = max(200, txt_surface.get_width() + 10)
                input_box.w = width
                screen.blit(txt_surface, (input_box.x + 5, input_box.y + 5))
                pg.draw.rect(screen, color, input_box, 2)
                pg.display.flip()
                if b == True:
                    break
            artistName = text
            results = spoyifyObj.search(artistName, 1, 0, "artist")
            try:
                artist = results['artists']['items'][0]
            except:
                screen.blit(bg, (0, 0))
                text = "artist wasnt found"
                txt_surface = font.render(text, True, color)
                width = max(200, txt_surface.get_width() + 10)
                input_box.w = width
                screen.blit(txt_surface, (input_box.x + 5, input_box.y + 5))
                pg.draw.rect(screen, color, input_box, 2)
                pg.display.flip()
                pg.time.wait(3000)
                screen.blit(yo, (0, 0))
                return
            #print(artist['name'] + " has " + str(artist['followers']['total']) + " followers , and his genre is " + artist['genres'][0])
            urllib.request.urlretrieve(artist['images'][0]['url'], 'pic.png')
            with open('pic.png', 'r+b') as f:
                with Image.open(f) as image:
                    artistpic = resizeimage.resize_cover(image, [640, 480])
                    artistpic.save('pic.png', image.format)
            artistpic = pg.image.load('pic.png')
            screen.blit(artistpic, (0, 0))
            pg.display.flip()
            text = "enter song name"
            txt_surface = font.render(text, True, color)
            width = max(200, txt_surface.get_width() + 10)
            input_box.w = width
            screen.blit(txt_surface, (input_box.x + 5, input_box.y + 5))
            pg.draw.rect(screen, color, input_box, 2)
            b = False
            active = False
            while not done:
                for event in pg.event.get():
                    if event.type == pg.QUIT:
                        pg.quit()
                    if event.type == pg.MOUSEBUTTONDOWN:
                        # If the user clicked on the input_box rect.
                        if input_box.collidepoint(event.pos):
                            # Toggle the active variable.
                            active = not active
                        else:
                            active = False
                        # Change the current color of the input box.
                        color = color_active if active else color_inactive
                    if event.type == pg.KEYDOWN:
                        if active:
                            if event.key == pg.K_RETURN:
                                b = True
                            elif event.key == pg.K_BACKSPACE:
                                text = text[:-1]
                            elif event.key == pg.K_v and pg.key.get_mods(
                            ) & pg.KMOD_CTRL:
                                win32clipboard.OpenClipboard()
                                text += win32clipboard.GetClipboardData()
                            else:
                                text += event.unicode
                screen.blit(artistpic, (0, 0))
                txt_surface = font.render(text, True, color)
                for c in text:
                    if c not in heb:
                        txt_surface = font.render(text, True, color)
                    else:
                        txt_surface = fontheb.render(text[::-1], True, color)
                        break
                width = max(200, txt_surface.get_width() + 10)
                input_box.w = width
                screen.blit(txt_surface, (input_box.x + 5, input_box.y + 5))
                pg.draw.rect(screen, color, input_box, 2)
                pg.display.flip()
                if b == True:
                    break
            songname = text.upper()

            artistId = artist["id"]
            albums = {}
            count = 0
            while len(albums) % 10 == 0:
                albums.update(
                    spoyifyObj.artist_albums(artistId, None, None, 20, count))
                count += 20
            print(albums)
            albums = spoyifyObj.artist_albums(artistId, None, None, 50)
            albums = albums['items']
            close = []
            closeuri = []
            albumsi = []
            names = {}

            def checker(na, di, al):
                if na in di:
                    if di[na] == al:
                        return False
                return True

            for album in albums:
                albumId = album['id']
                trackResults = spoyifyObj.album_tracks(albumId)
                trackResults = trackResults['items']
                for item in trackResults:
                    if (songname in item['name'].upper()
                            or songname == item['name'].upper()
                            or levenshtein(songname, item['name'].upper()) <
                            4.0) and item['uri'] not in closeuri and checker(
                                item['name'].upper(), names, album['name']):
                        close.append(item)
                        closeuri.append(item['uri'])
                        albumsi.append(album['name'])
                        names[item['name'].upper()] = album['name']
            if len(close) != 0:
                closest = ""
                mini = 5
                if len(close) > 1:
                    count = 1
                    for ite in close:
                        text4 = font2.render(
                            str(count) + ". " + ite['name'] + " from " +
                            albumsi[count - 1], True, (0, 255, 0), (0, 0, 128))
                        textRect4 = text4.get_rect()
                        textRect4.center = (640 // 2, (480 // 2) + count * 15)
                        screen.blit(text4, textRect4)
                        count += 1
                    pg.display.flip()
                    text = "enter song number"
                    txt_surface = font.render(text, True, color)
                    width = max(200, txt_surface.get_width() + 10)
                    input_box.w = width
                    screen.blit(txt_surface,
                                (input_box.x + 5, input_box.y + 5))
                    pg.draw.rect(screen, color, input_box, 2)
                    b = False
                    active = False
                    while not done:
                        for event in pg.event.get():
                            if event.type == pg.QUIT:
                                pg.quit()
                            if event.type == pg.MOUSEBUTTONDOWN:
                                # If the user clicked on the input_box rect.
                                if input_box.collidepoint(event.pos):
                                    # Toggle the active variable.
                                    active = not active
                                else:
                                    active = False
                                # Change the current color of the input box.
                                color = color_active if active else color_inactive
                            if event.type == pg.KEYDOWN:
                                if event.key == pg.K_RETURN:
                                    b = True
                                if active:
                                    if event.key == pg.K_RETURN:
                                        b = True
                                    elif event.key == pg.K_BACKSPACE:
                                        text = text[:-1]
                                    elif event.key == pg.K_v and pg.key.get_mods(
                                    ) & pg.KMOD_CTRL:
                                        win32clipboard.OpenClipboard()
                                        text += win32clipboard.GetClipboardData(
                                        )
                                    else:
                                        text += event.unicode
                        screen.blit(artistpic, (0, 0))
                        txt_surface = font.render(text, True, color)
                        for c in text:
                            if c not in heb:
                                txt_surface = font.render(text, True, color)
                            else:
                                txt_surface = fontheb.render(
                                    text[::-1], True, color)
                                break
                        width = max(200, txt_surface.get_width() + 10)
                        input_box.w = width
                        screen.blit(txt_surface,
                                    (input_box.x + 5, input_box.y + 5))
                        pg.draw.rect(screen, color, input_box, 2)
                        count = 1
                        for ite in close:
                            for c in ite['name']:
                                if c in heb:
                                    text4 = fontheb.render(
                                        str(count) + ". " + ite['name'][::-1] +
                                        " from " + albumsi[count - 1][::-1],
                                        True, (0, 255, 0), (0, 0, 128))
                                    break
                                text4 = font2.render(
                                    str(count) + ". " + ite['name'] +
                                    " from " + albumsi[count - 1], True,
                                    (0, 255, 0), (0, 0, 128))
                            textRect4 = text4.get_rect()
                            textRect4.center = (640 // 2,
                                                (480 // 2) + count * 15)
                            screen.blit(text4, textRect4)
                            count += 1
                        pg.display.flip()
                        if b == True:
                            break
                    closest = close[int(text) - 1]['uri']
                else:
                    closest = close[0]['uri']
                clientSocket.send(closest.encode())
                while True:
                    try:
                        print(clientSocket.recv(55).decode())
                        break
                    except:
                        pass

                screen.blit(yo, (0, 0))
                return
            screen.blit(yo, (0, 0))
            screen.blit(artistpic, (0, 0))
            text = "song wasnt found"
            txt_surface = font.render(text, True, color)
            width = max(200, txt_surface.get_width() + 10)
            input_box.w = width
            screen.blit(txt_surface, (input_box.x + 5, input_box.y + 5))
            pg.draw.rect(screen, color, input_box, 2)
            pg.display.flip()
            pg.time.wait(3000)
            screen.blit(yo, (0, 0))
            return

        while True:
            #if sp_oauth.is_token_expired:
            token_info = sp_oauth.get_cached_token()
            spoyifyObj = spotipy.Spotify(auth=token_info['access_token'])
            while isPlaying() != False:
                globals()
                try:
                    data = ""
                    data = clientSocket.recv(bsize)
                    data = data.decode('UTF8')
                    if data:
                        if data[0:4] == "next":
                            track = data[5:41]
                            pos = data[42:]
                            if pos == "":
                                spoyifyObj.start_playback(
                                    device['id'], None, [track])
                            else:
                                spoyifyObj.start_playback(
                                    device['id'], None, [track], None, pos)
                            while (isPlaying() == False):
                                pass
                        elif data[0:4] == "sms ":
                            if len(smslist) == 10:
                                smslist.remove(smslist[9])
                            smslist.insert(0, data[4:])

                except:
                    pass
                for event in pg.event.get():
                    if event.type == pg.QUIT:
                        pg.quit()
                    if event.type == pg.MOUSEBUTTONDOWN:
                        mouse_pos = event.pos  # gets mouse position
                        if nextbutton.collidepoint(mouse_pos):
                            nextsongpressed()
                        if addbutton.collidepoint(mouse_pos):
                            addsongpressed()
                        if textbutton.collidepoint(mouse_pos):
                            sendsms()
                screen.blit(yo, (0, 0))
                count = 0
                for sms in smslist:
                    for letter in sms:
                        if letter in heb:
                            text5 = fontheb.render(sms[::-1], True,
                                                   (0, 255, 0), (0, 0, 128))
                            break
                        text5 = font2.render(sms, True, (0, 255, 0),
                                             (0, 0, 128))
                    textRect5 = text5.get_rect()
                    textRect5.center = (100, (11) + count * 25)
                    textRect5.x = 40
                    screen.blit(text5, textRect5)
                    count += 1
                    pg.display.flip()
                pg.draw.rect(screen, [255, 0, 0], addbutton)  # draw button
                pg.draw.rect(screen, [255, 0, 0], nextbutton)  # draw button
                pg.draw.rect(screen, [255, 0, 0], textbutton)  # draw button
                screen.blit(nextbuttontext, nextbuttonRect)
                screen.blit(addbuttontext, addbuttonRect)
                screen.blit(smsbuttontext, smsbuttonRect)

                pg.display.update()
            while pygameanticrasher():
                clientSocket.send("song is done".encode())
                print('sent')
                while True:
                    try:
                        track = clientSocket.recv(bsize).decode()
                        break
                    except:
                        pass
                print(track)
                if "REC" in track:
                    clientSocket.send(
                        spoyifyObj.recommendations(
                            None, None, [track[17:]],
                            1)['tracks'][0]['id'].encode())
                    while True:
                        try:
                            track = clientSocket.recv(bsize).decode()
                            break
                        except:
                            pass

                if "!" in track:
                    track = track[0:36]
                    pos = track[38:]
                    spoyifyObj.start_playback(device['id'], None, [track],
                                              None, pos)
                else:
                    spoyifyObj.start_playback(device['id'], None, [track])
                while (isPlaying() == False):
                    pass
                break

    pg.QUIT()
""" Files holds all the code necessary for the application to request/store/modify a spotify user's data provided they went through the OAuth process
and we have a User object representing them stored in our DB """
import config_app
from math import ceil
import models
import random
import spotipy
from spotipy import oauth2

Config = config_app.Config

redirect_url = 'http://sorter.sampeters.me/callback'
oauth_client = oauth2.SpotifyOAuth(client_id=Config.SPOTIFY_CLIENT_ID,
					client_secret=Config.SPOTIFY_CLIENT_SECRET,
					redirect_uri=redirect_url,
					scope=Config.SCOPE,
                                        username="******")

app = config_app.app
db = models.db


def get_api_client(user):
    """ Creates a User specific spotify client that uses their access token to make Spotify API requests """
    if user.is_access_expired():
        user.refresh_access_token(oauth_client)
    return spotipy.client.Spotify(user.access_token)


def download_user_library(user):
    """ Saves a user's spotify library to the track table in our DB """
Beispiel #20
0
from app import app
from spotipy import Spotify, oauth2, SpotifyException
from flask import redirect, url_for, flash
import os
import wget
from datetime import datetime


spotify_token = None
sp = None
current_user = ""
currently_playing_id = ""
CACHE = app.config['SPOTIPY_CACHE']
sp_oauth = oauth2.SpotifyOAuth(app.config['SPOTIPY_CLIENT_ID'], app.config['SPOTIPY_CLIENT_SECRET'],
                               app.config['SPOTIPY_REDIRECT_URI'], scope=app.config['SPOTIPY_SCOPE'], cache_path=CACHE)
history = []


def logout():
    global sp, current_user
    sp = None
    current_user = ""


def set_cache(cache):
    global CACHE, sp_oauth
    CACHE = cache
    sp_oauth = oauth2.SpotifyOAuth(app.config['SPOTIPY_CLIENT_ID'], app.config['SPOTIPY_CLIENT_SECRET'],
                               app.config['SPOTIPY_REDIRECT_URI'], scope=app.config['SPOTIPY_SCOPE'], cache_path=CACHE)
    return
Beispiel #21
0
from justlisten.database import UsersDatabase
from justlisten.UsersPercentage import UsersPercentage
from justlisten.songsDatabase import SongsDatabase
from justlisten.users_and_songsDatabase import users_and_songsDatabase

PORT_NUMBER = 8080  # the port that the server run on
SPOTIPY_CLIENT_ID = 'f97d1c5036a046979fd80b06095282da'  # application id
SPOTIPY_CLIENT_SECRET = 'd57ba80dfd244a43a5e8139f21b6038a'  # application secret
SPOTIPY_REDIRECT_URI = 'http://80.178.34.235:8080'  # application uri
SCOPE = 'user-library-read playlist-modify-private user-read-currently-playing'  # the variable that say what i will do with the client
DATABASE_PATH = "database.db"

sp_oauth = oauth2.SpotifyOAuth(
    SPOTIPY_CLIENT_ID,
    SPOTIPY_CLIENT_SECRET,
    SPOTIPY_REDIRECT_URI,
    scope=SCOPE,
    open_browser=False)  #a variable that get access to the token_info
app = Flask(__name__)  # the server object


@app.route('/')  # connect to the function index
def index():
    """
    a function that connect the client
    """
    code = request.args.get('code')  # get the client code to the token
    if code:
        # if he already connect and he have a token
        print(
            "Found Spotify auth code in Request URL! Trying to get valid access token..."
Beispiel #22
0
def set_cache(cache):
    global CACHE, sp_oauth
    CACHE = cache
    sp_oauth = oauth2.SpotifyOAuth(app.config['SPOTIPY_CLIENT_ID'], app.config['SPOTIPY_CLIENT_SECRET'],
                               app.config['SPOTIPY_REDIRECT_URI'], scope=app.config['SPOTIPY_SCOPE'], cache_path=CACHE)
    return
    new_songs['tempo'] = tempo
    new_songs['mode'] = mode
    new_songs['speechiness'] = speechiness
    new_songs['time_signature'] = time_signature
    new_songs['valence'] = valence

    return new_songs


path_to_data = "/home/sayan/Documents/Data Science/DATA1030/project/data"

username = '******'
CLIENT_ID = 'a55d8d9617de463cad7abce998314bb3'
CLIENT_SECRET = '905ac33d383d47f6aca7cbb3f3c60d49'
sp_oauth = oauth2.SpotifyOAuth(client_id=CLIENT_ID,
                               client_secret=CLIENT_SECRET,
                               redirect_uri='http://localhost/')

token_info = sp_oauth.get_cached_token()
if not token_info:
    auth_url = sp_oauth.get_authorize_url()
    print(auth_url)
    response = input(
        'Paste the above link into your browser, then paste the redirect url here: '
    )

    code = sp_oauth.parse_response_code(response)
    token_info = sp_oauth.get_access_token(code)

    token = token_info['access_token']
from spotipy.oauth2 import SpotifyClientCredentials

app = Bottle()

# globals
logging.basicConfig(level=logging.DEBUG,
                    format="%(asctime)s - %(levelname)s - %(message)s")
CLIENT_ID = "e29426dfb22c41cdbc92122fbb9c398c"
CLIENT_SECRET = "837fd2824bec47e5a003419165674bdd"
SCOPE = "user-top-read user-read-recently-played playlist-modify-public playlist-modify-private"
CACHE = ".spotifyoauthcache"
CLIENT_CREDENTIALS = SpotifyClientCredentials(client_id=CLIENT_ID,
                                              client_secret=CLIENT_SECRET)
SP_OAUTH2 = oauth2.SpotifyOAuth(client_id=CLIENT_ID,
                                client_secret=CLIENT_SECRET,
                                redirect_uri="http://localhost:8000/verified",
                                scope=SCOPE,
                                cache_path=CACHE)
LIMIT = 50
OFFSET = 0

TEMPLATE_PATH.insert(0, "")

# global functions


def get_token():
    access_token = ""
    token_info = SP_OAUTH2.get_cached_token()
    if token_info:
        access_token = token_info["access_token"]
Beispiel #25
0
import configparser
import spotipy
import spotipy.oauth2 as oauth2
import spotipy.util as util

from knearest import k_nearest

app = Flask(__name__)

# config with secrets and IDs
config = configparser.ConfigParser()
config.read('config.cfg')
client_id = config.get('SPOTIFY', 'CLIENT_ID')
redirect_uri = config.get('SPOTIFY', 'REDIRECT_URL')
client_secret = config.get('SPOTIFY', 'CLIENT_SECRET')
sp_oauth = oauth2.SpotifyOAuth(client_id, client_secret, redirect_uri)


@app.route('/login')
def hello_world():
    genre = request.args['genre']
    scope = 'playlist-modify-public playlist-modify-private user-library-read user-top-read'
    auth_query_parameters = {
        "response_type": "code",
        "redirect_uri": redirect_uri,
        "scope": scope,
        "client_id": client_id,
        "state": genre
    }
    url_args = "&".join([
        "{}={}".format(key, urllib.parse.quote(val))
Beispiel #26
0
def prompt_for_user_token(username,
                          scope=None,
                          client_id=None,
                          client_secret=None,
                          redirect_uri=None):
    """
    prompts the user to login if necessary and returns
        the user token suitable for use with the spotipy.Spotify 
        constructor

        Parameters:

         - username - the Spotify username
         - scope - the desired scope of the request
         - client_id - the client id of your app
         - client_secret - the client secret of your app
         - redirect_uri - the redirect URI of your app
    """

    if not client_id:
        client_id = os.getenv("SPOTIPY_CLIENT_ID")

    if not client_secret:
        client_secret = os.getenv("SPOTIPY_CLIENT_SECRET")

    if not redirect_uri:
        redirect_uri = os.getenv("SPOTIPY_REDIRECT_URI",
                                 "http://localhost:8080")

    if not client_id:
        print('''
            You need to set your Spotify API credentials. You can do this by
            setting environment variables like so:

            export SPOTIPY_CLIENT_ID='your-spotify-client-id'
            export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
            export SPOTIPY_REDIRECT_URI='your-app-redirect-url'

            Get your credentials at     
                https://developer.spotify.com/my-applications
        ''')
        raise spotipy.SpotifyException(550, -1, 'no credentials set')

    sp_oauth = oauth2.SpotifyOAuth(client_id,
                                   client_secret,
                                   redirect_uri,
                                   scope=scope,
                                   cache_path=get_cache_path(username))

    # try to get a valid token for this user, from the cache,
    # if not in the cache, the create a new (this will send
    # the user to a web page where they can authorize this app)

    token_info = sp_oauth.get_cached_token()

    if not token_info:
        redirect_uri_parsed = urlparse(redirect_uri)

        run_server(redirect_uri_parsed.hostname, redirect_uri_parsed.port)

        auth_url = sp_oauth.get_authorize_url()
        try:
            import webbrowser
            webbrowser.open(auth_url)
        except:
            print("Please navigate here: %s" % auth_url)

        response = "%s?code=%s" % (redirect_uri, auth_token_queue.get())
        event_queue.put("done")

        code = sp_oauth.parse_response_code(response)
        token_info = sp_oauth.get_access_token(code)
    # Auth'ed API request
    if token_info:
        return token_info['access_token']
    else:
        return None
Beispiel #27
0
def request_token_web(force=False):
    '''request the (initial) auth token by webbrowser'''
    import spotipy
    from spotipy import oauth2
    xbmcvfs.mkdir("special://profile/addon_data/%s/" % ADDON_ID)
    cache_path = "special://profile/addon_data/%s/spotipy.cache" % ADDON_ID
    cache_path = xbmc.translatePath(cache_path).decode("utf-8")
    scope = " ".join(SCOPE)
    redirect_url = 'http://localhost:%s/callback' % PROXY_PORT
    sp_oauth = oauth2.SpotifyOAuth(CLIENTID,
                                   CLIENT_SECRET,
                                   redirect_url,
                                   scope=scope,
                                   cache_path=cache_path)
    # get token from cache
    token_info = sp_oauth.get_cached_token()
    if not token_info or force:
        # request token by using the webbrowser
        p = None
        auth_url = sp_oauth.get_authorize_url()

        # show message to user that the browser is going to be launched
        dialog = xbmcgui.Dialog()
        header = xbmc.getInfoLabel("System.AddonTitle(%s)" %
                                   ADDON_ID).decode("utf-8")
        msg = xbmc.getInfoLabel("$ADDON[%s 11049]" % ADDON_ID).decode("utf-8")
        dialog.ok(header, msg)
        del dialog

        if xbmc.getCondVisibility("System.Platform.Android"):
            # for android we just launch the default android browser
            xbmc.executebuiltin(
                "StartAndroidActivity(,android.intent.action.VIEW,,%s)" %
                auth_url)
        else:
            # use webbrowser module
            import webbrowser
            log_msg("Launching system-default browser")
            webbrowser.open(auth_url, new=1)

        count = 0
        while not xbmc.getInfoLabel(
                "Window(Home).Property(spotify-token-info)"):
            log_msg("Waiting for authentication token...")
            xbmc.sleep(2000)
            if count == 60:
                break
            count += 1

        response = xbmc.getInfoLabel(
            "Window(Home).Property(spotify-token-info)")
        xbmc.executebuiltin("ClearProperty(spotify-token-info,Home)")
        if response:
            response = sp_oauth.parse_response_code(response)
            token_info = sp_oauth.get_access_token(response)
        xbmc.sleep(2000)  # allow enough time for the webbrowser to stop
    log_msg("Token from web: %s" % token_info, xbmc.LOGDEBUG)
    sp = spotipy.Spotify(token_info['access_token'])
    username = sp.me()["id"]
    del sp
    addon_setting("username", username)
    return token_info
Beispiel #28
0
from flask import make_response
from slackclient import SlackClient
import base64, requests, six, json, os
import spotipy.oauth2 as spotipy_auth

__client_id__ = os.environ["CLIENT_ID"]
__client_secret__ = os.environ["CLIENT_SECRET"]
__pub_host__ = "https://dj-slacker.herokuapp.com/"
__spotify_auth__ = spotipy_auth.SpotifyOAuth(
    client_id=__client_id__,
    client_secret=__client_secret__,
    redirect_uri='https://dj-slacker.herokuapp.com/',
    scope=
    'user-read-currently-playing user-read-recently-played user-read-private')


class Spotibot:
    def _make_authorization_headers(self):
        auth_header = base64.b64encode(
            six.text_type(__client_id__ + ':' +
                          __client_secret__).encode('ascii'))
        return {'Authorization': 'Basic %s' % auth_header.decode('ascii')}

    def get_new_access_token(self, refresh_token):
        return __spotify_auth__.refresh_access_token(
            refresh_token=refresh_token)

    def get_currently_playing(self, access_token):
        headers = {'Authorization': 'Bearer ' + access_token}
        response = requests.get(
            'https://api.spotify.com/v1/me/player/currently-playing',

#EDIT THESE
client_id="YOUR CLIENT ID"
client_secret="YOUR CLIENT SECRET"
redirect_uri="YOUR REDIRECT URI"
username = '******'
playlist_id= 'YOUR PLAYLIST ID'

#Don't edit these
scope = 'playlist-modify-public'
track_id = ['']
token = 'this is a temp token'
currentdata = ''

sp_oauth = oauth2.SpotifyOAuth(client_id=client_id,client_secret=client_secret,redirect_uri=redirect_uri,scope=scope)
token_info = sp_oauth.get_cached_token()

if not token_info:
    auth_url = sp_oauth.get_authorize_url()
    print(auth_url)
    response = input('Paste the above link into your browser, then paste the redirect url here: ')

    code = sp_oauth.parse_response_code(response)
    token_info = sp_oauth.get_access_token(code)

    token = token_info['access_token']

if token:
    sp = spotipy.Spotify(auth=token)
    # for other channels you need to change the deepLinkId. This example code is for BPM which is channel 51.
Beispiel #30
0
import spotipy.util as util
from config import AccuWather_API_Key, Spotify_Client_Id, Spotify_Client_Secret, Redirect_Uri, SCOPE, CACHE, logout_url

app = Flask(__name__)

# Required to use Flask sessions and the debug toolbar
app.config['SECRET_KEY'] = os.environ['SECRET_KEY']

# Normally, if you use an undefined variable in Jinja2, it fails
# silently. This is horrible. Fix this so that, instead, it raises an
# error.
app.jinja_env.undefined = StrictUndefined

sp_oauth = oauth2.SpotifyOAuth(client_id=Spotify_Client_Id,
                               client_secret=Spotify_Client_Secret,
                               redirect_uri=Redirect_Uri,
                               scope=SCOPE,
                               cache_path=CACHE)
auth_url = sp_oauth.get_authorize_url()


@app.route('/')
def index():
    """Homepage."""
    return render_template("homepage.html", auth_url=auth_url)


@app.route('/login', methods=['GET', 'POST'])
def login():
    """User login"""