X-Git-Url: https://git.hcoop.net/clinton/xbmc-groove.git/blobdiff_plain/5e72534b4750dd1670b8e2940d408eef46a5fe4e..37e2f75d223428fa6e6cc05f0705612218d42869:/resources/lib/GroovesharkAPI.py diff --git a/resources/lib/GroovesharkAPI.py b/resources/lib/GroovesharkAPI.py index 767c0fb..a911570 100644 --- a/resources/lib/GroovesharkAPI.py +++ b/resources/lib/GroovesharkAPI.py @@ -15,7 +15,7 @@ # You should have received a copy of the GNU General Public License # along with xbmc-groove. If not, see . -import urllib2, pprint, md5, os, pickle, tempfile, time, re, simplejson, base64 +import urllib2, pprint, os, pickle, time, re, simplejson, base64, sys, socket, hashlib from blowfish import Blowfish SESSION_EXPIRY = 1209600 # 2 weeks @@ -38,19 +38,21 @@ class GrooveAPI: _sessionID = '' _userID = 0 _lastSessionTime = 0 - _lastStreamKey = '' - _lastStreamServerID = '' - _key = md5.new(os.path.basename("GroovesharkAPI.py")).hexdigest() - _apiDebug = False + _key = hashlib.md5(os.path.basename("GroovesharkAPI.py")).hexdigest() + _debugging = False # Constructor - def __init__(self): + def __init__(self, debug, tempDir): + self._debugging = debug self.simplejson = simplejson - self.cacheDir = os.path.join(tempfile.gettempdir(), 'groovesharkapi') + if "linux" in sys.platform.lower(): + socket.setdefaulttimeout(30) + + self.cacheDir = tempDir if os.path.isdir(self.cacheDir) == False: os.makedirs(self.cacheDir) - if self._apiDebug: + if self._debugging: print "Made " + self.cacheDir self._getSavedSession() # session ids last 2 weeks @@ -59,11 +61,12 @@ class GrooveAPI: if self._sessionID == '': raise StandardError('Failed to get session id') else: - if self._apiDebug: + if self._debugging: print "New GrooveAPI session id: " + self._sessionID self._ip = self._getIP() self._country = self._getCountry() self._setSavedSession() + self.logout() # Call to API def _callRemote(self, method, params): @@ -78,7 +81,7 @@ class GrooveAPI: req = urllib2.Request(url, postData) response = urllib2.urlopen(req) result = response.read() - if self._apiDebug: + if self._debugging: print "Response..." pprint.pprint(result) response.close() @@ -106,7 +109,7 @@ class GrooveAPI: req = urllib2.Request(url) response = urllib2.urlopen(req) result = response.read() - if self._apiDebug: + if self._debugging: print "Request..." pprint.pprint(result) response.close() @@ -127,7 +130,7 @@ class GrooveAPI: return '' def _getSavedSession(self): - path = os.path.join(self.cacheDir, 'session.dmp') + path = os.path.join(self.cacheDir, 'groovesharksession.dmp') try: f = open(path, 'rb') session = pickle.load(f) @@ -150,7 +153,7 @@ class GrooveAPI: # 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, 'session.dmp') + path = os.path.join(self.cacheDir, 'groovesharksession.dmp') f = open(path, 'wb') session = { 'sessionID' : self._sessionID, 'lastSessionTime' : self._lastSessionTime, 'userID': self._userID, 'ip' : self._ip, 'country' : self._country } pickle.dump(session, f, protocol=pickle.HIGHEST_PROTOCOL) @@ -158,26 +161,13 @@ 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): try: - myip = urllib2.urlopen('http://whatismyip.org').read() + myip = urllib2.urlopen('http://ipecho.net/plain').read() if re.match("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", myip): - if self._apiDebug: + if self._debugging: print "IP is " + myip return myip except: @@ -199,7 +189,7 @@ class GrooveAPI: # Authenticates the user for current API session def _authenticate(self, login, password): - md5pwd = md5.new(password).hexdigest() + md5pwd = hashlib.md5(password).hexdigest() params = {'login': login, 'password': md5pwd} result = self._callRemote('authenticate', params) @@ -239,14 +229,12 @@ class GrooveAPI: self._setSavedSession() return True return False - + # Gets a stream key and host to get song content def getSubscriberStreamKey(self, songID): params = { "songID": songID, "country": self._country } response = self._callRemote("getSubscriberStreamKey", params) try: - self._lastStreamKey = response["result"]["StreamKey"] - self._lastStreamServerID = response["result"]["StreamServerID"] res = response["result"] return res except: @@ -325,7 +313,7 @@ class GrooveAPI: if 'result' in result and 'SongID' in result['result']: info = result['result'] if 'CoverArtFilename' in info and info['CoverArtFilename'] != None: - info['CoverArtFilename'] = THUMB_URL+info['CoverArtFilename'].encode('ascii', 'ignore') + info['CoverArtFilename'] = THUMB_URL+info['CoverArtFilename'].encode('utf8', 'ignore') else: info['CoverArtFilename'] = 'None' return info @@ -410,14 +398,14 @@ class GrooveAPI: items = self._callRemote("getSimilarArtists", {"artistID": artistId, "limit": limit}) if 'result' in items: i = 0 - list = [] + itemList = [] artists = items['result']['artists'] while(i < len(artists)): s = artists[i] - list.append([s['artistName'].encode('ascii', 'ignore'),\ + itemList.append([s['artistName'].encode('utf8', 'ignore'),\ s['artistID']]) i = i + 1 - return list + return itemList else: return [] @@ -443,27 +431,20 @@ class GrooveAPI: return False # After 30s play time - def markStreamKeyOver30Secs(self): - params = { "streamKey" : self._lastStreamKey, "streamServerID" : self._lastStreamServerID } + def markStreamKeyOver30Secs(self, streamKey, streamServerID): + params = { "streamKey" : streamKey, "streamServerID" : streamServerID } self._callRemote("markStreamKeyOver30Secs", params) # Song complete - def markSongComplete(self, songid): - params = { "songID" : songid, "streamKey" : self._lastStreamKey, "streamServerID" : self._lastStreamServerID } + def markSongComplete(self, songid, streamKey, streamServerID): + params = { "songID" : songid, "streamKey" : streamKey, "streamServerID" : streamServerID } self._callRemote("markSongComplete", params) - - # Debug on off - def setDebug(self, state): - self._apiDebug = state - if (self._apiDebug): - print "API debug is on" - # Extract song data def _parseSongs(self, items, limit=0): if 'result' in items: i = 0 - list = [] + itemList = [] index = '' l = -1 try: @@ -501,18 +482,26 @@ class GrooveAPI: info = self.getSongsInfo(s['SongID']) coverart = info['CoverArtFilename'] elif s['CoverArtFilename'] != None: - coverart = THUMB_URL+s['CoverArtFilename'].encode('ascii', 'ignore') + coverart = THUMB_URL+s['CoverArtFilename'].encode('utf8', 'ignore') else: coverart = 'None' - list.append([s['SongName'].encode('ascii', 'ignore'),\ + if 'Name' in s: + name = s['Name'] + else: + name = s['SongName'] + if 'AlbumName' in s: + albumName = s['AlbumName'] + else: + albumName = "" + itemList.append([name.encode('utf8', 'ignore'),\ s['SongID'],\ - s['AlbumName'].encode('ascii', 'ignore'),\ + albumName.encode('utf8', 'ignore'),\ s['AlbumID'],\ - s['ArtistName'].encode('ascii', 'ignore'),\ + s['ArtistName'].encode('utf8', 'ignore'),\ s['ArtistID'],\ coverart]) i = i + 1 - return list + return itemList else: return [] @@ -520,14 +509,14 @@ class GrooveAPI: def _parseArtists(self, items): if 'result' in items: i = 0 - list = [] + itemList = [] artists = items['result']['artists'] while(i < len(artists)): s = artists[i] - list.append([s['ArtistName'].encode('ascii', 'ignore'),\ + itemList.append([s['ArtistName'].encode('utf8', 'ignore'),\ s['ArtistID']]) i = i + 1 - return list + return itemList else: return [] @@ -535,7 +524,7 @@ class GrooveAPI: def _parseAlbums(self, items, limit=0): if 'result' in items: i = 0 - list = [] + itemList = [] try: albums = items['result']['albums'] except: @@ -546,23 +535,27 @@ class GrooveAPI: l = limit while(i < l): s = albums[i] + if 'Name' in s: + name = s['Name'].encode('utf8', 'ignore') + else: + name = s['AlbumName'].encode('utf8', 'ignore') if 'CoverArtFilename' in s and s['CoverArtFilename'] != None: - coverart = THUMB_URL+s['CoverArtFilename'].encode('ascii', 'ignore') + coverart = THUMB_URL+s['CoverArtFilename'].encode('utf8', 'ignore') else: coverart = 'None' - list.append([s['ArtistName'].encode('ascii', 'ignore'),\ + itemList.append([s['ArtistName'].encode('utf8', 'ignore'),\ s['ArtistID'],\ - s['AlbumName'].encode('ascii', 'ignore'),\ + name,\ s['AlbumID'],\ coverart]) i = i + 1 - return list + return itemList else: return [] def _parsePlaylists(self, items): i = 0 - list = [] + itemList = [] if 'result' in items: playlists = items['result']['playlists'] elif len(items) > 0: @@ -572,6 +565,6 @@ class GrooveAPI: while (i < len(playlists)): s = playlists[i] - list.append([str(s['PlaylistName']).encode('ascii', 'ignore'), s['PlaylistID']]) + itemList.append([unicode(s['PlaylistName']).encode('utf8', 'ignore'), s['PlaylistID']]) i = i + 1 - return list + return itemList