+++ /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 ''
-
- # Get the url to link to a song on Grooveshark
- def getSongInfo(self, songID):
- result = self._callRemote('getSongInfoEx', {'songID' : songID})
- 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')
- else:
- info['CoverArtFilename'] = THUMB_URL_DEFAULT
- return info
- 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:
- return self._parsePlaylists(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'] == 'true':
- return result['result']['PlaylistID']
- elif 'errors' in result:
- for error in result['errors']:
- if (error['code'] == 800):
- 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'] == 'true':
- 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 self._parseSongs(result)
- else:
- return []
-
- # 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 = len(items['result'])
- index = ''
- while(i < l):
- if index == 'songs':
- s = items['result'][index][i]
- elif index == 'song':
- s = items['result'][index]
- else:
- s = items['result'][i]
- if 'CoverArtFilename' not in s:
- info = self.getSongInfo(s['SongID'])
- coverart = info['CoverArtFilename']
- elif 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 'CoverArtFilename' in s and 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']
- while(i < len(playlists)):
- s = playlists[i]
- list.append([s['PlaylistID'],\
- s['Name'].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()
-#res = groovesharkApi.getUserPlaylists()
-#res = groovesharkApi.getSongInfo('27425375')
-
-res = groovesharkApi.getPlaylistSongs(40902662)
-
-pprint.pprint(res)
-
-
-