More radio implementation.
[clinton/xbmc-groove.git] / default.py
index b0a86e9..cb5aa16 100644 (file)
@@ -1,4 +1,4 @@
-import urllib, urllib2, re, xbmcplugin, xbmcgui, xbmc, sys, os, time
+import urllib, urllib2, re, xbmcplugin, xbmcgui, xbmc, sys, os, time, pprint, shutil
 
 # plugin constants
 __plugin__ = "Grooveshark"
@@ -31,10 +31,11 @@ artistsearchlimit = 0
 
 lastID = 0
 
-resDir = xbmc.translatePath(os.path.join(os.getcwd(), 'resources'))
+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/plugin_data/music', os.path.basename(os.getcwd()))
+thumbDir = os.path.join('special://masterprofile/plugin_data/music', os.path.join(os.path.basename(os.getcwd()), 'thumb'))
 
 sys.path.append (libDir)
 from GrooveAPI import *
@@ -54,16 +55,17 @@ class GrovesharkPlayer(xbmc.Player):
         print "onPlayBackStopped"
         xbmc.sleep(300)
         if (not xbmc.Player().isPlayingAudio()):
-            self.function(stop=1)
+            self.function(0)
     
     def onPlayBackEnded(self):
         print "onPlayBackEnded"
         xbmc.sleep(300)
         if (not xbmc.Player().isPlayingAudio()):
-            self.function(stop=0)
-    
+            self.function(1)
+
     def onPlayBackStarted(self):
         print "onPlayBackStarted"
+        self.function(2)
 
 class Groveshark:
 
@@ -73,13 +75,14 @@ class Groveshark:
     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'))
+    fanImg = xbmc.translatePath(os.path.join(baseDir, 'fanart.jpg'))
 
     songsearchlimit = xbmcplugin.getSetting('songsearchlimit')
     albumsearchlimit = xbmcplugin.getSetting('albumsearchlimit')
     artistsearchlimit = xbmcplugin.getSetting('artistsearchlimit')
-    
-    musicplaylist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
-    
+
+
     def __init__( self ):
         self._handle = int(sys.argv[1])
 
@@ -89,7 +92,10 @@ class Groveshark:
         
         # Setup
         groovesharkApi.setRemoveDuplicates(True)
-
+        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)
@@ -103,7 +109,7 @@ class Groveshark:
         if (query): 
             songs = groovesharkApi.searchSongs(query, limit = xbmcplugin.getSetting('songsearchlimit'))
             if (len(songs) > 0):
-                self._get_songs(songs)
+                self._add_songs_directory(songs)
             else:
                 dialog = xbmcgui.Dialog()
                 dialog.ok('Grooveshark', 'No matching songs.')
@@ -114,7 +120,7 @@ class Groveshark:
         if (query): 
             albums = groovesharkApi.searchAlbums(query, limit = xbmcplugin.getSetting('albumsearchlimit'))
             if (len(albums) > 0):
-                self._get_albums(albums)
+                self._add_albums_directory(albums)
             else:
                 dialog = xbmcgui.Dialog()
                 dialog.ok('Grooveshark', 'No matching albums.')
@@ -125,7 +131,7 @@ class Groveshark:
         if (query): 
             artists = groovesharkApi.searchArtists(query, limit = xbmcplugin.getSetting('artistsearchlimit'))
             if (len(artists) > 0):
-                self._get_artists(artists)
+                self._add_artists_directory(artists)
             else:
                 dialog = xbmcgui.Dialog()
                 dialog.ok('Grooveshark', 'No matching artists.')
@@ -136,7 +142,7 @@ class Groveshark:
         if (userid != 0):
             favorites = groovesharkApi.userGetFavoriteSongs(userid)
             if (len(favorites) > 0):
-                self._get_songs(favorites)
+                self._add_songs_directory(favorites)
             else:
                 dialog = xbmcgui.Dialog()
                 dialog.ok('Grooveshark', 'You have no favorites.')
@@ -145,7 +151,7 @@ class Groveshark:
     def popular(self):
         popular = groovesharkApi.popularGetSongs(limit = xbmcplugin.getSetting('songsearchlimit'))
         if (len(popular) > 0):
-            self._get_songs(popular)
+            self._add_songs_directory(popular)
         else:
             dialog = xbmcgui.Dialog()
             dialog.ok('Grooveshark', 'No popular songs.')
@@ -156,7 +162,7 @@ class Groveshark:
         if (userid != 0):
             playlists = groovesharkApi.userGetPlaylists()
             if (len(playlists) > 0):
-                self._get_playlists(playlists)
+                self._add_playlists_directory(playlists)
             else:
                 dialog = xbmcgui.Dialog()
                 dialog.ok('Grooveshark', 'You have no playlists.')
@@ -195,7 +201,7 @@ class Groveshark:
         if (userid != 0):
             xbmc.log("Frown playSong: " + str(songid))
             if groovesharkApi.radioSong(songId = songid) and groovesharkApi.radioStartSongs() == True:
-                self.playRadio()
+                self.playNext()
             else:
                 dialog = xbmcgui.Dialog()
                 dialog.ok('Grooveshark', 'Cannot start radio')
@@ -208,7 +214,7 @@ class Groveshark:
         if (userid != 0):
             xbmc.log("Add radio artist of playSong: " + str(artistId))
             if groovesharkApi.radioArtist(artistId = artistId) and groovesharkApi.radioStartArtists() == True:
-                self.playRadio()
+                self.playNext()
             else:
                 dialog = xbmcgui.Dialog()
                 dialog.ok('Grooveshark', 'Cannot start radio')
@@ -218,38 +224,48 @@ class Groveshark:
     
     def album(self,albumid):
         album = groovesharkApi.albumGetSongs(albumId = albumid, limit = xbmcplugin.getSetting('songsearchlimit'))
-        self._get_songs(album)
+        self._add_songs_directory(album)
     
     def artist(self, artistid):
         albums = groovesharkApi.artistGetAlbums(artistId = artistid, limit = xbmcplugin.getSetting('albumsearchlimit'))
-        self._get_albums(albums)
+        self._add_albums_directory(albums)
     
     def playlist(self, playlistid):
         userid = self._get_login()
         if (userid != 0):
             songs = groovesharkApi.playlistGetSongs(playlistId = playlistid, limit = xbmcplugin.getSetting('songsearchlimit'))
-            self._get_songs(songs)
+            self._add_songs_directory(songs)
         else:
             dialog = xbmcgui.Dialog()
             dialog.ok('Grooveshark', 'You must be logged in', 'to get playlists.')
             
-    def playSong(self, songItem):
-        url = songItem.getProperty('url')
+    def playSong(self, item):
+        url = item.getProperty('url')
         xbmc.log("Playing: " + url)
-        player = GrovesharkPlayer(xbmc.PLAYER_CORE_PAPLAYER, function=self._add_next)
-        player.play(url, songItem, False)
+        xbmc.Player( xbmc.PLAYER_CORE_MPLAYER ).play(url, item)
     
-    def playRadio(self):
-        song = self._get_next()
-        self._get_next()
-        self.playSong(song)
-
-    def songItem(self, url, name, album, artist, duration, thumb, image):
-        songItem = xbmcgui.ListItem(label = name, path=url, thumbnailImage=thumb, iconImage=image)
-        songItem.setInfo( type="Music", infoLabels={ "title": name, "duration": duration, "album": album, "artist": artist} )
-        songItem.setProperty('mimetype', 'audio/mpeg')
-        songItem.setProperty('url', url)
-        return songItem
+    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)
+
+    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
+        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.setProperty('url', url)
+        item.setProperty('thumb', songThm)
+        item.setProperty('image', songImg)
+        item.setProperty('mimetype', 'audio/mpeg')
+        return item
         
     def _get_keyboard(self, default="", heading="", hidden=False):
             kb = xbmc.Keyboard(default, heading, hidden)
@@ -277,40 +293,74 @@ class Groveshark:
                 dialog.ok('Grooveshark', 'Unable to login.', 'Check username and password in settings.')
                 return 0
     
-    def _get_next(self):
-        song = groovesharkApi.radioNextSong()[0]
-        print song
-        url = groovesharkApi.getStreamURL(song[1])
-        songImg = self._get_thumb(song[9], str(song[1]) + "-image")
-        if songImg == "":
-            songImg = song[9]
-        songThm = self._get_thumb(song[5], str(song[1]) + "-thumb")
-        if songThm == "":
-            songThm = song[5]
-        item = self.songItem(url, song[0], song[3], song[6], song[2], songThm, songImg)
-        self.musicplaylist.add(url, item)            
-        print item
-        return item
-    
-    def _get_songs(self, songs):
-        xbmc.log("Found " + str(len(songs)) + " songs...")
+    def _get_song_item(self, song):
+        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)            
+        
+    # 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:
+                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 os.path.join(os.path.join(thumbDir, str(id))) + '.tbn'
+        
+    def _add_songs_directory(self, songs):
+        n = len(songs)
+        xbmc.log("Found " + str(n) + " songs...")
         i = 0
-        while i < len(songs):
+        while i < n:
             song = songs[i]
-            songName = song[0]
-            songID = song[1]
-            songDuration = song[2]
-            songAlbum = song[3]
-            songArtist = song[6]
-            songArtistId = song[7]
-            songThumb = song[8]
-            songImage = song[9]
-            songUrl = groovesharkApi.getStreamURL(songID)
-            self._add_song(songID, songName, songUrl, songDuration, songAlbum, songArtist, songArtistId, songThumb, songImage)
+            item = self._get_song_item(song)
+            songurl = item.getProperty('url')
+            songthumb = item.getProperty('thumb')
+            songimage = item.getProperty('image')
+            songname = song[0]
+            songid = song[1]
+            songduration = song[2]
+            songalbum = song[3]
+            songartist = song[6]
+            songartistid = song[7]
+            u=sys.argv[0]+"?url="+urllib.quote_plus(songurl) \
+            +"&mode="+str(MODE_SONG)+"&name="+urllib.quote_plus(songname)+"&id=" \
+            +str(songid) \
+            +"&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)
+            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+")"))
+            item.addContextMenuItems(menuItems, replaceItems=False)
+            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False)
             i = i + 1
         xbmcplugin.setContent(self._handle, 'songs')
             
-    def _get_albums(self, albums):
+    def _add_albums_directory(self, albums):
         xbmc.log("Found " + str(len(albums)) + " albums...")
         i = 0
         while i < len(albums):
@@ -324,7 +374,7 @@ class Groveshark:
         xbmcplugin.setContent(self._handle, 'albums')
         xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ALBUM_IGNORE_THE)
             
-    def _get_artists(self, artists):
+    def _add_artists_directory(self, artists):
         xbmc.log("Found " + str(len(artists)) + " artists...")
         i = 0
         while i < len(artists):
@@ -336,7 +386,7 @@ class Groveshark:
         xbmcplugin.setContent(self._handle, 'artists')
         xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_ARTIST_IGNORE_THE)
             
-    def _get_playlists(self, playlists):
+    def _add_playlists_directory(self, playlists):
         xbmc.log("Found " + str(len(playlists)) + " playlists...")
         i = 0
         while i < len(playlists):
@@ -347,59 +397,6 @@ class Groveshark:
             i = i + 1  
         xbmcplugin.setContent(self._handle, 'files')
         xbmcplugin.addSortMethod(self._handle, xbmcplugin.SORT_METHOD_PLAYLIST_ORDER)
-        
-    # File download            
-    def _get_thumb(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:
-                loc = urllib.URLopener()
-                loc.retrieve(url, localThumb)
-        except:
-            xbmc.log('URL download failed of ' + url + ' to ' + localThumb)
-            return ""
-
-        return os.path.join(os.path.join(thumbDir, str(id))) + '.tbn'
-        
-    def _add_song(self, songid, songname, songurl, songduration, songalbum, songartist, songartistid, songthumb, songimage):
-        songImg = self._get_thumb(songimage, str(songid) + "-image")
-        if songImg == "":
-            songImg = songimage
-        songThm = self._get_thumb(songthumb, str(songid) + "-thumb")
-        if songThm == "":
-            songThm = songthumb
-        u=sys.argv[0]+"?url="+urllib.quote_plus(songurl)+"&mode="+str(MODE_SONG)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid) \
-        +"&album="+urllib.quote_plus(songalbum) \
-        +"&artist="+urllib.quote_plus(songartist) \
-        +"&duration="+str(songduration) \
-        +"&thumb="+urllib.quote_plus(songThm) \
-        +"&image="+urllib.quote_plus(songImg)
-        songItem = xbmcgui.ListItem(label = songartist + " - " + songalbum + " - " + songname, iconImage=songImg, thumbnailImage=songThm, path=songurl)
-        songItem.setInfo( type="Music", infoLabels={ "title": songname, "duration": songduration, "album": songalbum, "artist": songartist} )
-        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)
-        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+")"))
-        songItem.addContextMenuItems(menuItems, replaceItems=False)
-        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=songItem,isFolder=False)
-        return songItem
-      
-    def _add_next(self, stop=0):
-        print "_add_next " + str(stop)
-        if stop == 1:
-            groovesharkApi.radioEnabled = False
-            self.playlist.clear()
-        elif groovesharkApi.radioTurnedOn() == True:
-            next = self._get_next()
-            self.playlist.add(url, next)
       
     def _add_dir(self, name, url, mode, iconimage, id):
         u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&id="+str(id)
@@ -410,7 +407,19 @@ class Groveshark:
         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):
+        print "onPlayBackChanged " + str(change)
+        if change == 0:
+            groovesharkApi.radioEnabled = False
+            self.musicplaylist.clear()
+        if change == 1 and groovesharkApi.radioTurnedOn() == True:
+            print "playnext"
+            self.player.playNext()
+        if change == 1 and groovesharkApi.radioTurnedOn() == False:
+            print "clear playlist"
+            self.musicplaylist.clear()
+
    
 def get_params():
     param=[]
@@ -484,7 +493,7 @@ elif mode==MODE_SONG:
     except: pass
     try: image=urllib.unquote_plus(params["image"])
     except: pass
-    song = grooveshark.songItem(url, name, album, artist, duration, thumb, image)
+    song = grooveshark.songItem(id, name, album, artist, duration, thumb, image)
     grooveshark.playSong(song)
 
 elif mode==MODE_ARTIST: