New API.
[clinton/xbmc-groove.git] / resources / lib / GroovesharkAPI.py
... / ...
CommitLineData
1import socket, hmac, urllib, urllib2, pprint, md5, uuid, re, hashlib, time, random, os, pickle
2
3# GrooveAPI constants
4THUMB_URL = 'http://beta.grooveshark.com/static/amazonart/'
5THUMB_URL_DEFAULT = 'http://grooveshark.com/webincludes/logo/Grooveshark_Logo_No-Text.png'
6SONG_LIMIT = 25
7ALBUM_LIMIT = 15
8ARTIST_LIMIT = 15
9
10# GrooveSong constants
11DOMAIN = "grooveshark.com"
12HOME_URL = "http://listen." + DOMAIN
13TOKEN_URL = "http://cowbell." + DOMAIN + "/more.php"
14API_URL = "http://cowbell." + DOMAIN + "/more.php"
15SERVICE_URL = "http://cowbell." + DOMAIN + "/service.php"
16
17CLIENT_NAME = "gslite" #htmlshark #jsqueue
18CLIENT_VERSION = "20101012.37" #"20100831.25"
19HEADERS = {"Content-Type": "application/json",
20 "User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 (.NET CLR 3.5.30729)",
21 "Referer": "http://listen.grooveshark.com/main.swf?cowbell=fe87233106a6cef919a1294fb2c3c05f"}
22
23RE_SESSION = re.compile('"sessionID":"\s*?([A-z0-9]+)"') #re.compile('sessionID:\s*?\'([A-z0-9]+)\',')
24RANDOM_CHARS = "1234567890abcdef"
25
26# Get a song
27class GrooveSong:
28
29 def __init__(self, cacheDir):
30
31 import simplejson
32 self.simplejson = simplejson
33
34 self.cacheDir = cacheDir
35 self._lastTokenTime = 0
36 self.uuid = self._getUUID()
37 self.sessionID = self._getSession(HOME_URL)
38 if self.sessionID == None:
39 raise StandardError("Cannot get session id")
40
41 # The actual call to the API
42 def _callRemote(self, method, params, type="default"):
43 postData = {
44 "header": {
45 "client": CLIENT_NAME,
46 "clientRevision": CLIENT_VERSION,
47 "uuid": self.uuid,
48 "session": self.sessionID},
49 "country": {"IPR":"1021", "ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"},
50 "privacy": 1,
51 "parameters": params,
52 "method": method}
53
54 token = self._getMethodToken(method)
55 if token == None:
56 raise StandardError("Cannot get token")
57
58 postData["header"]["token"] = token
59 if type == "service":
60 url = SERVICE_URL + "?" + method
61 else:
62 url = API_URL + "?" + method
63
64 postData = self.simplejson.dumps(postData)
65 print "GrooveSong URL: " + url
66 request = urllib2.Request(url, postData, HEADERS)
67
68 response = urllib2.urlopen(request).read()
69 try:
70 response = self.simplejson.loads(response)
71 print "GrooveSong Response..."
72 pprint.pprint(response)
73 except:
74 raise StandardError("API error: " + response)
75 try:
76 response["fault"]
77 except KeyError:
78 return response
79 else:
80 raise StandardError("API error: " + response["fault"]["message"])
81
82 # Generate a random uuid
83 def _getUUID(self):
84 return str(uuid.uuid4())
85
86 # Make a token ready for a request header
87 def _getMethodToken(self, method):
88 if (time.time() - self._lastTokenTime) >= 1000:
89 self._token = self._getCommunicationToken()
90 if self._token == None:
91 return None
92 self._lastTokenTime = time.time()
93
94 randomChars = ""
95 while 6 > len(randomChars):
96 randomChars = randomChars + random.choice(RANDOM_CHARS)
97
98 token = hashlib.sha1(method + ":" + self._token + ":quitStealinMahShit:" + randomChars).hexdigest()
99 return randomChars + token
100
101 # Generate a communication token
102 def _getCommunicationToken(self):
103 params = {"secretKey": self._getSecretKey(self.sessionID)}
104 postData = {
105 "header": {
106 "client": CLIENT_NAME,
107 "clientRevision": CLIENT_VERSION,
108 "uuid": self.uuid,
109 "session": self.sessionID},
110 "country": {"IPR":"1021", "ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"},
111 "privacy": 1,
112 "parameters": params,
113 "method": "getCommunicationToken"}
114
115 postData = self.simplejson.dumps(postData)
116 request = urllib2.Request(TOKEN_URL, postData, HEADERS)
117 response = urllib2.urlopen(request).read()
118 try:
119 response = self.simplejson.loads(response)
120 except:
121 raise StandardError("API error: " + response)
122 try:
123 response["fault"]
124 except KeyError:
125 return response["result"]
126 else:
127 return None
128
129 # Generate a secret key from a sessionID
130 def _getSecretKey(self, sessionID):
131 return hashlib.md5(sessionID).hexdigest()
132
133 # Get a session id from some HTML
134 def _getSession(self, html):
135 html = urllib2.urlopen(HOME_URL).read()
136 session = RE_SESSION.search(html)
137 if session:
138 return session.group(1)
139 else:
140 return None
141
142 # Gets a stream key and host to get song content
143 def _getStreamDetails(self, songID):
144 params = {
145 "songID": songID,
146 "prefetch": False,
147 "mobile": False,
148 "country": {"IPR":"1021","ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"}
149 }
150 response = self._callRemote("getStreamKeyFromSongIDEx", params)
151 self._lastStreamKey = response["result"]["streamKey"]
152 self._lastStreamServer = response["result"]["ip"]
153 self._lastStreamServerID = response["result"]["streamServerID"]
154
155 # Tells Grooveshark you have downloaded a song
156 def _markSongDownloaded(self, songID):
157 params = {
158 "streamKey": self._lastStreamKey,
159 "streamServerID": self._lastStreamServerID,
160 "songID": songID}
161 self._callRemote("markSongDownloaded", params)
162
163 # Download a song to a temporary file
164 def getSongURL(self, songID):
165 filename = os.path.join(self.cacheDir, songID + '.mp3')
166 if os.path.isfile(filename) == False:
167 self._getStreamDetails(songID)
168 postData = {"streamKey": self._lastStreamKey}
169 postData = urllib.urlencode(postData)
170 urllib.FancyURLopener().retrieve( "http://" + self._lastStreamServer + "/stream.php", filename, data=postData)
171 self._markSongDownloaded(songID)
172 return filename
173
174
175# Main API
176class GrooveAPI:
177
178 sessionID = ''
179 userID = 0
180 host = 'api.grooveshark.com'
181
182 # Constructor
183 def __init__(self, cacheDir):
184 import simplejson
185 self.simplejson = simplejson
186 socket.setdefaulttimeout(40)
187 self.cacheDir = cacheDir
188 self.sessionID = self._getSavedSessionID()
189 if self.sessionID == '':
190 self.sessionID = self._getSessionID()
191 if self.sessionID == '':
192 raise StandardError('Failed to get session id')
193 else:
194 self._setSavedSessionID()
195 # Sort keys
196 def _keySort(self, d):
197 return [(k,d[k]) for k in sorted(d.keys())]
198
199 # Make a message sig
200 def _createMessageSig(self, method, params, secret):
201 args = self._keySort(params);
202 data = '';
203 for arg in args:
204 data += str(arg[0])
205 data += str(arg[1])
206 data = method + data
207
208 h = hmac.new(secret, data)
209 return h.hexdigest()
210
211 # The actual call to the API
212 def _callRemote(self, method, params = {}):
213 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'))
214 print url
215 req = urllib2.Request(url)
216 response = urllib2.urlopen(req)
217 result = response.read()
218 pprint.pprint(result)
219 response.close()
220 try:
221 result = self.simplejson.loads(result)
222 return result
223 except:
224 return []
225
226 # Get a session id
227 def _getSessionID(self):
228 params = {}
229 result = self._callRemote('startSession', params)
230 return result['result']['sessionID']
231
232 def _getSavedSessionID(self):
233 sessionID = ''
234 path = os.path.join(self.cacheDir, 'session', 'session.txt')
235 try:
236 f = open(path, 'rb')
237 sessionID = pickle.load(f)
238 f.close()
239 except:
240 sessionID = ''
241 pass
242
243 return sessionID
244
245 def _setSavedSessionID(self):
246 try:
247 dir = os.path.join(self.cacheDir, 'session')
248 # Create the 'data' directory if it doesn't exist.
249 if not os.path.exists(dir):
250 os.makedirs(dir)
251 path = os.path.join(dir, 'session.txt')
252 f = open(path, 'wb')
253 pickle.dump(self.sessionID, f, protocol=pickle.HIGHEST_PROTOCOL)
254 f.close()
255 except:
256 print "An error occured during save session"
257 pass
258
259 # Make user authentication token
260 def _getUserToken(self, username, password):
261 return md5.new(username.lower() + md5.new(password).hexdigest()).hexdigest()
262
263 # Authenticates the user for current API session
264 def _authenticateUser(self, username, token):
265 params = {'sessionID': self.sessionID, 'username': username, 'token': token}
266 result = self._callRemote('authenticateUser', params)
267 return result['result']['UserID']
268
269 # Login
270 def login(self, username, password):
271 token = self._getUserToken(username, password)
272 self.userID = self._authenticateUser(username, token)
273 return self.userID
274
275 # Logs the user out
276 def logout(self):
277 self._callRemote('logout', {'sessionID' : self.sessionID})
278
279 # Return user id
280 def getUserID(self):
281 return self.userID
282
283 # Search for albums
284 def getArtistSearchResults(self, query, limit=ARTIST_LIMIT):
285 result = self._callRemote('getArtistSearchResults', {'query' : query,'limit' : limit})
286 if 'result' in result:
287 return self._parseArtists(result)
288 else:
289 return []
290
291 # Search for albums
292 def getAlbumSearchResults(self, query, limit=ALBUM_LIMIT):
293 result = self._callRemote('getAlbumSearchResults', {'query' : query,'limit' : limit})
294 if 'result' in result:
295 return self._parseAlbums(result)
296 else:
297 return []
298
299 # Search for songs
300 def getSongSearchResults(self, query, limit=SONG_LIMIT):
301 result = self._callRemote('getSongSearchResultsEx', {'query' : query, 'limit' : limit})
302 if 'result' in result:
303 return self._parseSongs(result)
304 else:
305 return []
306
307 # Gets the popular songs
308 def getPopularSongsToday(self, limit=SONG_LIMIT):
309 result = self._callRemote('getPopularSongsToday', {'limit' : limit})
310 if 'result' in result:
311 return self._parseSongs(result)
312 else:
313 return []
314
315 # Gets the favorite songs of the logged-in user
316 def getUserFavoriteSongs(self):
317 if (self.userID == 0):
318 return [];
319 result = self._callRemote('getUserFavoriteSongs', {'sessionID' : self.sessionID})
320 if 'result' in result:
321 return self._parseSongs(result)
322 else:
323 return []
324
325 # Get the url to link to a song on Grooveshark
326 def getSongURLFromSongID(self, songID):
327 song = GrooveSong(self.cacheDir)
328 return song.getSongURL(songID)
329
330 # Get the url to link to a song on Grooveshark
331 def getSongInfo(self, songID):
332 result = self._callRemote('getSongInfoEx', {'songID' : songID})
333 if 'result' in result and 'SongID' in result['result']:
334 info = result['result']
335 if 'CoverArtFilename' in info and info['CoverArtFilename'] != None:
336 info['CoverArtFilename'] = THUMB_URL+info['CoverArtFilename'].encode('ascii', 'ignore')
337 else:
338 info['CoverArtFilename'] = THUMB_URL_DEFAULT
339 return info
340 else:
341 return ''
342
343 # Gets the playlists of the logged-in user
344 def getUserPlaylists(self):
345 if (self.userID == 0):
346 return [];
347 result = self._callRemote('getUserPlaylists', {'sessionID' : self.sessionID})
348 if 'result' in result:
349 return self._parsePlaylists(result)
350 else:
351 return []
352
353 # Creates a playlist with songs
354 def createPlaylist(self, name, songIDs):
355 result = self._callRemote('createPlaylist', {'name' : name, 'songIDs' : songIDs, 'sessionID' : self.sessionID})
356 if 'result' in result and result['result']['success'] == 'true':
357 return result['result']['PlaylistID']
358 elif 'errors' in result:
359 return 0
360
361 # Sets the songs for a playlist
362 def setPlaylistSongs(self, playlistID, songIDs):
363 result = self._callRemote('setPlaylistSongs', {'playlistID' : playlistID, 'songIDs' : songIDs, 'sessionID' : self.sessionID})
364 if 'result' in result and result['result']['success'] == 'true':
365 return True;
366 else:
367 return False;
368
369 # Gets the songs of a playlist
370 def getPlaylistSongs(self, playlistID):
371 result = self._callRemote('getPlaylistSongs', {'playlistID' : playlistID});
372 if 'result' in result:
373 return self._parseSongs(result)
374 else:
375 return []
376
377 # Extract song data
378 def _parseSongs(self, items):
379 if 'result' in items:
380 i = 0
381 list = []
382 if 'songs' in items['result']:
383 l = len(items['result']['songs'])
384 index = 'songs'
385 elif 'song' in items['result']:
386 l = 1
387 index = 'song'
388 else:
389 l = len(items['result'])
390 index = ''
391 while(i < l):
392 if index == 'songs':
393 s = items['result'][index][i]
394 elif index == 'song':
395 s = items['result'][index]
396 else:
397 s = items['result'][i]
398 if 'CoverArtFilename' not in s:
399 info = self.getSongInfo(s['SongID'])
400 coverart = info['CoverArtFilename']
401 elif s['CoverArtFilename'] != None:
402 coverart = THUMB_URL+s['CoverArtFilename'].encode('ascii', 'ignore')
403 else:
404 coverart = THUMB_URL_DEFAULT
405 list.append([s['SongName'].encode('ascii', 'ignore'),\
406 s['SongID'],\
407 s['AlbumName'].encode('ascii', 'ignore'),\
408 s['AlbumID'],\
409 s['ArtistName'].encode('ascii', 'ignore'),\
410 s['ArtistID'],\
411 coverart])
412 i = i + 1
413 return list
414 else:
415 return []
416
417 # Extract artist data
418 def _parseArtists(self, items):
419 if 'result' in items:
420 i = 0
421 list = []
422 artists = items['result']['artists']
423 while(i < len(artists)):
424 s = artists[i]
425 list.append([s['ArtistName'].encode('ascii', 'ignore'),\
426 s['ArtistID']])
427 i = i + 1
428 return list
429 else:
430 return []
431
432 # Extract album data
433 def _parseAlbums(self, items):
434 if 'result' in items:
435 i = 0
436 list = []
437 albums = items['result']['albums']
438 while(i < len(albums)):
439 s = albums[i]
440 if 'CoverArtFilename' in s and s['CoverArtFilename'] != None:
441 coverart = THUMB_URL+s['CoverArtFilename'].encode('ascii', 'ignore')
442 else:
443 coverart = THUMB_URL_DEFAULT
444 list.append([s['ArtistName'].encode('ascii', 'ignore'),\
445 s['ArtistID'],\
446 s['AlbumName'].encode('ascii', 'ignore'),\
447 s['AlbumID'],\
448 coverart])
449 i = i + 1
450 return list
451 else:
452 return []
453
454 def _parsePlaylists(self, items):
455 if 'result' in items:
456 i = 0
457 list = []
458 playlists = items['result']
459 while(i < len(playlists)):
460 s = playlists[i]
461 list.append([s['PlaylistID'],\
462 s['Name'].encode('ascii', 'ignore')])
463 i = i + 1
464 return list
465 else:
466 return []
467
468
469
470# Test
471
472#res = []
473#groovesharkApi = GrooveAPI('/tmp')
474#res = groovesharkApi.login('stephendenham', '*******')
475#res = groovesharkApi.getSongSearchResults('jimmy jazz', 3)
476#res = groovesharkApi.getPopularSongsToday()
477#res = groovesharkApi.getSongURLFromSongID('27425375')
478#res = groovesharkApi.getAlbumSearchResults('london calling', 3)
479#res = groovesharkApi.getArtistSearchResults('the clash', 3)
480#res = groovesharkApi.getUserFavoriteSongs()
481#res = groovesharkApi.getUserPlaylists()
482#res = groovesharkApi.getSongInfo('27425375')
483#res = groovesharkApi.getPlaylistSongs(40902662)
484
485#pprint.pprint(res)
486
487
488