Fixes and tidy up.
authorstephendenham <stephendenham@2dec19e3-eb1d-4749-8193-008c8bba0994>
Sun, 2 Oct 2011 15:21:47 +0000 (15:21 +0000)
committerstephendenham <stephendenham@2dec19e3-eb1d-4749-8193-008c8bba0994>
Sun, 2 Oct 2011 15:21:47 +0000 (15:21 +0000)
git-svn-id: svn://svn.code.sf.net/p/xbmc-groove/code@61 2dec19e3-eb1d-4749-8193-008c8bba0994

default.py
resources/lib/GroovesharkAPI.py

index 50c904b..8f68fa5 100644 (file)
@@ -24,7 +24,7 @@ __cwd__       = __addon__.getAddonInfo('path')
 __author__    = __addon__.getAddonInfo('author')
 __version__   = __addon__.getAddonInfo('version')
 __language__  = __addon__.getLocalizedString
-
+__debuggui__  = __addon__.getSetting('debug')
 
 MODE_SEARCH_SONGS = 1
 MODE_SEARCH_ALBUMS = 2
@@ -63,8 +63,12 @@ NAME_ALBUM_ARTIST_LABEL = 1
 
 # Stream marking time (seconds)
 STREAM_MARKING_TIME = 30
+
+# Timeout
+STREAM_TIMEOUT = 30
+
 # Retry URL
-STREAM_RETRY = 10
+STREAM_RETRY = STREAM_TIMEOUT/2
 
 songMarkTime = 0
 player = xbmc.Player()
@@ -94,6 +98,7 @@ from threading import Event, Thread
 
 try:
     groovesharkApi = GrooveAPI()
+    groovesharkApi.setDebug(__debuggui__)
     if groovesharkApi.pingService() != True:
         raise StandardError(__language__(30007))
 except:
@@ -248,15 +253,14 @@ class Grooveshark:
     
     def __init__( self ):
         self._handle = int(sys.argv[1])
-        self.setDebug()
         if os.path.isdir(cacheDir) == False:
             os.makedirs(cacheDir)
-            if self.debug:
+            if __debuggui__:
                 xbmc.log(__language__(30012) + " " + cacheDir)
         artDir = xbmc.translatePath(thumbDir)
         if os.path.isdir(artDir) == False:
             os.makedirs(artDir)
-            if self.debug:
+            if __debuggui__:
                 xbmc.log(__language__(30012) + " " + artDir)
             
     # Top-level menu
@@ -346,7 +350,7 @@ class Grooveshark:
             if (len(artists) > 0):
                 artist = artists[0]
                 artistID = artist[1]
-                if self.debug:
+                if __debuggui__:
                     xbmc.log("Found " + artist[0] + "...")
                 albums = groovesharkApi.getArtistAlbums(artistID, limit = self.albumsearchlimit)
                 if (len(albums) > 0):
@@ -403,7 +407,7 @@ class Grooveshark:
     def favorite(self, songid):
         userid = self._get_login()
         if (userid != 0):
-            if self.debug:
+            if __debuggui__:
                 xbmc.log("Favorite song: " + str(songid))
             groovesharkApi.addUserFavoriteSong(songID = songid)
             xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30036) + ', 1000, ' + thumbDef + ')')
@@ -415,7 +419,7 @@ class Grooveshark:
     def unfavorite(self, songid, prevMode=0):
         userid = self._get_login()
         if (userid != 0):
-            if self.debug:
+            if __debuggui__:
                 xbmc.log("Unfavorite song: " + str(songid) + ', previous mode was ' + str(prevMode))
             groovesharkApi.removeUserFavoriteSongs(songIDs = songid)
             xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30038) + ', 1000, ' + thumbDef + ')')
@@ -455,7 +459,7 @@ class Grooveshark:
             if (len(artists) > 0):
                 artist = artists[0]
                 artistID = artist[1]
-                if self.debug:
+                if __debuggui__:
                     xbmc.log("Found " + artist[0] + "...")
                 songs = groovesharkApi.getArtistPopularSongs(artistID, limit = self.songsearchlimit)
                 if (len(songs) > 0):
@@ -476,18 +480,10 @@ class Grooveshark:
         global playTimer
         global player
         if item != None:
-            songid = item.getProperty('songid')
-            url = item.getProperty('url')
-            if url == '':
-                stream = groovesharkApi.getSubscriberStreamKey(songid)
-                url = stream['url']
-            item.setPath(url)
-            if self.debug:
-                xbmc.log("Grooveshark playing: " + url)
-            xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
-            # Wait for play then start time
+            songid = self._setItem(item)
+            # Wait for play then start timer
             seconds = 0
-            while seconds < STREAM_MARKING_TIME:
+            while seconds < STREAM_TIMEOUT:
                 try:
                     if player.isPlayingAudio() == True:
                         if playTimer != None:
@@ -500,11 +496,12 @@ class Grooveshark:
                 except: pass
                 time.sleep(1)
                 seconds = seconds + 1
+                # If not playing after a few seconds try to refresh the URL
                 if (seconds == STREAM_RETRY):
-                    stream = groovesharkApi.getSubscriberStreamKey(songid)
-                    url = stream['url']
-                    item.setPath(url)
-                    xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
+                    item.setProperty('url', '')
+                    self._setItem(item)
+                    self._setSongStream(songid, item.getProperty('duration'), item.getProperty('url'))
         else:
             xbmc.executebuiltin('XBMC.Notification(' + __language__(30008) + ', ' + __language__(30044) + ', 1000, ' + thumbDef + ')')
         
@@ -619,7 +616,7 @@ class Grooveshark:
                     else:
                         playlist = playlists[i]
                         playlistid = playlist[1]
-                        if self.debug:
+                        if __debuggui__:
                             xbmc.log("Add song " + str(songid) + " to playlist " + str(playlistid))
                         songIDs=[]
                         songs = groovesharkApi.getPlaylistSongs(playlistid)
@@ -673,16 +670,6 @@ class Grooveshark:
             dialog.ok(__language__(30008), __language__(30068))
             self.categories()
     
-    # Debug
-    def setDebug(self):
-        self.debug = self.settings.getSetting('debug')
-        if self.debug:
-            xbmc.log("Debug is on")
-
-    # Debug
-    def getDebug(self):
-        return self.debug
-        
     # Get keyboard input
     def _get_keyboard(self, default="", heading="", hidden=False):
         kb = xbmc.Keyboard(default, heading, hidden)
@@ -730,6 +717,19 @@ class Grooveshark:
         else:
             return thumbDef
     
+    # Set URL
+    def _setItem(self, item):
+        url = item.getProperty('url')
+        songid = item.getProperty('songid')
+        if url == '':
+            stream = groovesharkApi.getSubscriberStreamKey(songid)
+            url = stream['url']
+        item.setPath(url)
+        xbmcplugin.setResolvedUrl(handle=int(sys.argv[1]), succeeded=True, listitem=item)
+        if __debuggui__:
+            xbmc.log("Grooveshark playing: " + songid)
+        return songid
+
     # Add songs to directory
     def _add_songs_directory(self, songs, trackLabelFormat=ARTIST_ALBUM_NAME_LABEL, offset=0, playlistid=0, playlistname='', isFavorites=False):
 
@@ -740,7 +740,7 @@ class Grooveshark:
 
         # No pages needed
         if offset == 0 and totalSongs <= self.songspagelimit:
-            if self.debug:
+            if __debuggui__:
                 xbmc.log("Found " + str(totalSongs) + " songs...")
         # Pages
         else:
@@ -791,7 +791,7 @@ class Grooveshark:
                 id = id + 1
             else:
                 end = min(end + 1,totalSongs)
-                if self.debug:
+                if __debuggui__:
                     xbmc.log(song[0] + " does not exist.")
             n = n + 1
 
@@ -806,7 +806,7 @@ class Grooveshark:
     def _add_albums_directory(self, albums, artistid=0):
         n = len(albums)
         itemsExisting = n
-        if self.debug:
+        if __debuggui__:
             xbmc.log("Found " + str(n) + " albums...")
         i = 0
         while i < n:
@@ -831,7 +831,7 @@ class Grooveshark:
     def _add_artists_directory(self, artists):
         n = len(artists)
         itemsExisting = n
-        if self.debug:
+        if __debuggui__:
             xbmc.log("Found " + str(n) + " artists...")
         i = 0
         while i < n:
@@ -850,7 +850,7 @@ class Grooveshark:
     # Add playlists to directory          
     def _add_playlists_directory(self, playlists):
         n = len(playlists)
-        if self.debug:
+        if __debuggui__:
             xbmc.log("Found " + str(n) + " playlists...")
         i = 0
         while i < n:
@@ -930,6 +930,7 @@ class Grooveshark:
         except:
             pass
 
+        # Not in cache but exists
         if duration < 0 and groovesharkApi.getDoesSongExist(songid):
             stream = groovesharkApi.getSubscriberStreamKey(songid)
             url = stream['url']
@@ -939,13 +940,29 @@ class Grooveshark:
             duration = usecs / 1000000
             song = [id, duration, url]
             streams.append(song)                
-            self._setSongStream(streams)
+            self._setSongStreams(streams)
 
         return {'duration':duration, 'url':url}
+
+    def _setSongStream(self, songid, duration, url):            
+        path = os.path.join(cacheDir, 'streams.dmp')
+        try:
+            f = open(path, 'rb')
+            streams = pickle.load(f)
+            for song in streams:
+                if song[0] == songid:
+                    song[1] = duration
+                    song[2] = url
+                    self._setSongStreams(streams)
+                    break;
+            f.close()
+        except:
+            xbmc.log("An error occurred saving stream")
+            pass
         
-    def _setSongStream(self, streams):            
+    def _setSongStreams(self, streams):            
         try:
-            # Create the 'data' directory if it doesn't exist.
+            # Create the cache directory if it doesn't exist.
             if not os.path.exists(cacheDir):
                 os.makedirs(cacheDir)
             path = os.path.join(cacheDir, 'streams.dmp')
@@ -961,7 +978,7 @@ class Grooveshark:
 def get_params():
     param=[]
     paramstring=sys.argv[2]
-    if grooveshark.getDebug():
+    if __debuggui__:
         xbmc.log(paramstring)
     if len(paramstring)>=2:
         params=sys.argv[2]
@@ -979,8 +996,6 @@ def get_params():
         
 # Main
 grooveshark = Grooveshark();
-grooveshark.setDebug()
-groovesharkApi.setDebug(grooveshark.getDebug())
 
 params=get_params()
 mode=None
index 767c0fb..64e2504 100644 (file)
@@ -158,19 +158,6 @@ class GrooveAPI:
                except:
                        print "An error occurred during save session"
                        pass
-
-       def _setParams(self, params):                   
-               try:
-                       # Create the directory if it doesn't exist.
-                       if not os.path.exists(self.cacheDir):
-                               os.makedirs(self.cacheDir)
-                       path = os.path.join(self.cacheDir, 'params.dmp')
-                       f = open(path, 'wb')
-                       pickle.dump(params, f, protocol=pickle.HIGHEST_PROTOCOL)
-                       f.close()
-               except:
-                       print "An error occurred during save params"
-                       pass
        
        # Get IP
        def _getIP(self):