--- /dev/null
+import socket, hmac, urllib, urllib2, pprint, md5, os, pickle
+from operator import itemgetter
+
+THUMB_URL = 'http://beta.grooveshark.com/static/amazonart/'
+THUMB_URL_DEFAULT = 'http://grooveshark.com/webincludes/logo/Grooveshark_Logo_No-Text.png'
+SONG_LIMIT = 25
+ALBUM_LIMIT = 15
+ARTIST_LIMIT = 15
+
+
+class GrooveAPI:
+
+ sessionID = ''
+ userID = 0
+ host = 'api.grooveshark.com'
+
+ # Constructor
+ def __init__(self, sessionID = ''):
+ import simplejson
+ self.simplejson = simplejson
+ socket.setdefaulttimeout(40)
+ if sessionID == '':
+ self.sessionID = self._getSessionID()
+ else:
+ self.sessionID = sessionID
+
+ def _keySort(self, d):
+ return [(k,d[k]) for k in sorted(d.keys())]
+
+ # Make a message sig
+ def _createMessageSig(self, method, params, secret):
+ args = self._keySort(params);
+ data = '';
+ for arg in args:
+ data += str(arg[0])
+ data += str(arg[1])
+ data = method + data
+
+ h = hmac.new(secret, data)
+ return h.hexdigest()
+
+ # The actual call to the API
+ def _callRemote(self, method, params = {}):
+ url = 'http://%s/ws/2.1/?method=%s&%s&wsKey=wordpress&sig=%s&format=json' % (self.host, method, urllib.urlencode(params), self._createMessageSig(method, params, 'd6c59291620c6eaa5bf94da08fae0ecc'))
+ print url
+ req = urllib2.Request(url)
+ response = urllib2.urlopen(req)
+ result = response.read()
+ pprint.pprint(result)
+ response.close()
+ try:
+ result = self.simplejson.loads(result)
+ return result
+ except:
+ return []
+
+ def getUserID(self):
+ return self.userID
+
+ def getSessionID(self):
+ return self.sessionID
+
+ def _getSessionID(self):
+ params = {}
+ result = self._callRemote('startSession', params)
+ return result['result']['sessionID']
+
+ # Make user authentication token
+ def _getUserToken(self, username, password):
+ return md5.new(username.lower() + md5.new(password).hexdigest()).hexdigest()
+
+ # Authenticates the user for current API session
+ def _authenticateUser(self, username, token):
+ params = {'sessionID': self.sessionID, 'username': username, 'token': token}
+ result = self._callRemote('authenticateUser', params)
+ return result['result']['UserID']
+
+ # Login
+ def login(self, username, password):
+ token = self._getUserToken(username, password)
+ self.userID = self._authenticateUser(username, token)
+ return self.userID
+
+ # Logs the user out
+ def logout(self):
+ self._callRemote('logout', {'sessionID' : self.sessionID})
+
+ # Search for albums
+ def getArtistSearchResults(self, query, limit=ARTIST_LIMIT):
+ result = self._callRemote('getArtistSearchResults', {'query' : query,'limit' : limit})
+ if 'result' in result:
+ return self._parseArtists(result)
+ else:
+ return ''
+
+ # Search for albums
+ def getAlbumSearchResults(self, query, limit=ALBUM_LIMIT):
+ result = self._callRemote('getAlbumSearchResults', {'query' : query,'limit' : limit})
+ if 'result' in result:
+ return self._parseAlbums(result)
+ else:
+ return ''
+
+ # Search for songs
+ def getSongSearchResults(self, query, limit=SONG_LIMIT):
+ result = self._callRemote('getSongSearchResultsEx', {'query' : query, 'limit' : limit})
+ if 'result' in result:
+ return self._parseSongs(result)
+ else:
+ return ''
+
+ # Gets the popular songs
+ def getPopularSongsToday(self, limit=SONG_LIMIT):
+ result = self._callRemote('getPopularSongsToday', {'limit' : limit})
+ if 'result' in result:
+ return self._parseSongs(result)
+ else:
+ return ''
+
+ # Gets the favorite songs of the logged-in user
+ def getUserFavoriteSongs(self):
+ if (self.userID == 0):
+ return [];
+ result = self._callRemote('getUserFavoriteSongs', {'sessionID' : self.sessionID})
+ if 'result' in result:
+ return self._parseSongs(result)
+ else:
+ return ''
+
+ # Get the url to link to a song on Grooveshark
+ def getSongURLFromSongID(self, songID):
+ result = self._callRemote('getSongURLFromSongID', {'songID' : songID})
+ if 'result' in result:
+ url = result['result']['url']
+ return url.encode('ascii', 'ignore')
+ else:
+ return ''
+
+ # Gets the playlists of the logged-in user
+ def getUserPlaylists(self):
+ if (self.userID == 0):
+ return [];
+ result = self._callRemote('getUserPlaylists', {'sessionID' : self.sessionID})
+ if 'result' in result:
+ playlists = result['result']['playlists']
+ else:
+ return []
+ i = 0
+ list = []
+ while(i < len(playlists)):
+ p = playlists[i]
+ list.append([p['playlistName'].encode('ascii', 'ignore'), p['playlistID']])
+ i = i + 1
+ return sorted(list, key=itemgetter(0))
+
+ # Gets playlist information
+ def getPlaylistInfo(self, playlistID):
+ result = self._callRemote('getPlaylistInfo', {'playlistID' : playlistID})
+ if 'result' in result:
+ return result['result']
+ else:
+ return []
+
+ # Creates a playlist with songs
+ def createPlaylist(self, name, songIDs):
+ result = self._callRemote('createPlaylist', {'name' : name, 'songIDs' : songIDs, 'sessionID' : self.sessionID})
+ if 'result' in result and result['result']['success'] == 1:
+ return result['result']['playlistID']
+ elif 'errors' in result:
+ duplicate = False;
+ for error in result['errors']:
+ if (error['code'] == 800):
+ duplicate = True;
+ if (duplicate):
+ return -1
+ else:
+ return 0
+ else:
+ return 0
+
+ # Sets the songs for a playlist
+ def setPlaylistSongs(self, playlistID, songIDs):
+ result = self._callRemote('setPlaylistSongs', {'playlistID' : playlistID, 'songIDs' : songIDs, 'sessionID' : self.sessionID})
+ if 'result' in result and result['result']['success'] == 1:
+ return True;
+ else:
+ return False;
+
+ # Gets the songs of a playlist
+ def getPlaylistSongs(self, playlistID):
+ result = self._callRemote('getPlaylistSongs', {'playlistID' : playlistID});
+ if 'result' in result:
+ return result['result'];
+ elif result['errors'] in result :
+ return result['errors'][0]['code']
+ else:
+ return {'error':-512};
+
+ # Extract song data
+ def _parseSongs(self, items):
+ if 'result' in items:
+ i = 0
+ list = []
+ if 'songs' in items['result']:
+ l = len(items['result']['songs'])
+ index = 'songs'
+ elif 'song' in items['result']:
+ l = 1
+ index = 'song'
+ else:
+ l = 0
+ index = ''
+ while(i < l):
+ if index == 'songs':
+ s = items['result'][index][i]
+ else:
+ s = items['result'][index]
+ if s['CoverArtFilename'] != None:
+ coverart = THUMB_URL+s['CoverArtFilename'].encode('ascii', 'ignore')
+ else:
+ coverart = THUMB_URL_DEFAULT
+ list.append([s['SongName'].encode('ascii', 'ignore'),\
+ s['SongID'],\
+ s['AlbumName'].encode('ascii', 'ignore'),\
+ s['AlbumID'],\
+ s['ArtistName'].encode('ascii', 'ignore'),\
+ s['ArtistID'],\
+ coverart])
+ i = i + 1
+ return list
+ else:
+ return []
+
+ # Extract artist data
+ def _parseArtists(self, items):
+ if 'result' in items:
+ i = 0
+ list = []
+ artists = items['result']['artists']
+ while(i < len(artists)):
+ s = artists[i]
+ list.append([s['ArtistName'].encode('ascii', 'ignore'),\
+ s['ArtistID']])
+ i = i + 1
+ return list
+ else:
+ return []
+
+ # Extract album data
+ def _parseAlbums(self, items):
+ if 'result' in items:
+ i = 0
+ list = []
+ albums = items['result']['albums']
+ while(i < len(albums)):
+ s = albums[i]
+ if s['CoverArtFilename'] != None:
+ coverart = THUMB_URL+s['CoverArtFilename'].encode('ascii', 'ignore')
+ else:
+ coverart = THUMB_URL_DEFAULT
+ list.append([s['ArtistName'].encode('ascii', 'ignore'),\
+ s['ArtistID'],\
+ s['AlbumName'].encode('ascii', 'ignore'),\
+ s['AlbumID'],\
+ coverart])
+ i = i + 1
+ return list
+ else:
+ return []
+
+ def _parsePlaylists(self, items):
+ if 'result' in items:
+ i = 0
+ list = []
+ playlists = items['result']['playlists']
+ while(i < len(playlists)):
+ s = playlists[i]
+ list.append([s['PlaylistID'],\
+ s['PlaylistName'].encode('ascii', 'ignore'),\
+ s['Username'].encode('ascii', 'ignore')])
+ i = i + 1
+ return list
+ else:
+ return []
+
+
+groovesharkApi = GrooveAPI('c4285d93d556349d284704100eb557d7')
+print "SessionID: " + groovesharkApi.getSessionID()
+print "UserID: " + str(groovesharkApi.login('stephendenham', 'lond0n'))
+
+#res = groovesharkApi.getSongSearchResults('jimmy jazz', 3)
+#res = groovesharkApi.getPopularSongsToday()
+#res = groovesharkApi.getSongURLFromSongID('27425375')
+#res = groovesharkApi.getAlbumSearchResults('london calling', 3)
+#res = groovesharkApi.getArtistSearchResults('the clash', 3)
+res = groovesharkApi.getUserFavoriteSongs()
+
+
+pprint.pprint(res)
+
+
+