Fix item counts in directory generation.
[clinton/xbmc-groove.git] / default.py
index 42fad28..30460dd 100644 (file)
@@ -1,6 +1,5 @@
 import urllib, urllib2, re, xbmcplugin, xbmcgui, xbmc, sys, os, time, pprint, shutil, xbmcaddon
 
-
 MODE_SEARCH_SONGS = 1
 MODE_SEARCH_ALBUMS = 2
 MODE_SEARCH_ARTISTS = 3
@@ -17,10 +16,6 @@ MODE_SIMILAR_SONG = 13
 MODE_SIMILAR_ARTIST = 14
 MODE_FROWN = 15
 
-songsearchlimit = 0
-albumsearchlimit = 0
-artistsearchlimit = 0
-
 lastID = 0
 
 baseDir = os.getcwd()
@@ -28,6 +23,7 @@ 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')))
 
 sys.path.append (libDir)
 from GrooveAPI import *
@@ -37,32 +33,8 @@ class _Info:
     def __init__( self, *args, **kwargs ):
         self.__dict__.update( kwargs )
         
-class GrovesharkPlayer(xbmc.Player):
-    # Player Class: calls function when song changes or playback ends
-    def __init__(self, *args, **kwargs):
-        xbmc.Player.__init__(self)
-        self.function = kwargs[ "function" ]
-
-    def onPlayBackStopped(self):
-        print "onPlayBackStopped"
-        xbmc.sleep(300)
-        if (not xbmc.Player().isPlayingAudio()):
-            self.function(0)
-    
-    def onPlayBackEnded(self):
-        print "onPlayBackEnded"
-        xbmc.sleep(300)
-        if (not xbmc.Player().isPlayingAudio()):
-            self.function(1)
-
-    def onPlayBackStarted(self):
-        print "onPlayBackStarted"
-        self.function(2)
-
 class Groveshark:
     
-    settings = xbmcaddon.Addon(id='plugin.audio.groove')
-
     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'))
@@ -70,17 +42,21 @@ class Groveshark:
     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'))
-    fanImg = xbmc.translatePath(os.path.join(baseDir, 'fanart.jpg'))
+    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')
-
+    username = settings.getSetting('username')
+    password = settings.getSetting('password')
 
     def __init__( self ):
         self._handle = int(sys.argv[1])
 
     def categories(self):
+
+        xbmc.log(self.username + ", limits: " + str(self.songsearchlimit) + ", " + str(self.albumsearchlimit) + ", "  + str(self.artistsearchlimit))
         
         userid = self._get_login()
         
@@ -101,7 +77,7 @@ class Groveshark:
     def searchSongs(self):
         query = self._get_keyboard(default="", heading="Search songs")
         if (query): 
-            songs = groovesharkApi.searchSongs(query, limit = self.settings.getSetting('songsearchlimit'))
+            songs = groovesharkApi.searchSongs(query, limit = self.songsearchlimit)
             if (len(songs) > 0):
                 self._add_songs_directory(songs)
             else:
@@ -112,7 +88,7 @@ class Groveshark:
     def searchAlbums(self):
         query = self._get_keyboard(default="", heading="Search albums")
         if (query): 
-            albums = groovesharkApi.searchAlbums(query, limit = self.settings.getSetting('albumsearchlimit'))
+            albums = groovesharkApi.searchAlbums(query, limit = self.albumsearchlimit)
             if (len(albums) > 0):
                 self._add_albums_directory(albums)
             else:
@@ -123,7 +99,7 @@ class Groveshark:
     def searchArtists(self):
         query = self._get_keyboard(default="", heading="Search artists")
         if (query): 
-            artists = groovesharkApi.searchArtists(query, limit = self.settings.getSetting('artistsearchlimit'))
+            artists = groovesharkApi.searchArtists(query, limit = self.artistsearchlimit)
             if (len(artists) > 0):
                 self._add_artists_directory(artists)
             else:
@@ -132,18 +108,16 @@ class Groveshark:
                 self.categories()
                     
     def favorites(self):
-        userid = self._get_login()
-        if (userid != 0):
-            favorites = groovesharkApi.userGetFavoriteSongs(userid)
-            if (len(favorites) > 0):
-                self._add_songs_directory(favorites)
-            else:
-                dialog = xbmcgui.Dialog()
-                dialog.ok('Grooveshark', 'You have no favorites.')
-                self.categories()
+        favorites = self._get_favorites()
+        if (len(favorites) > 0):
+            self._add_songs_directory(favorites)
+        else:
+            dialog = xbmcgui.Dialog()
+            dialog.ok('Grooveshark', 'You have no favorites.')
+            self.categories()
     
     def popular(self):
-        popular = groovesharkApi.popularGetSongs(limit = self.settings.getSetting('songsearchlimit'))
+        popular = groovesharkApi.popularGetSongs(limit = self.songsearchlimit)
         if (len(popular) > 0):
             self._add_songs_directory(popular)
         else:
@@ -167,6 +141,7 @@ class Groveshark:
         if (userid != 0):
             xbmc.log("Favorite playSong: " + str(songid))
             groovesharkApi.favoriteSong(songID = songid)
+            os.remove(favoritesCache)
         else:
             dialog = xbmcgui.Dialog()
             dialog.ok('Grooveshark', 'You must be logged in', 'to add favorites.')
@@ -176,6 +151,7 @@ class Groveshark:
         if (userid != 0):
             xbmc.log("Unfavorite playSong: " + str(songid))
             groovesharkApi.unfavoriteSong(songID = songid)
+            os.remove(favoritesCache)
         else:
             dialog = xbmcgui.Dialog()
             dialog.ok('Grooveshark', 'You must be logged in', 'to remove favorites.')
@@ -193,8 +169,8 @@ class Groveshark:
     def similarSong(self, songid):
         userid = self._get_login()
         if (userid != 0):
-            xbmc.log("Frown playSong: " + str(songid))
-            if groovesharkApi.radioSong(songId = songid) and groovesharkApi.radioStartSongs() == True:
+            xbmc.log("Add song: " + str(songid))
+            if groovesharkApi.radioSong(songId = songid) != False and groovesharkApi.radioStartSongs() == True:
                 self.playNext()
             else:
                 dialog = xbmcgui.Dialog()
@@ -206,8 +182,8 @@ class Groveshark:
     def similarArtist(self, artistId):
         userid = self._get_login()
         if (userid != 0):
-            xbmc.log("Add radio artist of playSong: " + str(artistId))
-            if groovesharkApi.radioArtist(artistId = artistId) and groovesharkApi.radioStartArtists() == True:
+            xbmc.log("Add radio artist: " + str(artistId))
+            if groovesharkApi.radioArtist(artistId = artistId) != False and groovesharkApi.radioStartArtists() == True:
                 self.playNext()
             else:
                 dialog = xbmcgui.Dialog()
@@ -217,17 +193,17 @@ class Groveshark:
             dialog.ok('Grooveshark', 'You must be logged in', 'to update radio artists.')
     
     def album(self,albumid):
-        album = groovesharkApi.albumGetSongs(albumId = albumid, limit = self.settings.getSetting('songsearchlimit'))
+        album = groovesharkApi.albumGetSongs(albumId = albumid, limit = self.songsearchlimit)
         self._add_songs_directory(album)
     
     def artist(self, artistid):
-        albums = groovesharkApi.artistGetAlbums(artistId = artistid, limit = self.settings.getSetting('albumsearchlimit'))
+        albums = groovesharkApi.artistGetAlbums(artistId = artistid, limit = self.albumsearchlimit)
         self._add_albums_directory(albums)
     
     def playlist(self, playlistid):
         userid = self._get_login()
         if (userid != 0):
-            songs = groovesharkApi.playlistGetSongs(playlistId = playlistid, limit = self.settings.getSetting('songsearchlimit'))
+            songs = groovesharkApi.playlistGetSongs(playlistId = playlistid, limit = self.songsearchlimit)
             self._add_songs_directory(songs)
         else:
             dialog = xbmcgui.Dialog()
@@ -236,31 +212,51 @@ class Groveshark:
     def playSong(self, item):
         url = item.getProperty('url')
         xbmc.log("Playing: " + url)
-        xbmc.Player( xbmc.PLAYER_CORE_PAPLAYER ).play(url, item)
+        xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
     
     def playNext(self):
         item = self._get_song_item(groovesharkApi.radioNextSong()[0])
-        url = item.getProperty('url')
-        self.player = GrovesharkPlayer(xbmc.PLAYER_CORE_PAPLAYER, function=self.onPlayBackChanged)
-        self.player.play(url, item)
-        self.onPlayBackChanged(2)
+        self.playSong(item)
 
     def songItem(self, id, name, album, artist, duration, thumb, image):
         url = groovesharkApi.getStreamURL(id)
-        songImg = self._get_icon(image, str(id) + "-image")
-        print songImg
-        if songImg == "":
-            songImg = image
-        songThm = self._get_icon(thumb, str(id) + "-thumb")
-        if songThm == "":
-            songThm = thumb
+        # Only try to get the image
+        if image != "":
+            songImg = self._get_icon(image, 'song-' + str(id) + "-image")
+            songThm = songImg
+        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} )
+        item.setInfo( type="music", infoLabels={ "title": name, "duration": duration, "album": album, "artist": artist} )
+        item.setProperty('mimetype', 'audio/mpeg')
+        item.setProperty("IsPlayable", "true")
         item.setProperty('url', url)
         item.setProperty('thumb', songThm)
         item.setProperty('image', songImg)
-        item.setProperty('mimetype', 'audio/mpeg')
+        
         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
         
     def _get_keyboard(self, default="", heading="", hidden=False):
             kb = xbmc.Keyboard(default, heading, hidden)
@@ -270,16 +266,14 @@ class Groveshark:
             return ''
     
     def _get_login(self):
-        username = self.settings.getSetting('username')
-        password = self.settings.getSetting('password')
-        if (username == "" or password == ""):
+        if (self.username == "" or self.password == ""):
             dialog = xbmcgui.Dialog()
             dialog.ok('Grooveshark', 'Unable to login.', 'Check username and password in settings.')
             return 0
         else:
             if groovesharkApi.loggedInStatus() == 1:
                 groovesharkApi.logout()
-            userid = groovesharkApi.loginExt(username, password)
+            userid = groovesharkApi.loginExt(self.username, self.password)
             if (userid != 0):
                 xbmc.log("Logged in")
                 return userid
@@ -300,18 +294,15 @@ class Groveshark:
         
     # File download            
     def _get_icon(self, url, id):
-        # Get the channel icon
         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)
-            try:
-                shutil.copyfile(self.defImg, localThumb)
-            except: pass
-            return ""
+            return(self.defImg)
 
         return os.path.join(os.path.join(thumbDir, str(id))) + '.tbn'
         
@@ -330,7 +321,7 @@ class Groveshark:
             songduration = song[2]
             songalbum = song[3]
             songartist = song[6]
-            songartistid = song[7]
+            #songartistid = song[7]
             u=sys.argv[0]+"?url="+urllib.quote_plus(songurl) \
             +"&mode="+str(MODE_SONG)+"&name="+urllib.quote_plus(songname)+"&id=" \
             +str(songid) \
@@ -341,59 +332,66 @@ class Groveshark:
             +"&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)
-            similarArtist=sys.argv[0]+"?mode="+str(MODE_SIMILAR_ARTIST)+"&id="+str(songartistid)
-            similarSong=sys.argv[0]+"?mode="+str(MODE_SIMILAR_SONG)+"&id="+str(songid)
+            #similarArtist=sys.argv[0]+"?mode="+str(MODE_SIMILAR_ARTIST)+"&id="+str(songartistid)
+            #similarSong=sys.argv[0]+"?mode="+str(MODE_SIMILAR_SONG)+"&id="+str(songid)
             #frown=sys.argv[0]+"?mode="+str(MODE_FROWN)+"&id="+str(songid)
             menuItems = []
             menuItems.append(("Grooveshark Favorite", "XBMC.RunPlugin("+fav+")"))
             menuItems.append(("Not Grooveshark Favorite", "XBMC.RunPlugin("+unfav+")"))
-            menuItems.append(("Listen to similar artist", "XBMC.RunPlugin("+similarArtist+")"))
-            menuItems.append(("Listen to similar song", "XBMC.RunPlugin("+similarSong+")"))
-            # menuItems.append(("No thanks!", "XBMC.RunPlugin("+frown+")"))
+            #menuItems.append(("Listen to similar artist", "XBMC.RunPlugin("+similarArtist+")"))
+            #menuItems.append(("Listen to similar song", "XBMC.RunPlugin("+similarSong+")"))
+            #menuItems.append(("No thanks!", "XBMC.RunPlugin("+frown+")"))
             item.addContextMenuItems(menuItems, replaceItems=False)
-            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False)
+            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False,totalItems=n)
             i = i + 1
         xbmcplugin.setContent(self._handle, 'songs')
+        xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
             
     def _add_albums_directory(self, albums):
-        xbmc.log("Found " + str(len(albums)) + " albums...")
+        n = len(albums)
+        xbmc.log("Found " + str(n) + " albums...")
         i = 0
-        while i < len(albums):
+        while i < n:
             album = albums[i]
             albumArtistName = album[0]
             albumName = album[2]
             albumID = album[3]
-            albumImage = album[4]
-            self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID)
+            albumImage = self._get_icon(album[4], 'album-' + str(albumID))
+            self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID, n)
             i = i + 1
         xbmcplugin.setContent(self._handle, 'albums')
         xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE)
+        xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
             
     def _add_artists_directory(self, artists):
-        xbmc.log("Found " + str(len(artists)) + " artists...")
+        n = len(artists)
+        xbmc.log("Found " + str(n) + " artists...")
         i = 0
-        while i < len(artists):
+        while i < n:
             artist = artists[i]
             artistName = artist[0]
             artistID = artist[1]
-            self._add_dir(artistName, '', MODE_ARTIST, self.artistImg, artistID)
+            self._add_dir(artistName, '', MODE_ARTIST, self.artistImg, artistID, n)
             i = i + 1
         xbmcplugin.setContent(self._handle, 'artists')
         xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE)
+        xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
             
     def _add_playlists_directory(self, playlists):
-        xbmc.log("Found " + str(len(playlists)) + " playlists...")
+        n = len(playlists)
+        xbmc.log("Found " + str(n) + " playlists...")
         i = 0
-        while i < len(playlists):
+        while i < n:
             playlist = playlists[i]
             playlistName = playlist[0]
             playlistID = playlist[1]
-            self._add_dir(playlistName, '', MODE_PLAYLIST, self.playlistImg, playlistID)
+            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_PLAYLIST_ORDER)
+        xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
       
-    def _add_dir(self, name, url, mode, iconimage, id):
+    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)
         dir=xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
         dir.setInfo( type="Music", infoLabels={ "title": name } )
@@ -401,21 +399,7 @@ class Groveshark:
         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)
-
-    def onPlayBackChanged(self, change):
-        xbmc.log("onPlayBackChanged " + str(change))
-        if change == 0:
-            groovesharkApi.radioEnabled = False
-        if change == 1 and groovesharkApi.radioTurnedOn() == True:
-            xbmc.log("playnext")
-            self.player.playNext()
-        if change == 2:
-            xbmc.log("playback started")
-            xbmc.sleep(7500)
-            while self.player.isPlaying() or xbmc.Player(xbmc.PLAYER_CORE_PAPLAYER).isPlaying():
-                xbmc.sleep(1000)
-            xbmc.log("stopped playing")
+        return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=dir,isFolder=True, totalItems=items)
 
    
 def get_params():