def test_user_play_count_in_track_info(self): # Arrange artist = "Test Artist" title = "test title" track = pylast.Track( artist=artist, title=title, network=self.network, username=self.username) # Act count = track.get_userplaycount() # Assert self.assertGreaterEqual(count, 0)
def get_user_play_count_in_track_info(artist, title): # Arrange track = pylast.Track(artist=artist, title=title, network=network, username=lastfm_username) # Act try: count = track.get_userplaycount() except WSError: print('Unable to locate {0} - {1}'.format(artist, title)) return count
def test_track_get_similar(self): # Arrange track = pylast.Track("Cher", "Believe", self.network) # Act similar = track.get_similar() # Assert found = False for track in similar: if str(track.item) == "Madonna - Vogue": found = True break assert found
def test_create_track_dict(self): """Method testing create_track_dict method of lastfm module - tests if for the mocked LovedTrack object a correct dictionary is returned.""" for i in range(3): track_artist = 'test{}_artist'.format(i) track_title = 'test{}_track'.format(i) expected_dict = {'artist': track_artist, 'title': track_title} track = pylast.Track(track_artist, track_title, None) loved_track = pylast.LovedTrack(track, None, None) output_dict = lastfm.create_track_dict(loved_track) self.assertEqual(output_dict, expected_dict)
def toggle_loved(self, track): """ Toggles the loved state of a track :param track: the track to love/unlove :type track: `xl.trax.Track` """ lastfm_track = pylast.Track(track.get_tag_display('artist'), track.get_tag_display('title'), LASTFMLOVER.network) if lastfm_track in self.loved_tracks: self.unlove_track(lastfm_track) else: self.love_track(lastfm_track)
def test_user_loved_in_track_info(self): # Arrange artist = "Test Artist" title = "test title" track = pylast.Track( artist=artist, title=title, network=self.network, username=self.username ) # Act loved = track.get_userloved() # Assert assert loved is not None assert isinstance(loved, bool) assert not isinstance(loved, str)
def test_unlove(self): # Arrange artist = pylast.Artist("Test Artist", self.network) title = "test title" track = pylast.Track(artist, title, self.network) lastfm_user = self.network.get_user(self.username) track.love() # Act track.unlove() # Assert loved = lastfm_user.get_loved_tracks(limit=1) if len(loved): # OK to be empty but if not: self.assertNotEqual(str(loved.track.artist), "Test Artist") self.assertNotEqual(str(loved.track.title), "test title")
def get_similar(info, lastfm_user): """Get a playlist of song similar to the given one. TODO cache the list TODO match given items with the ones in the collection. A smart way could be generating uuid """ network = ScrobbleNetwork(api_key=API_KEY, api_secret=API_SECRET, username=lastfm_user.get('username'), password_hash=pylast.md5( lastfm_user.get('password'))) t = pylast.Track(info.get('artist'), info.get('title'), network) return [(x.item.artist.name, x.item.title) for x in t.get_similar()]
def test_unlove(self): # Arrange artist = pylast.Artist("Test Artist", self.network) title = "test title" track = pylast.Track(artist, title, self.network) lastfm_user = self.network.get_user(self.username) track.love() # Act track.unlove() time.sleep(1) # Delay, for Last.fm latency. TODO Can this be removed later? # Assert loved = lastfm_user.get_loved_tracks(limit=1) if len(loved): # OK to be empty but if not: assert str(loved[0].track.artist) != "Test Artist" assert str(loved[0].track.title) != "test title"
def data_func(self, column, cellrenderer, model, iter): """ Displays the loved state """ track = model.get_value(iter, 0) lastfm_track = pylast.Track(track.get_tag_display('artist'), track.get_tag_display('title'), self.last_fm_lover.network) cellrenderer.props.active = lastfm_track in self.last_fm_lover.loved_tracks if self.last_fm_lover.network is None: cellrenderer.props.sensitive = False cellrenderer.props.render_prelit = False else: cellrenderer.props.sensitive = True cellrenderer.props.render_prelit = True self.model = model
import sys import pylast from mylast import lastfm_network, lastfm_username # Loves whatever track is now playing on Last.fm, # then prints confirmation of last loved track. # Optional parameter: love "artist - title" instead. # Prerequisites: mylast.py, pyLast if len(sys.argv) > 1: (artist, title) = sys.argv[1].split("-") artist = artist.strip() title = title.strip() track = pylast.Track(artist, title, lastfm_network) else: track = lastfm_network.get_user(lastfm_username).get_now_playing() last_loved_track = str( lastfm_network.get_user(lastfm_username).get_loved_tracks(limit=1)[0][0]) print("Last:\t" + str(last_loved_track)) print("Loving:\t" + str(track)) if track is None: sys.exit("Didn't get the track now playing from Last.fm") track.love() # Confirm the track has been loved if track.get_userloved():
# Run this script from command line, supplying the required arguments. # # Example: # python get_lastfm_playcount.py --apikey=1234567890 --username=bob --artist=Tycho --song=Melanine parser = argparse.ArgumentParser( description='Gets your Last.fm play count of the supplied song') parser.add_argument('--apikey', help='Last.fm API Key') parser.add_argument('--username', help='Last.fm username') parser.add_argument('--artist', help='Name of artist') parser.add_argument('--song', help='Name of song') args = vars(parser.parse_args()) lastfm_username = args['username'] lastfm_apikey = args['apikey'] artist = args['artist'] song = args['song'] try: lastfm = pylast.LastFMNetwork(api_key=lastfm_apikey, api_secret="", username=lastfm_username, password_hash="") track = pylast.Track(artist=artist, title=song, network=lastfm, username=lastfm_username) print track.get_userplaycount() except: print 0
print while True: artist_name = subprocess.Popen(artist_name_cmd, shell=True, stdout=subprocess.PIPE).stdout.read() artist_name = artist_name.rstrip() track_name = subprocess.Popen(track_name_cmd, shell=True, stdout=subprocess.PIPE).stdout.read() track_name = track_name.rstrip() if current_track == track_name: sleep(5) else: current_track = track_name try: lastfm = pylast.LastFMNetwork(api_key=lastfm_apikey, api_secret="", username=lastfm_username, password_hash="") track = pylast.Track(artist=artist_name, title=track_name, network=lastfm, username=lastfm_username) plays = track.get_userplaycount() except: plays = 0 print artist_name + " - " + track_name + " - Plays: " + plays.__str__() print
def main(): global playing_station parser = argparse.ArgumentParser( description="BBC Radio scrobbler. " "On Mac: scrobbles BBC from iTunes if it's running, " "or the station of your choice if --ignore-itunes. " "On Windows: scrobbles BBC from Winamp if it's running, " "or the station of your choice if --ignore-winamp.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument( "-i", "--ignore-media-player", action="store_true", help= "Shortcut for --ignore-itunes on Mac or --ignore-winamp on Windows", ) parser.add_argument( "--ignore-itunes", action="store_true", help="Mac only: Ignore whatever iTunes is doing and scrobble the " "station. For example, use this if listening via web or a real " "radio.", ) parser.add_argument( "--ignore-winamp", action="store_true", help="Windows only: Ignore whatever Winamp is doing and scrobble the " "station. For example, use this if listening via web or a real " "radio.", ) parser.add_argument( "station", nargs="?", default="bbc6music", choices=("bbc6music", "bbcradio1", "bbcradio2", "bbc1xtra"), help="BBC station to scrobble", ) parser.add_argument("-s", "--say", action="store_true", help="Mac only: Announcertron 4000") args = parser.parse_args() atexit.register(restore_terminal_title) if args.ignore_media_player: if _platform == "darwin": args.ignore_itunes = True elif _platform == "win32": args.ignore_winamp = True network = pylast.LastFMNetwork(API_KEY, API_SECRET) if not os.path.exists(SESSION_KEY_FILE): skg = pylast.SessionKeyGenerator(network) url = skg.get_web_auth_url() print( "Please authorize the scrobbler to scrobble to your account: %s\n" % url) import webbrowser webbrowser.open(url) while True: try: session_key = skg.get_web_auth_session_key(url) fp = open(SESSION_KEY_FILE, "w") fp.write(session_key) fp.close() break except pylast.WSError: time.sleep(1) else: session_key = open(SESSION_KEY_FILE).read() network.session_key = session_key last_station = None last_scrobbled = None playing_track = None np_time = None scrobble_me_next = None playing_station = args.station try: while True: if not check_media_player(args.ignore_itunes, args.ignore_winamp): last_station = None last_scrobbled = None playing_track = None np_time = None scrobble_me_next = None else: if last_station != playing_station: last_station = playing_station out = f"Tuned in to {playing_station}" output(out + "\n" + "-" * len(out)) if args.say: say(playing_station) try: # Get now playing track realtime = bbcrealtime.nowplaying(playing_station) if realtime: new_track = pylast.Track(realtime["artist"], realtime["title"], network) new_track.start = realtime["start"] new_track.end = realtime["end"] else: new_track = None if (new_track and (time.time() - new_track.end) > ONE_HOUR_IN_SECONDS): print("Last track over an hour ago, don't scrobble") raise Escape # A new, different track if new_track != playing_track: if scrobble_me_next: scrobble(network, scrobble_me_next) scrobble_me_next = None last_scrobbled = scrobble_me_next playing_track = new_track update_now_playing(network, playing_track, args.say) np_time = int(time.time()) # Scrobblable if 30 seconds has gone by else: now = int(time.time()) if (playing_track and playing_track != last_scrobbled and now - np_time >= 30): scrobble_me_next = playing_track except Escape: pass except ( KeyError, pylast.NetworkError, pylast.MalformedResponseError, ) as e: output("Error: {}".format(repr(e)), "error") time.sleep(15) except KeyboardInterrupt: if scrobble_me_next: scrobble(network, scrobble_me_next) print("exit")
#/usr/bin/python import os import sys import time import pylast import subprocess artist = sys.argv[1] title = sys.argv[3] # Update your credentials here network = pylast.LastFMNetwork(api_key="", api_secret="", username="", password_hash=pylast.md5("")) track = pylast.Track(artist, title, network) track.love() print("LAST.FM: Loved a song: {0} - {1}").format(artist, title)
def get_playlist_playcounts(playlist): pylast_tracks = [pylast.Track(artist=item.track.artist, title=item.track.name, network=network, username=lastfm_username) for item in playlist.items] return get_playcounts_threaded(pylast_tracks, 64)