def get_session(): config = spotify.Config() filename = os.path.dirname( os.path.realpath(__file__)) + "/spotify_appkey.key" config.load_application_key_file(filename=filename) session = spotify.Session(config=config) return session
def __init__(self, controller): self._controller = controller self.current_track = None self.current_track_uri = None self.is_playing = False # spotify player instance variables self.logged_in_event = threading.Event() self.end_of_track_event = threading.Event() # spotify API config & login config = spotify.Config() keypath = sys.path[0]+"/spotify_appkey.key" config.load_application_key_file(filename=keypath) self.session = spotify.Session(config) self.session.login(SPOTIFY_AUTH['username'], SPOTIFY_AUTH['password']) # define audio sink spotify.AlsaSink(self.session, JUKEBIKE_CONF['PCM_ID']) # start event loop thread, which automatically processes events from lip event_loop = spotify.EventLoop(self.session) event_loop.start() # register listener for login, end of track / ... self.session.on(spotify.SessionEvent.LOGGED_IN, self.connection_state_listener) self.session.on(spotify.SessionEvent.END_OF_TRACK, self.track_state_listener) # is being called endlessly when track ends # TODO to be implemented, if necessary #CONNECTION_ERROR #MESSAGE_TO_USER # wait for login to succeed self.logged_in_event.wait()
def __init__(self, config=None): super(Session, self).__init__() if spotify._session_instance is not None: raise RuntimeError('Session has already been initialized') if config is not None: self.config = config else: self.config = spotify.Config() if self.config.application_key is None: self.config.load_application_key_file() sp_session_ptr = ffi.new('sp_session **') spotify.Error.maybe_raise( lib.sp_session_create(self.config._sp_session_config, sp_session_ptr)) self._sp_session = ffi.gc(sp_session_ptr[0], lib.sp_session_release) self._cache = weakref.WeakValueDictionary() self._emitters = [] self._callback_handles = set() self.connection = spotify.connection.Connection(self) self.offline = spotify.offline.Offline(self) self.player = spotify.player.Player(self) self.social = spotify.social.Social(self) spotify._session_instance = self
def __init__(self): config = spotify.Config() config.user_agent = 'Svanborg Spotify Client' self.session = spotify.Session(config) self.session.preferred_bitrate(1) # 320 kib/s self.Queue = PlayQueue(self.session) self.Player = Player(self.session, self.Queue)
def test_raises_error_if_not_ok(self, lib_mock): lib_mock.sp_session_create.return_value = ( spotify.ErrorType.BAD_API_VERSION) config = spotify.Config() config.application_key = b'\x01' * 321 with self.assertRaises(spotify.Error): spotify.Session(config=config)
def __init__(self): self.googleapi = Mobileclient() config = spotify.Config() config.cache_location = "tmp" config.load_application_key_file(SPOTIFY_APPKEY) self.spotify_session = spotify.Session(config) self.loop = spotify.EventLoop(self.spotify_session) self.logged_in_event = threading.Event() self._google_loggedin = False
def playtrack(tracks, username, password): logging.basicConfig(level=logging.DEBUG) config = spotify.Config() session = spotify.Session(config=config) #print session # Assuming a spotify_appkey.key in the current dir session.login(username, password, False) session.process_events() while session.connection.state != spotify.ConnectionState.LOGGED_IN: session.process_events() #print session.connection.state # Connect an audio sink audio = spotify.AlsaSink(session) # Events for coordination logged_in = threading.Event() end_of_track = threading.Event() def on_connection_state_updated(session): if session.connection.state is spotify.ConnectionState.LOGGED_IN: logged_in.set() def on_end_of_track(self): end_of_track.set() # Register event listeners session.on(spotify.SessionEvent.CONNECTION_STATE_UPDATED, on_connection_state_updated) session.on(spotify.SessionEvent.END_OF_TRACK, on_end_of_track) # Play a track #loop of tracks for i, track_uri in enumerate(tracks): if i < 4: #track_uri=random.choice(tracks) #print 'in for' track = session.get_track(track_uri).load() session.player.load(track) session.player.play() if i != 3: time.sleep(track.duration / 12000) #print 'hi' else: session.player.play(0) break audio.off()
def __init__(self, args): threading.Thread.__init__(self) # initialize progress meter self.progress = Progress(args, self) self.args = args # initially logged-out self.logged_out.set() config = spotify.Config() self.post = PostActions(args, self) self.web = WebAPI(args, self) proxy = os.environ.get('http_proxy') if proxy is not None: config.proxy = proxy # Application key if not path_exists(settings_dir()): os.makedirs(enc_str(settings_dir())) app_key_path = os.path.join(settings_dir(), "spotify_appkey.key") if not path_exists(app_key_path): print("\n" + Fore.RED + "Please copy your spotify_appkey.key to " + settings_dir() + Fore.RESET) sys.exit(1) config.load_application_key_file(app_key_path) config.settings_location = settings_dir() config.cache_location = settings_dir() self.session = spotify.Session(config=config) self.session.volume_normalization = args.normalize # disable scrobbling self.session.social.set_scrobbling(spotify.SocialProvider.SPOTIFY, spotify.ScrobblingState.LOCAL_DISABLED) self.session.social.set_scrobbling(spotify.SocialProvider.FACEBOOK, spotify.ScrobblingState.LOCAL_DISABLED) self.session.social.set_scrobbling(spotify.SocialProvider.LASTFM, spotify.ScrobblingState.LOCAL_DISABLED) bit_rates = dict([('160', BitRate.BITRATE_160K), ('320', BitRate.BITRATE_320K), ('96', BitRate.BITRATE_96K)]) self.session.preferred_bitrate(bit_rates[args.quality]) self.session.on(spotify.SessionEvent.CONNECTION_STATE_UPDATED, self.on_connection_state_changed) self.session.on(spotify.SessionEvent.END_OF_TRACK, self.on_end_of_track) self.session.on(spotify.SessionEvent.MUSIC_DELIVERY, self.on_music_delivery) self.session.on(spotify.SessionEvent.PLAY_TOKEN_LOST, self.play_token_lost) self.session.on(spotify.SessionEvent.LOGGED_IN, self.on_logged_in) self.event_loop = EventLoop(self.session, 0.1, self)
def test_releases_sp_session_when_session_dies(self, lib_mock): sp_session = spotify.ffi.NULL def func(sp_session_config, sp_session_ptr): sp_session_ptr[0] = sp_session return spotify.ErrorType.OK lib_mock.sp_session_create.side_effect = func config = spotify.Config() config.application_key = b'\x01' * 321 session = spotify.Session(config=config) session = None # noqa spotify._session_instance = None tests.gc_collect() lib_mock.sp_session_release.assert_called_with(sp_session)
def initialize(): global session global logged_in global playlist global length config = pyspotify.Config() config.user_agent = 'smart' # config.tracefile = b'/tmp/libspotify-trace.log' #if sys.argv[1:]: # track_uri = sys.argv[1] #else: # track_uri = 'spotify:track:6xZtSE6xaBxmRozKA0F6TA' # Assuming a spotify_appkey.key in the current dir session = pyspotify.Session(config) session.login('johnwbird', 'bitterjava60', True) # Process events in the background loop = pyspotify.EventLoop(session) loop.start() # Connect an audio sink audio = pyspotify.AlsaSink(session) # Register event listeners session.on(pyspotify.SessionEvent.CONNECTION_STATE_UPDATED, on_connection_state_updated) session.on(pyspotify.SessionEvent.END_OF_TRACK, on_end_of_track) # Assuming a previous login with remember_me=True and a proper logout #session.relogin() logged_in.wait() playlist = session.get_playlist( 'spotify:user:spotify:playlist:5FJXhjdILmRA2z5bvz4nzf') playlist.load().name length = len(playlist.tracks) random.seed() curSong = random.randint(0, length - 1)
def start(credentials=None, disable_spotify_logging=True): if credentials is None: with Path(__file__).with_name('credentials.json').open() as f: credentials = json.load(f) c = credentials if 'appkey64' in c and 'appkey' not in c: import base64 c['appkey'] = base64.b64decode(c['appkey64']) logger.debug('loading pyspotify') import spotify if disable_spotify_logging: logging.getLogger('spotify').setLevel(logging.WARN) logger.debug("pyspotify loaded") cfg = spotify.Config() cfg.application_key = c['appkey'] cfg.cache_location = c['cachedir'] cfg.settings_location = c['cachedir'] global session session = spotify.Session(cfg) session.preferred_bitrate(spotify.Bitrate.BITRATE_320k) logged_in = threading.Event() def connection_state_changed(session): if session.connection.state is spotify.ConnectionState.LOGGED_IN: logged_in.set() loop = spotify.EventLoop(session) loop.start() session.on(spotify.SessionEvent.CONNECTION_STATE_UPDATED, connection_state_changed) session.login(c['username'], c['password']) if not logged_in.wait(60): raise LoginError('Failed to login after 60 seconds') logger.debug("logged in to spotify")
def _get_spotify_config(self, config): ext = Extension() spotify_config = spotify.Config() spotify_config.load_application_key_file( pathlib.Path(__file__).parent / "spotify_appkey.key") if config["spotify"]["allow_cache"]: spotify_config.cache_location = bytes(ext.get_cache_dir(config)) else: spotify_config.cache_location = None spotify_config.settings_location = bytes(ext.get_data_dir(config)) proxy_uri = httpclient.format_proxy(config["proxy"], auth=False) if proxy_uri is not None: logger.debug(f"Connecting to Spotify through proxy: {proxy_uri}") spotify_config.proxy = proxy_uri spotify_config.proxy_username = config["proxy"].get("username") spotify_config.proxy_password = config["proxy"].get("password") return spotify_config
def _get_spotify_config(self, config): ext = Extension() spotify_config = spotify.Config() spotify_config.load_application_key_file( os.path.join(os.path.dirname(__file__), 'spotify_appkey.key')) if config['spotify']['allow_cache']: spotify_config.cache_location = ext.get_cache_dir(config) else: spotify_config.cache_location = None spotify_config.settings_location = ext.get_data_dir(config) proxy_uri = httpclient.format_proxy(config['proxy'], auth=False) if proxy_uri is not None: logger.debug('Connecting to Spotify through proxy: %s', proxy_uri) spotify_config.proxy = proxy_uri spotify_config.proxy_username = config['proxy'].get('username') spotify_config.proxy_password = config['proxy'].get('password') return spotify_config
def main(): #setup spotify config and initialize session config = spotify.Config() config.user_agent = 'spotify2playmusic' config.tracefile = b'/tmp/libspotify-trace.log' spot = spotify.Session(config=config) #log in and get playlist choice for cloning gpm = login_gpm() spot = login_spotify(spot) playlist = get_playlist(spot) #get google play playlist names and compare them to the chosen list #if there is a playlist with the same name already in google play then say so and exit gpm_playlist_names = [] for gpm_playlist in gpm.get_all_playlists(): gpm_playlist_names.append(gpm_playlist['name']) if playlist.load().name in gpm_playlist_names: print("Playlist already exists in Google Play... exiting") exit() #there will be two lists: one of tracks to be added and another #of songs that could not be matched tracks_to_match = [] to_add_list = [] unmatched_tracks = [] #searches user uploaded music first print("Searching in uploaded music first...") gpm_local = gpm.get_all_songs() print("Database loaded!") progress = 0 for track in playlist.load().tracks: progress += 1 track = track.load(timeout=30) title = track.name artist = track.artists[0].load().name album = track.album.load().name #for progress stdout.write("%i%% - %s - %s \r" % (((float(progress) / float(len(playlist.load().tracks))) * 100.0), title, artist)) stdout.flush() unmatched = True top5 = {} to_push_id = "" #checks against every song in the google play library and finds the #top 5 hits, then the one with the lowest levenshtein number is chosen for i in gpm_local: if is_similar(title, artist, album, i['title'], i['artist'], i['album']): print(" - Found a match in uploaded library: " + i['title'] + " - " + i['artist'] + " ") unmatched = False top5[i['title']] = i['id'] to_push_id = i['id'] if len(top5) == 5: break if len(top5) > 1: lowest_score = 999999 winning_track = "" for top in top5.keys(): val = levenshtein(title, top) if val < lowest_score: lowest_score = val to_push_id = top5[top] winning_track = top if winning_track is not "": print("Going with the closest match: " + winning_track) if unmatched: tracks_to_match.append(track) if to_push_id is not "": to_add_list.append(to_push_id) #all remaining unmatched tracks are searched in All Access print("Now searching All Access for the remaining tracks...") progress = 0 for track in tracks_to_match: progress +=1 track = track.load() title = track.name.lower() artist = track.artists[0].load().name.lower() album = track.album.load().name.lower() #only searches for title and artist because google play does not return #the correct results when album is included query = title + " " + artist #for progress stdout.flush() stdout.write("%i%% - %s - %s \r" % (((float(progress) / float(len(playlist.load().tracks))) * 100.0), title, artist)) unmatched = True #does two comparisons: one with the album and one where they both have #the same album, this will increase the chance of matching #I trust google's search function :) try: result = gpm.search_all_access(query, max_results = 10)['song_hits'][0]['track'] if is_similar(title, artist, album, result['title'].lower(), result['artist'].lower(), result['album']): print(" - Found a match in All Access: " + result['title'] + " - " + result['artist'] + " ") unmatched = False to_add_list.append(result['nid']) elif is_similar(title, artist, "analbumthebest", result['title'].lower(), result['artist'].lower(), "analbumthebest"): print(" - Found a match in All Access: " + result['title'] + " - " + result['artist'] + " ") unmatched = False to_add_list.append(result['nid']) else: unmatched_tracks.append(track) except Exception, e: print "Something went wrong while trying to search All Access...\n{}".format(str(e))
def check_pyspotify_logged_in(self): logger.debug('Checking if pyspotify is logged in...') config = spotify.Config() config.user_agent = 'Spoppy' config.cache_location = os.path.join(self.user_cache_dir, 'cache') config.settings_location = os.path.join(self.user_cache_dir, 'cache') config.load_application_key_file( os.path.join(os.path.dirname(__file__), 'spotify_appkey.key')) self._pyspotify_session = spotify.Session(config) self._pyspotify_session_loop = spotify.EventLoop( self._pyspotify_session) self._pyspotify_session_loop.start() # Connect an audio sink spotify.AlsaSink(self._pyspotify_session) # Events for coordination logged_in = threading.Event() # end_of_track = threading.Event() def on_connection_state_updated(session): KNOWN_STATES = ( 'DISCONNECTED', 'LOGGED_IN', 'LOGGED_OUT', 'OFFLINE', 'UNDEFINED', ) logger.debug('Checking connection state %s' % session.connection.state) for state in KNOWN_STATES: if (session.connection.state == getattr( spotify.ConnectionState, state)): logger.debug('Received connection state %s' % state) if session.connection.state == spotify.ConnectionState.LOGGED_IN: logged_in.set() disconnect_state = spotify.ConnectionState.DISCONNECTED if session.connection.state == disconnect_state: if self.player.is_playing(): self.player.play_pause() self.player.state = self.player.DISCONNECTED_INDICATOR logger.warning( 'Spoppy has been disconnected. DO YOU HAVE INTERNET?') else: if (self.player.state == self.player.DISCONNECTED_INDICATOR and not self.player.is_playing()): logger.debug('We got internet back, playing!') self.player.play_pause() self.player.state = None def on_lost_play_token(session): if self.player.is_playing(): self.player.play_pause() logger.warning( 'Spoppy has been paused. Spotify is probably playing ' 'somewhere else?') # Register event listeners self._pyspotify_session.on( spotify.SessionEvent.CONNECTION_STATE_UPDATED, on_connection_state_updated) self._pyspotify_session.on(spotify.SessionEvent.PLAY_TOKEN_LOST, on_lost_play_token) logger.debug('Actually logging in now...') self._pyspotify_session.login(self.username, self.password) logged_in.wait(5) if logged_in.is_set(): logger.debug('PySpotify logged in!') return True else: logger.warning('PySpotify login failed!') return False
def create_real_session(lib_mock): """Create a real :class:`spotify.Session` using ``lib_mock``.""" lib_mock.sp_session_create.return_value = spotify.ErrorType.OK config = spotify.Config() config.application_key = b'\x01' * 321 return spotify.Session(config=config)
def create_session(lib_mock): lib_mock.sp_session_create.return_value = spotify.ErrorType.OK config = spotify.Config() config.application_key = b'\x01' * 321 return spotify.Session(config=config)
def configsession(self): config = spotify.Config() # Insert configuration here return config
def __init__(self, args): threading.Thread.__init__(self) # initialize progress meter self.progress = Progress(args, self) self.args = args # initially logged-out self.logged_out.set() config = spotify.Config() default_dir = default_settings_dir() self.post = PostActions(args, self) # application key location if args.key is not None: config.load_application_key_file(args.key[0]) else: if not os.path.exists(default_dir): os.makedirs(default_dir) app_key_path = os.path.join(default_dir, "spotify_appkey.key") if not os.path.exists(app_key_path): print("\n" + Fore.YELLOW + "Please copy your spotify_appkey.key to " + default_dir + ", or use the --key|-k option" + Fore.RESET) sys.exit(1) config.load_application_key_file(app_key_path) # settings directory if args.settings is not None: settings_dir = norm_path(args.settings[0]) config.settings_location = settings_dir config.cache_location = settings_dir else: config.settings_location = default_dir config.cache_location = default_dir self.session = spotify.Session(config=config) self.session.volume_normalization = args.normalize # disable scrobbling self.session.social.set_scrobbling( spotify.SocialProvider.SPOTIFY, spotify.ScrobblingState.LOCAL_DISABLED) self.session.social.set_scrobbling( spotify.SocialProvider.FACEBOOK, spotify.ScrobblingState.LOCAL_DISABLED) self.session.social.set_scrobbling( spotify.SocialProvider.LASTFM, spotify.ScrobblingState.LOCAL_DISABLED) bit_rates = dict([('160', BitRate.BITRATE_160K), ('320', BitRate.BITRATE_320K), ('96', BitRate.BITRATE_96K)]) self.session.preferred_bitrate(bit_rates[args.quality]) self.session.on(spotify.SessionEvent.CONNECTION_STATE_UPDATED, self.on_connection_state_changed) self.session.on(spotify.SessionEvent.END_OF_TRACK, self.on_end_of_track) self.session.on(spotify.SessionEvent.MUSIC_DELIVERY, self.on_music_delivery) self.session.on(spotify.SessionEvent.PLAY_TOKEN_LOST, self.play_token_lost) self.session.on(spotify.SessionEvent.LOGGED_IN, self.on_logged_in) self.event_loop = EventLoop(self.session, 0.1, self)
def __init__(self, username): self.username = username self.config = spotify.Config() self.session_blob = None self.session = None self.logged_in_event = threading.Event()
def setUp(self): self.config = spotify.Config()
def __init__(self, user, password, key, sink, mixer='PCM', min_vol=0, max_vol=100): """ Initialises the Spotify Session, logs the user in and starts the session event loop. The player does not manage state, it simply cares about playing music. Arguments --------- user : str The Spotify User password : str The Spotify User Password key : str Path to the Spotify API Key File sink : str The audio sink to use mixer : str Mixer Name, default PCM min_vol : int Min volume level, default 0 max_vol : int Max volume level, default 100 """ # Mixer self.mixer = mixer # Volume Levels self.min_vol = int(min_vol) self.max_vol = int(max_vol) # Session Configuration logger.debug('Configuring Spotify Session') config = spotify.Config() config.load_application_key_file(key) config.dont_save_metadata_for_playlists = True config.initially_unload_playlists = True # Create session logger.debug('Creating Session') self.session = spotify.Session(config) self.register_session_events() self.session.preferred_bitrate(spotify.audio.Bitrate(1)) # Set the session event loop going logger.debug('Starting Spotify Event Loop') loop = spotify.EventLoop(self.session) loop.start() # Block until Login is complete logger.debug('Waiting for Login to Complete...') self.session.login(user, password, remember_me=True) LOGGED_IN_EVENT.wait() # Set the Audio Sink for the Session sinks = {'alsa': spotify.AlsaSink, 'fake': FakeSink} logger.info('Settingw Audio Sink to: {0}'.format(sink)) sinks.get(sink, FakeSink)(self.session)
#In development import spotify config = spotify.Config() config.user_agent = 'W.I.L.L' session = spotify.Session() def play(command): loop = spotify.EventLoop(session) loop.start() # Connect an audio sink audio = spotify.AlsaSink(session) # Events for coordination logged_in = threading.Event() end_of_track = threading.Event() def on_connection_state_updated(session): if session.connection.state is spotify.ConnectionState.LOGGED_IN: logged_in.set() def on_end_of_track(self): end_of_track.set() # Register event listeners session.on(spotify.SessionEvent.CONNECTION_STATE_UPDATED, on_connection_state_updated) session.on(spotify.SessionEvent.END_OF_TRACK, on_end_of_track)
def __init__(self, args): threading.Thread.__init__(self) # set to a daemon thread self.daemon = True # initialize progress meter self.progress = Progress(args, self) self.args = args self.logged_in = threading.Event() self.logged_out = threading.Event() self.logged_out.set() config = spotify.Config() default_dir = default_settings_dir() # create a log file for rip failures if args.fail_log is not None: _base_dir = base_dir(args) if not os.path.exists(_base_dir): os.makedirs(_base_dir) encoding = "ascii" if args.ascii else "utf-8" self.fail_log_file = codecs.open(os.path.join( _base_dir, args.fail_log[0]), 'w', encoding) # application key location if args.key is not None: config.load_application_key_file(args.key[0]) else: if not os.path.exists(default_dir): os.makedirs(default_dir) app_key_path = os.path.join(default_dir, "spotify_appkey.key") if not os.path.exists(app_key_path): print("\n" + Fore.YELLOW + "Please copy your spotify_appkey.key to " + default_dir + ", or use the --key|-k option" + Fore.RESET) sys.exit(1) config.load_application_key_file(app_key_path) # settings directory if args.settings is not None: settings_dir = norm_path(args.settings[0]) config.settings_location = settings_dir config.cache_location = settings_dir else: config.settings_location = default_dir config.cache_location = default_dir self.session = spotify.Session(config=config) self.session.volume_normalization = args.normalize bit_rates = dict([ ('160', BitRate.BITRATE_160K), ('320', BitRate.BITRATE_320K), ('96', BitRate.BITRATE_96K)]) self.session.preferred_bitrate(bit_rates[args.quality]) self.session.on(spotify.SessionEvent.CONNECTION_STATE_UPDATED, self.on_connection_state_changed) self.session.on(spotify.SessionEvent.END_OF_TRACK, self.on_end_of_track) self.session.on(spotify.SessionEvent.MUSIC_DELIVERY, self.on_music_delivery) self.session.on(spotify.SessionEvent.PLAY_TOKEN_LOST, self.play_token_lost) self.session.on(spotify.SessionEvent.LOGGED_IN, self.on_logged_in) self.event_loop = spotify.EventLoop(self.session) self.event_loop.start()