don't check isVerified flag when adding albums to directory
[clinton/xbmc-groove.git] / default.py
index c2cd794..a750f09 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')
@@ -26,6 +26,7 @@ __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
@@ -76,6 +79,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'))
 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(xbmc.translatePath('special://masterprofile/addon_data/'), os.path.basename(baseDir), thumbDirName)
 
@@ -99,10 +103,14 @@ else:
     __debugging__ = False
 
 try:
-    groovesharkApi = GrooveAPI(__debugging__)
+    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(__language__(30008),__language__(30009))
     sys.exit(-1)
@@ -144,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
@@ -349,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 __debugging__ :
                     xbmc.log("Found " + artist[0] + "...")
                 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()
@@ -440,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, True)
+        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):
@@ -452,30 +468,38 @@ 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 __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
@@ -523,7 +547,7 @@ class Grooveshark:
     def songItem(self, songid, name, album, artist, coverart, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL, tracknumber=1):
         
         stream = self._getSongStream(songid)
-        if stream != False:
+        if stream != None:
             duration = stream[1]
             url = stream[2]
             key = stream[3]
@@ -546,9 +570,10 @@ class Grooveshark:
             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 song URL")
+            xbmc.log("No access to song URL")
             return None
     
     # Next page of songs
@@ -707,8 +732,7 @@ class Grooveshark:
             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:
@@ -722,8 +746,12 @@ class Grooveshark:
             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'
@@ -813,13 +841,11 @@ class Grooveshark:
         while i < n:
             album = albums[i]
             albumID = album[3]
-            if isverified or groovesharkApi.getDoesAlbumExist(albumID):                    
-                albumArtistName = album[0]
-                albumName = album[2]
-                albumImage = self._get_icon(album[4], 'album-' + str(albumID))
-                self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID, itemsExisting)
-            else:
-                itemsExisting = itemsExisting - 1
+
+            albumArtistName = album[0]
+            albumName = album[2]
+            albumImage = self._get_icon(album[4], 'album-' + str(albumID))
+            self._add_dir(albumName + " - " + albumArtistName, '', MODE_ALBUM, albumImage, albumID, itemsExisting)
             i = i + 1
         # Not supported by key
         #if artistid > 0:
@@ -838,11 +864,8 @@ class Grooveshark:
         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)
@@ -873,6 +896,7 @@ class Grooveshark:
             u = url
         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 = []
@@ -922,21 +946,22 @@ class Grooveshark:
     def _getSongStream(self, songid):
         idSong = int(songid)
         stream = None
-        streams = []
+        streams = {}
         path = os.path.join(cacheDir, 'streams.dmp')
         try:
             f = open(path, 'rb')
             streams = pickle.load(f)
-            for song in streams:
-                if song[0] == idSong:
-                    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")
-                    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
@@ -956,7 +981,7 @@ class Grooveshark:
         
     def _addSongStream(self, stream):
         streams = self._getStreams()           
-        streams.append(stream)                
+        streams[int(stream[0])] = stream
         path = os.path.join(cacheDir, 'streams.dmp')
         try:
             f = open(path, 'wb')
@@ -972,21 +997,17 @@ class Grooveshark:
         stream[1] = self._setDuration(stream[1])
         streams = self._getStreams()
         path = os.path.join(cacheDir, 'streams.dmp')
-        i = 0
 
-        for song in streams:
-            if song[0] == idStream:
-                streams[i] = stream
-                try:
-                    f = open(path, 'wb')
-                    pickle.dump(streams, f, protocol=pickle.HIGHEST_PROTOCOL)
-                    f.close()
-                    if __debugging__ :
-                        xbmc.log("Updated " + str(idStream) + " in stream cache")
-                    break;
-                except:
-                    xbmc.log("An error occurred setting stream")                    
-            i = i + 1
+        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')
@@ -995,7 +1016,7 @@ class Grooveshark:
             streams = pickle.load(f)
             f.close()
         except:
-            streams = []
+            streams = {}
             pass
         return streams
 
@@ -1057,7 +1078,7 @@ elif mode==MODE_POPULAR_SONGS:
     grooveshark.popularSongs()
     
 elif mode==MODE_ARTIST_POPULAR:
-    grooveshark.artistPopularSongs()
+    grooveshark.searchArtistPopularSongs()
 
 elif mode==MODE_FAVORITES:
     grooveshark.favorites()
@@ -1119,6 +1140,9 @@ elif mode==MODE_REMOVE_PLAYLIST_SONG:
 
 elif mode==MODE_ADD_PLAYLIST_SONG:
     grooveshark.addPlaylistSong(itemId)        
+
+elif mode==MODE_ARTIST_POPULAR_FROM_ALBUMS:
+    grooveshark.artistPopularSongs(itemId)
     
 if mode < MODE_SONG:
     xbmcplugin.endOfDirectory(int(sys.argv[1]))