Some playlist updates.
[clinton/xbmc-groove.git] / default.py
index 6688267..06d8133 100644 (file)
@@ -16,8 +16,7 @@ MODE_UNFAVORITE = 13
 MODE_MAKE_PLAYLIST = 14
 MODE_REMOVE_PLAYLIST = 15
 MODE_RENAME_PLAYLIST = 16
-
-lastID = 0
+MODE_REMOVE_PLAYLIST_SONG = 17
 
 baseDir = os.getcwd()
 resDir = xbmc.translatePath(os.path.join(baseDir, 'resources'))
@@ -25,6 +24,13 @@ 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'))
 
+baseModeUrl = 'plugin://plugin.audio.groove/'
+playlistUrl = baseModeUrl + '?url=&mode=' + str(MODE_PLAYLIST)
+playlistsUrl = baseModeUrl + '?mode=' + str(MODE_PLAYLISTS)
+favoritesUrl = baseModeUrl + '?mode=' + str(MODE_FAVORITES)
+
+thumbDef = os.path.join(os.path.basename(os.getcwd()), 'default.tbn')
+
 sys.path.append (libDir)
 from GrooveAPI import *
 groovesharkApi = GrooveAPI()
@@ -50,7 +56,7 @@ class Groveshark:
     artistsearchlimit = settings.getSetting('artistsearchlimit')
     username = settings.getSetting('username')
     password = settings.getSetting('password')
-
+    
     def __init__( self ):
         self._handle = int(sys.argv[1])
 
@@ -61,7 +67,6 @@ class Groveshark:
         userid = self._get_login()
         
         # Setup
-        groovesharkApi.setRemoveDuplicates(True)
         xbmcplugin.setPluginFanart(int(sys.argv[1]), self.fanImg)
         if os.path.isdir(thumbDir) == False:
             os.makedirs(thumbDir)
@@ -76,7 +81,8 @@ class Groveshark:
             
     def searchSongs(self):
         query = self._get_keyboard(default="", heading="Search songs")
-        if (query): 
+        if (query):
+            groovesharkApi.setRemoveDuplicates(True)
             songs = groovesharkApi.searchSongs(query, limit = self.songsearchlimit)
             if (len(songs) > 0):
                 self._add_songs_directory(songs)
@@ -112,7 +118,7 @@ class Groveshark:
         if (userid != 0):
             favorites = groovesharkApi.userGetFavoriteSongs(userid)
             if (len(favorites) > 0):
-                self._add_songs_directory(favorites)
+                self._add_songs_directory(favorites, isFavorites=True)
             else:
                 dialog = xbmcgui.Dialog()
                 dialog.ok('Grooveshark', 'You have no favorites.')
@@ -161,15 +167,19 @@ class Groveshark:
         if (userid != 0):
             xbmc.log("Favorite song: " + str(songid))
             groovesharkApi.favoriteSong(songID = songid)
+            xbmc.executebuiltin('XBMC.Notification(Grooveshark, Added to favorites, 1000, ' + thumbDef + ')')
         else:
             dialog = xbmcgui.Dialog()
             dialog.ok('Grooveshark', 'You must be logged in', 'to add favorites.')
     
-    def unfavorite(self, songid):
+    def unfavorite(self, songid, prevMode):
         userid = self._get_login()
         if (userid != 0):
-            xbmc.log("Unfavorite song: " + str(songid))
+            xbmc.log("Unfavorite song: " + str(songid) + ', previous mode was ' + str(prevMode))
             groovesharkApi.unfavoriteSong(songID = songid)
+            xbmc.executebuiltin('XBMC.Notification(Grooveshark, Removed from favorites, 1000, ' + thumbDef + ')')
+            if (int(prevMode) == MODE_FAVORITES):
+                xbmc.executebuiltin("Container.Update(" + favoritesUrl + ",replace)")
         else:
             dialog = xbmcgui.Dialog()
             dialog.ok('Grooveshark', 'You must be logged in', 'to remove favorites.')
@@ -180,6 +190,8 @@ class Groveshark:
             xbmc.log("Frown song: " + str(songid))
             if groovesharkApi.radioFrown(songId = songid) != True:
                 xbmc.log("Unable to frown song " + str(songid))
+            else:
+                xbmc.executebuiltin('XBMC.Notification(Grooveshark, Frowned, 1000, ' + thumbDef + ')')
         else:
             dialog = xbmcgui.Dialog()
             dialog.ok('Grooveshark', 'You must be logged in', 'to frown a song.')
@@ -196,17 +208,21 @@ class Groveshark:
     def makePlaylist(self, albumid, name):
         userid = self._get_login()
         if (userid != 0):
-            name_re = re.compile(r'[- ]')
-            nameTokens = name_re.split("- ")
-            name = self._get_keyboard(default=nameTokens[1], heading="Playlist name")
-            album = groovesharkApi.albumGetSongs(albumid, self.songsearchlimit)
-            songids = []
-            for song in album:
-                songids.append(song[1])
-            id = groovesharkApi.playlistCreateUnique(name, songids)
-            if id == 0:
-                dialog = xbmcgui.Dialog()
-                dialog.ok('Grooveshark', 'Cannot create playlist ', name)
+            re.split(' - ',name,1)
+            nameTokens = re.split(' - ',name,1)
+            name = self._get_keyboard(default=nameTokens[0], heading="Playlist name")
+            if name != '':
+                groovesharkApi.setRemoveDuplicates(True)
+                album = groovesharkApi.albumGetSongs(albumid, self.songsearchlimit)
+                songids = []
+                for song in album:
+                    songids.append(song[1])
+                id = groovesharkApi.playlistCreateUnique(name, songids)
+                if id == 0:
+                    dialog = xbmcgui.Dialog()
+                    dialog.ok('Grooveshark', 'Cannot create playlist ', name)
+                else:
+                    xbmc.executebuiltin('XBMC.Notification(Grooveshark, Playlist created, 1000, ' + thumbDef + ')')
         else:
             dialog = xbmcgui.Dialog()
             dialog.ok('Grooveshark', 'You must be logged in ', ' to create a playlist.')
@@ -217,16 +233,32 @@ class Groveshark:
             userid = self._get_login()
             if (userid != 0):
                 groovesharkApi.playlistDelete(playlistid)
-                xbmc.executebuiltin("Container.Refresh")
+                xbmc.executebuiltin("Container.Update(" + playlistsUrl + ",replace)")
             else:
                 dialog = xbmcgui.Dialog()
                 dialog.ok('Grooveshark', 'You must be logged in ', ' to delete a playlist.')
 
+    def removePlaylistSong(self, playlistid, playlistname, songpos):
+        dialog = xbmcgui.Dialog()
+        if dialog.yesno('Grooveshark', 'Delete this song from the playlist?') == True:
+            userid = self._get_login()
+            if (userid != 0):
+                if groovesharkApi.playlistDeleteSong(playlistid, songpos) == 0:
+                    dialog = xbmcgui.Dialog()
+                    dialog.ok('Grooveshark', 'Failed to remove ', ' song from playlist.')
+                else:
+                    xbmc.executebuiltin("Container.Update(" + playlistUrl + "&id="+str(playlistid) + "&name=" + playlistname + ",replace)")
+            else:
+                dialog = xbmcgui.Dialog()
+                dialog.ok('Grooveshark', 'You must be logged in ', ' to delete a song from a playlist.')
+
     def renamePlaylist(self, playlistid, name):
         userid = self._get_login()
         if (userid != 0):
             newname = self._get_keyboard(default=name, heading="Playlist name")
-            if groovesharkApi.playlistRename(playlistid, newname) == 0:
+            if newname == '':
+                return
+            elif groovesharkApi.playlistRename(playlistid, newname) == 0:
                 dialog = xbmcgui.Dialog()
                 dialog.ok('Grooveshark', 'Cannot rename playlist ', name)
             else:
@@ -236,6 +268,7 @@ class Groveshark:
             dialog.ok('Grooveshark', 'You must be logged in ', ' to rename a playlist.')
     
     def album(self, albumid):
+        groovesharkApi.setRemoveDuplicates(True)
         album = groovesharkApi.albumGetSongs(albumId = albumid, limit = self.songsearchlimit)
         self._add_songs_directory(album)
     
@@ -243,11 +276,11 @@ class Groveshark:
         albums = groovesharkApi.artistGetAlbums(artistId = artistid, limit = self.albumsearchlimit)
         self._add_albums_directory(albums, artistid)
     
-    def playlist(self, playlistid):
+    def playlist(self, playlistid, playlistname):
         userid = self._get_login()
         if (userid != 0):
             songs = groovesharkApi.playlistGetSongs(playlistId = playlistid, limit = self.songsearchlimit)
-            self._add_songs_directory(songs)
+            self._add_songs_directory(songs, playlistid, playlistname)
         else:
             dialog = xbmcgui.Dialog()
             dialog.ok('Grooveshark', 'You must be logged in', 'to get playlists.')
@@ -277,11 +310,11 @@ class Groveshark:
         return item
     
     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 ''
     
     def _get_login(self):
         if (self.username == "" or self.password == ""):
@@ -324,7 +357,7 @@ class Groveshark:
 
         return os.path.join(os.path.join(thumbDir, str(id))) + '.tbn'
         
-    def _add_songs_directory(self, songs):
+    def _add_songs_directory(self, songs, playlistid=0, playlistname='', isFavorites=False):
         n = len(songs)
         xbmc.log("Found " + str(n) + " songs...")
         i = 0
@@ -348,10 +381,16 @@ class Groveshark:
             +"&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)
+            unfav=sys.argv[0]+"?url="+urllib.quote_plus(songurl)+"&mode="+str(MODE_UNFAVORITE)+"&name="+urllib.quote_plus(songname)+"&id="+str(songid)+"&prevmode="
             menuItems = []
-            menuItems.append(("Grooveshark Favorite", "XBMC.RunPlugin("+fav+")"))
+            if isFavorites == True:
+                unfav = unfav +str(MODE_FAVORITES)
+            else:
+                menuItems.append(("Grooveshark Favorite", "XBMC.RunPlugin("+fav+")"))
             menuItems.append(("Not Grooveshark Favorite", "XBMC.RunPlugin("+unfav+")"))
+            if playlistid > 0:
+                rmplaylstsong=sys.argv[0]+"?playlistid="+str(playlistid)+"&id="+str(i+1)+"&mode="+str(MODE_REMOVE_PLAYLIST_SONG)+"&name="+playlistname
+                menuItems.append(("Remove from playlist", "XBMC.RunPlugin("+rmplaylstsong+")"))
             item.addContextMenuItems(menuItems, replaceItems=False)
             xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=item,isFolder=False,totalItems=n)
             i = i + 1
@@ -458,9 +497,6 @@ except: pass
 try: id=int(params["id"])
 except: pass
 
-if (id > 0):
-    lastID = id
-
 if mode==None:
     grooveshark.categories()
        
@@ -483,8 +519,6 @@ elif mode==MODE_FAVORITES:
     grooveshark.favorites()
 
 elif mode==MODE_SONG:
-    try: name=urllib.unquote_plus(params["name"])
-    except: pass
     try: album=urllib.unquote_plus(params["album"])
     except: pass
     try: artist=urllib.unquote_plus(params["artist"])
@@ -499,32 +533,38 @@ elif mode==MODE_SONG:
     grooveshark.playSong(song)
 
 elif mode==MODE_ARTIST:
-    grooveshark.artist(lastID)
+    grooveshark.artist(id)
     
 elif mode==MODE_ALBUM:
-    grooveshark.album(lastID)
+    grooveshark.album(id)
     
 elif mode==MODE_PLAYLIST:
-    grooveshark.playlist(lastID)
+    grooveshark.playlist(id, name)
     
 elif mode==MODE_FAVORITE:
-    grooveshark.favorite(lastID)
+    grooveshark.favorite(id)
 
 elif mode==MODE_UNFAVORITE:
-    grooveshark.unfavorite(lastID)
+    try: prevMode=urllib.unquote_plus(params["prevmode"])
+    except: pass
+    grooveshark.unfavorite(id, prevMode)
 
 elif mode==MODE_SIMILAR_ARTISTS:
-    grooveshark.similarArtists(lastID)
+    grooveshark.similarArtists(id)
 
 elif mode==MODE_MAKE_PLAYLIST:
-    grooveshark.makePlaylist(lastID, name)
+    grooveshark.makePlaylist(id, name)
     
 elif mode==MODE_REMOVE_PLAYLIST:
-    grooveshark.removePlaylist(lastID, name)    
+    grooveshark.removePlaylist(id, name)    
 
 elif mode==MODE_RENAME_PLAYLIST:
-    grooveshark.renamePlaylist(lastID, name)    
+    grooveshark.renamePlaylist(id, name)    
 
+elif mode==MODE_REMOVE_PLAYLIST_SONG:
+    try: playlistID=urllib.unquote_plus(params["playlistid"])
+    except: pass
+    grooveshark.removePlaylistSong(playlistID, name, id)
 
 if (mode < MODE_SONG):    
     xbmcplugin.endOfDirectory(int(sys.argv[1]))