コード例 #1
0
ファイル: host.py プロジェクト: jetmets/Spotify2.bundle
    def start(self):
        self.messages = []

        if not self.username or not self.password:
            self.messages.append((logging.ERROR, 'Username or Password not entered'))
            Log.Error('Username or Password not entered')
            return

        Log.Debug('bundle_path: "%s"', self.bundle_path)

        if not self.client:
            self.client = SpotifyClient(self)

        # Start server (if 'proxy_tracks' is enabled)
        if not self.server and self.proxy_tracks:
            self.server = Server(self)
            self.server.start()

        # Stop server if 'proxy_tracks' has been disabled
        if self.server and not self.proxy_tracks:
            self.server.stop()
            self.server = None

        # Update server preferences
        if self.server:
            self.server.supports_ranges = PREF_SS_RANGES.get(Prefs['proxy_ranges'], True)

        # Update reference on SpotifyClient
        self.client.server = self.server

        # start/restart the client
        self.client.start()
コード例 #2
0
    def start(self):
        """ Start the Spotify client and HTTP server """
        if not self.username or not self.password:
            Log("Username or password not set: not logging in")
            return False

        can_start = self.start_lock.acquire(blocking=False)
        try:
            # If there is a start in process, just wait until it finishes, but don't raise another one
            if not can_start:
                Log.Debug(
                    "Start already in progress, waiting it finishes to return")
                self.start_lock.acquire()
            else:
                Log.Debug("Start triggered, entering private section")
                self.start_marker.clear()

                if self.client:
                    self.client.restart(self.username, self.password)
                else:
                    self.client = SpotifyClient(self.username, self.password)

                self.last_track_uri = None
                self.last_track_object = None
                Dict['play_count'] = 0
                Dict['last_restart'] = time.time()
                self.start_marker.set()
                Log.Debug("Start finished, leaving private section")
        finally:
            self.start_lock.release()

        return self.client and self.client.is_logged_in()
コード例 #3
0
 def start(self):
     ''' Start the Spotify client and HTTP server '''
     if not self.username or not self.password:
         Log("Username or password not set: not logging in")
         return
     self.client = SpotifyClient(self.username, self.password, self.ioloop)
     self.client.connect()
     self.server = SpotifyServer(self.client)
     self.server.start()
コード例 #4
0
def run():

    # # if you'd prefer an input
    # token = input("What's your OAUTH Token? ")
    # client = SpotifyClient(token)
    client = SpotifyClient(os.getenv('token'))
    print(f"token is: {os.getenv('token')}")

    choice = input("Return top 'artists' or 'tracks'?  ")
    if not (choice == 'artists' or choice == 'tracks'):
        print("Term not recognized. Default: tracks.")
        choice = 'tracks'

    if choice == 'tracks':
        want_analysis = input("Include audio analysis (y,n)?  ")
        tracks = client.get_top_tracks()
        print()
        print(
            'The following are your top tracks, starting with the most played')
        print()
        for i, track in enumerate(tracks):
            num = '{:<3}'.format(str(i + 1) + '.')
            print(f"{num} '{track['name']}' by {track['artists'][0]['name']} ")
            if (want_analysis == 'y'):
                features = client.get_analysis(track["id"])
                print(f"energy: {features['energy']}")
                print(f"valence: {features['valence']}")
                print(f"mode: {features['mode']}")
                print(f"danceability: {features['danceability']}")
                print(f"tempo: {features['tempo']}")
                print()

    if choice == 'artists':
        want_details = input("Include audio analysis (y,n)?  ")
        artists = client.get_top_artists()
        print()
        print(
            'The following are your top artists, starting with the most played'
        )
        print()
        for i, artist in enumerate(artists):
            num = '{:<3}'.format(str(i + 1) + '.')
            print(f"{num} {artist['name']} ")
            if (want_details == 'y'):
                details = client.get_artist_details(artist["id"])
                print(f"main genre: {details['genres'][0]}")
                print(f"popularity: {details['popularity']}")
                print()
コード例 #5
0
def run():

    # # if you'd prefer an input
    # token = input("What's your OAUTH Token? ")
    # client = SpotifyClient(token)
    client = SpotifyClient(os.getenv('token'))
    print(f"token is: {os.getenv('token')}")

    #--search for random songs
    tracks = client.get_tracks()

    # get each track id
    track_ids = [track['id'] for track in tracks]
    
    #--add songs to library
    was_added_to_library = client.add_tracks_to_library(track_ids)
    if (was_added_to_library == True):
        for track in tracks:
            print(f"Added {track['name']} to your library")
コード例 #6
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--size",
                        type=int,
                        help="Size of the generated playlist")
    parser.add_argument("--name",
                        type=str,
                        help="Name of the generated playlist")
    parser.add_argument("--user",
                        type=str,
                        help="User for whom to create the playlist")
    parser.add_argument("--seed", type=str, help="ID of the seed track")
    args = parser.parse_args()

    logging.basicConfig(level=logging.INFO, stream=sys.stdout)

    client = SpotifyClient(args.user)
    seed_track = client.get_track(args.seed)
    factory = ArtistChainFactory(client,
                                 seed_track,
                                 DriftingWeight(seed_track),
                                 unique_artists=False)

    # If a playlist of this name exists, use it, otherwise create one.
    for playlist_ in client.get_playlists():
        if playlist_.name == args.name:
            playlist = playlist_
            break
    else:
        playlist = Playlist(name=args.name)

    for _, track in zip(range(args.size), factory):
        playlist.append(track)

    LOG.info("Finished generating playlist %s", str(playlist))

    client.store_playlist(playlist)
コード例 #7
0
import logging
import os
import time
from pprint import pformat

import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import util
from client import SpotifyClient

util.set_logging_config()
api = SpotifyClient()


def extract_tracks(result):
    tracks = []
    while True:
        for item in result['items']:
            if not item['track']['is_local']:
                track_data = {
                    'id': item['track']['id'],
                    'name': item['track']['name'],
                    'added_at': item['added_at']
                }
                tracks.append(track_data)

        if not result['next']: break
        result = api.next(result)

    return tracks
コード例 #8
0
ファイル: spotapi.py プロジェクト: khafkaa/spotify-api
import time
import json
from datetime import datetime
from iter.accessories import fetch
from client import SpotifyClient

app = os.environ.get('spotify_app')
key = os.environ.get('spotify_key')
url = os.environ.get('app_redirect')
tkn = os.environ.get('csrf_token')
uri = os.environ.get('current_track_uri')

liked_tracks = os.environ.get('default_playlist')
authorization_file = os.environ.get('spotify_auth_file')

api = SpotifyClient(client=app, secret=key, csrf=tkn, redirect=url)
api.refresh = os.environ.get('spotify_access')


def create_tmp(path):
    """create tmp directory if it doesn't already exist"""
    if os.path.isdir(path):
        return 1
    try:
        os.mkdir(path)
        return 1

    except OSError as error:
        print(error)
        return 0
コード例 #9
0
def run():

    # set token
    client = SpotifyClient(os.getenv('token'))
    print(f"token is: {os.getenv('token')}")

    # # choose artists or tracks
    # choice = input("Return top 'artists' or 'tracks'?  ")
    # if not (choice == 'artists' or choice== 'tracks'):
    #     print("Term not recognized. Default: tracks.")
    #     choice = 'tracks'

    choice = 'tracks'

    if choice == 'tracks':
        # choose term/limit
        term = input(
            "Choose term 'long' (ever), 'medium' (1/2 year), or 'short' (month) :  "
        )
        if (term == 'long'): term = 'long_term'
        if (term == 'medium'): term = 'medium_term'
        if (term == 'short'): term = 'short_term'
        if not (term == 'long_term' or term == 'medium_term'
                or term == 'short_term'):
            print("Term not recognized. Default: short_term.")
            term = 'short_term'

        limit = input("How many items (max 50)?   ")
        try:
            if not (int(limit) > 0 and int(limit) < 51):
                print("Out of range. Default: 5.")
                limit = 5
        except:
            print("Invalid Input. Default: 5.")
            limit = 5

        # get tracks
        want_analysis = input("Print audio analysis (y,n)?  ")
        tracks = client.get_top_tracks(term, limit)

        print()
        print(
            'The following are your top tracks, starting with the most played')
        print()

        # create string of names like js array
        names = "const names = ["
        artists = "const artists = ["
        energies = "const energies = ["
        valences = "const valences = ["
        modes = "const modes = ["
        danceabilities = "const danceabilities = ["
        tempos = "const tempos = ["

        artworks = "const artworks = ["
        previews = "const previews = ["

        for track in tracks:
            names += ("\"" + track['name'] + "\"" + ', ')
            artists += ("\"" + track['artists'][0]['name'] + "\"" + ', ')

            print(f"'{track['name']}' by {track['artists'][0]['name']} ")

            features = client.get_analysis(track["id"])

            energies += (str(features['energy']) + ', ')
            valences += (str(features['valence']) + ', ')
            modes += (str(features['mode']) + ', ')
            danceabilities += (str(features['danceability']) + ', ')
            tempos += (str(features['tempo']) + ', ')

            if (want_analysis == 'y'):
                print(f"energy: {features['energy']}")
                print(f"valence: {features['valence']}")
                print(f"mode: {features['mode']}")
                print(f"danceability: {features['danceability']}")
                print(f"tempo: {features['tempo']}")
                print()

            # track artwork and preview
            track = client.get_track(track["id"])
            artworks += ("\"" + track['album']['images'][0]['url'] + "\"" +
                         ', ')
            if (track['preview_url'] == None):
                previews += ("\"" + " " + "\"" + ', ')
            else:
                previews += ("\"" + track['preview_url'] + "\"" + ', ')

        # remove last space and comms
        names = names[:-2]
        artists = artists[:-2]
        energies = energies[:-2]
        valences = valences[:-2]
        modes = modes[:-2]
        danceabilities = danceabilities[:-2]
        tempos = tempos[:-2]
        # lst commas weird but still fine
        artworks[:-2]
        previews[:-2]

        names += "]"
        artists += "]"
        energies += "]"
        valences += "]"
        modes += "]"
        danceabilities += "]"
        tempos += "]"
        artworks += "]"
        previews += "]"

        fname = 'track-data-' + term + '.js'
        # print(f'filemane: {fname}')

        f = open(fname, 'w')
        f.write(names)
        f.write("\n")
        f.write(artists)
        f.write("\n")
        f.write(energies)
        f.write("\n")
        f.write(valences)
        f.write("\n")
        f.write(modes)
        f.write("\n")
        f.write(danceabilities)
        f.write("\n")
        f.write(tempos)
        f.write("\n")
        f.write(artworks)
        f.write("\n")
        f.write(previews)
        f.write("\n")
        f.close()