Fix Windows https issue.
[clinton/xbmc-groove.git] / resources / lib / GroovesharkAPI.py
index 2f8f340..9a91245 100644 (file)
@@ -1,7 +1,11 @@
-import socket, hmac, urllib2, pprint, md5, os, pickle, tempfile, time, re, groovesharkAccess
+import socket, urllib, urllib2, pprint, md5, os, pickle, tempfile, time, re, simplejson, base64
+from blowfish import Blowfish
 
 SESSION_EXPIRY = 1209600 # 2 weeks
 
+# Web app
+WEB_APP_URL = "http://xbmc-groove.appspot.com/"
+
 # GrooveAPI constants
 THUMB_URL = 'http://beta.grooveshark.com/static/amazonart/m'
 SONG_LIMIT = 25
@@ -19,13 +23,12 @@ class GrooveAPI:
        _lastSessionTime = 0
        _lastStreamKey = ''
        _lastStreamServerID = ''
+       _key = md5.new(os.path.basename("GroovesharkAPI.py")).hexdigest()
 
        # Constructor
        def __init__(self):
                
-               import simplejson
                self.simplejson = simplejson
-               socket.setdefaulttimeout(40)
                self.cacheDir = os.path.join(tempfile.gettempdir(), 'groovesharkapi')
                if os.path.isdir(self.cacheDir) == False:
                        os.makedirs(self.cacheDir)
@@ -34,25 +37,69 @@ class GrooveAPI:
                # session ids last 2 weeks
                if self._sessionID == '' or time.time()- self._lastSessionTime >= SESSION_EXPIRY:
                        self._sessionID = self._getSessionID()
-                       self._ip = self._getIP()
-                       self._country = self._getCountry()
                        if self._sessionID == '':
                                raise StandardError('Failed to get session id')
                        else:
                                print "New GrooveAPI session id: " + self._sessionID
+                               self._ip = self._getIP()
+                               self._country = self._getCountry()
                                self._setSavedSession()
 
        # Call to API
        def _callRemote(self, method, params):
-               self._setParams(params)
-               return groovesharkAccess.callRemote(method, self._sessionID)
+               try:
+                       res = self._getRemote(method, params)
+                       url = res['url']
+                       postData = res['postData']
+               except:
+                       print "Failed to get request URL and post data"
+                       return []
+               try:
+                       req = urllib2.Request(url, postData)
+                       response = urllib2.urlopen(req)
+                       result = response.read()
+                       print "Response..."
+                       pprint.pprint(result)
+                       response.close()
+                       result = simplejson.loads(result)
+                       return result
+               except urllib2.HTTPError, e:
+                       print "HTTP error " + e.code
+               except urllib2.URLError, e:
+                       print "URL error " + e.reason
+               except:
+                       print "Request to Grooveshark API failed"
+                       return []       
+
+
+       # Get the API call
+       def _getRemote(self, method, params = {}):
+               postData = { "method": method, "sessionid": self._sessionID, "parameters": params }
+               postData = simplejson.dumps(postData)
                
+               cipher = Blowfish(self._key)
+               cipher.initCTR()
+               encryptedPostData = cipher.encryptCTR(postData)
+               encryptedPostData = base64.urlsafe_b64encode(encryptedPostData)
+               url = WEB_APP_URL + "?postData=" + encryptedPostData
+               req = urllib2.Request(url)
+               response = urllib2.urlopen(req)
+               result = response.read()
+               print "Request..."
+               pprint.pprint(result)
+               response.close()
+               try:
+                       result = simplejson.loads(result)
+                       return result
+               except:
+                       return []               
+
        # Get a session id
        def _getSessionID(self):
                params = {}
                result = self._callRemote('startSession', params)
-               self._lastSessionTime = time.time()
                if 'result' in result:
+                       self._lastSessionTime = time.time()
                        return result['result']['sessionID']
                else:
                        return ''
@@ -133,7 +180,10 @@ class GrooveAPI:
                params = {'login': login, 'password': md5pwd}
                
                result = self._callRemote('authenticate', params)
-               uid = result['result']['UserID']
+               try:
+                       uid = result['result']['UserID']
+               except:
+                       uid = 0
                if (uid > 0):
                        return uid
                else:
@@ -474,34 +524,3 @@ class GrooveAPI:
                        list.append([str(s['PlaylistName']).encode('ascii', 'ignore'), s['PlaylistID']])
                        i = i + 1
                return list
-
-# Test
-#import sys
-#res = []
-#groovesharkApi = GrooveAPI()
-#res = groovesharkApi.pingService()
-#res = groovesharkApi.login(sys.argv[1], sys.argv[2])
-#songIds = []
-#songIds.append('28645456')
-#songIds.append('26579347')
-#res=groovesharkApi.playlistRename(58197714, 'renamed playlist2')
-#res = groovesharkApi.createPlaylist("Test", songIDs)
-#res = groovesharkApi.setPlaylistSongs('58197714',songIds)
-#pprint.pprint(res)
-#res = groovesharkApi.getPlaylistSongs('58197714')
-#res = groovesharkApi.getSongSearchResults('jimmy jazz', 3)
-#res = groovesharkApi.getPopularSongsToday(3)
-#res = groovesharkApi.getSongURLFromSongID('26579347')
-#res = groovesharkApi.getAlbumSearchResults('london calling', 3)
-#res = groovesharkApi.getArtistAlbums('52283')
-#res = groovesharkApi.getArtistSearchResults('the clash', 3)
-#res = groovesharkApi.getUserFavoriteSongs()
-#res = groovesharkApi.getUserPlaylists()
-#res = groovesharkApi.getSongInfos('27425375')
-#res = groovesharkApi.getPlaylistSongs(40902662)
-#res = groovesharkApi.addUserFavoriteSong('27425375')
-#res = groovesharkApi.logout()
-#res = groovesharkApi.getUserPlaylistsByUsername('stephendenham')
-#res = groovesharkApi.getArtistPopularSongs('3707')
-#
-#pprint.pprint(res)