739416d8c7b2d9ab39ede3922fb1b08c4242af2a
1 import socket
, hmac
, urllib
, urllib2
, pprint
, md5
, os
, pickle
2 from operator
import itemgetter
4 THUMB_URL
= 'http://beta.grooveshark.com/static/amazonart/'
5 THUMB_URL_DEFAULT
= 'http://grooveshark.com/webincludes/logo/Grooveshark_Logo_No-Text.png'
15 host
= 'api.grooveshark.com'
18 def __init__(self
, sessionID
= ''):
20 self
.simplejson
= simplejson
21 socket
.setdefaulttimeout(40)
23 self
.sessionID
= self
._getSessionID
()
25 self
.sessionID
= sessionID
27 def _keySort(self
, d
):
28 return [(k
,d
[k
]) for k
in sorted(d
.keys())]
31 def _createMessageSig(self
, method
, params
, secret
):
32 args
= self
._keySort
(params
);
39 h
= hmac
.new(secret
, data
)
42 # The actual call to the API
43 def _callRemote(self
, method
, params
= {}):
44 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'))
46 req
= urllib2
.Request(url
)
47 response
= urllib2
.urlopen(req
)
48 result
= response
.read()
52 result
= self
.simplejson
.loads(result
)
60 def getSessionID(self
):
63 def _getSessionID(self
):
65 result
= self
._callRemote
('startSession', params
)
66 return result
['result']['sessionID']
68 # Make user authentication token
69 def _getUserToken(self
, username
, password
):
70 return md5
.new(username
.lower() + md5
.new(password
).hexdigest()).hexdigest()
72 # Authenticates the user for current API session
73 def _authenticateUser(self
, username
, token
):
74 params
= {'sessionID': self
.sessionID
, 'username': username
, 'token': token
}
75 result
= self
._callRemote
('authenticateUser', params
)
76 return result
['result']['UserID']
79 def login(self
, username
, password
):
80 token
= self
._getUserToken
(username
, password
)
81 self
.userID
= self
._authenticateUser
(username
, token
)
86 self
._callRemote
('logout', {'sessionID' : self
.sessionID
})
89 def getArtistSearchResults(self
, query
, limit
=ARTIST_LIMIT
):
90 result
= self
._callRemote
('getArtistSearchResults', {'query' : query
,'limit' : limit
})
91 if 'result' in result
:
92 return self
._parseArtists
(result
)
97 def getAlbumSearchResults(self
, query
, limit
=ALBUM_LIMIT
):
98 result
= self
._callRemote
('getAlbumSearchResults', {'query' : query
,'limit' : limit
})
99 if 'result' in result
:
100 return self
._parseAlbums
(result
)
105 def getSongSearchResults(self
, query
, limit
=SONG_LIMIT
):
106 result
= self
._callRemote
('getSongSearchResultsEx', {'query' : query
, 'limit' : limit
})
107 if 'result' in result
:
108 return self
._parseSongs
(result
)
112 # Gets the popular songs
113 def getPopularSongsToday(self
, limit
=SONG_LIMIT
):
114 result
= self
._callRemote
('getPopularSongsToday', {'limit' : limit
})
115 if 'result' in result
:
116 return self
._parseSongs
(result
)
120 # Gets the favorite songs of the logged-in user
121 def getUserFavoriteSongs(self
):
122 if (self
.userID
== 0):
124 result
= self
._callRemote
('getUserFavoriteSongs', {'sessionID' : self
.sessionID
})
125 if 'result' in result
:
126 return self
._parseSongs
(result
)
130 # Get the url to link to a song on Grooveshark
131 def getSongURLFromSongID(self
, songID
):
132 result
= self
._callRemote
('getSongURLFromSongID', {'songID' : songID
})
133 if 'result' in result
:
134 url
= result
['result']['url']
135 return url
.encode('ascii', 'ignore')
139 # Gets the playlists of the logged-in user
140 def getUserPlaylists(self
):
141 if (self
.userID
== 0):
143 result
= self
._callRemote
('getUserPlaylists', {'sessionID' : self
.sessionID
})
144 if 'result' in result
:
145 playlists
= result
['result']['playlists']
150 while(i
< len(playlists
)):
152 list.append([p
['playlistName'].encode('ascii', 'ignore'), p
['playlistID']])
154 return sorted(list, key
=itemgetter(0))
156 # Gets playlist information
157 def getPlaylistInfo(self
, playlistID
):
158 result
= self
._callRemote
('getPlaylistInfo', {'playlistID' : playlistID
})
159 if 'result' in result
:
160 return result
['result']
164 # Creates a playlist with songs
165 def createPlaylist(self
, name
, songIDs
):
166 result
= self
._callRemote
('createPlaylist', {'name' : name
, 'songIDs' : songIDs
, 'sessionID' : self
.sessionID
})
167 if 'result' in result
and result
['result']['success'] == 1:
168 return result
['result']['playlistID']
169 elif 'errors' in result
:
171 for error
in result
['errors']:
172 if (error
['code'] == 800):
181 # Sets the songs for a playlist
182 def setPlaylistSongs(self
, playlistID
, songIDs
):
183 result
= self
._callRemote
('setPlaylistSongs', {'playlistID' : playlistID
, 'songIDs' : songIDs
, 'sessionID' : self
.sessionID
})
184 if 'result' in result
and result
['result']['success'] == 1:
189 # Gets the songs of a playlist
190 def getPlaylistSongs(self
, playlistID
):
191 result
= self
._callRemote
('getPlaylistSongs', {'playlistID' : playlistID
});
192 if 'result' in result
:
193 return result
['result'];
194 elif result
['errors'] in result
:
195 return result
['errors'][0]['code']
197 return {'error':-512};
200 def _parseSongs(self
, items
):
201 if 'result' in items
:
204 if 'songs' in items
['result']:
205 l
= len(items
['result']['songs'])
207 elif 'song' in items
['result']:
215 s
= items
['result'][index
][i
]
217 s
= items
['result'][index
]
218 if s
['CoverArtFilename'] != None:
219 coverart
= THUMB_URL
+s
['CoverArtFilename'].encode('ascii', 'ignore')
221 coverart
= THUMB_URL_DEFAULT
222 list.append([s
['SongName'].encode('ascii', 'ignore'),\
224 s
['AlbumName'].encode('ascii', 'ignore'),\
226 s
['ArtistName'].encode('ascii', 'ignore'),\
234 # Extract artist data
235 def _parseArtists(self
, items
):
236 if 'result' in items
:
239 artists
= items
['result']['artists']
240 while(i
< len(artists
)):
242 list.append([s
['ArtistName'].encode('ascii', 'ignore'),\
250 def _parseAlbums(self
, items
):
251 if 'result' in items
:
254 albums
= items
['result']['albums']
255 while(i
< len(albums
)):
257 if s
['CoverArtFilename'] != None:
258 coverart
= THUMB_URL
+s
['CoverArtFilename'].encode('ascii', 'ignore')
260 coverart
= THUMB_URL_DEFAULT
261 list.append([s
['ArtistName'].encode('ascii', 'ignore'),\
263 s
['AlbumName'].encode('ascii', 'ignore'),\
271 def _parsePlaylists(self
, items
):
272 if 'result' in items
:
275 playlists
= items
['result']['playlists']
276 while(i
< len(playlists
)):
278 list.append([s
['PlaylistID'],\
279 s
['PlaylistName'].encode('ascii', 'ignore'),\
280 s
['Username'].encode('ascii', 'ignore')])
287 groovesharkApi
= GrooveAPI('c4285d93d556349d284704100eb557d7')
288 print "SessionID: " + groovesharkApi
.getSessionID()
289 print "UserID: " + str(groovesharkApi
.login('stephendenham', 'lond0n'))
291 #res = groovesharkApi.getSongSearchResults('jimmy jazz', 3)
292 #res = groovesharkApi.getPopularSongsToday()
293 #res = groovesharkApi.getSongURLFromSongID('27425375')
294 #res = groovesharkApi.getAlbumSearchResults('london calling', 3)
295 #res = groovesharkApi.getArtistSearchResults('the clash', 3)
296 res
= groovesharkApi
.getUserFavoriteSongs()