attempt to show songs for artist if not albums are found
[clinton/xbmc-groove.git] / default.py
index 50c904b..27fb276 100644 (file)
@@ -16,7 +16,7 @@
 #    along with xbmc-groove.  If not, see <http://www.gnu.org/licenses/>.
 
 
-import urllib, sys, os, shutil, re, pickle, time, tempfile, xbmcaddon, xbmcplugin, xbmcgui, xbmc
+import urllib, urllib2, sys, os, shutil, re, pickle, time, traceback, xbmcaddon, xbmcplugin, xbmcgui, xbmc
 
 __addon__     = xbmcaddon.Addon('plugin.audio.groove')
 __addonname__ = __addon__.getAddonInfo('name')
@@ -24,8 +24,9 @@ __cwd__       = __addon__.getAddonInfo('path')
 __author__    = __addon__.getAddonInfo('author')
 __version__   = __addon__.getAddonInfo('version')
 __language__  = __addon__.getLocalizedString
+__debugging__  = __addon__.getSetting('debug')
 
-
+# Directory listings must be < MODE_SONG
 MODE_SEARCH_SONGS = 1
 MODE_SEARCH_ALBUMS = 2
 MODE_SEARCH_ARTISTS = 3
@@ -40,14 +41,16 @@ MODE_ARTIST = 11
 MODE_PLAYLIST = 12
 MODE_SONG_PAGE = 13
 MODE_SIMILAR_ARTISTS = 14
-MODE_SONG = 15
-MODE_FAVORITE = 16
-MODE_UNFAVORITE = 17
-MODE_MAKE_PLAYLIST = 18
-MODE_REMOVE_PLAYLIST = 19
-MODE_RENAME_PLAYLIST = 20
-MODE_REMOVE_PLAYLIST_SONG = 21
-MODE_ADD_PLAYLIST_SONG = 22
+MODE_ARTIST_POPULAR_FROM_ALBUMS = 15
+MODE_SONG = 150
+
+MODE_FAVORITE = 160
+MODE_UNFAVORITE = 170
+MODE_MAKE_PLAYLIST = 180
+MODE_REMOVE_PLAYLIST = 190
+MODE_RENAME_PLAYLIST = 200
+MODE_REMOVE_PLAYLIST_SONG = 210
+MODE_ADD_PLAYLIST_SONG = 220
 
 ACTION_MOVE_LEFT = 1
 ACTION_MOVE_UP = 3
@@ -63,8 +66,9 @@ NAME_ALBUM_ARTIST_LABEL = 1
 
 # Stream marking time (seconds)
 STREAM_MARKING_TIME = 30
-# Retry URL
-STREAM_RETRY = 10
+
+# Timeout
+STREAM_TIMEOUT = 30
 
 songMarkTime = 0
 player = xbmc.Player()
@@ -75,8 +79,9 @@ resDir = xbmc.translatePath(os.path.join(baseDir, 'resources'))
 libDir = xbmc.translatePath(os.path.join(resDir,  'lib'))
 imgDir = xbmc.translatePath(os.path.join(resDir,  'img'))
 cacheDir = os.path.join(xbmc.translatePath('special://masterprofile/addon_data/'), os.path.basename(baseDir))
+tempDir = xbmc.translatePath('special://temp')
 thumbDirName = 'thumb'
-thumbDir = os.path.join('special://masterprofile/addon_data/', os.path.basename(baseDir), thumbDirName)
+thumbDir = os.path.join(xbmc.translatePath('special://masterprofile/addon_data/'), os.path.basename(baseDir), thumbDirName)
 
 baseModeUrl = 'plugin://plugin.audio.groove/'
 playlistUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLIST)
@@ -92,29 +97,38 @@ sys.path.append (libDir)
 from GroovesharkAPI import GrooveAPI
 from threading import Event, Thread
 
+if __debugging__ == 'true':
+    __debugging__ = True
+else:
+    __debugging__ = False
+
 try:
-    groovesharkApi = GrooveAPI()
+    groovesharkApi = GrooveAPI(__debugging__, tempDir)
     if groovesharkApi.pingService() != True:
         raise StandardError(__language__(30007))
 except:
+    print "Exception on initialisation"
+    print '-'*60
+    traceback.print_exc()
+    print '-'*60
     dialog = xbmcgui.Dialog(__language__(30008),__language__(30009),__language__(30010))
-    dialog.ok()
+    dialog.ok(__language__(30008),__language__(30009))
     sys.exit(-1)
   
 # Mark song as playing or played
-def markSong(songid, duration):
+def markSong(songid, duration, streamKey, streamServerID):
     global songMarkTime
     global playTimer
     global player
     if player.isPlayingAudio():
         tNow = player.getTime()
         if tNow >= STREAM_MARKING_TIME and songMarkTime == 0:
-            groovesharkApi.markStreamKeyOver30Secs()
+            groovesharkApi.markStreamKeyOver30Secs(streamKey, streamServerID)
             songMarkTime = tNow
         elif duration > tNow and duration - tNow < 2 and songMarkTime >= STREAM_MARKING_TIME:
             playTimer.cancel()
             songMarkTime = 0
-            groovesharkApi.markSongComplete(songid)
+            groovesharkApi.markSongComplete(songid, streamKey, streamServerID)
     else:
         playTimer.cancel()
         songMarkTime = 0
@@ -138,7 +152,8 @@ class GroovesharkPlaylistSelect(xbmcgui.WindowDialog):
         self.imgBg = xbmcgui.ControlImage(x+gap, 5*gap+y, w-2*gap, h-5*gap, listBackground)
         self.addControl(self.imgBg)
 
-        self.playlistControl = xbmcgui.ControlList(2*gap+x, y+3*gap+30, w-4*gap, h-10*gap, textColor='0xFFFFFFFF', selectedColor='0xFFFF4242', itemTextYOffset=0, itemHeight=50, alignmentY = 0)
+        self.playlistControl = xbmcgui.ControlList(2*gap+x, y+3*gap+30, w-4*gap, h-10*gap, textColor='0xFFFFFFFF', selectedColor='0xFFFF4242')
+        self.playlistControl.setItemHeight(50)
         self.addControl(self.playlistControl)
 
         self.lastPos = 0
@@ -234,7 +249,7 @@ class Grooveshark:
     popularSongsArtistImg = xbmc.translatePath(os.path.join(imgDir, 'popularSongsArtist.png'))
     songImg = xbmc.translatePath(os.path.join(imgDir, 'song.png'))
     defImg = xbmc.translatePath(os.path.join(imgDir, 'default.tbn'))
-    fanImg = xbmc.translatePath(os.path.join(baseDir, 'fanart.png'))
+    fanImg = xbmc.translatePath(os.path.join(baseDir, 'fanart.jpg'))
 
     settings = xbmcaddon.Addon(id='plugin.audio.groove')
     songsearchlimit = int(settings.getSetting('songsearchlimit'))
@@ -248,15 +263,14 @@ class Grooveshark:
     
     def __init__( self ):
         self._handle = int(sys.argv[1])
-        self.setDebug()
         if os.path.isdir(cacheDir) == False:
             os.makedirs(cacheDir)
-            if self.debug:
+            if __debugging__ :
                 xbmc.log(__language__(30012) + " " + cacheDir)
         artDir = xbmc.translatePath(thumbDir)
         if os.path.isdir(artDir) == False:
             os.makedirs(artDir)
-            if self.debug:
+            if __debugging__ :
                 xbmc.log(__language__(30012) + " " + artDir)
             
     # Top-level menu
@@ -344,12 +358,14 @@ class Grooveshark:
         if (query != ''): 
             artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
             if (len(artists) > 0):
-                artist = artists[0]
+                # check for artist name match, first result is sometimes not the closest lexical match
+                artist = next ((a for a in artists if a[0].lower() == query.lower()), artists[0])
                 artistID = artist[1]
-                if self.debug:
+                if __debugging__ :
                     xbmc.log("Found " + artist[0] + "...")
-                albums = groovesharkApi.getArtistAlbums(artistID, limit = self.albumsearchlimit)
+                albums = groovesharkApi.getArtistAlbums(artistID, self.albumsearchlimit)
                 if (len(albums) > 0):
+                    self._add_dir(__language__(30016), '', MODE_ARTIST_POPULAR_FROM_ALBUMS, self.popularSongsArtistImg, artistID)
                     self._add_albums_directory(albums, artistID)
                 else:
                     dialog = xbmcgui.Dialog()
@@ -403,7 +419,7 @@ class Grooveshark:
     def favorite(self, songid):
         userid = self._get_login()
         if (userid != 0):
-            if self.debug:
+            if __debugging__ :
                 xbmc.log("Favorite song: " + str(songid))
             groovesharkApi.addUserFavoriteSong(songID = songid)
             xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30036) + ', 1000, ' + thumbDef + ')')
@@ -415,7 +431,7 @@ class Grooveshark:
     def unfavorite(self, songid, prevMode=0):
         userid = self._get_login()
         if (userid != 0):
-            if self.debug:
+            if __debugging__ :
                 xbmc.log("Unfavorite song: " + str(songid) + ', previous mode was ' + str(prevMode))
             groovesharkApi.removeUserFavoriteSongs(songIDs = songid)
             xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30038) + ', 1000, ' + thumbDef + ')')
@@ -435,7 +451,12 @@ class Grooveshark:
     # Show selected artist
     def artist(self, artistid):
         albums = groovesharkApi.getArtistAlbums(artistid, limit = self.albumsearchlimit)
-        self._add_albums_directory(albums, artistid)
+        if (len(albums) > 0):
+            self._add_dir(__language__(30016), '', MODE_ARTIST_POPULAR_FROM_ALBUMS, self.popularSongsArtistImg, artistid)
+            self._add_albums_directory(albums, artistid, True)
+        else:
+            # There are likely songs for the artist even when no verified albums are found
+            self.artistPopularSongs(artistid)
     
     # Show selected playlist
     def playlist(self, playlistid, playlistname):
@@ -447,90 +468,113 @@ class Grooveshark:
             dialog = xbmcgui.Dialog()
             dialog.ok(__language__(30008), __language__(30034), __language__(30040))
             
-    # Show popular songs of the artist
-    def artistPopularSongs(self):
+    # Search for artist show popular songs of the artist
+    def searchArtistPopularSongs(self):
         query = self._get_keyboard(default="", heading=__language__(30041))
-        if (query != ''): 
+        if (query != ''):
             artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
             if (len(artists) > 0):
-                artist = artists[0]
+                # check for exact artist name match, sometimes a more
+                # popular artist is returned first (e.g. 'Angel Dust'
+                # gets you 'Faith No More' because of their popular
+                # album 'Angel Dust')
+                artist = next ((a for a in artists if a[0].lower() == query.lower()), artists[0])
                 artistID = artist[1]
-                if self.debug:
+                if __debugging__ :
                     xbmc.log("Found " + artist[0] + "...")
-                songs = groovesharkApi.getArtistPopularSongs(artistID, limit = self.songsearchlimit)
-                if (len(songs) > 0):
-                    self._add_songs_directory(songs, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL)
-                else:
-                    dialog = xbmcgui.Dialog()
-                    dialog.ok(__language__(30008), __language__(30042))
-                    self.categories()
+                self.artistPopularSongs (artistID)
             else:
                 dialog = xbmcgui.Dialog()
                 dialog.ok(__language__(30008), __language__(30043))
                 self.categories()
         else:
             self.categories()
-            
+
+    # Show popular songs of the artist
+    def artistPopularSongs(self, artistID):
+        songs = groovesharkApi.getArtistPopularSongs(artistID, limit = self.songsearchlimit)
+        if (len(songs) > 0):
+            self._add_songs_directory(songs, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL)
+        else:
+            dialog = xbmcgui.Dialog()
+            dialog.ok(__language__(30008), __language__(30042))
+            self.categories()            
+
     # Play a song
     def playSong(self, item):
         global playTimer
         global player
         if item != None:
+            # Get stream as it could have expired
+            item.select(True)
+            url = ''
             songid = item.getProperty('songid')
-            url = item.getProperty('url')
-            if url == '':
-                stream = groovesharkApi.getSubscriberStreamKey(songid)
+            stream = groovesharkApi.getSubscriberStreamKey(songid)
+            if stream != False:
                 url = stream['url']
-            item.setPath(url)
-            if self.debug:
-                xbmc.log("Grooveshark playing: " + url)
-            xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
-            # Wait for play then start time
-            seconds = 0
-            while seconds < STREAM_MARKING_TIME:
-                try:
-                    if player.isPlayingAudio() == True:
-                        if playTimer != None:
-                            playTimer.cancel()
-                            songMarkTime = 0
-                        duration = int(item.getProperty('duration'))
-                        playTimer = PlayTimer(1, markSong, duration, [songid, duration])
-                        playTimer.start()
-                        break
-                except: pass
-                time.sleep(1)
-                seconds = seconds + 1
-                if (seconds == STREAM_RETRY):
-                    stream = groovesharkApi.getSubscriberStreamKey(songid)
-                    url = stream['url']
+                key = stream['StreamKey']
+                server = stream['StreamServerID']
+                duration = int(self._setDuration(stream['uSecs']))
+                stream = [songid, duration, url, key, server]
+                self._setSongStream(stream)
+                if url != '':
                     item.setPath(url)
                     xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
+                    if __debugging__ :
+                        xbmc.log("Grooveshark playing: " + url)
+                    # Wait for play then start timer
+                    seconds = 0
+                    while seconds < STREAM_TIMEOUT:
+                        try:
+                            if player.isPlayingAudio() == True:
+                                if playTimer != None:
+                                    playTimer.cancel()
+                                    songMarkTime = 0
+                                playTimer = PlayTimer(1, markSong, self._setDuration(duration), [songid, duration, key, server])
+                                playTimer.start()
+                                break
+                        except: pass
+                        time.sleep(1)
+                        seconds = seconds + 1
+                else:
+                    xbmc.log("No song URL")
+            else:
+                xbmc.log("No song stream")
         else:
             xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30044) + ', 1000, ' + thumbDef + ')')
         
     # Make a song directory item
-    def songItem(self, songid, name, album, artist, coverart, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL):
-        songImg = self._get_icon(coverart, 'song-' + str(songid) + "-image")
-        if int(trackLabelFormat) == NAME_ALBUM_ARTIST_LABEL:
-            trackLabel = name + " - " + album + " - " + artist
-        else:
-            trackLabel = artist + " - " + album + " - " + name
-        stream = self._getSongStream(songid)
-        duration = stream['duration']
-        url = stream['url']
-        item = xbmcgui.ListItem(label = trackLabel, thumbnailImage=songImg, iconImage=songImg)
-        item.setInfo( type="music", infoLabels={ "title": name, "album": album, "artist": artist, "duration": duration} )
-        item.setProperty('mimetype', 'audio/mpeg')
-        item.setProperty("IsPlayable", "true")
-        item.setProperty('songid', str(songid))
-        item.setProperty('coverart', songImg)
-        item.setProperty('title', name)
-        item.setProperty('album', album)
-        item.setProperty('artist', artist)
-        item.setProperty('duration', str(duration))
-        item.setProperty('url', str(url))
+    def songItem(self, songid, name, album, artist, coverart, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL, tracknumber=1):
         
-        return item
+        stream = self._getSongStream(songid)
+        if stream != None:
+            duration = stream[1]
+            url = stream[2]
+            key = stream[3]
+            server = stream[4]
+            songImg = self._get_icon(coverart, 'song-' + str(songid) + "-image")
+            if int(trackLabelFormat) == NAME_ALBUM_ARTIST_LABEL:
+                trackLabel = name + " - " + album + " - " + artist
+            else:
+                trackLabel = artist + " - " + album + " - " + name
+            item = xbmcgui.ListItem(label = trackLabel, thumbnailImage=songImg, iconImage=songImg)
+            item.setPath(url)
+            item.setInfo( type="music", infoLabels={ "title": name, "album": album, "artist": artist, "duration": duration, "tracknumber" : tracknumber} )
+            item.setProperty('mimetype', 'audio/mpeg')
+            item.setProperty("IsPlayable", "true")
+            item.setProperty('songid', str(songid))
+            item.setProperty('coverart', songImg)
+            item.setProperty('title', name)
+            item.setProperty('album', album)
+            item.setProperty('artist', artist)
+            item.setProperty('duration', str(duration))
+            item.setProperty('key', str(key))
+            item.setProperty('server', str(server))
+            item.setProperty('fanart_image', self.fanImg)
+            return item
+        else:
+            xbmc.log("No access to song URL")
+            return None
     
     # Next page of songs
     def songPage(self, offset, trackLabelFormat, playlistid = 0, playlistname = ''):
@@ -619,7 +663,7 @@ class Grooveshark:
                     else:
                         playlist = playlists[i]
                         playlistid = playlist[1]
-                        if self.debug:
+                        if __debugging__ :
                             xbmc.log("Add song " + str(songid) + " to playlist " + str(playlistid))
                         songIDs=[]
                         songs = groovesharkApi.getPlaylistSongs(playlistid)
@@ -658,7 +702,7 @@ class Grooveshark:
                 else:
                     # Refresh to remove item from directory
                     xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ',' + __language__(30066)+ ', 1000, ' + thumbDef + ')')
-                    xbmc.executebuiltin("Container.Update(" + playlistUrl + "&id="+str(playlistid) + "&name=" + playlistname + ")")
+                    xbmc.executebuiltin("Container.Update(" + playlistUrl + "&id="+str(playlistid) + "&name=" + str(playlistname) + ")")
             else:
                 dialog = xbmcgui.Dialog()
                 dialog.ok(__language__(30008), __language__(30034), __language__(30067))
@@ -673,16 +717,6 @@ class Grooveshark:
             dialog.ok(__language__(30008), __language__(30068))
             self.categories()
     
-    # Debug
-    def setDebug(self):
-        self.debug = self.settings.getSetting('debug')
-        if self.debug:
-            xbmc.log("Debug is on")
-
-    # Debug
-    def getDebug(self):
-        return self.debug
-        
     # Get keyboard input
     def _get_keyboard(self, default="", heading="", hidden=False):
         kb = xbmc.Keyboard(default, heading, hidden)
@@ -695,35 +729,29 @@ class Grooveshark:
     def _get_login(self):
         if (self.username == "" or self.password == ""):
             dialog = xbmcgui.Dialog()
-            dialog.ok(__language__(30008), __language__(30069), __language__(30070))
+            dialog.ok(__language__(30008), __language__(30069), __language__(30070), __language__(30082))
             return 0
         else:
-            if self.userid == 0:
-                uid = groovesharkApi.login(self.username, self.password)
+            uid = groovesharkApi.login(self.username, self.password)
             if (uid != 0):
                 return uid
             else:
                 dialog = xbmcgui.Dialog()
-                dialog.ok(__language__(30008), __language__(30069), __language__(30070))
+                dialog.ok(__language__(30008), __language__(30069), __language__(30070), __language__(30082))
                 return 0
     
-    # Get a song directory item
-    def _get_song_item(self, song, trackLabelFormat):
-        name = song[0]
-        songid = song[1]
-        album = song[2]
-        artist = song[4]
-        coverart = song[6]
-        return self.songItem(songid, name, album, artist, coverart, trackLabelFormat)            
-        
     # File download            
     def _get_icon(self, url, songid):
         if url != 'None':
             localThumb = os.path.join(xbmc.translatePath(os.path.join(thumbDir, str(songid)))) + '.tbn'
             try:
                 if os.path.isfile(localThumb) == False:
-                    loc = urllib.URLopener()
-                    loc.retrieve(url, localThumb)
+                    headers = { 'User-Agent' : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.102 Chrome/32.0.1700.102 Safari/537.36' }
+                    req = urllib2.Request(url, None, headers)
+                    loc = urllib2.urlopen(req)
+                    output = open(localThumb,'wb')
+                    output.write(loc.read())
+                    output.close()
             except:
                 shutil.copy2(thumbDef, localThumb)
             return os.path.join(os.path.join(thumbDir, str(songid))) + '.tbn'
@@ -740,7 +768,7 @@ class Grooveshark:
 
         # No pages needed
         if offset == 0 and totalSongs <= self.songspagelimit:
-            if self.debug:
+            if __debugging__ :
                 xbmc.log("Found " + str(totalSongs) + " songs...")
         # Pages
         else:
@@ -755,15 +783,17 @@ class Grooveshark:
                 start = offset
                 end = min(start + self.songspagelimit,totalSongs)
         
-        id = 0
         n = start
         items = end - start
         while n < end:
             song = songs[n]
+            name = song[0]
             songid = song[1]
-            stream = self._getSongStream(songid)
-            if stream['url'] != '':   
-                item = self._get_song_item(song, trackLabelFormat)
+            album = song[2]
+            artist = song[4]
+            coverart = song[6]
+            item = self.songItem(songid, name, album, artist, coverart, trackLabelFormat, (n+1))
+            if item != None:   
                 coverart = item.getProperty('coverart')
                 songname = song[0]
                 songalbum = song[2]
@@ -781,38 +811,37 @@ class Grooveshark:
                     menuItems.append((__language__(30071), "XBMC.RunPlugin("+fav+")"))
                 menuItems.append((__language__(30072), "XBMC.RunPlugin("+unfav+")"))
                 if playlistid > 0:
-                    rmplaylstsong=sys.argv[0]+"?playlistid="+str(playlistid)+"&id="+str(songid)+"&mode="+str(MODE_REMOVE_PLAYLIST_SONG)+"&name="+playlistname
+                    rmplaylstsong=sys.argv[0]+"?playlistid="+str(playlistid)+"&id="+str(songid)+"&mode="+str(MODE_REMOVE_PLAYLIST_SONG)+"&name="+str(playlistname)
                     menuItems.append((__language__(30073), "XBMC.RunPlugin("+rmplaylstsong+")"))
                 else:
                     addplaylstsong=sys.argv[0]+"?id="+str(songid)+"&mode="+str(MODE_ADD_PLAYLIST_SONG)
                     menuItems.append((__language__(30074), "XBMC.RunPlugin("+addplaylstsong+")"))
                 item.addContextMenuItems(menuItems, replaceItems=False)
                 xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False, totalItems=items)
-                id = id + 1
             else:
                 end = min(end + 1,totalSongs)
-                if self.debug:
+                if __debugging__ :
                     xbmc.log(song[0] + " does not exist.")
             n = n + 1
 
         if totalSongs > end:
-            u=sys.argv[0]+"?mode="+str(MODE_SONG_PAGE)+"&id=playlistid"+"&offset="+str(end)+"&label="+str(trackLabelFormat)+"&name="+playlistname
+            u=sys.argv[0]+"?mode="+str(MODE_SONG_PAGE)+"&id=playlistid"+"&offset="+str(end)+"&label="+str(trackLabelFormat)+"&name="+str(playlistname)
             self._add_dir(__language__(30075) + '...', u, MODE_SONG_PAGE, self.songImg, 0, totalSongs - end)
 
         xbmcplugin.setContent(self._handle, 'songs')
         xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
     
     # Add albums to directory
-    def _add_albums_directory(self, albums, artistid=0):
+    def _add_albums_directory(self, albums, artistid=0, isverified=False):
         n = len(albums)
         itemsExisting = n
-        if self.debug:
+        if __debugging__ :
             xbmc.log("Found " + str(n) + " albums...")
         i = 0
         while i < n:
             album = albums[i]
             albumID = album[3]
-            if groovesharkApi.getDoesAlbumExist(albumID):                    
+            if isverified:
                 albumArtistName = album[0]
                 albumName = album[2]
                 albumImage = self._get_icon(album[4], 'album-' + str(albumID))
@@ -831,17 +860,14 @@ class Grooveshark:
     def _add_artists_directory(self, artists):
         n = len(artists)
         itemsExisting = n
-        if self.debug:
+        if __debugging__ :
             xbmc.log("Found " + str(n) + " artists...")
         i = 0
         while i < n:
             artist = artists[i]
             artistID = artist[1]
-            if groovesharkApi.getDoesArtistExist(artistID):                    
-                artistName = artist[0]
-                self._add_dir(artistName, '', MODE_ARTIST, self.artistImg, artistID, itemsExisting)
-            else:
-                itemsExisting = itemsExisting - 1
+            artistName = artist[0]
+            self._add_dir(artistName, '', MODE_ARTIST, self.artistImg, artistID, itemsExisting)
             i = i + 1
         xbmcplugin.setContent(self._handle, 'artists')
         xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE)
@@ -850,43 +876,44 @@ class Grooveshark:
     # Add playlists to directory          
     def _add_playlists_directory(self, playlists):
         n = len(playlists)
-        if self.debug:
+        if __debugging__ :
             xbmc.log("Found " + str(n) + " playlists...")
         i = 0
         while i < n:
             playlist = playlists[i]
             playlistName = playlist[0]
             playlistID = playlist[1]
-            dir = self._add_dir(playlistName, '', MODE_PLAYLIST, self.playlistImg, playlistID, n)
+            self._add_dir(playlistName, '', MODE_PLAYLIST, self.playlistImg, playlistID, n)
             i = i + 1  
         xbmcplugin.setContent(self._handle, 'files')
         xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_LABEL)
         xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
       
     # Add whatever directory
-    def _add_dir(self, name, url, mode, iconimage, id, items=1):
+    def _add_dir(self, name, url, mode, iconimage, itemId, items=1):
 
         if url == '':
-            u=sys.argv[0]+"?mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&id="+str(id)
+            u=sys.argv[0]+"?mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&id="+str(itemId)
         else:
             u = url
-        dir=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
-        dir.setInfo( type="Music", infoLabels={ "title": name } )
+        directory=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
+        directory.setInfo( type="Music", infoLabels={ "title": name } )
+        directory.setProperty('fanart_image', self.fanImg)
         
         # Custom menu items
         menuItems = []
         if mode == MODE_ALBUM:
-            mkplaylst=sys.argv[0]+"?mode="+str(MODE_MAKE_PLAYLIST)+"&name="+name+"&id="+str(id)
+            mkplaylst=sys.argv[0]+"?mode="+str(MODE_MAKE_PLAYLIST)+"&name="+name+"&id="+str(itemId)
             menuItems.append((__language__(30076), "XBMC.RunPlugin("+mkplaylst+")"))
         if mode == MODE_PLAYLIST:
-            rmplaylst=sys.argv[0]+"?mode="+str(MODE_REMOVE_PLAYLIST)+"&name="+urllib.quote_plus(name)+"&id="+str(id)
+            rmplaylst=sys.argv[0]+"?mode="+str(MODE_REMOVE_PLAYLIST)+"&name="+urllib.quote_plus(name)+"&id="+str(itemId)
             menuItems.append((__language__(30077), "XBMC.RunPlugin("+rmplaylst+")"))
-            mvplaylst=sys.argv[0]+"?mode="+str(MODE_RENAME_PLAYLIST)+"&name="+urllib.quote_plus(name)+"&id="+str(id)
+            mvplaylst=sys.argv[0]+"?mode="+str(MODE_RENAME_PLAYLIST)+"&name="+urllib.quote_plus(name)+"&id="+str(itemId)
             menuItems.append((__language__(30078), "XBMC.RunPlugin("+mvplaylst+")"))
 
-        dir.addContextMenuItems(menuItems, replaceItems=False)
+        directory.addContextMenuItems(menuItems, replaceItems=False)
         
-        return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=dir,isFolder=True, totalItems=items)
+        return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=directory,isFolder=True, totalItems=items)
     
     def _getSavedSongs(self):
         path = os.path.join(cacheDir, 'songs.dmp')
@@ -912,56 +939,95 @@ class Grooveshark:
             xbmc.log("An error occurred saving songs")
             pass
 
+    # Duration to seconds
+    def _setDuration(self, usecs):
+        if usecs < 60000000:
+            usecs = usecs * 10 # Some durations are 10x to small
+        return int(usecs / 1000000)
+    
     def _getSongStream(self, songid):
-        id = int(songid)
-        duration = -1
-        streams = []
-        url = ''
+        idSong = int(songid)
+        stream = None
+        streams = {}
         path = os.path.join(cacheDir, 'streams.dmp')
         try:
             f = open(path, 'rb')
             streams = pickle.load(f)
-            for song in streams:
-                if song[0] == id:
-                    duration = song[1]
-                    url = song[2]
-                    break;
+            song = streams[songid]
+
+            duration = song[1]
+            url = song[2]
+            key = song[3]
+            server = song[4]
+            stream = [idSong, duration, url, key, server]
+
+            if __debugging__ :
+                xbmc.log("Found " + str(idSong) + " in stream cache")
+
             f.close()
         except:
             pass
 
-        if duration < 0 and groovesharkApi.getDoesSongExist(songid):
+        # Not in cache
+        if stream == None:
             stream = groovesharkApi.getSubscriberStreamKey(songid)
-            url = stream['url']
-            usecs = stream['uSecs']
-            if usecs < 60000000:
-                usecs = usecs * 10 # Some durations are 10x to small
-            duration = usecs / 1000000
-            song = [id, duration, url]
-            streams.append(song)                
-            self._setSongStream(streams)
-
-        return {'duration':duration, 'url':url}
+            if stream != False and stream['url'] != '':
+                duration = self._setDuration(stream['uSecs'])
+                url = stream['url']
+                key = stream['StreamKey']
+                server = stream['StreamServerID']
+                stream = [idSong, duration, url, key, server]
+                self._addSongStream(stream)
+
+        return stream
         
-    def _setSongStream(self, streams):            
+    def _addSongStream(self, stream):
+        streams = self._getStreams()           
+        streams[int(stream[0])] = stream
+        path = os.path.join(cacheDir, 'streams.dmp')
         try:
-            # Create the 'data' directory if it doesn't exist.
-            if not os.path.exists(cacheDir):
-                os.makedirs(cacheDir)
-            path = os.path.join(cacheDir, 'streams.dmp')
             f = open(path, 'wb')
             pickle.dump(streams, f, protocol=pickle.HIGHEST_PROTOCOL)
             f.close()
+            if __debugging__ :
+                xbmc.log("Added " + str(stream[0]) + " to stream cache")
         except:
-            xbmc.log("An error occurred saving streams")
+            xbmc.log("An error occurred adding to stream")
+    
+    def _setSongStream(self, stream):
+        idStream = int(stream[0])
+        stream[1] = self._setDuration(stream[1])
+        streams = self._getStreams()
+        path = os.path.join(cacheDir, 'streams.dmp')
+
+        try:
+            streams[idStream] = stream
+            f = open(path, 'wb')
+            pickle.dump(streams, f, protocol=pickle.HIGHEST_PROTOCOL)
+            f.close()
+            if __debugging__ :
+                xbmc.log("Updated " + str(idStream) + " in stream cache")
+
+        except:
+            xbmc.log("An error occurred setting stream")
+    
+    def _getStreams(self):
+        path = os.path.join(cacheDir, 'streams.dmp')
+        try:
+            f = open(path, 'rb')
+            streams = pickle.load(f)
+            f.close()
+        except:
+            streams = {}
             pass
+        return streams
 
     
 # Parse URL parameters
 def get_params():
     param=[]
     paramstring=sys.argv[2]
-    if grooveshark.getDebug():
+    if __debugging__ :
         xbmc.log(paramstring)
     if len(paramstring)>=2:
         params=sys.argv[2]
@@ -979,15 +1045,13 @@ def get_params():
         
 # Main
 grooveshark = Grooveshark();
-grooveshark.setDebug()
-groovesharkApi.setDebug(grooveshark.getDebug())
 
 params=get_params()
 mode=None
 try: mode=int(params["mode"])
 except: pass
-id=0
-try: id=int(params["id"])
+itemId=0
+try: itemId=int(params["id"])
 except: pass
 name = None
 try: name=urllib.unquote_plus(params["name"])
@@ -1016,7 +1080,7 @@ elif mode==MODE_POPULAR_SONGS:
     grooveshark.popularSongs()
     
 elif mode==MODE_ARTIST_POPULAR:
-    grooveshark.artistPopularSongs()
+    grooveshark.searchArtistPopularSongs()
 
 elif mode==MODE_FAVORITES:
     grooveshark.favorites()
@@ -1029,7 +1093,7 @@ elif mode==MODE_SONG_PAGE:
     except: pass
     try: label=urllib.unquote_plus(params["label"])
     except: pass
-    grooveshark.songPage(offset, label, id, name)
+    grooveshark.songPage(offset, label, itemId, name)
 
 elif mode==MODE_SONG:
     try: album=urllib.unquote_plus(params["album"])
@@ -1038,46 +1102,49 @@ elif mode==MODE_SONG:
     except: pass
     try: coverart=urllib.unquote_plus(params["coverart"])
     except: pass
-    song = grooveshark.songItem(id, name, album, artist, coverart)
+    song = grooveshark.songItem(itemId, name, album, artist, coverart)
     grooveshark.playSong(song)
 
 elif mode==MODE_ARTIST:
-    grooveshark.artist(id)
+    grooveshark.artist(itemId)
     
 elif mode==MODE_ALBUM:
-    grooveshark.album(id)
+    grooveshark.album(itemId)
     
 elif mode==MODE_PLAYLIST:
-    grooveshark.playlist(id, name)
+    grooveshark.playlist(itemId, name)
     
 elif mode==MODE_FAVORITE:
-    grooveshark.favorite(id)
+    grooveshark.favorite(itemId)
     
 elif mode==MODE_UNFAVORITE:
     try: prevMode=int(urllib.unquote_plus(params["prevmode"]))
     except:
         prevMode = 0
-    grooveshark.unfavorite(id, prevMode)
+    grooveshark.unfavorite(itemId, prevMode)
 
 elif mode==MODE_SIMILAR_ARTISTS:
-    grooveshark.similarArtists(id)
+    grooveshark.similarArtists(itemId)
 
 elif mode==MODE_MAKE_PLAYLIST:
-    grooveshark.makePlaylist(id, name)
+    grooveshark.makePlaylist(itemId, name)
     
 elif mode==MODE_REMOVE_PLAYLIST:
-    grooveshark.removePlaylist(id, name)    
+    grooveshark.removePlaylist(itemId, name)    
 
 elif mode==MODE_RENAME_PLAYLIST:
-    grooveshark.renamePlaylist(id, name)    
+    grooveshark.renamePlaylist(itemId, name)    
 
 elif mode==MODE_REMOVE_PLAYLIST_SONG:
     try: playlistID=urllib.unquote_plus(params["playlistid"])
     except: pass
-    grooveshark.removePlaylistSong(playlistID, name, id)
+    grooveshark.removePlaylistSong(playlistID, name, itemId)
 
 elif mode==MODE_ADD_PLAYLIST_SONG:
-    grooveshark.addPlaylistSong(id)        
+    grooveshark.addPlaylistSong(itemId)        
+
+elif mode==MODE_ARTIST_POPULAR_FROM_ALBUMS:
+    grooveshark.artistPopularSongs(itemId)
     
 if mode < MODE_SONG:
     xbmcplugin.endOfDirectory(int(sys.argv[1]))