Add search of artist's albums.
[clinton/xbmc-groove.git] / default.py
index 0e0261e..7fdcb3d 100644 (file)
-import urllib, urllib2, re, xbmcplugin, xbmcgui, xbmc, sys, os, time, pprint, shutil, xbmcaddon
-
+import urllib, sys, os, shutil, re, time, xbmcaddon, xbmcplugin, xbmcgui, xbmc
 MODE_SEARCH_SONGS = 1
 MODE_SEARCH_ALBUMS = 2
 MODE_SEARCH_ARTISTS = 3
 MODE_SEARCH_SONGS = 1
 MODE_SEARCH_ALBUMS = 2
 MODE_SEARCH_ARTISTS = 3
-MODE_POPULAR = 4
-MODE_FAVORITES = 5
-MODE_PLAYLISTS = 6
-MODE_ALBUM = 7
-MODE_ARTIST = 8
-MODE_PLAYLIST = 9
-MODE_SIMILAR_ARTISTS = 10
-MODE_SONG = 11
-MODE_FAVORITE = 12
-MODE_UNFAVORITE = 13
+MODE_SEARCH_ARTISTS_ALBUMS = 4
+MODE_SEARCH_PLAYLISTS = 5
+MODE_POPULAR_SONGS = 6
+MODE_FAVORITES = 7
+MODE_PLAYLISTS = 8
+MODE_ALBUM = 9
+MODE_ARTIST = 10
+MODE_PLAYLIST = 11
+MODE_SONG = 12
+MODE_FAVORITE = 13
+
+ACTION_MOVE_LEFT = 1
+ACTION_MOVE_UP = 3
+ACTION_MOVE_DOWN = 4
+ACTION_PAGE_UP = 5
+ACTION_PAGE_DOWN = 6
+ACTION_SELECT_ITEM = 7
+ACTION_PREVIOUS_MENU = 10
 
 
-lastID = 0
+# Formats for track labels
+ARTIST_ALBUM_NAME_LABEL = 0
+NAME_ALBUM_ARTIST_LABEL = 1
 
 baseDir = os.getcwd()
 resDir = xbmc.translatePath(os.path.join(baseDir, 'resources'))
 libDir = xbmc.translatePath(os.path.join(resDir,  'lib'))
 imgDir = xbmc.translatePath(os.path.join(resDir,  'img'))
 
 baseDir = os.getcwd()
 resDir = xbmc.translatePath(os.path.join(baseDir, 'resources'))
 libDir = xbmc.translatePath(os.path.join(resDir,  'lib'))
 imgDir = xbmc.translatePath(os.path.join(resDir,  'img'))
-thumbDir = os.path.join('special://masterprofile/addon_data/', os.path.join(os.path.basename(os.getcwd()), 'thumb'))
-favoritesCache = xbmc.translatePath(os.path.join('special://masterprofile/addon_data/', os.path.join(os.path.basename(os.getcwd()), 'favorites.dmp')))
+cacheDir = os.path.join(xbmc.translatePath('special://masterprofile/addon_data/'), os.path.basename(os.getcwd()))
+thumbDirName = 'thumb'
+thumbDir = os.path.join('special://masterprofile/addon_data/', os.path.basename(os.getcwd()), thumbDirName)
+
+baseModeUrl = 'plugin://plugin.audio.groove/'
+playlistUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLIST)
+playlistsUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLISTS)
+favoritesUrl = baseModeUrl + '?mode=' + str(MODE_FAVORITES)
+
+thumbDef = os.path.join(imgDir, 'default.tbn')
 
 sys.path.append (libDir)
 
 sys.path.append (libDir)
-from GrooveAPI import *
-groovesharkApi = GrooveAPI()
+from GroovesharkAPI import GrooveAPI
+
+try:
+    groovesharkApi = GrooveAPI()
+    if groovesharkApi.pingService() != True:
+        raise StandardError('No Grooveshark service')
+except:
+    dialog = xbmcgui.Dialog()
+    dialog.ok('Grooveshark XBMC', 'Unable to connect with Grooveshark.', 'Please try again later')
+    sys.exit(-1)
+  
 
 class _Info:
     def __init__( self, *args, **kwargs ):
         self.__dict__.update( kwargs )
 
 class _Info:
     def __init__( self, *args, **kwargs ):
         self.__dict__.update( kwargs )
-        
+
+     
 class Groveshark:
     
 class Groveshark:
     
-    albumImg = xbmc.translatePath(os.path.join(imgDir,  'album.png'))
-    artistImg = xbmc.translatePath(os.path.join(imgDir,  'artist.png'))
-    favoritesImg = xbmc.translatePath(os.path.join(imgDir,  'favorites.png'))
-    playlistImg = xbmc.translatePath(os.path.join(imgDir,  'playlist.png'))
-    popularImg = xbmc.translatePath(os.path.join(imgDir,  'popular.png'))
-    songImg = xbmc.translatePath(os.path.join(imgDir,  'song.png'))
-    defImg = xbmc.translatePath(os.path.join(imgDir,  'default.tbn'))
+    albumImg = xbmc.translatePath(os.path.join(imgDir, 'album.png'))
+    artistImg = xbmc.translatePath(os.path.join(imgDir, 'artist.png'))
+    artistsAlbumsImg = xbmc.translatePath(os.path.join(imgDir, 'artistsalbums.png'))
+    favoritesImg = xbmc.translatePath(os.path.join(imgDir, 'favorites.png'))
+    playlistImg = xbmc.translatePath(os.path.join(imgDir, 'playlist.png'))
+    usersplaylistsImg = xbmc.translatePath(os.path.join(imgDir, 'usersplaylists.png'))
+    popularSongsImg = xbmc.translatePath(os.path.join(imgDir, 'popularSongs.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'))
 
     settings = xbmcaddon.Addon(id='plugin.audio.groove')
     fanImg = xbmc.translatePath(os.path.join(baseDir, 'fanart.png'))
 
     settings = xbmcaddon.Addon(id='plugin.audio.groove')
-    songsearchlimit = settings.getSetting('songsearchlimit')
-    albumsearchlimit = settings.getSetting('albumsearchlimit')
-    artistsearchlimit = settings.getSetting('artistsearchlimit')
+    songsearchlimit = int(settings.getSetting('songsearchlimit'))
+    albumsearchlimit = int(settings.getSetting('albumsearchlimit'))
+    artistsearchlimit = int(settings.getSetting('artistsearchlimit'))
     username = settings.getSetting('username')
     password = settings.getSetting('password')
     username = settings.getSetting('username')
     password = settings.getSetting('password')
-
+    userid = 0
+    
     def __init__( self ):
         self._handle = int(sys.argv[1])
     def __init__( self ):
         self._handle = int(sys.argv[1])
+        if os.path.isdir(cacheDir) == False:
+            os.makedirs(cacheDir)
+            xbmc.log("Made " + cacheDir)
+        artDir = xbmc.translatePath(thumbDir)
+        if os.path.isdir(artDir) == False:
+            os.makedirs(artDir)
+            xbmc.log("Made " + artDir)
 
 
+    # Top-level menu
     def categories(self):
 
     def categories(self):
 
-        xbmc.log(self.username + ", limits: " + str(self.songsearchlimit) + ", " + str(self.albumsearchlimit) + ", "  + str(self.artistsearchlimit))
-        
-        userid = self._get_login()
+        self.userid = self._get_login()
         
         # Setup
         
         # Setup
-        groovesharkApi.setRemoveDuplicates(True)
         xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
         xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
-        if os.path.isdir(thumbDir) == False:
-            os.makedirs(thumbDir)
         
         
-        self._add_dir('Search songs', '', MODE_SEARCH_SONGS, self.songImg, 0)
-        self._add_dir('Search albums', '', MODE_SEARCH_ALBUMS, self.albumImg, 0)
-        self._add_dir('Search artists', '', MODE_SEARCH_ARTISTS, self.artistImg, 0)
-        self._add_dir('Popular', '', MODE_POPULAR, self.popularImg, 0)
-        if (userid != 0):
-            self._add_dir('Favorites', '', MODE_FAVORITES, self.favoritesImg, 0)
-            self._add_dir('Playlists', '', MODE_PLAYLISTS, self.playlistImg, 0)
-            
+        self._add_dir('Search for songs...', '', MODE_SEARCH_SONGS, self.songImg, 0)
+        self._add_dir('Search for albums...', '', MODE_SEARCH_ALBUMS, self.albumImg, 0)
+        self._add_dir('Search for artists...', '', MODE_SEARCH_ARTISTS, self.artistImg, 0)
+        self._add_dir("Search for artist's albums...", '', MODE_SEARCH_ARTISTS_ALBUMS, self.artistsAlbumsImg, 0)
+        self._add_dir("Search for user's playlists...", '', MODE_SEARCH_PLAYLISTS, self.usersplaylistsImg, 0)
+        self._add_dir('Popular songs', '', MODE_POPULAR_SONGS, self.popularSongsImg, 0)
+        if (self.userid != 0):
+            self._add_dir('My favorites', '', MODE_FAVORITES, self.favoritesImg, 0)
+            self._add_dir('My playlists', '', MODE_PLAYLISTS, self.playlistImg, 0)
+
+    # Search for songs            
     def searchSongs(self):
     def searchSongs(self):
-        query = self._get_keyboard(default="", heading="Search songs")
-        if (query): 
-            songs = groovesharkApi.searchSongs(query, limit = self.songsearchlimit)
+        query = self._get_keyboard(default="", heading="Search for songs")
+        if (query != ''):
+            songs = groovesharkApi.getSongSearchResults(query, limit = self.songsearchlimit)
             if (len(songs) > 0):
                 self._add_songs_directory(songs)
             else:
                 dialog = xbmcgui.Dialog()
             if (len(songs) > 0):
                 self._add_songs_directory(songs)
             else:
                 dialog = xbmcgui.Dialog()
-                dialog.ok('Grooveshark', 'No matching songs.')
+                dialog.ok('Grooveshark XBMC', 'No matching songs.')
                 self.categories()
                 self.categories()
+        else:
+            self.categories()
     
     
+    # Search for albums
     def searchAlbums(self):
     def searchAlbums(self):
-        query = self._get_keyboard(default="", heading="Search albums")
-        if (query): 
-            albums = groovesharkApi.searchAlbums(query, limit = self.albumsearchlimit)
+        query = self._get_keyboard(default="", heading="Search for albums")
+        if (query != ''): 
+            albums = groovesharkApi.getAlbumSearchResults(query, limit = self.albumsearchlimit)
             if (len(albums) > 0):
                 self._add_albums_directory(albums)
             else:
                 dialog = xbmcgui.Dialog()
             if (len(albums) > 0):
                 self._add_albums_directory(albums)
             else:
                 dialog = xbmcgui.Dialog()
-                dialog.ok('Grooveshark', 'No matching albums.')
+                dialog.ok('Grooveshark XBMC', 'No matching albums.')
                 self.categories()
                 self.categories()
+        else:
+            self.categories()
     
     
+    # Search for artists
     def searchArtists(self):
     def searchArtists(self):
-        query = self._get_keyboard(default="", heading="Search artists")
-        if (query): 
-            artists = groovesharkApi.searchArtists(query, limit = self.artistsearchlimit)
+        query = self._get_keyboard(default="", heading="Search for artists")
+        if (query != ''): 
+            artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
             if (len(artists) > 0):
                 self._add_artists_directory(artists)
             else:
                 dialog = xbmcgui.Dialog()
             if (len(artists) > 0):
                 self._add_artists_directory(artists)
             else:
                 dialog = xbmcgui.Dialog()
-                dialog.ok('Grooveshark', 'No matching artists.')
+                dialog.ok('Grooveshark XBMC', 'No matching artists.')
+                self.categories()
+        else:
+            self.categories()
+
+    # Search for playlists
+    def searchPlaylists(self):
+        query = self._get_keyboard(default="", heading="Search for user's playlists")
+        if (query != ''): 
+            playlists = groovesharkApi.getUserPlaylistsEx(query)
+            if (len(playlists) > 0):
+                self._add_playlists_directory(playlists)
+            else:
+                dialog = xbmcgui.Dialog()
+                dialog.ok('Grooveshark XBMC', 'No Grooveshark playlists found.')
+                self.categories()
+        else:
+            self.categories()
+
+    # Search for artists albums
+    def searchArtistsAlbums(self):
+        query = self._get_keyboard(default="", heading="Search for artist's albums")
+        if (query != ''): 
+            artists = groovesharkApi.getArtistSearchResults(query, limit = self.artistsearchlimit)
+            if (len(artists) > 0):
+                artist = artists[0]
+                artistID = artist[1]
+                xbmc.log("Found " + artist[0] + "...")
+                albums = groovesharkApi.getArtistAlbums(artistID, limit = self.albumsearchlimit)
+                if (len(albums) > 0):
+                    self._add_albums_directory(albums)
+                else:
+                    dialog = xbmcgui.Dialog()
+                    dialog.ok('Grooveshark XBMC', 'No matching albums.')
+                    self.categories()
+            else:
+                dialog = xbmcgui.Dialog()
+                dialog.ok('Grooveshark XBMC', 'No matching artists.')
                 self.categories()
                 self.categories()
-                    
-    def favorites(self):
-        favorites = self._get_favorites()
-        if (len(favorites) > 0):
-            self._add_songs_directory(favorites)
         else:
         else:
-            dialog = xbmcgui.Dialog()
-            dialog.ok('Grooveshark', 'You have no favorites.')
             self.categories()
             self.categories()
+                  
+    # Get my favorites
+    def favorites(self):
+        userid = self._get_login()
+        if (userid != 0):
+            favorites = groovesharkApi.getUserFavoriteSongs()
+            if (len(favorites) > 0):
+                self._add_songs_directory(favorites)
+            else:
+                dialog = xbmcgui.Dialog()
+                dialog.ok('Grooveshark XBMC', 'You have no favorites.')
+                self.categories()
     
     
-    def popular(self):
-        popular = groovesharkApi.popularGetSongs(limit = self.songsearchlimit)
+    # Get popular songs
+    def popularSongs(self):
+        popular = groovesharkApi.getPopularSongsToday(limit = self.songsearchlimit)
         if (len(popular) > 0):
             self._add_songs_directory(popular)
         else:
             dialog = xbmcgui.Dialog()
         if (len(popular) > 0):
             self._add_songs_directory(popular)
         else:
             dialog = xbmcgui.Dialog()
-            dialog.ok('Grooveshark', 'No popular songs.')
+            dialog.ok('Grooveshark XBMC', 'No popular songs.')
             self.categories()
             self.categories()
-                 
+
+    # Get my playlists             
     def playlists(self):
         userid = self._get_login()
         if (userid != 0):
     def playlists(self):
         userid = self._get_login()
         if (userid != 0):
-            playlists = groovesharkApi.userGetPlaylists()
+            playlists = groovesharkApi.getUserPlaylists()
             if (len(playlists) > 0):
                 self._add_playlists_directory(playlists)
             else:
                 dialog = xbmcgui.Dialog()
             if (len(playlists) > 0):
                 self._add_playlists_directory(playlists)
             else:
                 dialog = xbmcgui.Dialog()
-                dialog.ok('Grooveshark', 'You have no playlists.')
+                dialog.ok('Grooveshark XBMC', 'You have no Grooveshark playlists.')
                 self.categories()
                 self.categories()
+        else:
+            dialog = xbmcgui.Dialog()
+            dialog.ok('Grooveshark XBMC', 'You must be logged in ', ' to see your Grooveshark playlists.')
                 
                 
+    # Make songs a favorite 
     def favorite(self, songid):
         userid = self._get_login()
         if (userid != 0):
             xbmc.log("Favorite song: " + str(songid))
     def favorite(self, songid):
         userid = self._get_login()
         if (userid != 0):
             xbmc.log("Favorite song: " + str(songid))
-            groovesharkApi.favoriteSong(songID = songid)
-            os.remove(favoritesCache)
-        else:
-            dialog = xbmcgui.Dialog()
-            dialog.ok('Grooveshark', 'You must be logged in', 'to add favorites.')
-    
-    def unfavorite(self, songid):
-        userid = self._get_login()
-        if (userid != 0):
-            xbmc.log("Unfavorite song: " + str(songid))
-            groovesharkApi.unfavoriteSong(songID = songid)
-            os.remove(favoritesCache)
+            groovesharkApi.addUserFavoriteSong(songID = songid)
+            xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Added to favorites, 1000, ' + thumbDef + ')')
         else:
             dialog = xbmcgui.Dialog()
         else:
             dialog = xbmcgui.Dialog()
-            dialog.ok('Grooveshark', 'You must be logged in', 'to remove favorites.')
+            dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to add favorites.')
 
 
-    def frown(self, songid):
-        userid = self._get_login()
-        if (userid != 0):
-            xbmc.log("Frown song: " + str(songid))
-            if groovesharkApi.radioFrown(songId = songid) != True:
-                xbmc.log("Unable to frown song " + str(songid))
-        else:
-            dialog = xbmcgui.Dialog()
-            dialog.ok('Grooveshark', 'You must be logged in', 'to frown a song.')
+    # Show selected album
+    def album(self, albumid):
+        album = groovesharkApi.getAlbumSongs(albumid, limit = self.songsearchlimit)
+        self._add_songs_directory(album, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL)
 
 
-    def similarArtists(self, artistId):
-        similar = groovesharkApi.artistGetSimilar(artistId, limit = self.artistsearchlimit)
-        if (len(similar) > 0):
-            self._add_artists_directory(similar)
-        else:
-            dialog = xbmcgui.Dialog()
-            dialog.ok('Grooveshark', 'No similar artists.')
-            self.categories()
-    
-    def album(self,albumid):
-        album = groovesharkApi.albumGetSongs(albumId = albumid, limit = self.songsearchlimit)
-        self._add_songs_directory(album)
-    
+    # Show selected artist
     def artist(self, artistid):
     def artist(self, artistid):
-        albums = groovesharkApi.artistGetAlbums(artistId = artistid, limit = self.albumsearchlimit)
-        self._add_albums_directory(albums, artistid)
+        albums = groovesharkApi.getArtistAlbums(artistid, limit = self.albumsearchlimit)
+        self._add_albums_directory(albums)
     
     
+    # Show selected playlist
     def playlist(self, playlistid):
         userid = self._get_login()
         if (userid != 0):
     def playlist(self, playlistid):
         userid = self._get_login()
         if (userid != 0):
-            songs = groovesharkApi.playlistGetSongs(playlistId = playlistid, limit = self.songsearchlimit)
-            self._add_songs_directory(songs)
+            songs = groovesharkApi.getPlaylistSongs(playlistid)
+            self._add_songs_directory(songs, trackLabelFormat=NAME_ALBUM_ARTIST_LABEL)
         else:
             dialog = xbmcgui.Dialog()
         else:
             dialog = xbmcgui.Dialog()
-            dialog.ok('Grooveshark', 'You must be logged in', 'to get playlists.')
+            dialog.ok('Grooveshark XBMC', 'You must be logged in', 'to get Grooveshark playlists.')
             
             
+    # Play a song
     def playSong(self, item):
     def playSong(self, item):
-        url = item.getProperty('url')
-        xbmc.log("Playing: " + url)
-        xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
+        songid = item.getProperty('songid')
+        song = groovesharkApi.getSongURLFromSongID(songid)
+        if song != '':
+            item.setPath(song)
+            xbmc.log("Playing: " + song)
+            xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
+        else:
+            xbmc.executebuiltin('XBMC.Notification(Grooveshark XBMC, Unable to play song, 1000, ' + thumbDef + ')')
     
     
-    def songItem(self, id, name, album, artist, duration, thumb, image):
-        url = groovesharkApi.getStreamURL(id)
-        # Only try to get the image
-        if image != "":
-            songImg = self._get_icon(image, 'song-' + str(id) + "-image")
-            songThm = songImg
+    # 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 trackLabelFormat == NAME_ALBUM_ARTIST_LABEL:
+            trackLabel = name + " - " + album + " - " + artist
         else:
         else:
-            songThm = self._get_icon(thumb, 'song-' + str(id) + "-thumb")
-            songImg = songThm
-        item = xbmcgui.ListItem(label = artist + " - " + album + " - " + name, path=url, thumbnailImage=songThm, iconImage=songImg)
-        item.setInfo( type="music", infoLabels={ "title": name, "duration": duration, "album": album, "artist": artist} )
+            trackLabel = artist + " - " + album + " - " + name
+        item = xbmcgui.ListItem(label = trackLabel, thumbnailImage=songImg, iconImage=songImg)
+        item.setInfo( type="music", infoLabels={ "title": name, "album": album, "artist": artist} )
         item.setProperty('mimetype', 'audio/mpeg')
         item.setProperty("IsPlayable", "true")
         item.setProperty('mimetype', 'audio/mpeg')
         item.setProperty("IsPlayable", "true")
-        item.setProperty('url', url)
-        item.setProperty('thumb', songThm)
-        item.setProperty('image', songImg)
+        item.setProperty('songid', str(songid))
+        item.setProperty('coverart', songImg)
+        item.setProperty('title', name)
+        item.setProperty('album', album)
+        item.setProperty('artist', artist)
         
         return item
     
         
         return item
     
-    def _get_favorites(self):
-        favorites = []
-        # if the cache does not exist or is older than x hours then reload
-        if (os.path.isfile(favoritesCache) == False) or (time.time() - os.path.getmtime(favoritesCache) > 3*60*60):
-            xbmc.log("Refresh favorites cache")
-            userid = self._get_login()
-            if (userid != 0):
-                favorites = groovesharkApi.userGetFavoriteSongs(userid)
-                f = open(favoritesCache, 'wb')
-                pickle.dump(favorites, f, protocol=pickle.HIGHEST_PROTOCOL)
-                f.close()
-                xbmc.log("Refreshed favorites cache")
-        # if not old then read from cache
-        elif os.path.isfile(favoritesCache):
-            xbmc.log("Existing favorites cache")
-            f = open(favoritesCache, 'rb')
-            favorites = pickle.load(f)
-            f.close()
-            
-        return favorites
-        
+    # Get keyboard input
     def _get_keyboard(self, default="", heading="", hidden=False):
     def _get_keyboard(self, default="", heading="", hidden=False):
-            kb = xbmc.Keyboard(default, heading, hidden)
-            kb.doModal()
-            if (kb.isConfirmed()):
-                return unicode(kb.getText(), "utf-8")
-            return ''
+        kb = xbmc.Keyboard(default, heading, hidden)
+        kb.doModal()
+        if (kb.isConfirmed()):
+            return unicode(kb.getText(), "utf-8")
+        return ''
     
     
+    # Login to grooveshark
     def _get_login(self):
         if (self.username == "" or self.password == ""):
             dialog = xbmcgui.Dialog()
     def _get_login(self):
         if (self.username == "" or self.password == ""):
             dialog = xbmcgui.Dialog()
-            dialog.ok('Grooveshark', 'Unable to login.', 'Check username and password in settings.')
+            dialog.ok('Grooveshark XBMC', 'Unable to login.', 'Check username and password in settings.')
             return 0
         else:
             return 0
         else:
-            if groovesharkApi.loggedInStatus() == 1:
-                groovesharkApi.logout()
-            userid = groovesharkApi.loginExt(self.username, self.password)
-            if (userid != 0):
-                xbmc.log("Logged in")
-                return userid
+            if self.userid == 0:
+                uid = groovesharkApi.login(self.username, self.password)
+            if (uid != 0):
+                return uid
             else:
                 dialog = xbmcgui.Dialog()
             else:
                 dialog = xbmcgui.Dialog()
-                dialog.ok('Grooveshark', 'Unable to login.', 'Check username and password in settings.')
+                dialog.ok('Grooveshark XBMC', 'Unable to login.', 'Check username and password in settings.')
                 return 0
     
                 return 0
     
-    def _get_song_item(self, song):
+    # Get a song directory item
+    def _get_song_item(self, song, trackLabelFormat):
         name = song[0]
         name = song[0]
-        id = song[1]
-        duration = song[2]
-        album = song[3]
-        artist = song[6]
-        thumb = song[8]
-        image = song[9]
-        return self.songItem(id, name, album, artist, duration, thumb, image)            
+        songid = song[1]
+        album = song[2]
+        artist = song[4]
+        coverart = song[6]
+        return self.songItem(songid, name, album, artist, coverart, trackLabelFormat)            
         
     # File download            
         
     # File download            
-    def _get_icon(self, url, id):
-        localThumb = os.path.join(xbmc.translatePath(os.path.join(thumbDir, str(id)))) + '.tbn'
-        try:
-            if os.path.isfile(localThumb) == False:
-                xbmc.log('Downloading ' + url + ' to ' + localThumb)
-                loc = urllib.URLopener()
-                loc.retrieve(url, localThumb)
-        except:
-            xbmc.log('URL download failed of ' + url + ' to ' + localThumb)
-            return(self.defImg)
-
-        return os.path.join(os.path.join(thumbDir, str(id))) + '.tbn'
-        
-    def _add_songs_directory(self, songs):
+    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)
+            except:
+                shutil.copy2(thumbDef, localThumb)
+            return os.path.join(os.path.join(thumbDir, str(songid))) + '.tbn'
+        else:
+            return thumbDef
+    
+    # Add songs to directory
+    def _add_songs_directory(self, songs, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL):
         n = len(songs)
         xbmc.log("Found " + str(n) + " songs...")
         i = 0
         while i < n:
             song = songs[i]
         n = len(songs)
         xbmc.log("Found " + str(n) + " songs...")
         i = 0
         while i < n:
             song = songs[i]
-            item = self._get_song_item(song)
-            songurl = item.getProperty('url')
-            songthumb = item.getProperty('thumb')
-            songimage = item.getProperty('image')
+            item = self._get_song_item(song, trackLabelFormat)
+            coverart = item.getProperty('coverart')
             songname = song[0]
             songid = song[1]
             songname = song[0]
             songid = song[1]
-            songduration = song[2]
-            songalbum = song[3]
-            songartist = song[6]
-            u=sys.argv[0]+"?url="+urllib.quote_plus(songurl) \
-            +"&mode="+str(MODE_SONG)+"&name="+urllib.quote_plus(songname)+"&id=" \
-            +str(songid) \
+            songalbum = song[2]
+            songartist = song[4]
+            u=sys.argv[0]+"?mode="+str(MODE_SONG)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid) \
             +"&album="+urllib.quote_plus(songalbum) \
             +"&artist="+urllib.quote_plus(songartist) \
             +"&album="+urllib.quote_plus(songalbum) \
             +"&artist="+urllib.quote_plus(songartist) \
-            +"&duration="+str(songduration) \
-            +"&thumb="+urllib.quote_plus(songthumb) \
-            +"&image="+urllib.quote_plus(songimage)
-            fav=sys.argv[0]+"?url="+urllib.quote_plus(songurl)+"&mode="+str(MODE_FAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)
-            unfav=sys.argv[0]+"?url="+urllib.quote_plus(songurl)+"&mode="+str(MODE_UNFAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)
+            +"&coverart="+urllib.quote_plus(coverart)
+            fav=sys.argv[0]+"?mode="+str(MODE_FAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)
             menuItems = []
             menuItems = []
-            menuItems.append(("Grooveshark Favorite", "XBMC.RunPlugin("+fav+")"))
-            menuItems.append(("Not Grooveshark Favorite", "XBMC.RunPlugin("+unfav+")"))
+            menuItems.append(("Grooveshark favorite", "XBMC.RunPlugin("+fav+")"))
             item.addContextMenuItems(menuItems, replaceItems=False)
             item.addContextMenuItems(menuItems, replaceItems=False)
-            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False,totalItems=n)
+            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False, totalItems=n)
             i = i + 1
             i = i + 1
+
         xbmcplugin.setContent(self._handle, 'songs')
         xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
         xbmcplugin.setContent(self._handle, 'songs')
         xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
-            
-    def _add_albums_directory(self, albums, artistid=0):
+    
+    # Add albums to directory
+    def _add_albums_directory(self, albums):
         n = len(albums)
         xbmc.log("Found " + str(n) + " albums...")
         i = 0
         n = len(albums)
         xbmc.log("Found " + str(n) + " albums...")
         i = 0
@@ -329,12 +371,11 @@ class Groveshark:
             albumImage = self._get_icon(album[4], 'album-' + str(albumID))
             self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID, n)
             i = i + 1
             albumImage = self._get_icon(album[4], 'album-' + str(albumID))
             self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID, n)
             i = i + 1
-        if artistid > 0:
-            self._add_dir('Similar artists...', '', MODE_SIMILAR_ARTISTS, self.artistImg, artistid)
         xbmcplugin.setContent(self._handle, 'albums')
         xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE)
         xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
         xbmcplugin.setContent(self._handle, 'albums')
         xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE)
         xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
-            
+    
+    # Add artists to directory
     def _add_artists_directory(self, artists):
         n = len(artists)
         xbmc.log("Found " + str(n) + " artists...")
     def _add_artists_directory(self, artists):
         n = len(artists)
         xbmc.log("Found " + str(n) + " artists...")
@@ -348,7 +389,8 @@ class Groveshark:
         xbmcplugin.setContent(self._handle, 'artists')
         xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE)
         xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
         xbmcplugin.setContent(self._handle, 'artists')
         xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE)
         xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
-            
+
+    # Add playlists to directory          
     def _add_playlists_directory(self, playlists):
         n = len(playlists)
         xbmc.log("Found " + str(n) + " playlists...")
     def _add_playlists_directory(self, playlists):
         n = len(playlists)
         xbmc.log("Found " + str(n) + " playlists...")
@@ -357,26 +399,26 @@ class Groveshark:
             playlist = playlists[i]
             playlistName = playlist[0]
             playlistID = playlist[1]
             playlist = playlists[i]
             playlistName = playlist[0]
             playlistID = playlist[1]
-            self._add_dir(playlistName, '', MODE_PLAYLIST, self.playlistImg, playlistID, n)
+            dir = self._add_dir(playlistName, '', MODE_PLAYLIST, self.playlistImg, playlistID, n)
             i = i + 1  
         xbmcplugin.setContent(self._handle, 'files')
             i = i + 1  
         xbmcplugin.setContent(self._handle, 'files')
-        xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_PLAYLIST_ORDER)
+        xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_LABEL)
         xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
       
         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, id, items=1):
-        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&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(id)
         dir=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
         dir.setInfo( type="Music", infoLabels={ "title": name } )
         dir=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
         dir.setInfo( type="Music", infoLabels={ "title": name } )
-        # Codes from http://xbmc-scripting.googlecode.com/svn/trunk/Script%20Templates/common/gui/codes.py
-        menuItems = []
-        menuItems.append(("Select", "XBMC.executebuiltin(Action(7))"))
-        dir.addContextMenuItems(menuItems, replaceItems=True)
         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=dir,isFolder=True, totalItems=items)
 
-   
+
+# Parse URL parameters
 def get_params():
     param=[]
     paramstring=sys.argv[2]
 def get_params():
     param=[]
     paramstring=sys.argv[2]
+    xbmc.log(paramstring)
     if len(paramstring)>=2:
         params=sys.argv[2]
         cleanedparams=params.replace('?','')
     if len(paramstring)>=2:
         params=sys.argv[2]
         cleanedparams=params.replace('?','')
@@ -389,29 +431,20 @@ def get_params():
             splitparams=pairsofparams[i].split('=')
             if (len(splitparams))==2:
                 param[splitparams[0]]=splitparams[1]
             splitparams=pairsofparams[i].split('=')
             if (len(splitparams))==2:
                 param[splitparams[0]]=splitparams[1]
-    print param              
     return param
         
     return param
         
+# Main
 grooveshark = Groveshark();
 grooveshark = Groveshark();
-    
+
 params=get_params()
 params=get_params()
-url=None
-name=None
 mode=None
 mode=None
-id=None
-
-try: url=urllib.unquote_plus(params["url"]) 
-except: pass
-try: name=urllib.unquote_plus(params["name"])
-except: pass
 try: mode=int(params["mode"])
 except: pass
 try: mode=int(params["mode"])
 except: pass
+id=0
 try: id=int(params["id"])
 except: pass
 
 try: id=int(params["id"])
 except: pass
 
-if (id > 0):
-    lastID = id
-
+# Call function for URL
 if mode==None:
     grooveshark.categories()
        
 if mode==None:
     grooveshark.categories()
        
@@ -423,16 +456,22 @@ elif mode==MODE_SEARCH_ALBUMS:
 
 elif mode==MODE_SEARCH_ARTISTS:
     grooveshark.searchArtists()
 
 elif mode==MODE_SEARCH_ARTISTS:
     grooveshark.searchArtists()
+    
+elif mode==MODE_SEARCH_ARTISTS_ALBUMS:
+    grooveshark.searchArtistsAlbums()
+    
+elif mode==MODE_SEARCH_PLAYLISTS:
+    grooveshark.searchPlaylists() 
 
 
-elif mode==MODE_POPULAR:
-    grooveshark.popular()
-
-elif mode==MODE_PLAYLISTS:
-    grooveshark.playlists()
+elif mode==MODE_POPULAR_SONGS:
+    grooveshark.popularSongs()
 
 elif mode==MODE_FAVORITES:
     grooveshark.favorites()
 
 
 elif mode==MODE_FAVORITES:
     grooveshark.favorites()
 
+elif mode==MODE_PLAYLISTS:
+    grooveshark.playlists()
+
 elif mode==MODE_SONG:
     try: name=urllib.unquote_plus(params["name"])
     except: pass
 elif mode==MODE_SONG:
     try: name=urllib.unquote_plus(params["name"])
     except: pass
@@ -440,32 +479,22 @@ elif mode==MODE_SONG:
     except: pass
     try: artist=urllib.unquote_plus(params["artist"])
     except: pass
     except: pass
     try: artist=urllib.unquote_plus(params["artist"])
     except: pass
-    try: duration=int(params["duration"])
-    except: pass
-    try: thumb=urllib.unquote_plus(params["thumb"])
-    except: pass
-    try: image=urllib.unquote_plus(params["image"])
+    try: coverart=urllib.unquote_plus(params["coverart"])
     except: pass
     except: pass
-    song = grooveshark.songItem(id, name, album, artist, duration, thumb, image)
+    song = grooveshark.songItem(id, name, album, artist, coverart)
     grooveshark.playSong(song)
 
 elif mode==MODE_ARTIST:
     grooveshark.playSong(song)
 
 elif mode==MODE_ARTIST:
-    grooveshark.artist(lastID)
+    grooveshark.artist(id)
     
 elif mode==MODE_ALBUM:
     
 elif mode==MODE_ALBUM:
-    grooveshark.album(lastID)
+    grooveshark.album(id)
     
 elif mode==MODE_PLAYLIST:
     
 elif mode==MODE_PLAYLIST:
-    grooveshark.playlist(lastID)
+    grooveshark.playlist(id)
     
 elif mode==MODE_FAVORITE:
     
 elif mode==MODE_FAVORITE:
-    grooveshark.favorite(lastID)
-
-elif mode==MODE_UNFAVORITE:
-    grooveshark.unfavorite(lastID)
-
-elif mode==MODE_SIMILAR_ARTISTS:
-    grooveshark.similarArtists(lastID)
+    grooveshark.favorite(id)
 
 
-if (mode < MODE_SONG):    
+if mode < MODE_SONG:
     xbmcplugin.endOfDirectory(int(sys.argv[1]))
     xbmcplugin.endOfDirectory(int(sys.argv[1]))