Beispiel #1
0
    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)
        self.web = WebAPI(args, self)

        proxy = os.environ.get('http_proxy')
        if proxy is not None:
            config.proxy = proxy

        # application key location
        if args.key is not None:
            config.load_application_key_file(args.key[0])
        else:
            if not path_exists(default_dir):
                os.makedirs(enc_str(default_dir))

            app_key_path = os.path.join(default_dir, "spotify_appkey.key")
            if not 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)
Beispiel #2
0
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')


# SETUP #
logged_in_event = threading.Event()


def connection_state_listener(session):
    if session.connection.state is spotify.ConnectionState.LOGGED_IN:
        logged_in_event.set()


session = spotify.Session()
loop = spotify.EventLoop(session)
loop.start()
session.on(spotify.SessionEvent.CONNECTION_STATE_UPDATED,
           connection_state_listener)

session.login(config.user, config.secret)

logged_in_event.wait()
print(session.user)
session.preferred_bitrate(spotify.Bitrate.BITRATE_320k)

playlist = ClearQueue()
bot.add_cog(search.Search(bot, session, playlist))
bot.add_cog(music.Music(bot, session, playlist))
Beispiel #3
0
    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()
    def _start_session(self):
        """Starts a Spotify session attribute."""

        # TODO: should check if a session is already running
        # or end all other active sessions... hmmm.
        self._session = spotify.Session()
Beispiel #5
0
    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)
import logging
import json
import spotify
import codecs
import os

username = '******'  #'tegjyotsingh'
password = '******'  #'werunited'

logging.basicConfig(level=logging.DEBUG)
config = spotify.Config()
config.user_agent = 'Playlist Manager'
session = spotify.Session(config=config)
session.login(username, password, True)

session.process_events()
while session.connection.state != spotify.ConnectionState.LOGGED_IN:
    print session.connection.state
    session.process_events()
print session.connection.state
#p=session.search('e')
#p.load()
#p = session.playlist_container[0]
p = session.get_starred()
#p=session.get_playlist('spotify:user:anuteja:playlist:6ksaskR08sDR57kCtLI3W1')
p.load()
print p
print p.tracks

#playlist = session.playlist_container
Beispiel #7
0
def test():
    print "Running tests..."
    import time
    session = spotify.Session()
    spotify.EventLoop(session).start()
    session.relogin()
    time.sleep(3)

    if os.path.exists("test_queue.txt"): os.remove("test_queue.txt")

    queue = MusicQueue("test_queue.txt")
    # Ensure we created a fresh queue.
    assert queue.get_queue_list() == []

    print "Queue Creation Test Passed"

    # Test basic queue operations
    queue.insert("spotify:track:4hTt1HfFo0l5VuCOxhSFup")
    assert queue.get_queue_list() == ["spotify:track:4hTt1HfFo0l5VuCOxhSFup"]
    queue.insert("spotify:track:7HzCxalzzYQOFb9a7Xs3j6")
    assert queue.get_queue_list() == [
        "spotify:track:4hTt1HfFo0l5VuCOxhSFup",
        "spotify:track:7HzCxalzzYQOFb9a7Xs3j6"
    ]
    queue.remove(1)
    assert queue.get_queue_list() == ["spotify:track:4hTt1HfFo0l5VuCOxhSFup"]
    queue.clear()
    assert queue.get_queue_list() == []

    print "Basic Queue Operations Passed"

    # Test track selection/playlist management operations
    queue.set_fallback_playlist(
        "spotify:user:abartow123:playlist:0x0YazVnty6kO5U2l5OD5E")
    assert queue.get_next_track(
        session).link.uri == "spotify:track:3ezkJgagRPZ39KCTrKcSI7"
    queue.insert("spotify:track:4hTt1HfFo0l5VuCOxhSFup")
    assert queue.get_next_track(
        session).link.uri == "spotify:track:4hTt1HfFo0l5VuCOxhSFup"
    queue.current_track_complete()
    queue.clear_fallback_playlist()
    assert queue.get_queue_list() == []

    print "Track selection tasks passed"

    # Test a handful of synchronous operations.
    def insertFromOtherThread():
        other_queue = MusicQueue("test_queue.txt")
        other_queue.insert("spotify:track:7HzCxalzzYQOFb9a7Xs3j6")

    testComplete = threading.Event()

    def onTestFailure():
        assert False
        testComplete.set()

    threading.Timer(0.25, insertFromOtherThread).start()
    failureWatchdog = threading.Timer(1, onTestFailure)
    failureWatchdog.start()

    def testNextTrack():
        assert queue.get_next_track(
            session).link.uri == "spotify:track:7HzCxalzzYQOFb9a7Xs3j6"
        print "-- Testing get_next_track() Passed -- "
        failureWatchdog.cancel()
        testComplete.set()

    threading.Thread(None, testNextTrack).start()

    testComplete.wait()

    print "Synchronous Operations Passed"

    # Clean up.
    os.remove("test_queue.txt")

    print "All Tests Pass. :D"
Beispiel #8
0
 def __init__(self, credentials):
     self.session = spotify.Session(credentials.spotify_client_id,
                                    credentials.spotify_client_secret,
                                    credentials.spotify_username)
Beispiel #9
0
    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
        self._sink_klass(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(user_initiated=False)
                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(user_initiated=False)
                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 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))
Beispiel #11
0
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)
Beispiel #12
0
def getURI(searchTerm):

    try:
        search = session.search(searchTerm)
        print(search.load())
        #(search.artist_total, search.album_total, search.track_total, track.playlist_total)
        print(search.artists[0].load().name)  #get first result
        #eventually will go and get cover art at the same time
        #getCover(theAlbumURI)
        print(len(search.tracks))  #the total number of tracks
        print([a.load() for a in search.tracks
               ])  #if you leave "name" off, you get the uris
        trackNames = [a.load().name for a in search.tracks
                      ]  #make the list of all the track names
        trackURIs = [a.load() for a in search.tracks
                     ]  #make a list with all the track URIs
        return trackNames, trackURIs
        #lets play blackbird - which is 1 location
    except:
        print("sorry, I couldn't find ", searchTerm, " for you...")
        # Assuming a spotify_appkey.key in the current dir
        session = spotify.Session()
        # Process events in the background
        loop = spotify.EventLoop(session)
        loop.start()
        # Connect an audio sink - alsaSink is used on unix systems
        audio = spotify.AlsaSink(session)
        # Events for coordination
        logged_in = threading.Event()
        end_of_track = threading.Event()
        # 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)
        # Assuming a previous login, we may want to logout, especially if remember_me=True previously
        session.logout()  #clear out any priors just in case
        session.forget_me()
    try:
        session.relogin()
        print("I re-logged you in good Sir...")
    except:
        session.login(username="******",
                      password="******",
                      remember_me=False)
        print("You have\'t been here in a bit...")
        #login and wait for the end of the track
        logged_in.wait()
        ##use this to print out what playlists you have
        #getPlaylist(trackURI)
        ##get the cover info - this one is still in progress
        #getCover(someTrackURIthatYouHave)
        #loop through the tracks for the Beatles and Play them all....
        trackNames, trackURIs = getURI("The Beatles")
        #for every trackName and trackURI in the found lists
        for trackName, trackURI in zip(trackNames, trackURIs):
            #ask if we should play that song
            answer = str(input("Play " + trackName + " now?(Y,N)>"))
        #if yes, then stream it
        if answer != "N":
            print("Playing ", trackName, " ...")
            playTrack(trackURI)
        else:
            pass
            #make sure you log out
            session.logout()
            session.forget_me()